diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 00000000..3a3d67f9 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,7 @@ +{ + "permissions": { + "deny": [ + "Agent" + ] + } +} diff --git a/.github/workflows/ci-quality-gates.yml b/.github/workflows/ci-quality-gates.yml index 83986f9e..d26c661c 100644 --- a/.github/workflows/ci-quality-gates.yml +++ b/.github/workflows/ci-quality-gates.yml @@ -57,20 +57,10 @@ jobs: run: ./gradlew :verifyStrictLaneStages --dry-run --stacktrace - name: Verify Compose profile contracts render exactly as declared run: bash scripts/verify-compose-profile-contracts.sh - - sample-portfolio: - # The sample is excluded from production architecture/runtime membership policy, but it is still - # the reference implementation adopters copy. Compile/test/OpenAPI drift must therefore block PRs. - runs-on: ubuntu-latest - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - - uses: ./.github/actions/setup-gradle-java - # `qualityCheck` too: the root one covers the production leaves only, so the sample — the code - # adopters copy first — was analysed by no stage, and its SpotBugs exclusions matched nothing - # (review 2026-11-03 RR-06-05). - - name: Verify the standalone sample application - working-directory: src - run: ./gradlew :sample-portfolio:check :sample-portfolio:qualityCheck --stacktrace + # The repository root and src/ hold only the entries on the allow list (owner decision + # 2026-11-07): a new top-level folder is a decision, not a side effect of a feature commit. + - name: Refuse a top-level folder outside the allow list + run: python3 scripts/check-repo-layout.py optional-platforms: runs-on: ubuntu-latest @@ -79,15 +69,15 @@ jobs: - uses: ./.github/actions/setup-gradle-java - name: Verify the optional gRPC platform build working-directory: src - run: ./gradlew -p optional-platforms ci --stacktrace + run: ./gradlew -p platforms/optional-build ci --stacktrace # The optional build's own lane-reachability check: the main build's cannot see these lanes # (review 2026-11-03 RR-06-03). - name: Require every optional-platform strict lane to be in an executed stage working-directory: src - run: ./gradlew -p optional-platforms :verifyStrictLaneStages --dry-run --stacktrace + run: ./gradlew -p platforms/optional-build :verifyStrictLaneStages --dry-run --stacktrace - # gRPC schema policy (owner decision 18). protoc compiles src/grpc/grpc-contract inside the - # optional-platforms build above; lint and breaking-change policy belong to Buf, configured by + # gRPC schema policy (owner decision 18). protoc compiles src/platforms/grpc/grpc-contract inside + # the optional-platforms build above; lint and breaking-change policy belong to Buf, configured by # buf.yaml next to the schema. Buf is a native binary rather than a Maven artifact, so it runs here # and not inside Gradle — and nothing in the repository re-implements its rules. grpc-proto-buf: @@ -102,28 +92,38 @@ jobs: version: 1.73.0 setup_only: true - name: Lint the gRPC schema - working-directory: src/grpc/grpc-contract + working-directory: src/platforms/grpc/grpc-contract run: buf lint - name: Refuse a breaking change to the gRPC schema - working-directory: src/grpc/grpc-contract + working-directory: src/platforms/grpc/grpc-contract env: # Pull request: the target branch. Push: the commit this push replaced. BASELINE: ${{ github.event_name == 'pull_request' && format('origin/{0}', github.base_ref) || github.event.before }} run: | set -euo pipefail baseline_commit="$(git rev-parse --verify --quiet "${BASELINE}^{commit}" || true)" - if [[ -z "${baseline_commit}" ]] \ - || ! git cat-file -e "${baseline_commit}:src/grpc/grpc-contract/buf.yaml" 2>/dev/null; then + # The module moved from src/grpc to src/platforms/grpc on 2026-11-07. A baseline from + # before the move holds it at the old path, and comparing against that path keeps the + # breaking check running across the move instead of skipping it once. + baseline_dir="" + if [[ -n "${baseline_commit}" ]]; then + for candidate in src/platforms/grpc/grpc-contract src/grpc/grpc-contract; do + if git cat-file -e "${baseline_commit}:${candidate}/buf.yaml" 2>/dev/null; then + baseline_dir="${candidate}" + break + fi + done + fi + if [[ -z "${baseline_dir}" ]]; then # The first change that introduces the module has nothing to be compatible with. - echo "::notice::grpc-proto-buf: baseline ${BASELINE} has no src/grpc/grpc-contract/buf.yaml; breaking check skipped." + echo "::notice::grpc-proto-buf: baseline ${BASELINE} has no grpc-contract/buf.yaml; breaking check skipped." exit 0 fi - buf breaking --against "../../../.git#ref=${baseline_commit},subdir=src/grpc/grpc-contract" + buf breaking --against "../../../../.git#ref=${baseline_commit},subdir=${baseline_dir}" release-gate: needs: - quality-gates - - sample-portfolio - optional-platforms - grpc-proto-buf if: always() @@ -134,14 +134,12 @@ jobs: - name: Require every current blocking job to succeed env: QUALITY_RESULT: ${{ needs.quality-gates.result }} - SAMPLE_RESULT: ${{ needs.sample-portfolio.result }} OPTIONAL_PLATFORMS_RESULT: ${{ needs.optional-platforms.result }} GRPC_PROTO_BUF_RESULT: ${{ needs.grpc-proto-buf.result }} run: | set -euo pipefail for result in \ "${QUALITY_RESULT}" \ - "${SAMPLE_RESULT}" \ "${OPTIONAL_PLATFORMS_RESULT}" \ "${GRPC_PROTO_BUF_RESULT}"; do if [[ "${result}" != "success" ]]; then diff --git a/.github/workflows/docs-check.yml b/.github/workflows/docs-check.yml new file mode 100644 index 00000000..932a3fa6 --- /dev/null +++ b/.github/workflows/docs-check.yml @@ -0,0 +1,28 @@ +name: docs-check + +# Document language, record head blocks, references and copied numbers (scripts/check-docs.py). +# It runs on every pull request, not on a docs/** path filter: deleting a file or a Gradle project +# in code is exactly what makes a living document point at nothing, and that change touches no +# document. The checker is plain Python outside Gradle, because the build does not parse documents. +on: + pull_request: + push: + branches: ["main"] + workflow_dispatch: + +permissions: + contents: read + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: true + +jobs: + docs: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 + - name: Test the document checker + run: python3 -m unittest discover -s scripts/tests + - name: Check documents + run: python3 scripts/check-docs.py diff --git a/.github/workflows/fileserver-nightly.yml b/.github/workflows/fileserver-nightly.yml index dc026c36..20bd2d67 100644 --- a/.github/workflows/fileserver-nightly.yml +++ b/.github/workflows/fileserver-nightly.yml @@ -26,7 +26,7 @@ jobs: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java - name: Start the NFSv4 certification environment - run: docker compose -f infra/fileserver/nfs/compose.yml up -d --wait + run: docker compose -f src/adapter/outbound/fileserver/compose/nfs/compose.yml up -d --wait - name: Run the network-filesystem ambiguity suite working-directory: src run: >- @@ -35,7 +35,7 @@ jobs: --stacktrace - name: Tear down the NFS environment if: always() - run: docker compose -f infra/fileserver/nfs/compose.yml down -v + run: docker compose -f src/adapter/outbound/fileserver/compose/nfs/compose.yml down -v fileserver-process-kill-matrix: runs-on: ubuntu-latest diff --git a/.github/workflows/fileserver-pr.yml b/.github/workflows/fileserver-pr.yml index 780ab5f2..7dae30d0 100644 --- a/.github/workflows/fileserver-pr.yml +++ b/.github/workflows/fileserver-pr.yml @@ -24,10 +24,8 @@ on: - 'src/.env' - 'docs/registries/env-keys.yaml' - 'src/Dockerfile' - - 'docker-compose.yml' - - 'infra/fileserver/nginx/**' - - 'infra/fileserver/kubernetes/**' - - 'infra/fileserver/nfs/**' + - 'compose.yaml' + - 'src/app-bootstrap/compose-lanes/fileserver.yaml' - '.github/workflows/fileserver-pr.yml' # Every Gradle job here installs its toolchain through this composite action, so a change to # it changes what this gate runs. diff --git a/.github/workflows/integration-main.yml b/.github/workflows/integration-main.yml index 7bd70230..4c676633 100644 --- a/.github/workflows/integration-main.yml +++ b/.github/workflows/integration-main.yml @@ -60,7 +60,7 @@ concurrency: jobs: # The main-branch stage of the Gradle gates (`:mainCheck`): the environment contract, full-boot - # qualification, the sample web contract, the public-path baseline, the conditional transport + # qualification, the public-path baseline, the conditional transport # lanes, the messaging contract lanes and each leaf's document-contract lanes. API surfaces are # in the pull-request `check` (owner decision 20). The rest left the pull-request gate (review # 2026-09-24 BUILD, item 12); none of them is deleted. @@ -189,13 +189,12 @@ jobs: # never catches. This job replaced `web-load-abuse-and-shutdown`, which despite its name ran # `:adapter:inbound:web:test` and `webJettyCompatTest` — two lanes the pull-request and main stages # already run — and never the load lanes (review 2026-11-01 08-01), and `httpclient-performance`. + # No assertions switch: the strict-lane convention asserts every performance lane's bounds, so this + # job and a person on a workstation run the same command and get the same bounds. performance-check: runs-on: ubuntu-latest timeout-minutes: 120 env: - # A project property rather than a command-line flag, so the run command stays a plain, - # verifiable task invocation while the machine-dependent bounds are still asserted. - GRADLE_OPTS: -Dorg.gradle.project.performance.assertions.enabled=true TESTCONTAINERS_REUSE_ENABLE: "false" steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 @@ -208,7 +207,7 @@ jobs: - name: Run every optional-platform performance-category strict lane if: always() working-directory: src - run: ./gradlew -p optional-platforms performanceCheck --continue --stacktrace + run: ./gradlew -p platforms/optional-build performanceCheck --continue --stacktrace - name: Publish the performance lane reports if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 @@ -235,7 +234,7 @@ jobs: # `grpc-operation-ledger-jpa:integrationTest`, which certifies the atomic # `INSERT ... ON CONFLICT DO NOTHING` claim that durable mutation idempotency rests on against a # real PostgreSQL. It was registered in Gradle, listed in `strictTestLanes`, and invoked by - # nothing: `-p optional-platforms ci` reaches `checkAll`, `qualityCheck` and the dependency + # nothing: `-p platforms/optional-build ci` reaches `checkAll`, `qualityCheck` and the dependency # verifier, none of which runs a lane whose category is INTEGRATION, and release.yml's gRPC gate # names only the three grpc-testkit lanes. # @@ -251,13 +250,13 @@ jobs: - uses: ./.github/actions/setup-gradle-java - name: Certify the gRPC operation ledger against real PostgreSQL working-directory: src - run: ./gradlew -p optional-platforms integrationCheck --stacktrace + run: ./gradlew -p platforms/optional-build integrationCheck --stacktrace - name: Publish the optional-platform lane reports if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 with: name: grpc-optional-platform-integration-reports - path: src/optional-platforms/**/build/reports/tests/ + path: src/platforms/grpc*/**/build/reports/tests/ if-no-files-found: warn # Dynamic half of the compose-profile contract. Every blocking lane the matrix declares runs on @@ -273,7 +272,7 @@ jobs: steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - name: Run every blocking Compose runtime lane - run: bash scripts/run-compose-runtime-smoke.sh --matrix src/config/runtime/compose-profile-contracts.json + run: bash scripts/run-compose-runtime-smoke.sh --matrix src/app-bootstrap/compose-lanes/compose-profile-contracts.json - name: Publish sanitized runtime-smoke evidence if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 diff --git a/.github/workflows/messaging-certification.yml b/.github/workflows/messaging-certification.yml index d20e9ca8..726ba8e8 100644 --- a/.github/workflows/messaging-certification.yml +++ b/.github/workflows/messaging-certification.yml @@ -15,7 +15,7 @@ name: messaging-certification on: pull_request: paths: - - "src/messaging/**" + - "src/platforms/messaging/**" - ".github/workflows/messaging-certification.yml" # Every Gradle job here installs its toolchain through this composite action, so a change to # it changes what this gate runs. @@ -47,5 +47,5 @@ jobs: uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 with: name: messaging-broker-certification-evidence - path: src/messaging/messaging-kafka/build/messaging-certification/ + path: src/platforms/messaging/messaging-kafka/build/messaging-certification/ if-no-files-found: warn diff --git a/.github/workflows/notification-platform.yml b/.github/workflows/notification-platform.yml index 127c10b2..2f131a09 100644 --- a/.github/workflows/notification-platform.yml +++ b/.github/workflows/notification-platform.yml @@ -30,7 +30,7 @@ on: - 'src/config/architecture/modules.json' - 'src/.env' - 'docs/notification/**' - - 'infra/notification/**' + - 'src/app-bootstrap/compose-lanes/smoke/notification-smoke.sh' - '.github/workflows/notification-platform.yml' # Every Gradle job here installs its toolchain through this composite action, so a change to # it changes what this gate runs. diff --git a/.github/workflows/pr-adapters.yml b/.github/workflows/pr-adapters.yml index 11f0633a..da1ca9f6 100644 --- a/.github/workflows/pr-adapters.yml +++ b/.github/workflows/pr-adapters.yml @@ -123,7 +123,6 @@ jobs: '^src/config/architecture/modules\.json$' \ '^docs/jpa/' \ '^docs/adr/ADR-JPA-' \ - '^infra/jpa/' \ "${common}" # The servlet system contract on both containers the template supports (Tomcat, Jetty). Real diff --git a/.github/workflows/redis-sdk-topology.yml b/.github/workflows/redis-sdk-topology.yml index d29b8a77..2e099e99 100644 --- a/.github/workflows/redis-sdk-topology.yml +++ b/.github/workflows/redis-sdk-topology.yml @@ -1,6 +1,6 @@ # Redis SDK topology evidence. # -# The lanes in infra/redis-sdk answer what the deterministic in-memory gateway cannot — Sentinel +# The lanes in src/adapter/outbound/redis-sdk/compose answer what the deterministic in-memory gateway cannot — Sentinel # promotion behaviour, Cluster redirects, ACL coverage. docs/redis/support-matrix.md records which # lane produced which evidence, and RedisSupportMatrixTest refuses an evidence claim that does not # name the test class behind it. @@ -34,7 +34,7 @@ on: - "src/adapter/outbound/redis-runtime/**" - "src/adapter/outbound/redis-sdk/**" - "src/adapter/outbound/cache-redis/**" - - "infra/redis-sdk/**" + - "compose/redis/**" - ".github/workflows/redis-sdk-topology.yml" # Every Gradle job here installs its toolchain through this composite action, so a change to # it changes what this gate runs. @@ -122,7 +122,7 @@ jobs: - name: Start the topology env: REDIS_VERSION: ${{ matrix.redis_version }} - run: docker compose -f "infra/redis-sdk/${{ matrix.topology }}/compose.yml" up -d --wait + run: docker compose -f "src/adapter/outbound/redis-sdk/compose/${{ matrix.topology }}/compose.yml" up -d --wait - name: Record the image digest id: image run: | @@ -161,7 +161,7 @@ jobs: # however loudly the file is named "test". tls) port=6390 - docker compose -f ../infra/redis-sdk/tls/compose.yml cp redis:/tls/ca.crt "$RUNNER_TEMP/redis-lane-ca.pem" + docker compose -f adapter/outbound/redis-sdk/compose/tls/compose.yml cp redis:/tls/ca.crt "$RUNNER_TEMP/redis-lane-ca.pem" extra="-Predis.topology.trust-material=$RUNNER_TEMP/redis-lane-ca.pem" tasks="$runtime" ;; @@ -199,4 +199,4 @@ jobs: retention-days: 90 - name: Stop the topology if: always() - run: docker compose -f "infra/redis-sdk/${{ matrix.topology }}/compose.yml" down -v + run: docker compose -f "src/adapter/outbound/redis-sdk/compose/${{ matrix.topology }}/compose.yml" down -v diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 8cdecab9..8a0593e4 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -132,7 +132,7 @@ jobs: - uses: ./.github/actions/setup-gradle-java - name: Run the gRPC Stable certification lanes working-directory: src - run: ./gradlew -p optional-platforms releaseCheck --stacktrace + run: ./gradlew -p platforms/optional-build releaseCheck --stacktrace # The operation ledger's real-PostgreSQL lane ran only on main and nightly # (integration-main.yml), so a tag could be cut from a main whose ledger lane was red. It needs # Docker, which a release runner has (review 2026-11-01 03-12). @@ -140,15 +140,15 @@ jobs: working-directory: src env: TESTCONTAINERS_REUSE_ENABLE: "false" - run: ./gradlew -p optional-platforms integrationCheck --stacktrace + run: ./gradlew -p platforms/optional-build integrationCheck --stacktrace - name: Publish the gRPC release evidence if: always() uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # actions/upload-artifact@v4.6.2 with: name: grpc-release-evidence path: | - src/grpc/grpc-testkit/build/reports/tests/ - src/grpc/grpc-operation-ledger-jpa/build/reports/tests/ + src/platforms/grpc/grpc-testkit/build/reports/tests/ + src/platforms/grpc/grpc-operation-ledger-jpa/build/reports/tests/ if-no-files-found: warn # Each gate runs as its own single-line `./gradlew ` step so that a failure names the gate @@ -160,10 +160,6 @@ jobs: defaults: run: working-directory: src - env: - # A project property rather than a command-line flag, so each run command stays a plain, - # verifiable task invocation while the machine-dependent bounds are still asserted. - GRADLE_OPTS: -Dorg.gradle.project.performance.assertions.enabled=true steps: - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - uses: ./.github/actions/setup-gradle-java @@ -198,7 +194,7 @@ jobs: # docs/jpa/support-matrix.md recorded all three as covered. start() now fails closed on a # multi-version selection, so this matrix is the only way the Stable majors get covered. # - # config/jpa/release-registry.json is the gate-task source: jpaReleaseQualification (persistence-jpa + # persistence-jpa release/release-registry.json is the gate-task source: jpaReleaseQualification (persistence-jpa # build.gradle) depends on its blocking gates, so a gate naming a missing task fails when the task # graph is built, and JpaReleaseRenderingTest holds this matrix and the promotion list below to the # registry's Stable majors. Editing one without the other fails the persistence-jpa unit lane. @@ -330,27 +326,6 @@ jobs: :composition:fileserver-platform:test --tests '*FileserverDocumentationCoverageTest' --stacktrace - fileserver-pvc-certification: - runs-on: ubuntu-latest - timeout-minutes: 45 - steps: - - uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # actions/checkout@v4.2.2 - # This job checks the manifest, and only the manifest; it applies nothing to a cluster. The - # cluster result comes from an operator running infra/fileserver/kubernetes/ - # pvc-certification-job.yaml and recording it in docs/fileserver/storage-certification.md, - # where the absence of a cluster result is stated rather than hidden behind a green check. - - name: Check the certification manifest still says what the claim depends on - run: | - set -euo pipefail - manifest=infra/fileserver/kubernetes/pvc-certification-job.yaml - test -f "$manifest" - grep -q 'kind: PersistentVolumeClaim' "$manifest" - grep -q 'kind: Job' "$manifest" - # ReadWriteMany is explicitly not claimed; a manifest that quietly widened the access - # mode would certify a topology the support matrix says is uncertified. - grep -q 'ReadWriteOnce' "$manifest" - ! grep -q 'ReadWriteMany' "$manifest" - fileserver-sensitive-telemetry-scan: runs-on: ubuntu-latest timeout-minutes: 20 @@ -376,7 +351,6 @@ jobs: - jpa-registry-and-docs - fileserver-full-verification - fileserver-documentation-gate - - fileserver-pvc-certification - fileserver-sensitive-telemetry-scan # Job-level, because a job that declares `permissions:` replaces the workflow set entirely: this # job and app-image-signing are the only ones that write anything anywhere, and diff --git a/.gitignore b/.gitignore index b2ef4065..f22be9da 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,9 @@ .vscode/ src/**/bin/ -.claude/ +# Local Claude Code state (worktrees, settings.local.json, notes) stays out. The shared project +# settings file is committed: it denies the Agent tool for everyone (AGENTS.md 「Superpowers Workflow」). +.claude/* +!.claude/settings.json # Operator input, not a build input. The examples beside it are the tracked contract; # verifyEnvKeys reads the registry, the profile YAMLs and .env.example, never a real one. @@ -15,3 +18,7 @@ src/.env.lane graphify-out/ src/graphify-out/ .playwright-mcp/ + +# Python bytecode from running scripts/ checks; never committed. +__pycache__/ +*.pyc diff --git a/AGENTS.md b/AGENTS.md index b37bbaf3..ce0f3085 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -4,7 +4,7 @@ 이 저장소는 단순한 예제 블로그 애플리케이션이 아니라, Java 21 + 버전 카탈로그에 고정된 Spring Boot 4.x + Gradle 멀티모듈 기반의 Clean Architecture 템플릿이다. -기본 패키지는 `dev.caskeleton`이며, 예시 도메인은 production 모듈이 아니라 `sample-portfolio` 모듈(WorkLog 엔지니어링 작업 기록 게시판)에 격리한다. 새 프로젝트를 시작할 때는 도메인 이름, 패키지, 엔티티, 유스케이스를 교체할 수 있지만, 모듈 경계와 의존성 방향은 유지해야 한다. +기본 패키지는 `dev.caskeleton`이다. 업무 기능의 예시는 `scripts/new-feature.sh`의 출력과 `docs/manual/`이다. 새 프로젝트를 시작할 때는 도메인 이름, 패키지, 엔티티, 유스케이스를 교체할 수 있지만, 모듈 경계와 의존성 방향은 유지해야 한다. ## Prime Directive @@ -22,8 +22,9 @@ 6. 관련 검증 없이, 또는 실행하지 못한 이유를 밝히지 않고 완료를 주장한다. 7. 결론의 범위와 위험에 맞는 증거 없이 repository/corpus 전체 결론을 내린다. -root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어긋나면 이 `AGENTS.md` 목록이 -우선한다. 자동 강제 범위는 아래 Gradle 정책 권위와 ArchUnit/Test가 담당한다. +root `CLAUDE.md`는 작업을 시작할 때 읽는 지도이고, 이 목록을 한 줄씩 가리킨다. 두 문서가 어긋나면 +이 `AGENTS.md` 목록이 우선한다. 일의 종류별 절차는 `docs/work/`에 있다. 자동 강제 범위는 아래 Gradle +정책 권위와 ArchUnit/Test가 담당한다. ## Superpowers Workflow @@ -35,8 +36,10 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 - `superpowers:brainstorming`: 기능 설계, 구조 변경, 동작 변경, 새 문서 정책 수립 전에 사용한다. - `superpowers:writing-plans`: 승인된 설계가 있고 작업이 여러 단계로 나뉠 때 사용한다. - `superpowers:executing-plans`: 작성된 계획을 현재 세션에서 순차 실행할 때 사용한다. -- `superpowers:subagent-driven-development`: 계획을 작업 단위로 나누어 독립 에이전트에게 맡길 때 사용한다. -- `superpowers:dispatching-parallel-agents`: 서로 독립적인 조사나 구현을 병렬로 진행할 때 사용한다. +- `superpowers:subagent-driven-development`, `superpowers:dispatching-parallel-agents`: 이 저장소에서는 + 쓰지 않는다. 세션 안의 하위 에이전트(Agent 도구)는 `.claude/settings.json`이 막는다. 일을 나눠 + 맡길 때는 사람이 열어 보고 멈출 수 있는 별도 세션에 맡긴다(`docs/work/delegate.md`). 다른 스킬이 + 하위 에이전트를 띄우라고 하면 그 단계는 같은 세션이 직접 한다. - `superpowers:test-driven-development`: 기능 추가와 버그 수정을 테스트 우선으로 진행할 때 사용한다. - `superpowers:systematic-debugging`: 버그, 실패한 테스트, 예상 밖 동작을 다룰 때 사용한다. - `superpowers:verification-before-completion`: 완료, 수정됨, 통과함을 주장하기 전에 사용한다. @@ -73,13 +76,17 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 `INTEGRATION`·`SYSTEM`·`PERFORMANCE` lane과 `mainStage()` lane은 이미지·네트워크·시간·문서처럼 입력으로 잡히지 않는 것에 기대므로 매번 다시 돈다. hermetic lane이 저장소 파일을 읽으면 그 파일을 입력으로 선언해야 캐시가 거짓 통과를 내지 않는다. -- `verifyEnvKeys`는 app-bootstrap 태스크로 유지한다(소유자 결정 4). 구현은 build-logic의 +- `PERFORMANCE` lane은 상한을 매번 단언한다. 끄는 스위치가 없다: convention이 테스트 JVM에 + `performance.assertions.enabled=true`를 넣고, 빌드(`-P`·`GRADLE_OPTS`)나 lane이 다른 값을 주면 + 테스트 전에 실패한다. skip된 테스트가 하나라도 있어도 실패한다(`rejectSkipped`를 따로 쓰지 않아도). + 사람이 손으로 돌리는 `./gradlew performanceCheck`와 workflow가 같은 상한을 단언한다. +- `verifyEnvKeys`는 app-bootstrap 태스크로 유지한다(2026-09-25 소유자 결정). 구현은 build-logic의 `ca.config-contract`다. `src/build-tools/` included build는 비워서 삭제했다. - `src/build.gradle`: 루트 라이프사이클(`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, `releaseCheck`, `qualityCheck`, `configContractCheck`)과 버전/리비전. `verifyStrictLaneStages --dry-run`(PR 게이트)은 그 빌드에서 `explicitOnly`가 아닌 strict lane이 workflow가 실제로 실행하는 - 단계(main 빌드: `ci`·`sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`· - `releaseCheck`, optional-platforms 빌드: `-p optional-platforms`로 부르는 `ci`·`integrationCheck`· + 단계(main 빌드: `ci`·`mainCheck`·`integrationCheck`·`performanceCheck`· + `releaseCheck`, optional-platforms 빌드: `-p platforms/optional-build`로 부르는 `ci`·`integrationCheck`· `performanceCheck`·`releaseCheck`) 중 하나에 들어 있는지, 그리고 workflow의 접힌(`>`) run 블록이 빈 줄 때문에 옵션을 별개 명령으로 떼어 내지 않는지 검사한다. 두 빌드가 각자 검사를 돌린다. `-x`로 뺀 lane(Gradle처럼 축약 이름도 맞춰 본다)은 덮이지 않는다. Gradle이 작업을 돌리지 않는 명령(`--dry-run`· @@ -91,8 +98,11 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 `&&` 목록의 뒤쪽, `if`·`while`·`for`·`case`·함수 본문 안, 최상위 `exit`·`exec`·`set -n` 뒤, 조건부이거나 부른 함수 안의 `exit 0`(인자 없는 `exit`, 값을 모르는 `exit` 포함)·`exec`·`set -n` 뒤, 상태 함수(`always()`·`success()`·`!cancelled()`)가 아닌 `if:` 아래, 요청으로만 - 시작하는 workflow(`workflow_dispatch`·`repository_dispatch`·`issue_comment` 등), 세는 job이 부르지 않는 - `workflow_call` 재사용 workflow, 조건부이거나 `continue-on-error`인 job을 `needs`로 기다리는 job. + 시작하는 workflow(`workflow_dispatch`·`repository_dispatch`·`issue_comment` 등), `paths`·`paths-ignore` + 필터가 붙은 change trigger로만 시작하는 workflow(그 경로 밖 변경에는 돌지 않는다), 태그 push(`branches` + 없는 `tags`)나 `release`로만 시작하는 workflow(`releaseCheck` 밖의 단계), 세는 job이 + 부르지 않는 `workflow_call` 재사용 workflow, 조건부이거나 `continue-on-error`인 job을 `needs`로 기다리는 + job. (3) 실패하면 단계도 실패하지만 검사가 읽지 않는다: `|| exit 1`, `{ }`·`( )`·`$( )`·`bash -c` 안, 다른 명령의 인자인 `gradlew`, 따라갈 수 없는 `cd`(`cd "$VAR"`·`cd -`·`pushd`·조건부·서브셸 등) 뒤, `bash`·`sh`가 아닌 `shell:`, Windows일 수 있는 runner의 기본 셸(`pwsh`). 실패 메시지는 명령마다 이유를 @@ -105,6 +115,8 @@ root `CLAUDE.md`는 이 목록의 동기화된 요약이다. 두 문서가 어 변경한 경계와 런타임·보안·데이터 영향에 맞춰 설계·리뷰·검증 강도를 높인다. commit 정책은 모든 플랫폼에서 `human-only`이며 agent는 stage/commit/amend/push하지 않는다. +예외는 하나다: brief가 허용한 것만(commit과 push는 따로) 그 작업의 자기 브랜치에 한다. main 병합, +다른 브랜치 push, force push는 하지 않는다(`docs/work/README.md` 「커밋」). ## 강제 수준 @@ -136,7 +148,6 @@ commit 정책은 모든 플랫폼에서 `human-only`이며 agent는 stage/commit file server, HTTP client, identifier 능력을 port 뒤에서 구현한다. adapter 간 허용 edge는 registry만 따른다. - `shared-contract`: skeleton-wide 운영 계약. business/domain 개념 저장 금지. -- `sample-portfolio`: 샘플/fixture consumer. production leaf가 의존하면 안 된다. - `app-bootstrap`: Spring Boot entrypoint와 composition root. 비즈니스 유스케이스 금지. ## 의존성 방향 @@ -147,7 +158,6 @@ family 수준 기본 방향: app-bootstrap -> adapter:inbound:* -> application-core -> domain-core app-bootstrap -> adapter:outbound:* -> application-core -> domain-core runtime modules -> shared-contract -sample-portfolio -> registered runtime leaves (fixture consumer only) ``` 개별 edge는 `src/config/architecture/modules.json`의 `allowed_dependencies`가 유일한 목록이다. @@ -159,8 +169,8 @@ Gradle 의존성 검증도 같은 registry를 읽는다. root 문서나 기억 1. 요구사항을 읽고 소유 계층을 판단한다. 2. 구조나 동작이 바뀌면 `superpowers:brainstorming`으로 설계를 먼저 확정한다. -3. 여러 단계의 작업이면 `docs/superpowers/specs/`에 설계 문서를 남긴다. -4. 구현 전 `docs/superpowers/plans/`에 실행 계획을 작성한다. +3. 여러 단계의 작업이면 `docs/design/`에 설계 문서를 남긴다. 맨 위에 머리 블록(상태·작성일·요약·현재 정본)을 단다. +4. 실행 계획이 필요하면 구현 전 `docs/history/plans/`에 둔다. 계획서도 머리 블록을 단다. 머리 블록 형식은 `docs/README.md`다. 5. 동작 변경은 테스트를 먼저 작성한다. 6. 새 비즈니스 개념은 `domain-core`에 먼저 둔다. 7. 유스케이스는 `application-core` command와 use case/service method로 표현한다. @@ -169,8 +179,7 @@ Gradle 의존성 검증도 같은 registry를 읽는다. root 문서나 기억 10. focused test를 먼저 돌리고, 가능한 경우 전체 Gradle test를 돌린다. 단계별 판단 지점(배치·저장 포트·트랜잭션·멱등성·오류·권한)은 `docs/manual/`, 뼈대는 -`scripts/new-feature.sh `이 계층 leaf에 만든다. `sample-portfolio`는 모든 계층을 한 leaf에 -두는 지울 수 있는 샘플이라 배치 예시가 아니다. 실제 기능은 계층 leaf별로 나눈다. +`scripts/new-feature.sh `이 계층 leaf에 만든다. 실제 기능은 계층 leaf별로 나눈다. ## 테스트 전략 @@ -187,7 +196,7 @@ Gradle 의존성 검증도 같은 registry를 읽는다. root 문서나 기억 1. 이름은 lowerCamelCase 행동 문장(`<상황/주체><결과>`)이다. 이름에 적은 성질은 반드시 단언한다. 2. `@DisplayName`은 메서드 이름으로 못 쓰는 내용(숫자, 기호, 이유)이 있을 때만 쓰고, 한국어로 - 쓴다(소유자 결정 5). 기존 영어 `@DisplayName`은 그 테스트를 고칠 때 한국어로 바꾼다. + 쓴다(2026-09-25 소유자 결정). 기존 영어 `@DisplayName`은 그 테스트를 고칠 때 한국어로 바꾼다. 3. 본문 문장이 3개 이상이면 `// given` `// when` `// then` 주석과 구역 사이 빈 줄을 둔다. 준비할 것이 없으면 `// given`은 생략한다. `// when`은 정확히 하나다. 두 번 필요하면 테스트를 나눈다. 예외 테스트는 `catchThrowable`로 when을 분리한다(기존 `assertThatThrownBy`는 손댈 때 @@ -220,10 +229,10 @@ cd src ./gradlew qualityCheck # SpotBugs + FindSecBugs (leaf check에는 없다) ./gradlew testQualityCheck # 같은 분석을 테스트 source set에(config/spotbugs/exclude-test.xml, main 단계·optional 빌드는 ci) ./gradlew ci # PR 게이트 = leaf check + architecture + quality -./gradlew mainCheck # main 단계 = env 계약·전체 기동(샘플 포함)·public path·전송/메시징 레인·leaf 문서 대조 레인·기능 생성 왕복(verifyFeatureScaffold)·테스트 코드 정적 분석(testQualityCheck) +./gradlew mainCheck # main 단계 = env 계약·전체 기동·public path·전송/메시징 레인·leaf 문서 대조 레인·기능 생성 왕복(verifyFeatureScaffold)·테스트 코드 정적 분석(testQualityCheck) ./gradlew integrationCheck # 실제 컨테이너 integration 레인 전체(main·nightly, Docker 필요) -./gradlew performanceCheck # 부하·종료·자원 한계 레인(main·nightly) -./gradlew verifyStrictLaneStages --dry-run # 이 빌드의 strict lane이 workflow가 실행하는 단계에 속하는지(optional 빌드는 -p optional-platforms로 따로) +./gradlew performanceCheck # 부하·종료·자원 한계 레인(main·nightly). 상한은 항상 단언, 끄면 실패 +./gradlew verifyStrictLaneStages --dry-run # 이 빌드의 strict lane이 workflow가 실행하는 단계에 속하는지(optional 빌드는 -p platforms/optional-build로 따로) ./gradlew verifyPublicPathSnapshot ./gradlew :app-bootstrap:verifyEnvKeys ``` @@ -237,7 +246,7 @@ leaf의 `check`는 그 leaf만 검사한다. 저장소 전체 질문은 이름 Redis, Kafka, JPA 같은 부가 기능은 "의존성을 붙이면 켜지고, 떼면 사라지는 모듈"로 제공한다. 각 서비스는 `app-bootstrap/build.gradle`에 필요한 모듈만 `runtimeOnly` 한 줄로 고른다. -설계 근거는 `docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md`. +설계 근거는 `docs/design/2026-09-25-capability-module-packaging-design.md`. 템플릿 기본 조립은 web에서 쓰는 부분뿐이다: `adapter:inbound:web`, 운영 관측(actuator·metrics· tracing·로그), `domain-core`·`application-core`·`shared-contract`, `adapter:outbound:support`· @@ -252,7 +261,7 @@ capability 모듈 완료 기준 (7개 모두 충족해야 "포장 완료"): 자체를 두지 않는다. 4. 설정 prefix는 하나만 쓴다. 바인딩은 `StrictSettingsBinder`, 값 검증은 설정 record의 compact constructor에서 한다. - 예외(리뷰 05-18): Redis는 `app.redis.*`(redis-runtime, setter+`validate()`)·`app.capabilities.*`· + 예외(2026-11-03 정함): Redis는 `app.redis.*`(redis-runtime, setter+`validate()`)·`app.capabilities.*`· `app.rate-limit.*` 세 트리를 유지한다. 키를 바꾸면 운영 env가 깨진다. 새 Redis 설정은 이 셋 중 하나에 넣고 네 번째 트리는 만들지 않는다. 이유는 `src/adapter/outbound/cache-redis/CLAUDE.md`. 5. 포트 소유 모듈 testFixtures의 포트 계약 테스트(추상 클래스)를 fake와 실제 어댑터가 모두 @@ -292,10 +301,10 @@ Docker/runtime 규칙: 1. `src/settings.gradle`의 `rootProject.name`을 새 프로젝트명으로 바꾼다. 2. Java package `dev.caskeleton`을 새 organization/project package로 바꾼다. - gRPC 플랫폼을 쓰면 proto 조직 이름 `caskeleton`(`src/grpc/grpc-contract/src/main/proto/caskeleton/`의 + gRPC 플랫폼을 쓰면 proto 조직 이름 `caskeleton`(`src/platforms/grpc/grpc-contract/src/main/proto/caskeleton/`의 디렉터리, 각 `.proto`의 `package`·`java_package`)도 함께 바꾸고 `buf lint`로 확인한다. 3. `CaSkeletonApplication` 이름을 새 애플리케이션 이름으로 바꾼다. -4. production 모듈에는 목표 도메인의 entity, repository port, use case, adapter만 추가하고, 예시 코드는 `sample-portfolio`에 격리한다. +4. production 모듈에는 목표 도메인의 entity, repository port, use case, adapter만 추가한다. 5. 모듈 이름과 경계는 유지한다. 6. Docker image/application 이름을 새 프로젝트 기준으로 수정한다. 7. `.env`, `.env.local`, `application.yml`의 예시 값을 새 런타임 요구사항에 맞춘다. diff --git a/CLAUDE.md b/CLAUDE.md index 4921a632..6458871f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,136 +1,45 @@ -# CLAUDE.md +# CLAUDE.md — 이 repo의 지도 -Repository guidance for the Java 21 + Spring Boot 4.0.8 Clean Architecture template. +이 파일은 세션이 처음 읽는 지도다. 규칙을 담지 않고, 어떤 일이면 무엇을 읽을지 가리킨다. -## Prime Directive +## 1. 이 repo -Preserve architecture before optimizing for speed. The following seven HARD-STOP conditions are a -synchronized summary of the canonical local policy in `AGENTS.md`: +- Java 21 + Spring Boot Gradle 멀티모듈(버전은 `src/gradle/libs.versions.toml`) Clean Architecture 백엔드 템플릿이다. 서비스는 이 repo를 받아 도메인을 채운다. +- Gradle 루트는 `src/`다. Gradle 명령은 `src/`에서 실행한다. +- 규칙의 정본은 `AGENTS.md`다. leaf 목록·경로·허용 의존의 정본은 `src/config/architecture/modules.json`(registry)이다. 각 leaf의 지역 규칙은 가장 가까운 `src/**/CLAUDE.md`가 정한다. -1. `domain-core` gains framework, transport, database, or cloud dependencies. -2. A controller directly uses a repository, Spring Data interface, or persistence entity. -3. An inbound DTO leaks into `application-core` or `domain-core`. -4. Business rules move into mappers, filters, configuration, settings, or controllers. -5. Project dependencies violate `src/config/architecture/modules.json` or the Gradle dependency - gate. -6. Completion is claimed without the relevant verification or a named reason it could not run. -7. A repository/corpus conclusion is made without evidence proportional to its scope and risk. +## 2. HARD-STOP — 하나라도 어기면 완료가 아니다 -If this summary drifts from `AGENTS.md`, `AGENTS.md` wins and this summary must be resynchronized. +정본은 `AGENTS.md` 「Prime Directive」다. 두 문서가 다르면 `AGENTS.md`가 맞다. -## Gradle policy authorities +1. `domain-core`가 framework·transport·database·cloud 의존성을 가진다. +2. controller가 repository·Spring Data interface·persistence entity를 직접 쓴다. +3. inbound DTO가 `application-core`나 `domain-core`로 들어간다. +4. 업무 규칙이 mapper·filter·configuration·settings·controller로 옮겨 간다. +5. 프로젝트 의존성이 registry나 Gradle 의존성 검증을 어긴다. +6. 관련 검증 없이, 또는 돌리지 못한 이유를 밝히지 않고 완료를 말한다. +7. 결론의 범위와 위험에 맞는 증거 없이 저장소 전체에 대한 결론을 낸다. -- `src/config/architecture/modules.json`: every registered leaf identity, repository-relative source - paths, Gradle paths and allowed production project dependency edges. There is no runtime - membership list: what a composition root may take is its `allowed_dependencies`, and the direction - gate refuses any other edge. The registry owns the leaf list and its size; no document restates - the count, because a number written in prose drifts the moment a leaf is added. -- `src/settings.gradle`: fail-closed registry validation, project inclusion, and directory mapping. -- `src/build-logic/`: the architecture core (registry, direction and purity tasks), the conventions, - and one test-lane mechanism (`strictTestLanes`). Feature-specific checks are the owning leaf's - tests; a test that reads repository files declares them as that leaf's test `inputs`, and a test - that compares a leaf with repository documents is a `mainStage()` lane (tag `document-contract`) - in that leaf's `mainCheck`; a merge-blocking contract over non-document repository files is a - pull-request lane whose inputs are exactly those files (app-bootstrap `repository-contract`). - `TEST`/`ARCHITECTURE` lanes are cacheable; `INTEGRATION`/`SYSTEM`/`PERFORMANCE` and main-stage - lanes rerun every time. -- `verifyEnvKeys` stays an app-bootstrap task (owner decision 4); its implementation is build-logic's - `ca.config-contract`. The `src/build-tools/` included build was emptied and removed. -- `src/build.gradle`: the root lifecycle (`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, - `releaseCheck` and the named repository-wide gates). `verifyStrictLaneStages --dry-run` (pull - request; the main build and, as `-p optional-platforms`, the optional build each run their own) - fails when a non-`explicitOnly` strict lane is in no stage a workflow executes — a lane the - command removes with `-x` (abbreviations matched as Gradle does) is not covered; a command after - which Gradle runs no task (`--dry-run`, `-v`, `--help`, `--status`, `--stop`, …, bundles such as - `-qm` included), a short-option bundle Gradle rejects (`-mx`) and a command for another build do - not count, nor does one that does not gate for one of three reasons: (1) its failure may not fail - its step (an `||` other than `|| exit `, a pipe without pipefail, an `if` condition, - after `set +e` or an `exit 0` trap, `continue-on-error`, …); (2) it may not run (inside - `if`/`for`/`case` or a function, after a top-level or conditional `exit 0`, `exec` or `set -n`, - under a non-status `if:`, in a workflow only a request starts or a `workflow_call` one no counted - job calls, in a job that `needs` a conditional job, …); (3) the check does not read it although - its failure would fail the step (`|| exit 1`, inside `{ }`, `( )`, `$( )` or `bash -c`, after a - `cd` it cannot follow, a `shell:` other than bash or sh, a runner that may be Windows with its - `pwsh` default, …) — the failure names each command's reason and says to put the stage command - on a line of its own; the build a command runs is its `working-directory`, then the - `cd ` the same shell surely ran before it, joined with `-p` — or a folded workflow - `run:` block splits an option off its command. +## 3. 맡은 일 → 읽을 문서 -Commit policy is `human-only`: agents do not stage, commit, amend, or push implementation changes. +먼저 [docs/work/README.md](docs/work/README.md)를 읽는다. 크기 정하기, 모든 작업의 공통 단계, 커밋 규칙이 거기 있다. 그다음 맡은 일의 playbook 하나를 끝까지 읽는다. -## Proportional workflow +| 맡은 일 | playbook | +| --- | --- | +| 새 업무 기능, 새 capability 모듈 | [docs/work/new-feature.md](docs/work/new-feature.md) → `docs/manual/` | +| 리뷰, 결함 수정, 리팩터링, 성능, 구조·테스트 구조 개선 | [docs/work/improve.md](docs/work/improve.md) | +| 바꾸기 전에 대안 비교와 소유자 결정 | [docs/work/research-design.md](docs/work/research-design.md) | +| 매뉴얼·안내 문서 쓰기 | [docs/work/docs-writing.md](docs/work/docs-writing.md) | +| 게이트 실행, desktop 검증, 릴리스, 파생 서비스 | [docs/work/operate.md](docs/work/operate.md) | +| 큰 일을 나눠 다른 세션에 맡기기 | [docs/work/delegate.md](docs/work/delegate.md) | -- Low risk: work in the owning leaf, follow its nearest guidance, and run the focused check. -- Medium risk: use the relevant Superpowers design, planning, TDD, debugging, and review workflows - in proportion to the affected boundaries. -- High risk: make architecture and behavior decisions explicit, use staged architecture/spec/quality - review, and run architecture-wide verification authorized by the task. +brief(작업 지시문)가 있으면 brief의 범위·크기·완료 기준이 먼저다. playbook은 brief에 없는 공통 절차를 채운다. -Risk comes from change surface and runtime, security, data, or public-contract impact, not file -count. +## 4. 검증 명령과 실행 위치 -## Module families - -`src/config/architecture/modules.json` owns the complete leaf list. Root guidance summarizes -families; the nearest `src/**/CLAUDE.md` owns local rules. No task enforces this any more: -`verifyDocumentedLeafCount` was deleted along with the other documentation-drift parsers. A stated -count that disagrees with the registry is a defect, not a build failure — so do not state one. - -| Family | Responsibility | Stable dependency direction | -| --- | --- | --- | -| `domain-core` | Pure domain model, invariants, events, ports | Java stdlib and registered value-only contracts | -| `application-core` | Commands, use cases, application policies, transaction ports | `domain-core`, `shared-contract` | -| `adapter:inbound:*` | HTTP, gRPC, GraphQL, WebSocket transport boundaries | application/domain/shared contracts | -| `adapter:outbound:persistence-*` | JPA/PostgreSQL and MongoDB persistence adapters | application/domain/shared contracts as registered | -| `adapter:outbound:*` | support, messaging, cache, notification, storage, file, HTTP client, identifier capabilities | application/domain/shared and registered support edge | -| `shared-contract` | Skeleton-wide operational contracts | Java stdlib only | -| `messaging:*` | Vendored messaging platform: a product with its own API, SPI, adapters and composition boundary, not a layer of this application | `messaging:*` only — it depends on no `domain-core`, `application-core`, or `shared-contract` type | -| `sample-portfolio` | Fixture/reference consumer | registered runtime leaves; never a production dependency | -| `app-bootstrap` | Spring Boot entrypoint and composition root | registered runtime leaves | - -The `messaging:*` family is the one entry that is not a Clean Architecture layer, and it is listed so -that the exception is stated rather than inferred from a directory. It is a vendored library — its -own `*-api` leaves are its ports, its broker leaves are its adapters, its starter is its composition -root — and the messaging module review (`docs/reviews/2026-08-14-messaging-module-code-review.md` -MSG-023 §6.2) chose that layout deliberately over folding it into `adapter:outbound:*`. This -application reaches it through the application-owned anti-corruption bridge in -`adapter:outbound:messaging` (MSG-015). The canonical bridge is the only path: the legacy outbox -append port and the legacy Kafka publishing seam were deleted (owner decision 7). - -Never infer an individual leaf's Gradle path, allowed dependency, or test command from this table. -Read its `gradle_path` and `allowed_dependencies` from `src/config/architecture/modules.json`; runtime -composition is established by actual Gradle dependencies/auto-configuration, not a registry -`runtime_memberships` field that does not exist. - -## Layer workflow - -For a full use case, work in this order: - -```text -domain-core - -> application-core - -> adapter:outbound:* (or persistence/identifier) - -> adapter:inbound:* - -> app-bootstrap wiring -``` - -Layer-only work stays inside that registered leaf plus its tests. If a required fix crosses a layer -or writable scope, stop and request context rather than expanding silently. - -## Testing - -- `domain-core`: pure JUnit unit tests. -- `application-core`: use-case tests with hand-rolled fakes; no web or persistence context. -- inbound adapters: focused transport slice/contract tests. -- persistence adapters: mapping/port contract tests; use a real datastore only when vendor semantics - require it. -- other outbound adapters: port contract tests with fake external systems; no real network. -- identifier: pure deterministic unit tests. -- bootstrap/settings: binding, validation, wiring, and architecture tests. - -From `src/`, read the owning leaf's `gradle_path` from -`config/architecture/modules.json` and run `./gradlew :test --console=plain`. -Architecture-wide commands: +- **실행 위치**: 소유자 환경에서는 Gradle·Docker·테스트·게이트를 desktop에서만 돌린다. 절차는 [docs/work/operate.md](docs/work/operate.md) 4.1절이다. +- **leaf 하나**: registry에서 그 leaf의 `gradle_path`를 읽고 `./gradlew :test --console=plain` 또는 `:check`를 돌린다. 기억이나 디렉터리 이름으로 Gradle path를 짐작하지 않는다. +- **저장소 전체 질문**: ```bash ./gradlew architectureCheck --console=plain @@ -139,45 +48,28 @@ Architecture-wide commands: ./gradlew :app-bootstrap:verifyEnvKeys --console=plain ``` -A leaf's `check` covers that leaf only — compile, its tests, Spotless, Checkstyle, Error Prone. -Repository-wide questions have their own names: `architectureCheck` (dependency direction, purity -of domain-core/shared-contract/application-*, Git-carryable sources, ArchUnit), `qualityCheck` -(SpotBugs, FindSecBugs over production code), `testQualityCheck` (the same over every test source -set, against `config/spotbugs/exclude-test.xml`), `configContractCheck` (the environment contract), `integrationCheck` (the -declared strict integration lanes; a lane that needs an input the build was not given is left out -and named), `performanceCheck` (the declared performance lanes; main and nightly). `ci` (pull -request) is leaf checks (API surfaces included, owner decision 20) + architectureCheck + -qualityCheck, and the workflow also runs `verifyStrictLaneStages --dry-run`; `mainCheck` (main branch) is configContractCheck + -qualificationCheck (which includes testQualityCheck) + the sample web contract + the sample full boot (`:sample-portfolio:systemTest`) -+ the public-path snapshot + the transport and messaging qualification lanes + the feature -generator round trip (`verifyFeatureScaffold`) + every leaf's `mainCheck` (document-contract lanes -and any lane the leaf adds). `releaseCheck` is the tag-only checks: release provenance and the -public-path snapshot. +- 공개 경로 검사와 env 키 검사는 그 표면이 바뀌었을 때 돌린다. 전체 `test`·`check`·`ci`는 brief가 시킬 때 돌린다. +- 게이트 목록(`ci`, `mainCheck`, `integrationCheck`, `performanceCheck`, `releaseCheck` 등)과 바꾼 것에 맞는 게이트는 [docs/work/reference/gates.md](docs/work/reference/gates.md)다. +- `docs/work/`, 이 파일, `AGENTS.md`, `src/**/CLAUDE.md`를 고쳤으면 `python3 scripts/check-work-docs.py`를 돌린다(분량, 본문 이력 ID 0, 상대 링크). +- 문서(`.md`)나 문서가 가리키는 경로·Gradle 프로젝트를 바꿨으면 `python3 scripts/check-docs.py`를 돌린다(언어, 기록의 머리 블록, 참조, 복사한 숫자). PR마다 `docs-check` workflow가 같은 검사를 돈다. 규칙은 [docs/README.md](docs/README.md)다. -Test-writing rules (behavior-sentence names that assert what they promise, `@DisplayName` in Korean -only when the name cannot say it (owner decision 5), given/when/then comments, one `// when`, one -fake per port in the port owner's testFixtures, fake and adapter sharing one abstract contract test) -are canonical in `AGENTS.md`. +## 5. 코드만 보고는 헷갈리는 곳 -Use public-path and env-key checks only when their surfaces changed. Full `test`, `check` or `ci` -requires the controller's workflow authorization. +- **최상위 폴더는 정해진 것만 둔다.** 저장소 루트는 `compose.yaml`(개발 환경)·`compose/`(그 보조 파일)·`docs/`·`scripts/`·`src/`(Gradle 루트)다. `src/` 아래는 계층 leaf 폴더, `composition/`(조립), `platforms/`(들여온 제품: `messaging`·`grpc`·`grpc-advanced`와 optional 빌드 `optional-build`), Gradle 루트 표준(`build-logic`·`gradle`·`config`)이다. 테스트 환경 파일은 그 lane을 가진 leaf 안에 둔다. `scripts/check-repo-layout.py`(PR 게이트)가 허용 목록 밖의 최상위 항목을 막는다. +- **leaf 목록은 registry 하나다.** 문서는 leaf 개수를 적지 않는다(적힌 수는 leaf가 늘면 틀린다). runtime membership 목록은 없다. 조립 루트가 받을 수 있는 모듈은 registry의 `allowed_dependencies`가 정하고, 방향 게이트가 그 밖의 edge를 막는다. +- **`src/platforms/messaging/*`는 Clean Architecture 계층이 아니다.** 자기 API·SPI·adapter·조립 경계를 가진, 들여온(vendored) 메시징 제품이다. `domain-core`·`application-core`·`shared-contract`에 의존하지 않는다. 이 애플리케이션은 `adapter:outbound:messaging`의 bridge로만 닿는다. 이유와 지역 규칙은 `src/platforms/messaging/CLAUDE.md`다. +- **`composition:*` leaf는 조립만 한다.** outbox relay, 멱등성 executor, durable operation처럼 bootstrap에서 떼어 낸 조립이다. 각각 `runtimeOnly` 한 줄로 고른다. +- **capability는 한 줄로 켜고 끈다.** 기본 조립은 web inbound, 운영 관측, core들, support·identifier뿐이다. JPA도 `src/app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄로 켠다. 규칙은 `AGENTS.md` 「부가 기능(capability) 모듈 규칙」이다. +- **gRPC 플랫폼 라이브러리는 다른 빌드다.** `src/platforms/grpc/*`·`src/platforms/grpc-advanced/*`(registry의 `"build": "optional-grpc"`)는 `-p platforms/optional-build`로 돈다. `adapter:inbound:grpc`는 애플리케이션 adapter라 주 빌드에 있다. +- **새 기능의 예시는 `scripts/new-feature.sh`의 출력이다.** 샘플 모듈은 2026-11-07에 지웠다. 기법 예시는 `docs/manual/`이 실제 코드(fileserver, durable operation)를 가리킨다. +- **성능 lane에는 단언을 끄는 스위치가 없다.** convention이 상한을 매번 단언하고, `performance.assertions.enabled`에 `true` 아닌 값이 들어오거나 skip이 있으면 테스트 전에 실패한다. 손으로 돌리든 workflow든 같다(`AGENTS.md` 「Gradle 정책 권위」). +- **저장소 파일을 읽는 테스트는 태그가 있다.** 문서와 대조하는 테스트는 `document-contract`(main 단계 `mainCheck`), 빌드 스크립트·workflow를 읽는 테스트는 `repository-contract`(PR)다. 문서를 고치면 그 문서를 읽는 테스트를 찾는다. +- **커밋 정책은 `human-only`다.** brief가 허용한 것만 자기 브랜치에 한다. 커밋과 push는 따로 허용된다. 자세한 것은 [docs/work/README.md](docs/work/README.md) 4절이다. +- **문서 위치 규칙은 [docs/README.md](docs/README.md)다.** 설계서는 `docs/design/`, 결정 기록은 `docs/adr/`, 리뷰는 `docs/reviews/`, 고치지 않는 기록(계획서·납품 패키지·증거·학습)은 `docs/history/`, 파생 서비스용 변경 안내는 `docs/upgrade/`다. 기록은 맨 위 머리 블록만 고친다. -## Capability modules +## 6. 소유자 환경 -Optional features (JPA, Redis, Kafka, notification, Mongo, object storage, HTTP client, GraphQL, -WebSocket, gRPC, file server) are modules that turn on when present and disappear when removed. A -service selects them with one `runtimeOnly` line each in `app-bootstrap/build.gradle`; the template's -default composition is the web inbound adapter, observability, the cores, and support/identifier. The -seven completion criteria for a capability module are canonical in `AGENTS.md`. - -## Advisory and reporting - -Use dependency-DAG/topological reasoning and 3–5 materially distinct alternatives when that many -exist; use fewer when the option set is smaller. Judgment findings include falsifiable assumptions -and counterarguments. Deterministic compile, dependency, secret, or failed-test findings use -Rule → Evidence → Fix without manufactured debate. - -Citation verification is profile-based: none for `review-lite`, blocking citations for -`review-standard`, and all material citations for `audit-deep`/`regulated`. Durable reports are -triggered by high risk, at least 3 blocking findings, an architecture decision, explicit user request, -or the regulated profile. Otherwise a concise result is allowed. +- 이 repo 소유자의 기계·세션 도구에 묶인 규칙은 두 곳에만 있다: [docs/work/operate.md](docs/work/operate.md) 4.1절(실행 위치)과 [docs/work/delegate.md](docs/work/delegate.md) 4.3절(세션). 공용 정본은 design-docs `conventions/delegation-loop.md` 11절이다. +- Agent 도구(세션 안의 하위 에이전트)는 이 repo의 `.claude/settings.json`이 막는다. 일을 나눌 때는 delegate.md대로 별도 세션에 맡긴다. +- 작업 사고 순서의 정본은 design-docs `conventions/work-thinking-order.md`, 커밋·PR 형식은 `conventions/commit-and-pr.md`다. +- 보고 말투와 형식은 소유자의 전역 `~/.claude/CLAUDE.md`를 따른다. diff --git a/README.md b/README.md index d114e00a..7e375860 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ # ca-skeleton — Clean Architecture Spring Boot 템플릿 -ca-skeleton은 Java 21과 버전 카탈로그에 고정된 Spring Boot 4.x, Gradle 멀티모듈 기반의 Clean Architecture 백엔드 템플릿입니다. fork해서 도메인·패키지·엔티티·유스케이스만 교체하면 새 서비스를 시작할 수 있고, 모듈 경계와 의존 방향은 그대로 유지합니다. 기본 패키지는 `dev.caskeleton`이며, 예시 도메인은 production 모듈이 아니라 `sample-portfolio` 모듈(WorkLog 작업 기록 게시판)에 격리합니다. +ca-skeleton은 Java 21과 버전 카탈로그에 고정된 Spring Boot 4.x, Gradle 멀티모듈 기반의 Clean Architecture 백엔드 템플릿입니다. fork해서 도메인·패키지·엔티티·유스케이스만 교체하면 새 서비스를 시작할 수 있고, 모듈 경계와 의존 방향은 그대로 유지합니다. 기본 패키지는 `dev.caskeleton`입니다. 업무 기능의 예시는 생성 명령 `scripts/new-feature.sh`의 출력과 [docs/manual/](docs/manual/README.md)입니다. 이 문서는 전체 구조와 첫 실행만 다룹니다. 모듈별 상세 규칙과 설계 근거는 각 모듈의 README와 `CLAUDE.md`가, 빌드·환경 변수 상세는 [src/README.md](src/README.md)가 소유합니다. @@ -12,7 +12,6 @@ ca-skeleton은 Java 21과 버전 카탈로그에 고정된 Spring Boot 4.x, Grad app-bootstrap -> adapter:inbound:* -> application-core -> domain-core app-bootstrap -> adapter:outbound:* -> application-core -> domain-core 모든 런타임 모듈 -> shared-contract -sample-portfolio -> 등록된 런타임 리프 (fixture 소비자 전용) ``` family 수준의 책임은 다음과 같습니다. @@ -26,7 +25,6 @@ family 수준의 책임은 다음과 같습니다. | `adapter:outbound:*` | support(공유 베이스)·messaging·cache·notification·object storage·file·HTTP client·identifier 능력을 port 뒤에서 구현. 기본 조립에는 support·identifier만 들어 있고, 나머지는 `app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄로 고릅니다 | | `shared-contract` | skeleton 전역 운영 계약. business/domain 개념 저장 금지 | | `app-bootstrap` | Spring Boot entrypoint와 composition root | -| `sample-portfolio` | WorkLog 예시 도메인(fixture/reference). production이 의존하지 않음 | 등록된 leaf 목록과 각 leaf의 Gradle path·소스 경로·허용 production 의존 edge는 [src/config/architecture/modules.json](src/config/architecture/modules.json)이 SSOT입니다. focused @@ -38,10 +36,10 @@ test는 해당 Gradle path에서 `./gradlew :test --console=plain` 전제조건은 Temurin 21(루트 [.tool-versions](.tool-versions)에 고정)과 Docker Engine 또는 Docker Desktop입니다. Gradle은 저장소 wrapper를 씁니다. 첫 실행 진입점은 하나입니다. ```bash -scripts/bootstrap-local.sh # 다른 Compose overlay는 scripts/bootstrap-local.sh +scripts/bootstrap-local.sh ``` -`scripts/bootstrap-local.sh`는 compile 검사, PostgreSQL Compose 기동, 애플리케이션 이미지 build·기동, `GET /api/healthcheck` HTTP smoke를 순서대로 실행합니다. 각 단계가 `bootstrap N/4` 줄을 찍고 실패하면 그 단계에서 멈추므로 실패 단계가 드러납니다. 기동을 확인하려면 health endpoint를 호출합니다. +`scripts/bootstrap-local.sh`는 compile 검사, PostgreSQL Compose 기동, 애플리케이션 이미지 build·기동, `GET /api/healthcheck` HTTP smoke를 순서대로 실행합니다. 쓰는 compose 파일은 저장소 루트의 `compose.yaml` 하나입니다. 각 단계가 `bootstrap N/4` 줄을 찍고 실패하면 그 단계에서 멈추므로 실패 단계가 드러납니다. 기동을 확인하려면 health endpoint를 호출합니다. ```bash curl -fsS http://localhost:8080/api/healthcheck @@ -50,9 +48,13 @@ curl -fsS http://localhost:8080/api/healthcheck 로컬 스택을 내릴 때는 저장소 루트에서 실행합니다. ```bash -docker compose -f docker-compose.yml -f docker-compose.local.yml down +docker compose --profile '*' down ``` +`--profile '*'`가 없으면 profile이 달린 `db`가 남습니다. compose는 켜진 profile의 서비스만 내립니다. + +Redis·Kafka·MongoDB 같은 뒷단 서비스는 `compose.yaml`의 profile로 고릅니다(`docker compose --profile redis up -d --wait`). profile 목록은 그 파일 머리에 있습니다. + `src/.env.example`은 배포 환경 변수의 추적 가능한 복사/검증 계약이고 `src/.env`는 로컬 실행 입력입니다. 전체 환경 변수 목록과 조정 시점은 [src/README.md](src/README.md)와 [docs/registries/env-keys.yaml](docs/registries/env-keys.yaml)에 있습니다. ### 기본 조립과 부가 기능 @@ -91,10 +93,10 @@ H2 실행은 wiring과 애플리케이션 동작만 검증하고, migration과 v 애플리케이션 이름 등 나머지 rename 단계는 위 체크리스트를 따릅니다. -3. `CaSkeletonApplication`을 새 애플리케이션 이름으로 바꾸고, 목표 도메인의 엔티티·repository port·유스케이스·adapter를 production 모듈에 추가합니다. 예시 코드는 `sample-portfolio`에만 둡니다. +3. `CaSkeletonApplication`을 새 애플리케이션 이름으로 바꾸고, 목표 도메인의 엔티티·repository port·유스케이스·adapter를 production 모듈에 추가합니다. 새 업무 기능은 `scripts/new-feature.sh `으로 만듭니다. 4. 모듈 이름과 경계는 그대로 유지합니다. -검증은 먼저 composition root의 빠른 테스트와 sample-off 계약을 확인합니다. 루트에서 +검증은 먼저 composition root의 빠른 테스트와 아키텍처 검사를 확인합니다. 루트에서 `./gradlew test`를 호출하면 등록된 모든 하위 프로젝트의 `test`를 실행하므로 일상적인 로컬 피드백 명령으로 사용하지 않습니다. 저장소 전체 qualification은 CI 또는 명시적인 `ci` task가 담당합니다. @@ -102,18 +104,16 @@ H2 실행은 wiring과 애플리케이션 동작만 검증하고, migration과 v ```bash cd src ./gradlew :app-bootstrap:test -./gradlew :sample-portfolio:check ./gradlew architectureCheck ``` 병합 전 저장소 전체 검증이 필요하면 `./gradlew ci`를 실행합니다. -`sample-portfolio`는 템플릿이 유지하는 fixture/reference 모듈이라 production 모듈이 의존하지 않고, runtime에 sample bean이나 endpoint를 넣지 않습니다. 다운스트림 fork에서 fixture가 더 필요 없을 때만 sample-off 테스트를 통과시킨 뒤 정리합니다. - ## 아키텍처 규칙과 검증 -애플리케이션이 동작하더라도 아래를 어기면 병합하지 않습니다. 8개 HARD-STOP 조건의 정본 로컬 -정책 권위는 [AGENTS.md](AGENTS.md)이며, [CLAUDE.md](CLAUDE.md)는 동기화된 요약입니다. +애플리케이션이 동작하더라도 아래를 어기면 병합하지 않습니다. HARD-STOP 7개 조건의 정본 로컬 +정책 권위는 [AGENTS.md](AGENTS.md)이며, [CLAUDE.md](CLAUDE.md)는 작업을 시작할 때 읽는 지도입니다. +일의 종류별 절차는 [docs/work/](docs/work/README.md)에 있습니다. - `domain-core`는 Spring·JPA·Servlet·HTTP·DB·cloud SDK 타입을 import하지 않습니다. - controller는 repository를 직접 호출하거나 persistence entity를 반환하지 않습니다. @@ -134,8 +134,7 @@ cd src ## 수동 전용 Gradle 태스크 -아래 세 태스크는 **어떤 워크플로도 실행하지 않으며, 그게 의도다.** 자동 실행이 틀린 이유를 각각 -적어 둔다. +아래 태스크는 **어떤 워크플로도 실행하지 않으며, 그게 의도다.** 자동 실행이 틀린 이유를 적어 둔다. 여기 적힌 태스크 이름이 실재하는지 검사하던 `verifyReadmeCommands`는 삭제했다. 그건 이 문서의 ```bash 블록을 직접 파싱해 `./gradlew`·`docker compose`·`make` 토큰을 실제 태스크 그래프와 대조하는 @@ -145,16 +144,11 @@ Markdown 명령 파서였고, 그 결과 "README에 무엇을 쓸 수 있는가" ```bash cd src ./gradlew :grpc:grpc-testkit:grpcPerformanceTest -./gradlew :sample-portfolio:openapiCheckSnapshot -PapproveOpenApiChange ``` - `grpcPerformanceTest` — latency percentile·saturation·drain budget을 **측정**한다. 공유 CI runner의 측정값은 흔들리고, 흔들리는 게이트는 결국 꺼진다. leaf `build.gradle`이 이 태스크의 태그를 `test`에서 제외하는 이유도 같다. 성능 회귀가 의심될 때 사람이 이름으로 부른다. -- `openapiCheckSnapshot` — 드리프트 검사 자체는 이미 자동으로 돈다. 이 태스크가 감싸는 - `OpenApiDriftContractTest`는 `:sample-portfolio:test`의 일부이고, 그건 `check` 안이며 stage 1에서 - 실행된다. 이 태스크의 고유한 역할은 `-PapproveOpenApiChange`로 **커밋된 스냅샷을 다시 만드는 것** - — 의도된 API 변경을 사람이 승인하는 지점이다. 자동으로 돌리면 승인이 승인이 아니게 된다. ## 더 알아보기 diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..3c47648e --- /dev/null +++ b/compose.yaml @@ -0,0 +1,426 @@ +# ============================================================================= +# 개발 환경 — 이 repo의 compose 파일은 이것 하나다. +# +# docker compose up -d --wait app # 앱 컨테이너(기본 조립, local 런타임) +# docker compose up -d --wait db # 뒷단 서비스 하나만(이름을 대면 그 profile이 켜진다) +# docker compose --profile jpa --profile redis up -d --wait # 뒷단 서비스 묶음 +# docker compose --profile '*' down # 내린다. 데이터까지 지우려면 down -v +# +# 내릴 때 --profile '*'를 붙인다. 붙이지 않으면 compose는 켜진 profile의 서비스만 내리므로, 이름으로 +# 띄운 db 같은 profile 서비스가 남는다. +# +# 뒷단 서비스는 capability 이름의 profile로 고른다. profile을 대지 않으면 app만 뜬다. +# +# profile 서비스 쓰는 기능 +# jpa db (PostgreSQL 16) JPA +# redis redis (ACL 계정) Redis +# kafka kafka Kafka 발행 +# mongo mongo, mongo-rs-init MongoDB +# objectstorage minio, minio-init 객체 저장소 +# auth keycloak JWT 발급자 +# mail mailpit (STARTTLS 필수) SMTP 발송 +# +# 이 파일이 마운트하는 보조 파일은 compose/ 아래에 있다. compose lane(테스트)은 이 파일을 바탕으로 +# 쓰고, lane에만 필요한 overlay·smoke client·스키마 적용은 src/app-bootstrap/compose-lanes/에 있다. +# 경로는 모두 이 파일이 있는 저장소 루트 기준이다. +# +# auth profile은 keycloak client secret 파일이 있어야 뜬다. lane은 실행마다 만들고 지운다. 손으로 띄울 +# 때는 compose/keycloak/secrets/graphql-smoke-client-secret에 아무 값이나 한 줄 넣는다(그 폴더는 +# Git이 무시한다). mail profile도 같다: compose/mailpit/tls/에 server.crt·server.key가 있어야 한다. +# +# Graceful-shutdown sync table (feature-container-runtime-contract D5): +# App shutdown timeout : 30s (APP_SERVER_SHUTDOWN_TIMEOUT — SSOT: docs/registries/ +# env-keys.yaml, owner feature-env-driven-runtime-configuration) +# Async executor wait : 19s (AsyncExecutorConfig.AWAIT_TERMINATION_SECONDS) +# Container preStop : 5s (handled by the orchestrator / stop_grace_period offset) +# stop_grace_period : 60s (30s app drain + 19s async + 5s preStop + 6s safety margin) +# +# The drain and the async wait are consecutive, not concurrent: Spring finishes the lifecycle +# phase (the web server's graceful drain) before it destroys the executor, which then waits for +# its queue. A 40s grace let the container be killed 9s into that wait (07-07). +# DeveloperExperienceContractTest fails when this value is below the sum. +# +# Memory limit (D4): +# The container memory limit MUST be set for -XX:MaxRAMPercentage=75 to be meaningful. +# Default 512m suits a small service; adjust per deployment. A compose lane that boots every +# capability at once raises it for itself (compose-profile-contracts.json, appMemoryLimit). +# ============================================================================= + +# The local MinIO runtime, used by the server below and by the lane's object storage smoke client. +# +# It is the image the MinIO qualification lanes measured, by the same digest: +# src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json +# records it with the conditional-write findings, and ComposeMinioImageMatchesEvidenceTest in that +# leaf fails when this default (or the lane file's copy) and the evidence disagree. Change them +# together. +# +# Source: pgsty/minio, a community fork on Docker Hub, after Docker Hub's minio/minio and quay.io +# stopped serving MinIO images (review 05-09). cgr.dev/chainguard/minio measured the same but was +# not chosen; the evidence file's rejectedCandidates says why. LOCAL_MINIO_IMAGE points this runtime +# at a mirror; the lanes take OBJECT_STORAGE_MINIO_IMAGE, digest-checked. +x-local-minio-image: &local-minio-image "${LOCAL_MINIO_IMAGE:-pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372}" + +services: + app: + build: + context: src/ + dockerfile: Dockerfile + args: + RELEASE_VERSION: "${RELEASE_VERSION:-0.0.1}" + BUILD_VERSION: "${BUILD_VERSION:-0.0.1+0000000}" + GIT_SHA: "${GIT_SHA:-0000000}" + SOURCE_URL: "${SOURCE_URL:-https://example.invalid/ca-tmpl}" + # default = the composition a service ships. scripts/run-compose-runtime-smoke.sh sets + # qualification: every capability module present, each lane switching on what it tests. + COMPOSITION: "${COMPOSITION:-default}" + # The composition is in the tag, so a lane's qualification image is never reused as the + # default one (Compose reuses a matching tag instead of building). + image: caskeleton:${BUILD_VERSION:-0.0.1_local_0000000}-${COMPOSITION:-default} + # Optional, because src/.env is operator input and a fresh clone does not have one. Before this + # was marked optional, untracking that file made `docker compose config` fail outright on a + # clone. The tracked contract is src/.env.example; copy it. A compose lane does not depend on it: + # its values go into a generated `environment:` block, which outranks every env_file. + env_file: + - path: ./src/.env + required: false + ports: + - "${APP_SERVER_PORT:-8080}:8080" + # Management (health, info, prometheus — answered without authentication) on loopback only: + # published on every interface it reaches the whole LAN (07-13). The smoke lanes read it from + # inside the container, so they need no host port at all. + - "127.0.0.1:9001:9001" + environment: + # Explicit, not inherited. A Compose profile selects services; it says nothing about which + # environment the application believes it is in. The dev and prod-smoke lane overlays set + # their own. + SPRING_PROFILES_ACTIVE: "local" + TZ: "UTC" + LANG: "C.UTF-8" + LC_ALL: "C.UTF-8" + # Graceful shutdown — fallback matches the env-keys.yaml SSOT default (30s). + # Override via .env or docker compose --env-file if you need a different value. + APP_SERVER_SHUTDOWN_TIMEOUT: "${APP_SERVER_SHUTDOWN_TIMEOUT:-30s}" + APP_SERVER_SHUTDOWN: "graceful" + # The `db` service below, on the internal network. The default composition does not read + # these; a service that selects the relational capability does. + APP_DATASOURCE_URL: "jdbc:postgresql://db:5432/${POSTGRES_DB:-ca_skeleton}" + APP_DATASOURCE_USERNAME: "${APP_DATASOURCE_USERNAME:-ca_skeleton}" + APP_DATASOURCE_PASSWORD: "${APP_DATASOURCE_PASSWORD:-ca_skeleton}" + # ---- Read-only root filesystem (D2) ------------------------------------- + # The application must write only to the tmpfs mounts declared below. + # /tmp — Tomcat basedir (see -Dserver.tomcat.basedir=/tmp in Dockerfile). + # /var/tmp/heap — heap dump landing zone (see -XX:HeapDumpPath=/var/tmp/heap). + read_only: true + tmpfs: + - /tmp:mode=1777,size=128m + - /var/tmp/heap:mode=1777,size=512m + # No volume: the shipped composition keeps nothing on disk. A capability that does brings its + # mount in its own overlay, added with -f when the capability is selected, so this file never + # names one (07-08). + # ---- Memory limit (D4) -------------------------------------------------- + # Must be set so -XX:MaxRAMPercentage=75 can compute a meaningful heap bound. + mem_limit: 512m + memswap_limit: 512m + # ---- Graceful shutdown (D5) --------------------------------------------- + # stop_grace_period = app drain (30s, env-keys SSOT) + async wait (19s) + preStop (5s) + # + margin (6s) = 60s. + stop_grace_period: 60s + # ---- Health check ------------------------------------------------------- + # The actuator readiness probe on the management port (9001). It answers under every runtime + # (local, dev, prod), unlike the public health path, whose base path differs by runtime. + healthcheck: + test: + - "CMD" + - "wget" + - "--no-verbose" + - "--tries=1" + - "--spider" + - "http://localhost:9001/actuator/health/readiness" + interval: 5s + timeout: 3s + start_period: 60s + retries: 12 + restart: unless-stopped + networks: + - caskeleton-infra + + # ---- PostgreSQL -------------------------------------------------------------- + # Published on the loopback interface only, so a host-side run (`./gradlew :app-bootstrap:bootRun`, + # IDE) reaches the same database the containerised app reaches over the internal network. The + # port is the one src/.env.example's APP_DATASOURCE_URL names. + db: + profiles: + - jpa + image: postgres:16-alpine + environment: + POSTGRES_DB: "${POSTGRES_DB:-ca_skeleton}" + POSTGRES_USER: "${APP_DATASOURCE_USERNAME:-ca_skeleton}" + POSTGRES_PASSWORD: "${APP_DATASOURCE_PASSWORD:-ca_skeleton}" + TZ: "UTC" + volumes: + - type: volume + source: caskeleton-db-data + target: /var/lib/postgresql/data + ports: + - "127.0.0.1:5433:5432" + networks: + - caskeleton-infra + healthcheck: + test: + [ + "CMD-SHELL", + "pg_isready -U ${APP_DATASOURCE_USERNAME:-ca_skeleton} -d ${POSTGRES_DB:-ca_skeleton}", + ] + interval: 10s + timeout: 5s + retries: 5 + start_period: 30s + + # ---- MongoDB ----------------------------------------------------------------- + # A replica set of one. Single-node is still a replica set: transactions and change streams need + # one, and a standalone mongod that "works for reads" is a deployment that discovers the + # difference at the first transaction. + mongo: + profiles: + - mongo + image: mongo:8.0.16 + command: ["mongod", "--replSet", "rs0", "--bind_ip_all"] + volumes: + - type: volume + source: caskeleton-mongo-data + target: /data/db + networks: + - caskeleton-infra + healthcheck: + test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"] + interval: 10s + timeout: 5s + retries: 10 + start_period: 20s + + mongo-rs-init: + profiles: + - mongo + image: mongo:8.0.16 + depends_on: + mongo: + condition: service_healthy + # Idempotent: rs.initiate() on an already-initiated set returns an error this swallows, so the + # stack can be re-run against a surviving volume without a manual reset. + command: + - mongosh + - --host + - mongo + - --quiet + - --eval + - >- + try { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongo:27017'}]}) } + catch (e) { if (!/already initialized/i.test(e.message)) { throw e } } + networks: + - caskeleton-infra + restart: "no" + + # ---- Kafka ------------------------------------------------------------------- + kafka: + profiles: + - kafka + image: apache/kafka:3.8.0 + environment: + KAFKA_NODE_ID: "1" + KAFKA_PROCESS_ROLES: "broker,controller" + KAFKA_LISTENERS: "PLAINTEXT://:9092,CONTROLLER://:9093" + KAFKA_ADVERTISED_LISTENERS: "PLAINTEXT://kafka:9092" + KAFKA_CONTROLLER_QUORUM_VOTERS: "1@kafka:9093" + KAFKA_CONTROLLER_LISTENER_NAMES: "CONTROLLER" + KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: "CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT" + KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: "1" + KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: "1" + KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: "1" + networks: + - caskeleton-infra + healthcheck: + test: + ["CMD-SHELL", "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server kafka:9092"] + interval: 10s + timeout: 10s + retries: 12 + start_period: 30s + + # ---- Redis ------------------------------------------------------------------- + # Authenticated the way a deployment authenticates, with the lanes' test-fixture accounts: + # compose/redis/acl/lane-fixture-accounts.acl, the same file the Redis topology lanes use, mounted + # as it is rather than copied. It is not a deployment file — its passwords are public and it carries + # a lane-only `+@all` account (compose/redis/acl/README.md). Its first line turns the passwordless + # `default` user off, so the application connects as the named accounts the lane contract gives it + # (compose-profile-contracts.json, $redisComment). + # + # This Redis was open and the lanes declared app.redis.authentication.anonymous-access-accepted. + # The application then logged that trade, and the missing advanced account, as two startup + # warnings — correctly, because in production both are risks — and every Redis lane failed its + # "startup is silent" check. Quieting the warning would hide the same trade in production; the + # lane now authenticates the way a deployment does instead. + # + # The passwords are the file's fixture values (compose/redis/acl/README.md); this container is + # on the internal network only and publishes no port. + redis: + profiles: + - redis + image: redis:7.4 + command: + - redis-server + - --appendonly + - "no" + - --save + - "" + - --aclfile + - /etc/redis/acl/lane-fixture-accounts.acl + volumes: + - type: bind + source: ./compose/redis/acl + target: /etc/redis/acl + read_only: true + networks: + - caskeleton-infra + healthcheck: + test: + # As the application account: with `default` off, an unauthenticated PING answers NOAUTH. + - "CMD-SHELL" + - "[ \"$$(redis-cli --user ca-skeleton-application --pass fixture-application --no-auth-warning ping)\" = PONG ]" + interval: 5s + timeout: 3s + retries: 12 + start_period: 5s + + # ---- Mailpit — the reference SMTP relay ---------------------------------------- + mailpit: + profiles: + - mail + image: axllent/mailpit:v1.21 + environment: + MP_SMTP_AUTH_ACCEPT_ANY: "1" + # MP_SMTP_AUTH_ALLOW_INSECURE is deliberately absent, and Mailpit refuses to start with both: + # "TLS cannot be required with --smtp-auth-allow-insecure". It existed to permit credentials + # over a plaintext connection, which is exactly what requiring STARTTLS removes the need for — + # any AUTH now happens inside the TLS session. + # STARTTLS, required. Not a hardening extra: SmtpProviderProperties.TlsMode has two members and + # neither is plaintext, so the platform cannot describe an unencrypted relay at all. A stack + # that wanted a plaintext Mailpit would be asking for a transport the type refuses to express, + # and the honest way to satisfy it is to give the relay a certificate. + MP_SMTP_TLS_CERT: /run/mailpit-tls/server.crt + MP_SMTP_TLS_KEY: /run/mailpit-tls/server.key + MP_SMTP_REQUIRE_STARTTLS: "true" + volumes: + # Generated per run by the qualification wrapper for the host name `mailpit`, and removed on + # teardown, exactly like the PostgreSQL lane certificate. A committed test certificate is a + # private key in Git. + - type: bind + source: ./compose/mailpit/tls + target: /run/mailpit-tls + read_only: true + networks: + - caskeleton-infra + healthcheck: + test: ["CMD", "/mailpit", "readyz"] + interval: 5s + timeout: 3s + retries: 12 + start_period: 5s + + # ---- MinIO ------------------------------------------------------------------- + minio: + profiles: + - objectstorage + image: *local-minio-image + command: ["server", "/data"] + environment: + MINIO_ROOT_USER: "${MINIO_ROOT_USER:-caskeleton}" + MINIO_ROOT_PASSWORD: "${MINIO_ROOT_PASSWORD:-caskeleton-local}" + volumes: + - type: volume + source: caskeleton-minio-data + target: /data + networks: + - caskeleton-infra + healthcheck: + test: ["CMD", "mc", "ready", "local"] + interval: 10s + timeout: 5s + retries: 10 + start_period: 10s + + # Bucket and policy bootstrap. Not a substitute for the round trip: creating a bucket proves the + # server accepts an admin command, not that an object survives being written and read back. + minio-init: + profiles: + - objectstorage + # The client from the same supplier as the server. cgr.dev/chainguard/minio-client was not used: + # it has no shell, and the bootstrap below is a shell script. + image: "${LOCAL_MINIO_MC_IMAGE:-pgsty/mc@sha256:ce62c9053c69ce12a527a322345b5ad9f44b5f8a7b8189f82e516f2e3f30f1d8}" + depends_on: + minio: + condition: service_healthy + entrypoint: ["/bin/sh", "/opt/minio/bucket-bootstrap.sh"] + environment: + MINIO_ENDPOINT: "http://minio:9000" + MINIO_ROOT_USER: "${MINIO_ROOT_USER:-caskeleton}" + MINIO_ROOT_PASSWORD: "${MINIO_ROOT_PASSWORD:-caskeleton-local}" + MINIO_BUCKET: "${MINIO_BUCKET:-ca-skeleton-objects}" + volumes: + - type: bind + source: ./compose/minio/init + target: /opt/minio + read_only: true + networks: + - caskeleton-infra + restart: "no" + + # ---- Keycloak ---------------------------------------------------------------- + keycloak: + profiles: + - auth + image: quay.io/keycloak/keycloak:26.0 + # The wrapper reads the client secret from a mounted file and execs kc.sh. The realm artifact + # carries only a ${...} reference, so no secret value is in Git, in the rendered config, or on a + # command line. + entrypoint: ["/bin/bash", "/opt/keycloak-entrypoint/entrypoint.sh"] + environment: + KC_BOOTSTRAP_ADMIN_USERNAME: "${KEYCLOAK_ADMIN:-admin}" + KC_BOOTSTRAP_ADMIN_PASSWORD: "${KEYCLOAK_ADMIN_PASSWORD:-admin}" + KC_HEALTH_ENABLED: "true" + volumes: + - type: bind + source: ./compose/keycloak/entrypoint.sh + target: /opt/keycloak-entrypoint/entrypoint.sh + read_only: true + - type: bind + source: ./compose/keycloak/realms + target: /opt/keycloak/data/import + read_only: true + secrets: + - keycloak-graphql-smoke-client-secret + networks: + - caskeleton-infra + healthcheck: + test: + - "CMD-SHELL" + - "exec 3<>/dev/tcp/127.0.0.1/9000 && echo -e 'GET /health/ready HTTP/1.1\\r\\nHost: localhost\\r\\nConnection: close\\r\\n\\r\\n' >&3 && cat <&3 | grep -q '\"status\": \"UP\"'" + interval: 10s + timeout: 5s + retries: 20 + start_period: 30s + +networks: + caskeleton-infra: + driver: bridge + +volumes: + caskeleton-db-data: + driver: local + caskeleton-mongo-data: + driver: local + caskeleton-minio-data: + driver: local + +secrets: + keycloak-graphql-smoke-client-secret: + file: ./compose/keycloak/secrets/graphql-smoke-client-secret diff --git a/infra/keycloak/README.md b/compose/keycloak/README.md similarity index 98% rename from infra/keycloak/README.md rename to compose/keycloak/README.md index 07400b3a..57266885 100644 --- a/infra/keycloak/README.md +++ b/compose/keycloak/README.md @@ -1,6 +1,6 @@ # Keycloak realm artifact -`realms/ca-skeleton-realm.json` is imported by the `keycloak` service in `docker-compose.infra.yml` +`realms/ca-skeleton-realm.json` is imported by the `keycloak` service in the root `compose.yaml` and is the same realm every GraphQL qualification lane authenticates against. ## The client secret is a reference, never a value diff --git a/infra/keycloak/entrypoint.sh b/compose/keycloak/entrypoint.sh similarity index 100% rename from infra/keycloak/entrypoint.sh rename to compose/keycloak/entrypoint.sh diff --git a/infra/keycloak/realms/ca-skeleton-realm.json b/compose/keycloak/realms/ca-skeleton-realm.json similarity index 100% rename from infra/keycloak/realms/ca-skeleton-realm.json rename to compose/keycloak/realms/ca-skeleton-realm.json diff --git a/infra/keycloak/secrets/.gitignore b/compose/keycloak/secrets/.gitignore similarity index 100% rename from infra/keycloak/secrets/.gitignore rename to compose/keycloak/secrets/.gitignore diff --git a/infra/mailpit/tls/.gitignore b/compose/mailpit/tls/.gitignore similarity index 100% rename from infra/mailpit/tls/.gitignore rename to compose/mailpit/tls/.gitignore diff --git a/infra/minio/init/bucket-bootstrap.sh b/compose/minio/init/bucket-bootstrap.sh similarity index 100% rename from infra/minio/init/bucket-bootstrap.sh rename to compose/minio/init/bucket-bootstrap.sh diff --git a/infra/redis-sdk/acl/README.md b/compose/redis/acl/README.md similarity index 94% rename from infra/redis-sdk/acl/README.md rename to compose/redis/acl/README.md index cbbfd494..adfc2118 100644 --- a/infra/redis-sdk/acl/README.md +++ b/compose/redis/acl/README.md @@ -42,9 +42,10 @@ a fork that copied one of them got an open account and a green lane. ## Who loads `lane-fixture-accounts.acl` -The Redis topology lanes (`../standalone`, `../sentinel`, `../cluster`, `../tls`) and the +The Redis topology lanes (`src/adapter/outbound/redis-sdk/compose/{standalone,sentinel,cluster,tls}`), the application's Compose lanes that switch Redis on (`local-redis`, `all-adapters` in -`src/config/runtime/compose-profile-contracts.json`). Both mount this directory read-only; neither +`src/app-bootstrap/compose-lanes/compose-profile-contracts.json`), and the development stack's +`redis` service (root `compose.yaml`). They all mount this directory read-only; neither keeps a copy, because a second copy of these lines is a second place for a password or a key pattern to drift. diff --git a/infra/redis-sdk/acl/admin-readonly.acl b/compose/redis/acl/admin-readonly.acl similarity index 100% rename from infra/redis-sdk/acl/admin-readonly.acl rename to compose/redis/acl/admin-readonly.acl diff --git a/infra/redis-sdk/acl/application-advanced.acl b/compose/redis/acl/application-advanced.acl similarity index 100% rename from infra/redis-sdk/acl/application-advanced.acl rename to compose/redis/acl/application-advanced.acl diff --git a/infra/redis-sdk/acl/application.acl b/compose/redis/acl/application.acl similarity index 100% rename from infra/redis-sdk/acl/application.acl rename to compose/redis/acl/application.acl diff --git a/infra/redis-sdk/acl/lane-fixture-accounts.acl b/compose/redis/acl/lane-fixture-accounts.acl similarity index 100% rename from infra/redis-sdk/acl/lane-fixture-accounts.acl rename to compose/redis/acl/lane-fixture-accounts.acl diff --git a/infra/redis-sdk/acl/raw-gateway.acl b/compose/redis/acl/raw-gateway.acl similarity index 100% rename from infra/redis-sdk/acl/raw-gateway.acl rename to compose/redis/acl/raw-gateway.acl diff --git a/infra/redis-sdk/acl/sentinel-accounts.acl b/compose/redis/acl/sentinel-accounts.acl similarity index 100% rename from infra/redis-sdk/acl/sentinel-accounts.acl rename to compose/redis/acl/sentinel-accounts.acl diff --git a/docker-compose.infra.yml b/docker-compose.infra.yml deleted file mode 100644 index 4ae89ea3..00000000 --- a/docker-compose.infra.yml +++ /dev/null @@ -1,579 +0,0 @@ -# ============================================================================= -# Shared infrastructure, owned here and nowhere else. -# -# Environment overlays (local, dev, prod-smoke) describe how the application runs. This file -# describes what it runs against. Keeping the two apart is why `local` could stop meaning "the app -# plus a database" and start meaning "the app, with whichever services the lane asked for". -# -# Every service carries a Compose profile, so nothing here starts unless a lane names it. A profile -# selects services; it never implies a Spring profile. The lane definitions live in -# src/config/runtime/compose-profile-contracts.json, and scripts/verify-compose-profile-contracts.sh -# checks this file against them. -# ============================================================================= - -# The local MinIO runtime, used by the server and by the object-storage smoke client below. -# -# It is the image the MinIO qualification lanes measured, by the same digest: -# src/adapter/outbound/objectstorage/src/test/resources/object-storage/minio-provider-evidence.json -# records it with the conditional-write findings, and ComposeMinioImageMatchesEvidenceTest in that -# leaf fails when this default and the evidence disagree. Change both together. -# -# Source: pgsty/minio, a community fork on Docker Hub, after Docker Hub's minio/minio and quay.io -# stopped serving MinIO images (review 05-09). cgr.dev/chainguard/minio measured the same but was -# not chosen; the evidence file's rejectedCandidates says why. LOCAL_MINIO_IMAGE points this runtime -# at a mirror; the lanes take OBJECT_STORAGE_MINIO_IMAGE, digest-checked. -x-local-minio-image: &local-minio-image "${LOCAL_MINIO_IMAGE:-pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372}" - -services: - # ---- PostgreSQL -------------------------------------------------------------- - db: - profiles: - - local-jpa - - local-messaging-outbox - - local-fileserver - - local-notification-ingest - - local-notification-serving - - local-notification-handoff - - shared-infra - - prod-smoke - - all-adapters - image: postgres:16-alpine - environment: - POSTGRES_DB: "${POSTGRES_DB:-ca_skeleton}" - POSTGRES_USER: "${APP_DATASOURCE_USERNAME:-ca_skeleton}" - POSTGRES_PASSWORD: "${APP_DATASOURCE_PASSWORD:-ca_skeleton}" - TZ: "UTC" - volumes: - - type: volume - source: caskeleton-db-data - target: /var/lib/postgresql/data - ports: - - "127.0.0.1:5433:5432" - networks: - - caskeleton-infra - healthcheck: - test: - [ - "CMD-SHELL", - "pg_isready -U ${APP_DATASOURCE_USERNAME:-ca_skeleton} -d ${POSTGRES_DB:-ca_skeleton}", - ] - interval: 10s - timeout: 5s - retries: 5 - start_period: 30s - - # ---- MongoDB ----------------------------------------------------------------- - # A replica set of one. Single-node is still a replica set: transactions and change streams need - # one, and a standalone mongod that "works for reads" is a deployment that discovers the - # difference at the first transaction. - mongo: - profiles: - - local-mongo - - all-adapters - image: mongo:8.0.16 - command: ["mongod", "--replSet", "rs0", "--bind_ip_all"] - volumes: - - type: volume - source: caskeleton-mongo-data - target: /data/db - networks: - - caskeleton-infra - healthcheck: - test: ["CMD", "mongosh", "--quiet", "--eval", "db.adminCommand('ping').ok"] - interval: 10s - timeout: 5s - retries: 10 - start_period: 20s - - mongo-rs-init: - profiles: - - local-mongo - - all-adapters - image: mongo:8.0.16 - depends_on: - mongo: - condition: service_healthy - # Idempotent: rs.initiate() on an already-initiated set returns an error this swallows, so the - # lane can be re-run against a surviving volume without a manual reset. - command: - - mongosh - - --host - - mongo - - --quiet - - --eval - - >- - try { rs.initiate({_id:'rs0',members:[{_id:0,host:'mongo:27017'}]}) } - catch (e) { if (!/already initialized/i.test(e.message)) { throw e } } - networks: - - caskeleton-infra - restart: "no" - - # ---- Kafka ------------------------------------------------------------------- - kafka: - profiles: - - local-messaging - - local-messaging-outbox - - all-adapters - image: apache/kafka:3.8.0 - environment: - KAFKA_NODE_ID: "1" - KAFKA_PROCESS_ROLES: "broker,controller" - KAFKA_LISTENERS: "PLAINTEXT://:9092,CONTROLLER://:9093" - KAFKA_ADVERTISED_LISTENERS: "PLAINTEXT://kafka:9092" - KAFKA_CONTROLLER_QUORUM_VOTERS: "1@kafka:9093" - KAFKA_CONTROLLER_LISTENER_NAMES: "CONTROLLER" - KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: "CONTROLLER:PLAINTEXT,PLAINTEXT:PLAINTEXT" - KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: "1" - KAFKA_TRANSACTION_STATE_LOG_REPLICATION_FACTOR: "1" - KAFKA_TRANSACTION_STATE_LOG_MIN_ISR: "1" - networks: - - caskeleton-infra - healthcheck: - test: - ["CMD-SHELL", "/opt/kafka/bin/kafka-broker-api-versions.sh --bootstrap-server kafka:9092"] - interval: 10s - timeout: 10s - retries: 12 - start_period: 30s - - # ---- Redis — local compose contract for the shipped Redis runtime ---------------- - # Authenticated the way a deployment authenticates, with the lanes' test-fixture accounts: - # infra/redis-sdk/acl/lane-fixture-accounts.acl, the same file the Redis topology lanes use, mounted - # as it is rather than copied. It is not a deployment file — its passwords are public and it carries - # a lane-only `+@all` account (infra/redis-sdk/acl/README.md). Its first line turns the passwordless - # `default` user off, so the application connects as the named accounts the lane contract gives it - # (compose-profile-contracts.json, $redisComment). - # - # This Redis was open and the lanes declared app.redis.authentication.anonymous-access-accepted. - # The application then logged that trade, and the missing advanced account, as two startup - # warnings — correctly, because in production both are risks — and every Redis lane failed its - # "startup is silent" check. Quieting the warning would hide the same trade in production; the - # lane now authenticates the way a deployment does instead. - # - # The passwords are the file's fixture values (infra/redis-sdk/acl/README.md); this container is - # on the lane's internal network only and publishes no port. - redis: - profiles: - - local-redis - - all-adapters - image: redis:7.4 - command: - - redis-server - - --appendonly - - "no" - - --save - - "" - - --aclfile - - /etc/redis/acl/lane-fixture-accounts.acl - volumes: - - type: bind - source: ./infra/redis-sdk/acl - target: /etc/redis/acl - read_only: true - networks: - - caskeleton-infra - healthcheck: - # As the application account: with `default` off, an unauthenticated PING answers NOAUTH. - test: - - "CMD-SHELL" - - "[ \"$$(redis-cli --user ca-skeleton-application --pass fixture-application --no-auth-warning ping)\" = PONG ]" - interval: 5s - timeout: 3s - retries: 12 - start_period: 5s - - # ---- Mailpit — the reference SMTP provider for notification serving ---------- - mailpit: - profiles: - - local-notification-serving - - local-notification-handoff - - all-adapters - image: axllent/mailpit:v1.21 - environment: - MP_SMTP_AUTH_ACCEPT_ANY: "1" - # MP_SMTP_AUTH_ALLOW_INSECURE is deliberately absent, and Mailpit refuses to start with both: - # "TLS cannot be required with --smtp-auth-allow-insecure". It existed to permit credentials - # over a plaintext connection, which is exactly what requiring STARTTLS removes the need for — - # any AUTH now happens inside the TLS session. - # STARTTLS, required. Not a hardening extra: SmtpProviderProperties.TlsMode has two members and - # neither is plaintext, so the platform cannot describe an unencrypted relay at all. A lane that - # wanted a plaintext Mailpit would be asking for a transport the type refuses to express, and - # the honest way to satisfy it is to give the relay a certificate. - MP_SMTP_TLS_CERT: /run/mailpit-tls/server.crt - MP_SMTP_TLS_KEY: /run/mailpit-tls/server.key - MP_SMTP_REQUIRE_STARTTLS: "true" - volumes: - # Generated per run by the qualification wrapper for the host name `mailpit`, and removed on - # teardown, exactly like the PostgreSQL lane certificate. A committed test certificate is a - # private key in Git. - - type: bind - source: ./infra/mailpit/tls - target: /run/mailpit-tls - read_only: true - networks: - - caskeleton-infra - healthcheck: - test: ["CMD", "/mailpit", "readyz"] - interval: 5s - timeout: 3s - retries: 12 - start_period: 5s - - # ---- MinIO ------------------------------------------------------------------- - minio: - profiles: - - shared-infra - - prod-smoke - image: *local-minio-image - command: ["server", "/data"] - environment: - MINIO_ROOT_USER: "${MINIO_ROOT_USER:-caskeleton}" - MINIO_ROOT_PASSWORD: "${MINIO_ROOT_PASSWORD:-caskeleton-local}" - volumes: - - type: volume - source: caskeleton-minio-data - target: /data - networks: - - caskeleton-infra - healthcheck: - test: ["CMD", "mc", "ready", "local"] - interval: 10s - timeout: 5s - retries: 10 - start_period: 10s - - # Bucket and policy bootstrap. Not a substitute for the round trip: creating a bucket proves the - # server accepts an admin command, not that an object survives being written and read back. - minio-init: - profiles: - - shared-infra - - prod-smoke - # The client from the same supplier as the server. cgr.dev/chainguard/minio-client was not used: - # it has no shell, and the bootstrap below is a shell script. - image: "${LOCAL_MINIO_MC_IMAGE:-pgsty/mc@sha256:ce62c9053c69ce12a527a322345b5ad9f44b5f8a7b8189f82e516f2e3f30f1d8}" - depends_on: - minio: - condition: service_healthy - entrypoint: ["/bin/sh", "/opt/minio/bucket-bootstrap.sh"] - environment: - MINIO_ENDPOINT: "http://minio:9000" - MINIO_ROOT_USER: "${MINIO_ROOT_USER:-caskeleton}" - MINIO_ROOT_PASSWORD: "${MINIO_ROOT_PASSWORD:-caskeleton-local}" - MINIO_BUCKET: "${MINIO_BUCKET:-ca-skeleton-objects}" - volumes: - - type: bind - source: ./infra/minio/init - target: /opt/minio - read_only: true - networks: - - caskeleton-infra - restart: "no" - - # ---- Keycloak ---------------------------------------------------------------- - keycloak: - profiles: - - local-graphql - - local-notification-ingest - - local-notification-serving - - local-notification-handoff - - shared-infra - - prod-smoke - - all-adapters - image: quay.io/keycloak/keycloak:26.0 - # The wrapper reads the client secret from a mounted file and execs kc.sh. The realm artifact - # carries only a ${...} reference, so no secret value is in Git, in the rendered config, or on a - # command line. - entrypoint: ["/bin/bash", "/opt/keycloak-entrypoint/entrypoint.sh"] - environment: - KC_BOOTSTRAP_ADMIN_USERNAME: "${KEYCLOAK_ADMIN:-admin}" - KC_BOOTSTRAP_ADMIN_PASSWORD: "${KEYCLOAK_ADMIN_PASSWORD:-admin}" - KC_HEALTH_ENABLED: "true" - volumes: - - type: bind - source: ./infra/keycloak/entrypoint.sh - target: /opt/keycloak-entrypoint/entrypoint.sh - read_only: true - - type: bind - source: ./infra/keycloak/realms - target: /opt/keycloak/data/import - read_only: true - secrets: - - keycloak-graphql-smoke-client-secret - networks: - - caskeleton-infra - healthcheck: - test: - - "CMD-SHELL" - - "exec 3<>/dev/tcp/127.0.0.1/9000 && echo -e 'GET /health/ready HTTP/1.1\\r\\nHost: localhost\\r\\nConnection: close\\r\\n\\r\\n' >&3 && cat <&3 | grep -q '\"status\": \"UP\"'" - interval: 10s - timeout: 5s - retries: 20 - start_period: 30s - - # ---- Capability schema streams ------------------------------------------------ - # Two pre-start one-shots, in this order, because a capability stream is an operator sequence - # rather than a property. - # - # Install: each stream under db/migration/jpa keeps its own Flyway history table — they all declare - # a V1, so one Flyway pointed at all of them fails outright — and each registers itself - # INSTALLED_INACTIVE. - # - # Promote: an operator sanctions the installed schema, and the application refuses to start until - # that has happened. That is the fail-closed half of the same design, so it cannot be folded into - # the install step without making "the tables exist" and "this is sanctioned" the same event. - # - # They are also two images because they must be: flyway/flyway ships no psql, so the promotion - # could not have run in the migration container at all. - # - # Both run before `up`, not with the smoke clients after it — the application is what they are a - # precondition for. The lane contract's preStartServices carries that ordering. - db-migrate-capabilities: - profiles: - - local-notification-ingest - - local-notification-serving - - local-notification-handoff - - local-fileserver - - all-adapters - image: flyway/flyway:11.1.0 - depends_on: - db: - condition: service_healthy - entrypoint: ["/bin/sh", "/opt/capability-streams/apply-capability-streams.sh"] - environment: - PGHOST: "db" - PGUSER: "${APP_DATASOURCE_USERNAME:-ca_skeleton}" - PGPASSWORD: "${APP_DATASOURCE_PASSWORD:-ca_skeleton}" - PGDATABASE: "${POSTGRES_DB:-ca_skeleton}" - CAPABILITY_STREAMS: "${CAPABILITY_STREAMS:-}" - volumes: - - type: bind - source: ./infra/postgres/apply-capability-streams.sh - target: /opt/capability-streams/apply-capability-streams.sh - read_only: true - # The whole migration tree, not just db/migration/jpa: the application's own postgresql stream - # has to be installed first, or the capability tables arrive in a schema whose flyway_schema_history - # does not exist yet and the application refuses to start — which is its baseline-on-migrate: false - # policy working as designed. - - type: bind - source: ./src/adapter/outbound/persistence-jpa/src/main/resources/db/migration - target: /flyway/sql - read_only: true - # Each capability stream from the leaf that owns it, beside rather than inside /flyway/sql: a - # bind mount nested in that read-only one would need its mount point created in the source - # tree. They moved out of persistence-jpa with their capabilities, and the mount above stopped - # reaching them — the script then refused with "no such stream". - - type: bind - source: ./src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform - target: /flyway/streams/notification-platform - read_only: true - - type: bind - source: ./src/adapter/outbound/persistence-fileserver/src/main/resources/db/migration/jpa/fileserver - target: /flyway/streams/fileserver - read_only: true - networks: - - caskeleton-infra - restart: "no" - - db-promote-capabilities: - profiles: - - local-notification-ingest - - local-notification-serving - - local-notification-handoff - - local-fileserver - - all-adapters - image: postgres:16-alpine - depends_on: - db: - condition: service_healthy - entrypoint: ["/bin/sh", "/opt/capability-streams/promote-capability-streams.sh"] - environment: - PGHOST: "db" - PGUSER: "${APP_DATASOURCE_USERNAME:-ca_skeleton}" - PGPASSWORD: "${APP_DATASOURCE_PASSWORD:-ca_skeleton}" - PGDATABASE: "${POSTGRES_DB:-ca_skeleton}" - CAPABILITY_STREAMS: "${CAPABILITY_STREAMS:-}" - volumes: - - type: bind - source: ./infra/postgres/promote-capability-streams.sh - target: /opt/capability-streams/promote-capability-streams.sh - read_only: true - networks: - - caskeleton-infra - restart: "no" - - # The GraphQL transport, as a request. auth-smoke proves a token can be obtained and that public - # health answers; this proves /graphql is guarded and that an authenticated query executes. - graphql-smoke: - profiles: - - local-graphql - - all-adapters - image: curlimages/curl:8.10.1 - depends_on: - keycloak: - condition: service_healthy - # uid 0 for the mounted 0600 client secret, same as auth-smoke. - user: "0:0" - entrypoint: ["/bin/sh", "/opt/graphql-smoke/graphql-smoke.sh"] - environment: - APP_BASE_URL: "http://app:8080" - KEYCLOAK_ISSUER: "http://keycloak:8080/realms/ca-skeleton" - KEYCLOAK_CLIENT_ID: "ca-skeleton-api" - # Spring for GraphQL serves its own endpoint through a router function rather than an - # annotated controller, so the presentation base-path prefix does not apply to it. - GRAPHQL_PATH: "${GRAPHQL_PATH:-/graphql}" - volumes: - - type: bind - source: ./infra/graphql/smoke - target: /opt/graphql-smoke - read_only: true - secrets: - - keycloak-graphql-smoke-client-secret - networks: - - caskeleton-infra - restart: "no" - - # ---- One-shot smoke clients -------------------------------------------------- - # Never `up --wait` targets. Each is run with `run --rm` and must exit zero; a missing, skipped or - # non-zero one fails its lane rather than being treated as "not applicable". - auth-smoke: - profiles: - - local-graphql - - shared-infra - - prod-smoke - - all-adapters - image: curlimages/curl:8.10.1 - depends_on: - keycloak: - condition: service_healthy - # The client secret is written on the host at mode 0600 by the qualification wrapper and mounted - # in. The Keycloak image happens to run as the same uid the wrapper writes as; this image runs as - # uid 100, so it read "Permission denied" and the lane failed on the smoke client rather than on - # anything it was checking. Compose ignores the secret's uid/gid/mode options outside swarm, so - # the container reads it as root instead. The two alternatives are both worse: loosening the host - # file to world-readable leaves a credential readable by every process on the machine, and passing - # the value as an environment variable puts it in `docker compose config` output and in ps. - user: "0:0" - entrypoint: ["/bin/sh", "/opt/auth-smoke/auth-smoke.sh"] - environment: - # The same issuer URL the application is given. A token obtained from one URL and validated - # against another proves nothing, and localhost means a different host inside each container. - KEYCLOAK_ISSUER: "http://keycloak:8080/realms/ca-skeleton" - KEYCLOAK_CLIENT_ID: "ca-skeleton-api" - APP_BASE_URL: "http://app:8080" - # Supplied per runtime, because the same endpoint has two addresses: application-local.yml - # pins presentation.api-base-path to /api and the shipped default is /v1. The qualification - # wrapper exports the value that matches the lane's Spring runtime. - APP_HEALTH_PATH: "${APP_HEALTH_PATH:-/v1/healthcheck}" - volumes: - - type: bind - source: ./infra/keycloak/smoke - target: /opt/auth-smoke - read_only: true - secrets: - - keycloak-graphql-smoke-client-secret - networks: - - caskeleton-infra - restart: "no" - - # The server image, not the mc client image: the mc image ships no sed, grep or cmp, and the round-trip - # client needs a digest tool. See infra/minio/smoke/object-storage-smoke.sh for how that went - # unnoticed. The lane already pulls this image for the server itself. - object-storage-smoke: - profiles: - - shared-infra - - prod-smoke - image: *local-minio-image - depends_on: - minio-init: - condition: service_completed_successfully - entrypoint: ["/bin/sh", "/opt/minio-smoke/object-storage-smoke.sh"] - environment: - MINIO_ENDPOINT: "http://minio:9000" - MINIO_ROOT_USER: "${MINIO_ROOT_USER:-caskeleton}" - MINIO_ROOT_PASSWORD: "${MINIO_ROOT_PASSWORD:-caskeleton-local}" - MINIO_BUCKET: "${MINIO_BUCKET:-ca-skeleton-objects}" - volumes: - - type: bind - source: ./infra/minio/smoke - target: /opt/minio-smoke - read_only: true - networks: - - caskeleton-infra - restart: "no" - - notification-smoke: - profiles: - - local-notification-ingest - - local-notification-serving - - local-notification-handoff - - all-adapters - image: curlimages/curl:8.10.1 - depends_on: - keycloak: - condition: service_healthy - # uid 0 for the same reason auth-smoke uses it: the mounted client secret is mode 0600 on the - # host and this image otherwise runs as uid 100, which reads "Permission denied". The lane then - # fails on the smoke client rather than on anything it was checking. - user: "0:0" - entrypoint: ["/bin/sh", "/opt/notification-smoke/notification-smoke.sh"] - environment: - APP_BASE_URL: "http://app:8080" - MAILPIT_BASE_URL: "http://mailpit:8025" - # ingest | serving | handoff-verify — which phase of the lane this invocation is. - # - # No default, deliberately. It defaulted to `ingest`, and local-notification-serving therefore - # ran the ingest assertions — "accepted, and nothing was delivered" — against an application in - # SERVING mode. The lane passed while testing the opposite of what it is named for, and would - # have kept passing for as long as the check happened to run before the dispatch worker. An - # unset value now renders empty and the client refuses it. - # `:-` and not a value: an explicit empty default keeps Compose from warning about an unset - # variable on every lane that never runs this client, while still rendering empty so the - # client refuses it. - NOTIFICATION_SMOKE_PHASE: "${NOTIFICATION_SMOKE_PHASE:-}" - # Submission and template publication are authenticated like every other non-public path, so - # this client obtains a token the same way auth-smoke does — client credentials against the - # same issuer URL the application validates against. - APP_BASE_PATH: "${APP_BASE_PATH:-/api}" - KEYCLOAK_ISSUER: "http://keycloak:8080/realms/ca-skeleton" - KEYCLOAK_CLIENT_ID: "ca-skeleton-api" - volumes: - - type: bind - source: ./infra/notification/smoke - target: /opt/notification-smoke - read_only: true - # The handoff lane runs this client twice in one project and the second run needs the request - # id the first accepted, so the state lives in a named volume that outlives a `run --rm` - # container and is removed with the project by the teardown's --volumes. - # - # Its own path, not a subdirectory of the script mount above: a volume nested inside a - # read-only bind cannot be created, because the runtime has to mkdir the mountpoint in a - # filesystem it was just told is read-only. - - type: volume - source: caskeleton-notification-smoke-state - target: /opt/notification-smoke-state - secrets: - - keycloak-graphql-smoke-client-secret - networks: - - caskeleton-infra - restart: "no" - -networks: - caskeleton-infra: - driver: bridge - -volumes: - caskeleton-notification-smoke-state: - driver: local - caskeleton-db-data: - driver: local - caskeleton-mongo-data: - driver: local - caskeleton-minio-data: - driver: local - -secrets: - # Written per run at mode 0600 by the qualification wrapper and removed on teardown. The realm - # artifact references it by name; the value never reaches Git, a rendered config, a command line, - # or an evidence file. - keycloak-graphql-smoke-client-secret: - file: ./infra/keycloak/secrets/graphql-smoke-client-secret diff --git a/docker-compose.local.yml b/docker-compose.local.yml deleted file mode 100644 index 3e6f777f..00000000 --- a/docker-compose.local.yml +++ /dev/null @@ -1,64 +0,0 @@ -# ============================================================================= -# feature-container-runtime-contract — local infrastructure override -# -# Merge with base (and optionally dev): -# docker compose -f docker-compose.yml -f docker-compose.local.yml up -# -# Local intent: -# - Wires the app environment to point at the shared `db` service, which lives in -# docker-compose.infra.yml and starts only for lanes whose Compose profile names it. -# - Declares no depends_on: a depends_on aimed at a profiled service makes every lane that does -# not enable that profile fail to render at all, and ordering is the runtime-smoke wrapper's -# job — it knows which services a lane actually starts. -# - Keeps read-only filesystem and memory limits from the base compose. -# - Publishes the DB on the loopback interface only, so a host-side run -# (`./gradlew :app-bootstrap:bootRun`, IDE) reaches the same database the -# containerised app reaches over the internal `caskeleton-local` network. -# ============================================================================= - -services: - app: - # Optional, because src/.env is operator input and a fresh clone does not have one. Before this - # was marked optional, untracking that file made `docker compose config` fail outright on a - # clone — the environment override that exists for convenience became a hard prerequisite for - # rendering the stack at all. The tracked contract is src/.env.example; copy it. - env_file: - - path: ./src/.env - required: false - # Wire the app to the local Postgres service on the internal network. - environment: - # Explicit, not inherited. A Compose profile selects services; it says nothing about which - # environment the application believes it is in, and the two drifting is how a dev stack ends - # up running local's settings. - SPRING_PROFILES_ACTIVE: "local" - TZ: "UTC" - LANG: "C.UTF-8" - LC_ALL: "C.UTF-8" - # fallback matches env-keys.yaml SSOT default (30s); base compose grace is 60s. - APP_SERVER_SHUTDOWN_TIMEOUT: "${APP_SERVER_SHUTDOWN_TIMEOUT:-30s}" - APP_SERVER_SHUTDOWN: "graceful" - # Database connection — points to the local `db` service below. - # Override with your actual DB credentials in a local .env file. - APP_DATASOURCE_URL: "jdbc:postgresql://db:5432/${POSTGRES_DB:-ca_skeleton}" - APP_DATASOURCE_USERNAME: "${APP_DATASOURCE_USERNAME:-ca_skeleton}" - APP_DATASOURCE_PASSWORD: "${APP_DATASOURCE_PASSWORD:-ca_skeleton}" - healthcheck: - test: - - "CMD" - - "wget" - - "--no-verbose" - - "--tries=1" - - "--spider" - - "http://localhost:8080/api/healthcheck" - interval: 5s - timeout: 3s - start_period: 20s - retries: 12 - networks: - - caskeleton-infra - -networks: - # Defined in docker-compose.infra.yml, where the services that share it live. - caskeleton-infra: - external: false - diff --git a/docker-compose.yml b/docker-compose.yml deleted file mode 100644 index 39d0562f..00000000 --- a/docker-compose.yml +++ /dev/null @@ -1,107 +0,0 @@ -# ============================================================================= -# feature-container-runtime-contract — base docker-compose service definition -# -# Usage: -# docker compose up # base only -# docker compose -f docker-compose.yml -f docker-compose.dev.yml up # dev override -# docker compose -f docker-compose.yml -f docker-compose.local.yml up # local override -# -# Graceful-shutdown sync table (feature-container-runtime-contract D5): -# App shutdown timeout : 30s (APP_SERVER_SHUTDOWN_TIMEOUT — SSOT: docs/registries/ -# env-keys.yaml, owner feature-env-driven-runtime-configuration) -# Async executor wait : 19s (AsyncExecutorConfig.AWAIT_TERMINATION_SECONDS) -# Container preStop : 5s (handled by the orchestrator / stop_grace_period offset) -# stop_grace_period : 60s (30s app drain + 19s async + 5s preStop + 6s safety margin) -# -# The drain and the async wait are consecutive, not concurrent: Spring finishes the lifecycle -# phase (the web server's graceful drain) before it destroys the executor, which then waits for -# its queue. A 40s grace let the container be killed 9s into that wait (07-07). -# DeveloperExperienceContractTest fails when this value is below the sum. -# -# Ownership: env-driven-config owns the app shutdown *value* (30s); this contract owns the -# *relationship* (stop_grace_period >= app timeout + async wait + preStop + margin). The grace is therefore -# sized UP to the env-keys SSOT value (30s) — you do not shrink the app drain window to fit an -# arbitrary grace. This resolves the earlier 20s/35s drift, which had assumed an app-timeout -# value this branch does not own (env-keys.yaml is the SSOT and sets 30s). -# -# Memory limit (D4): -# The container memory limit MUST be set for -XX:MaxRAMPercentage=75 to be meaningful. -# Default 512m suits a small service; adjust per deployment. -# ============================================================================= - -services: - app: - build: - context: src/ - dockerfile: Dockerfile - args: - RELEASE_VERSION: "${RELEASE_VERSION:-0.0.1}" - BUILD_VERSION: "${BUILD_VERSION:-0.0.1+0000000}" - GIT_SHA: "${GIT_SHA:-0000000}" - SOURCE_URL: "${SOURCE_URL:-https://example.invalid/ca-tmpl}" - # default = the composition a service ships. scripts/run-compose-runtime-smoke.sh sets - # qualification: every capability module present, each lane switching on what it tests. - COMPOSITION: "${COMPOSITION:-default}" - # The composition is in the tag, so a lane's qualification image is never reused as the - # default one (Compose reuses a matching tag instead of building). - image: caskeleton:${BUILD_VERSION:-0.0.1_local_0000000}-${COMPOSITION:-default} - # Generated per run by scripts/run-compose-runtime-smoke.sh and removed on teardown. Seven values - # have no inline default on purpose — the datasource address and credential, the application - # name, and the JWT issuer and audience — so a lane has to supply them, and a lane that borrowed - # the developer's own src/.env would be reproducible only on that developer's machine. Optional, - # so an ordinary `docker compose up` is unaffected. - env_file: - - path: ./src/.env.lane - required: false - ports: - - "${APP_SERVER_PORT:-8080}:8080" - # Management (health, info, prometheus — answered without authentication) on loopback only: - # published on every interface it reaches the whole LAN (07-13). The smoke lanes read it from - # inside the container, so they need no host port at all. - - "127.0.0.1:9001:9001" - environment: - TZ: "UTC" - LANG: "C.UTF-8" - LC_ALL: "C.UTF-8" - # Graceful shutdown — fallback matches the env-keys.yaml SSOT default (30s). - # Override via .env or docker compose --env-file if you need a different value. - APP_SERVER_SHUTDOWN_TIMEOUT: "${APP_SERVER_SHUTDOWN_TIMEOUT:-30s}" - APP_SERVER_SHUTDOWN: "graceful" - # ---- Read-only root filesystem (D2) ------------------------------------- - # The application must write only to the tmpfs mounts declared below. - # /tmp — Tomcat basedir (see -Dserver.tomcat.basedir=/tmp in Dockerfile). - # /var/tmp/heap — heap dump landing zone (see -XX:HeapDumpPath=/var/tmp/heap). - read_only: true - tmpfs: - - /tmp:mode=1777,size=128m - - /var/tmp/heap:mode=1777,size=512m - # No volume: the shipped composition keeps nothing on disk. A capability that does brings its - # mount in its own overlay file under infra//compose/, added with -f when the - # capability is selected, so this file never names one (07-08). - # ---- Memory limit (D4) -------------------------------------------------- - # Must be set so -XX:MaxRAMPercentage=75 can compute a meaningful heap bound. - mem_limit: 512m - memswap_limit: 512m - # ---- Graceful shutdown (D5) --------------------------------------------- - # stop_grace_period = app drain (30s, env-keys SSOT) + async wait (19s) + preStop (5s) - # + margin (6s) = 60s. - stop_grace_period: 60s - # ---- Health check ------------------------------------------------------- - # Targets the actuator readiness probe on the management port (9001). - # The warning that used to stand here — that this probe would report UNHEALTHY until two - # parallel branches merged — outlived the branches. src/Dockerfile removed its copy and said - # why: "a stale warning about a healthcheck is the kind of comment that gets a real red - # container ignored." - healthcheck: - test: - - "CMD" - - "wget" - - "--no-verbose" - - "--tries=1" - - "--spider" - - "http://localhost:9001/actuator/health/readiness" - interval: 30s - timeout: 5s - start_period: 60s - retries: 3 - restart: unless-stopped diff --git a/docs/README.md b/docs/README.md index 4d745431..54351e62 100644 --- a/docs/README.md +++ b/docs/README.md @@ -1,7 +1,8 @@ # docs -저장소의 모든 문서는 이 디렉터리 아래에 있다. 어떤 문서를 어디에 두는지가 유일한 규칙이고, -파일 목록은 디렉터리를 직접 읽는다. 개수를 여기에 적으면 다음 문서가 추가되는 순간 틀린 글이 된다. +저장소의 모든 문서는 이 디렉터리 아래에 있다. 규칙은 둘이다: 어떤 문서를 어디에 두는지(아래 표), +문서의 수명에 따라 무엇을 어떤 언어로 고치는지(「문서 수명과 언어」). 파일 목록은 디렉터리를 직접 읽는다. +개수를 여기에 적으면 다음 문서가 추가되는 순간 틀린 글이 된다. ## 어댑터별 운영 문서 @@ -24,30 +25,121 @@ | --- | --- | | `adr/` | 아키텍처 결정 기록 | | `architecture/` | 공개 API 표면 스냅숏 | -| `manual/` | 개발 매뉴얼: 새 기능을 만드는 순서와 판단 지점, 생성 명령(`scripts/new-feature.sh`) | -| `evidence/` | 작업 단계별 증거·체크포인트 | +| `work/` | 작업 매뉴얼: 이 repo에서 하는 일(새 기능, 개선, 조사·설계, 문서 작성, 운영, 총괄)의 절차서. 루트 `CLAUDE.md` 다음에 읽는다 | +| `manual/` | 개발 매뉴얼: 새 기능을 만드는 순서와 판단 지점, 생성 명령(`scripts/new-feature.sh`). 입구는 `work/new-feature.md` | | `registries/` | env 키·에러 코드·메트릭·헤더 등 레지스트리 SSOT | | `reviews/` | 모듈 코드 리뷰 결과 | | `runbooks/` | 장애 코드별 대응 런북 (`template.md` 기준) | | `security/` | 공개 경로 스냅숏 | -## 설계와 계획 +## 설계와 기록 + +설계서와 기록은 쓴 때의 글이다. 지금 동작을 설명하지 않는다. 그래서 살아 있는 문서와 다른 폴더에 둔다. | 디렉터리 | 대상 | | --- | --- | -| `superpowers/specs/` | 설계서. `YYYY-MM-DD-<주제>-design.md` | -| `superpowers/plans/` | 구현·확장 계획서. `YYYY-MM-DD-<주제>-plan.md` | -| `superpowers/packages/` | 외부에서 납품된 설계 패키지의 README와 정적 검증 결과 | +| `design/` | 설계서. `YYYY-MM-DD-<주제>-design.md` | +| `history/plans/` | 구현·확장 계획서. `YYYY-MM-DD-<주제>-plan.md` | +| `history/packages/` | 외부에서 납품된 설계 패키지의 README와 정적 검증 결과 | +| `history/evidence/` | 작업 단계별 증거·체크포인트 | +| `history/study/` | 학습 문서. 쓴 때의 코드를 따라 읽은 기록이다 | -`superpowers/packages/<어댑터>/` 는 설계서가 처음 전달됐을 때의 안내와 `VALIDATION.md` 검증 이력을 -남긴 기록 보관소다. 설계서·계획서 본문은 전부 `specs/` 와 `plans/` 에 있으므로 이 디렉터리에서 +`history/packages/<어댑터>/` 는 설계서가 처음 전달됐을 때의 안내와 `VALIDATION.md` 검증 이력을 +남긴 기록 보관소다. 설계서·계획서 본문은 전부 `design/` 과 `history/plans/` 에 있으므로 이 디렉터리에서 문서를 찾을 필요는 없다. 각 README 상단의 보존 안내가 무엇이 옮겨졌고 무엇이 제거됐는지 밝힌다. +`history/packages/*-superpowers-package/` 셋은 납품된 묶음 그대로이고, 그 안의 `MANIFEST.sha256` 은 +납품 당시 바이트의 해시다. 계획서 본문에는 당시 계획한 경로와 명령이 그대로 남아 있다. 그중 일부는 실제 구현에서 다른 위치로 조정됐고, 저장소에 어떻게 대응시켰는지는 각 어댑터의 `repository-adaptation.md` 또는 `module-mapping.md` 가 기록한다. 계획서를 사후에 고치지 않는 이유는 그렇게 하면 계획의 기록이 아니라 결과를 계획처럼 보이게 만든 글이 되기 때문이다. +## 문서 수명과 언어 + +규칙의 정본은 design-docs `conventions/docs-system.md`다. 이 절은 이 repo에 적용한 내용이고, +이 템플릿을 받은 파생 서비스도 이 절을 따른다. + +| 수명 | 문서 | 위치 | 언어 | 고치는 법 | +| --- | --- | --- | --- | --- | +| 살아 있음 | README, `CLAUDE.md`, `AGENTS.md`, 매뉴얼(`manual/`, `work/`), 영역 운영 문서, `registries/`, `runbooks/`, `upgrade/` | 제자리 | 한국어 | 코드와 같은 변경에서 고친다 | +| 결정 | 결정 기록(ADR) | `adr/`, `notification/adr/` | 한국어 | 본문은 고치지 않는다. 일부가 바뀌면 상태를 「채택(보완)」으로 하고 보완 절을 덧붙인다. 크게 바뀌면 새 ADR을 쓰고 옛 ADR을 「대체됨」으로 한다 | +| 기록 | 설계서, 계획서, 납품 패키지, 증거, 학습 문서, 리뷰 | `design/`, `history/`, `reviews/` | 머리 블록은 한국어, 본문은 쓴 때의 원문 | 머리 블록의 칸만 고친다 | + +- 코드 식별자, 명령, 경로, 설정 키, 오류 코드, 로그·출력 인용, 제품 이름은 원문으로 둔다. +- 문체는 「~한다」다. 한 문서 안에서 「~합니다」와 섞지 않는다. +- 아직 한국어로 옮기지 않은 살아 있는 문서와 ADR은 문서 검사의 예외 목록에 있다(「문서 검사」). + +## 기록 문서의 머리 블록 + +`design/`, `history/`, `adr/`, `notification/adr/`의 `.md` 파일은 맨 위에 이 블록을 둔다. +블록을 빼면 원문 그대로다(옮길 때 깨진 상대 링크의 대상만 고쳤다). + +```text + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 구현됨 +- 작성일: 2026-08-11 +- 요약: 한국어 한 문장 +- 현재 정본: `docs/jpa/repository-adaptation.md` +- 대체됨: `docs/design/<대체한 문서>.md` + +``` + +- 종류는 폴더가 정하고 둘째 줄에 굵게 적는다: `design/` 설계서, `history/plans/` 계획서, + `history/evidence/`·`history/plans/evidence/` 증거, `history/packages/` 납품 패키지, + `history/study/` 학습 문서. ADR의 둘째 줄은 + `> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다.`다. +- 상태는 종류마다 고정 어휘다. + + | 종류 | 상태 | + | --- | --- | + | 설계서 | 제안 · 채택 · 구현됨 · 보류 · 폐기 · 대체됨 · 확인 안 함 | + | 결정 기록 | 제안 · 채택 · 채택(보완) · 폐기 · 대체됨 | + | 계획서 | 실행 중 · 끝남 · 중단 · 대체됨 · 확인 안 함 | + | 납품 패키지 · 증거 · 학습 문서 | 보관 | + +- 「현재 정본」은 지금 동작을 설명하는 살아 있는 문서의 경로다. 여럿이면 쉼표로 잇고, 없으면 「없음 — 이유」로 쓴다. +- 「대체됨」은 상태가 대체됨일 때 대체한 문서의 경로다. 이 문서가 다른 문서를 대체했으면 「대체」 칸에 그 경로를 쓴다. +- 상태는 그 결정을 바꾼 변경이 같이 바꾼다. 기능을 지우는 커밋이 그 기능의 설계서를 「폐기」나 「대체됨」으로 바꾼다. +- 2026-11-07에 처음 단 상태는 문서의 원래 상태 줄을 바꾼 값이다: Accepted·Approved·확정·승인 → 채택, + Superseded → 대체됨, Proposed → 제안, implemented → 구현됨, 보완 메모가 있는 ADR → 채택(보완). + 상태 줄이 없던 설계서와 체크 상자가 모두 표시되지 않은 계획서는 「확인 안 함」이다. + `capability-status.md` 「제거된 코드」로 지운 것이 확인된 설계서 다섯은 「폐기」다. +- 리뷰(`reviews/`)는 아직 머리 블록을 요구하지 않는다. + +## 문서와 코드를 같은 변경에서 고친다 + +- 코드나 규칙을 바꾸는 변경이 그것을 설명하는 살아 있는 문서도 고친다. 찾는 법: + `grep -rn '<바꾼 이름>' docs src --include=*.md`. +- 살아 있는 문서는 지금 있는 것만 쓴다. 지운 타입·경로·태스크는 `capability-status.md` 「제거된 코드」나 + `upgrade/`에 쓴다. 살아 있는 문서 안에서 꼭 써야 하면 `> 이력` 으로 시작하는 인용 블록 안에 쓴다. +- 숫자·버전을 복사하지 않는다. Spring Boot 버전은 `src/gradle/libs.versions.toml`, leaf 목록과 개수는 + registry(`src/config/architecture/modules.json`)를 가리킨다. +- 루트 README는 「프로젝트 구조」(최상위 폴더와 `src/` 폴더가 하는 일)와 「문서 지도」(매뉴얼·계약·운영·결정·기록이 + 어디 있나) 절을 반드시 둔다. 전체 절 목록과 순서는 design-docs `conventions/docs-system.md` 6절이다. + +## 문서 검사 + +`python3 scripts/check-docs.py`가 위 규칙 중 기계로 볼 수 있는 넷을 본다. PR마다 workflow `docs-check`가 +돌리고, 하나라도 걸리면 실패한다. 경로 필터가 없다: 코드에서 파일이나 Gradle 프로젝트를 지우는 변경이 +문서를 낡게 만든다. + +| 검사 | 보는 것 | +| --- | --- | +| `language` | 살아 있는 문서와 ADR 본문이 한국어인가(코드·명령·경로·인용은 세지 않는다) | +| `head` | 기록과 ADR 맨 위의 머리 블록: 칸, 상태 어휘, 날짜, 한국어 요약, 현재 정본·대체됨 경로가 있는지 | +| `reference` | 살아 있는 문서의 인라인 코드 안 경로(`src/`, `docs/`, `scripts/`, `compose/`, `.github/`로 시작하는 것과 지운 infra 폴더 아래 경로)와 Gradle 경로가 지금 트리·registry에 있는가. 코드 블록, `> 이력` 인용 블록, 제거 표, `upgrade/`는 보지 않는다 | +| `number` | 살아 있는 문서가 Spring Boot 버전이나 leaf 개수를 복사했는가 | + +- 하나만 돌리기: `python3 scripts/check-docs.py --only head`. +- 예외 목록 `scripts/check-docs-exceptions.txt`는 2026-11-07의 기준선이고 줄기만 한다. 문서를 번역하거나 고쳐서 + 더는 걸리지 않으면 그 줄을 지운다(남겨 두면 실패한다). 목록에 새 줄을 더하면 실패한다. 기준선을 늘리는 것은 + 규칙을 바꾸는 일이라 소유자 결정이 필요하다. +- 검사 자신의 시험: `python3 -m unittest discover -s scripts/tests`. +- 마크다운 상대 링크는 이 검사가 아니라 lychee(`link-check` workflow)와 `scripts/check-work-docs.py --links`가 본다. + ## 여기에 없는 것 - 실행되는 검증 스크립트는 문서가 아니다. `scripts/` 와 `.github/scripts/` 에 있다. diff --git a/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md b/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md index 8e722cca..2e109b0a 100644 --- a/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md +++ b/docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-09-07 +- 요약: 공유 테스트 코드는 java-test-fixtures 한 가지 방식으로 둔다는 결정이다. +- 현재 정본: `src/build-logic/README.md` + + # ADR-BUILD-001: `java-test-fixtures` is the standard for shared test code - Status: Accepted diff --git a/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md b/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md index cacb5f0f..57af5bc7 100644 --- a/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md +++ b/docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-24 +- 요약: GraphQL context는 inbound에 두고 객체 권한 판단은 application-core로 옮긴다는 결정이다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # ADR-GQL-001 — GraphQL context stays inbound; object authorization moves to application-core; the persisted-operation store stays an inbound SPI - Status: Accepted diff --git a/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md b/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md index f2eabfde..c45ff9c8 100644 --- a/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md +++ b/docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-30 +- 요약: gRPC 플랫폼을 adapter leaf 하나가 아니라 registry에 등록한 family로 낸다는 결정이다. +- 현재 정본: `docs/compatibility/grpc-support-matrix.md` + + # ADR-GRPC-001: The gRPC platform ships as a registered family, not as one adapter leaf - Status: accepted diff --git a/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md b/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md index 5e3b523e..82641867 100644 --- a/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md +++ b/docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md @@ -1,3 +1,13 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 대체됨 +- 작성일: 2026-08-30 +- 요약: protoc와 Buf CLI 없이 스키마를 관리하려던 결정이다. 2026-09-28 Gradle protobuf plugin과 buf로 바뀌었다. +- 현재 정본: `docs/compatibility/grpc-support-matrix.md` +- 대체됨: `docs/capability-status.md` + + # ADR-GRPC-002: Schema governance runs without protoc and without the Buf CLI - Status: **superseded (2026-09-28)** by owner decision 18 of the 2026-09-25 review follow-up diff --git a/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md b/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md index e4f6d50d..9a944e96 100644 --- a/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md +++ b/docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-30 +- 요약: 전송·업무·스트림 증거를 서로 대신하지 않는 세 축으로 본다는 결정이다. +- 현재 정본: `docs/compatibility/grpc-support-matrix.md` + + # ADR-GRPC-003: Transport, business and stream evidence are three axes, and none implies another - Status: accepted diff --git a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md index 78984639..00a03ed1 100644 --- a/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +++ b/docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-30 +- 요약: 재시도 주인은 하나이고 키가 있는 변경은 영속 원장이 필요하다는 결정이다. +- 현재 정본: `docs/compatibility/grpc-support-matrix.md` + + # ADR-GRPC-004: One retry owner, and keyed mutations need a durable ledger - Status: accepted diff --git a/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md b/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md index b648be9e..712eddf8 100644 --- a/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md +++ b/docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-30 +- 요약: 서버 스트림은 writer 하나, 제한된 큐, 추측하지 않는 resume로 다룬다는 결정이다. +- 현재 정본: `docs/compatibility/grpc-support-matrix.md` + + # ADR-GRPC-005: One writer per stream, a bounded queue, and resume that refuses to guess - Status: accepted diff --git a/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md b/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md index 3be4e14a..17e677a6 100644 --- a/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md +++ b/docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-31 +- 요약: Stable discovery는 DNS와 정적 목록이고 Kubernetes에서는 누가 부하를 나누는지 profile이 정한다는 결정이다. +- 현재 정본: `docs/compatibility/grpc-support-matrix.md` + + # ADR-GRPC-006: Stable discovery is DNS and static, and a Kubernetes profile names who balances - Status: accepted diff --git a/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md b/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md index 041a85ab..63e6bfde 100644 --- a/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md +++ b/docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-30 +- 요약: gRPC 고급 기능마다 따로 플래그·등급·승격 기준을 둔다는 결정이다. +- 현재 정본: `docs/compatibility/grpc-advanced-support-matrix.md` + + # ADR-GRPC-ADV-001: Each advanced capability has its own flag, its own grade and its own promotion - Status: accepted diff --git a/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md b/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md index 835275e5..24a06a89 100644 --- a/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md +++ b/docs/adr/ADR-JPA-001-domain-owns-persistence-model.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-11 +- 요약: 영속성 모델은 도메인이 소유한다는 결정이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # ADR-JPA-001 — The domain owns the persistence model - Status: Accepted diff --git a/docs/adr/ADR-JPA-002-full-transaction-retry.md b/docs/adr/ADR-JPA-002-full-transaction-retry.md index e10b4063..a2491bce 100644 --- a/docs/adr/ADR-JPA-002-full-transaction-retry.md +++ b/docs/adr/ADR-JPA-002-full-transaction-retry.md @@ -1,3 +1,13 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 대체됨 +- 작성일: 2026-08-11 +- 요약: 재시도는 유스케이스 전체를 다시 돌린다는 결정이다. 그 재시도 엔진은 2026-09-25에 지웠다. +- 현재 정본: `docs/jpa/transaction-guide.md` +- 대체됨: `docs/capability-status.md` + + # ADR-JPA-002 — Retry re-runs the whole use case - Status: Superseded (2026-09-25) — the retry engine this ADR describes diff --git a/docs/adr/ADR-JPA-003-completion-unknown.md b/docs/adr/ADR-JPA-003-completion-unknown.md index 4c1d5b1e..c283d6db 100644 --- a/docs/adr/ADR-JPA-003-completion-unknown.md +++ b/docs/adr/ADR-JPA-003-completion-unknown.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택(보완) +- 작성일: 2026-08-11 +- 요약: commit 결과를 모르는 실패는 재시도하지 않는다는 결정이다. 2026-09-25 보완이 있다. +- 현재 정본: `docs/jpa/transaction-guide.md` + + # ADR-JPA-003 — Completion unknown is never retried - Status: Accepted; amended 2026-09-25 — `TransactionCompletionResolver`, `CommitFailureClassifier` diff --git a/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md b/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md index c063e5e0..63be96de 100644 --- a/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md +++ b/docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-11 +- 요약: 스키마의 정본은 Flyway라는 결정이다. +- 현재 정본: `docs/jpa/migration-guide.md` + + # ADR-JPA-004 — Flyway is the schema source of truth - Status: Accepted diff --git a/docs/adr/ADR-JPA-005-postgresql-real-contract.md b/docs/adr/ADR-JPA-005-postgresql-real-contract.md index 20d1806c..116d2487 100644 --- a/docs/adr/ADR-JPA-005-postgresql-real-contract.md +++ b/docs/adr/ADR-JPA-005-postgresql-real-contract.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-11 +- 요약: 영속성 계약은 실제 PostgreSQL에서 돌린다는 결정이다. +- 현재 정본: `docs/jpa/support-matrix.md` + + # ADR-JPA-005 — Contracts run against real PostgreSQL - Status: Accepted diff --git a/docs/adr/ADR-JPA-006-canonical-technical-audit.md b/docs/adr/ADR-JPA-006-canonical-technical-audit.md index cf3bd995..80aadd31 100644 --- a/docs/adr/ADR-JPA-006-canonical-technical-audit.md +++ b/docs/adr/ADR-JPA-006-canonical-technical-audit.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-24 +- 요약: 기술 감사 모델은 audit 하나뿐이라는 결정이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # ADR-JPA-006 — `audit` is the sole technical audit model - Status: Accepted diff --git a/docs/adr/ADR-MONGO-001-platform-boundary.md b/docs/adr/ADR-MONGO-001-platform-boundary.md index 43d3e45c..62358927 100644 --- a/docs/adr/ADR-MONGO-001-platform-boundary.md +++ b/docs/adr/ADR-MONGO-001-platform-boundary.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-13 +- 요약: MongoDB 플랫폼의 경계를 정한 결정이다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + # ADR-MONGO-001 — MongoDB platform boundary - **Status:** Accepted diff --git a/docs/adr/ADR-MONGO-002-bson-representation.md b/docs/adr/ADR-MONGO-002-bson-representation.md index 40f9f443..73e478a7 100644 --- a/docs/adr/ADR-MONGO-002-bson-representation.md +++ b/docs/adr/ADR-MONGO-002-bson-representation.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-13 +- 요약: BSON 표현을 고정한 목록으로 관리한다는 결정이다. +- 현재 정본: `docs/mongodb/bson-mapping-guide.md` + + # ADR-MONGO-002 — BSON representation is a pinned manifest - **Status:** Accepted diff --git a/docs/adr/ADR-MONGO-003-transaction-retry.md b/docs/adr/ADR-MONGO-003-transaction-retry.md index d5501285..7d675461 100644 --- a/docs/adr/ADR-MONGO-003-transaction-retry.md +++ b/docs/adr/ADR-MONGO-003-transaction-retry.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-13 +- 요약: 트랜잭션 본문 재시도와 commit 재시도를 다른 반복으로 둔다는 결정이다. +- 현재 정본: `docs/mongodb/consistency-transaction-guide.md` + + # ADR-MONGO-003 — Transaction body retry and commit retry are separate loops - **Status:** Accepted diff --git a/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md b/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md index f39fffa8..eeb2896c 100644 --- a/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md +++ b/docs/adr/ADR-MONGO-004-index-schema-admin-plane.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-13 +- 요약: 인덱스와 스키마 변경은 관리 평면이 맡는다는 결정이다. +- 현재 정본: `docs/mongodb/schema-index-migration-guide.md` + + # ADR-MONGO-004 — Index and schema changes belong to the admin plane - **Status:** Accepted diff --git a/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md b/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md index a3b54030..9b3bc6b3 100644 --- a/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md +++ b/docs/adr/ADR-MONGO-ADV-001-capability-promotion.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택(보완) +- 작성일: 2026-08-13 +- 요약: MongoDB 고급 기능의 승격 기준을 정한 결정이다. 2026-09-25 보완이 있다. +- 현재 정본: `docs/mongodb/support-matrix.md` + + # ADR-MONGO-ADV-001 — Advanced capability promotion - **Status:** Accepted diff --git a/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md b/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md index e54311a0..8883fe61 100644 --- a/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md +++ b/docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-25 +- 요약: 스트리밍은 실시간 전달이고 web 모듈은 이력을 저장하지 않는다는 결정이다. +- 현재 정본: `docs/web/streaming-contract.md` + + # ADR-WEB-ADV-001: Streaming is live delivery, and the web module stores no history - Status: Accepted diff --git a/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md b/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md index e76ebc72..fafaeeae 100644 --- a/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md +++ b/docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-25 +- 요약: 가상 스레드는 스케줄링을 바꿀 뿐 동시성 예산을 없애지 않는다는 결정이다. +- 현재 정본: `docs/web/virtual-thread-profile.md` + + # ADR-WEB-ADV-002: Virtual threads change scheduling, not the concurrency budget - Status: Accepted diff --git a/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md b/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md index f91133d0..d850da30 100644 --- a/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md +++ b/docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-25 +- 요약: OpenAPI 3.2 문서는 나란히 만들고 실험 등급으로 둔다는 결정이다. +- 현재 정본: `docs/web/openapi-32-compatibility.md` + + # ADR-WEB-ADV-003: OpenAPI 3.2 is generated in parallel and stays experimental - Status: Accepted diff --git a/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md b/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md index 442ebee5..69cc7efb 100644 --- a/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md +++ b/docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md @@ -1,3 +1,13 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 대체됨 +- 작성일: 2026-08-25 +- 요약: WebSocket 플랫폼을 leaf 하나의 패키지들로 내고 경계를 기계로 검사한다는 결정이다. 2026-09-25 플랫폼을 줄이면서 바뀌었다. +- 현재 정본: `src/adapter/inbound/websocket/README.md` +- 대체됨: `docs/capability-status.md` + + # ADR-WS-001: The WebSocket platform ships as packages in one leaf, with machine-checked boundaries - Status: Superseded 2026-09-25 — the eighteen-package platform was cut to the parts a Spring diff --git a/docs/adr/ADR-WS-002-resume-and-cluster.md b/docs/adr/ADR-WS-002-resume-and-cluster.md index 6f2be96e..6f089e9d 100644 --- a/docs/adr/ADR-WS-002-resume-and-cluster.md +++ b/docs/adr/ADR-WS-002-resume-and-cluster.md @@ -1,3 +1,13 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 대체됨 +- 작성일: 2026-08-25 +- 요약: resume·cluster 상태는 캐시로 다룬다는 결정이다. 그 기능은 2026-09-25에 지웠다. +- 현재 정본: `src/adapter/inbound/websocket/README.md` +- 대체됨: `docs/capability-status.md` + + # ADR-WS-002: Resume and cluster state are caches, and are treated as caches - Status: Superseded 2026-09-25 — `advanced.resume`, `advanced.cluster` and `advanced.presence` diff --git a/docs/adr/ADR-WS-003-stomp-and-broker-relay.md b/docs/adr/ADR-WS-003-stomp-and-broker-relay.md index 6f8aff4b..fab91a73 100644 --- a/docs/adr/ADR-WS-003-stomp-and-broker-relay.md +++ b/docs/adr/ADR-WS-003-stomp-and-broker-relay.md @@ -1,3 +1,13 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 대체됨 +- 작성일: 2026-08-25 +- 요약: STOMP를 목적지 목록이 있는 고급 어댑터로 둔다는 결정이다. 그 고급 STOMP는 2026-09-25에 지웠다. +- 현재 정본: `src/adapter/inbound/websocket/README.md` +- 대체됨: `docs/capability-status.md` + + # ADR-WS-003: STOMP is an Advanced adapter with a declared destination catalog - Status: Superseded 2026-09-25 — `advanced.stomp` and `advanced.stomp.rabbit` were removed; the diff --git a/docs/capability-status.md b/docs/capability-status.md index b70e0120..d0e0bdb2 100644 --- a/docs/capability-status.md +++ b/docs/capability-status.md @@ -27,11 +27,11 @@ lanes and CI; it is not a deployment artifact. | Capability | Enabled key (property / env, default) | IMPLEMENTED | WIRED | QUALIFIED | Evidence | | --- | --- | --- | --- | --- | --- | -| Relational persistence (JPA/PostgreSQL) | `ca-skeleton.persistence-jpa.enabled` / `APP_PERSISTENCE_JPA_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-jpa')`) | yes | Not in the default composition. The one line brings everything — its own `AutoConfiguration.imports` (`PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig`, `JpaStartupAutoConfiguration`), its environment handling (`JpaActivationEnvironmentPostProcessor`, `spring.factories`: readiness `db` while on; with `false` it also excludes Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configuration, so no DataSource is bound), the startup guards (Flyway strategy, datasource/OSIV/DDL/pool/TLS/vendor checks, exit codes unchanged) and its settings (`config/module-defaults/persistence-jpa.yml`). `persistence-jpa:PersistenceJpaCapabilityAssemblyTest` proves the module assembles on its own; the `postgresql*IntegrationTest` readiness lanes, run by `integration-main.yml` → `integration-check` (`:integrationCheck`), qualify it against PostgreSQL. `sample-portfolio` selects it by its build dependency and the module's auto-configuration (no broad scan of the persistence package). `bootRunH2` adds the module to its own classpath only. | +| Relational persistence (JPA/PostgreSQL) | `ca-skeleton.persistence-jpa.enabled` / `APP_PERSISTENCE_JPA_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-jpa')`) | yes | Not in the default composition. The one line brings everything — its own `AutoConfiguration.imports` (`PersistenceJpaAutoConfiguration`, `PersistenceJpaRuntimeConfig`, `JpaStartupAutoConfiguration`), its environment handling (`JpaActivationEnvironmentPostProcessor`, `spring.factories`: readiness `db` while on; with `false` it also excludes Boot's JDBC, Hibernate, Spring Data JPA and Flyway auto-configuration, so no DataSource is bound), the startup guards (Flyway strategy, datasource/OSIV/DDL/pool/TLS/vendor checks, exit codes unchanged) and its settings (`config/module-defaults/persistence-jpa.yml`). `persistence-jpa:PersistenceJpaCapabilityAssemblyTest` proves the module assembles on its own; the `postgresql*IntegrationTest` readiness lanes, run by `integration-main.yml` → `integration-check` (`:integrationCheck`), qualify it against PostgreSQL. `bootRunH2` adds the module to its own classpath only. | | Document persistence (MongoDB) | `ca-skeleton.persistence-mongo.enabled` / `APP_PERSISTENCE_MONGO_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:persistence-mongo')`) | yes | On when present; `false` also excludes Boot's Mongo auto-configuration (`MongoCapabilityActivationTest`). The connection-source rule (`SPRING_MONGODB_URI` or the selected profile's `uri-secret`) is checked by the module's own `MongoDefaultsEnvironmentPostProcessor`. Six container lanes (`mongoReplicaSetTest`, `mongoFailoverTest`, …), run by `integration-main.yml` → `integration-check` (`:integrationCheck`) | | Messaging (Kafka) | `app.messaging.enabled` / `APP_MESSAGING_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:messaging-kafka')`, which brings the application bridge, the legacy `KafkaSender` seam and the vendored platform with its Kafka transport) | Kafka only | On when present (`KafkaCapabilityActivationTest`). `messaging-kafka:messagingCertificationTest` behind `verifyMessagingCertificationEvidence`, run by `messaging-certification.yml`; the starter's `integrationTest` is the live Kafka round trip. Kafka is the only registered broker; the RabbitMQ broker keys were removed (no transport). | | Redis capabilities (cache / rate-limit / lease / idempotency) | `app.redis.enabled` / `APP_REDIS_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':adapter:outbound:cache-redis')`, which brings `redis-runtime`) | yes | `cache-redis:redisContainerContractTest` (Testcontainers Redis, `integrationCheck`); `cache-redis:redisTopologyTest`, run by `redis-sdk-topology.yml`. Not in the default composition. On when present; `false` contributes no Redis bean — no settings, client, connection, thread or health contributor. The module owns its readiness contribution (`RedisReadinessGroupPostProcessor`, `spring.factories`) and its settings (`config/module-defaults/cache-redis.yml`: `app.redis.enabled`, `app.rate-limit.*`, the Redis `ca-skeleton.capabilities.*`). No `app-bootstrap` main source names a Redis type. | -| Request idempotency | `APP_IDEMPOTENCY_PROVIDER` (`disabled` \| `redis` \| `postgresql`; a selector, not an on/off key) | yes | yes | Redis and PostgreSQL | One generation: the application `IdempotencyExecutor`, built once by `composition:idempotency` (`IdempotencyAutoConfiguration`) over the one store the selected provider contributes (`cache-redis` or `persistence-jpa`); startup is refused unless exactly one store exists. `app-bootstrap` and `sample-portfolio` both take that module with one `runtimeOnly` line, so there is no second assembly. Redis is covered by the row above. PostgreSQL has `persistence-jpa:postgresqlIdempotencyIntegrationTest`, run by `integration-main.yml` → `integration-check` (`:integrationCheck`). The `postgresql` provider refuses a non-PostgreSQL data source, so `bootRunH2` uses `disabled` or `redis`. Each store comes with its module: `postgresql` needs the persistence-jpa line, `redis` the cache-redis one. | +| Request idempotency | `APP_IDEMPOTENCY_PROVIDER` (`disabled` \| `redis` \| `postgresql`; a selector, not an on/off key) | yes | yes | Redis and PostgreSQL | One generation: the application `IdempotencyExecutor`, built once by `composition:idempotency` (`IdempotencyAutoConfiguration`) over the one store the selected provider contributes (`cache-redis` or `persistence-jpa`); startup is refused unless exactly one store exists. `app-bootstrap`이 그 모듈을 `runtimeOnly` 한 줄로 받고, 다른 조립은 없다. Redis is covered by the row above. PostgreSQL has `persistence-jpa:postgresqlIdempotencyIntegrationTest`, run by `integration-main.yml` → `integration-check` (`:integrationCheck`). The `postgresql` provider refuses a non-PostgreSQL data source, so `bootRunH2` uses `disabled` or `redis`. Each store comes with its module: `postgresql` needs the persistence-jpa line, `redis` the cache-redis one. | | Transactional outbox relay | `ca-skeleton.outbox.enabled` / `APP_OUTBOX_ENABLED`, `false` (+ `APP_OUTBOX_RELAY_ENABLED`, `false`; persistence-jpa settings) | yes | yes (with the persistence-jpa line; the scheduler also needs the messaging-kafka line) | yes | The store and its settings are persistence-jpa's; the relay (`OutboxConfig`) is application composition in `app-bootstrap` because a driven adapter must not build or call a use case. It turns on only when an `OutboxStorePort` bean exists, and the scheduler only when an `OutboxMessagePublishPort` does (the messaging bridge), each ordered after its contributor by `afterName` — so an environment with no publisher keeps its PENDING rows. The bridge registers no stand-in publisher: a present-and-enabled bridge with a blank broker and no canonical transport is refused at startup. `postgresqlLegacyOutboxConcurrentRelayIntegrationTest` qualifies claim/fencing against PostgreSQL. | | Notification platform | `ca-skeleton.notification.platform.enabled` / `APP_NOTIFICATION_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:notification-platform')`, plus the persistence-jpa line) | claim-scoped | Not in the default composition. The one line brings the use-case assembly, `adapter:outbound:notification`, the HTTP surface `adapter:inbound:web-notification` and its own settings (`config/module-defaults/notification.yml`), each registered through the module's own `AutoConfiguration.imports`; `adapter:inbound:web` no longer depends on `application-notification`. `verifyNotificationEvidence` refuses a grade in `docs/notification/support-matrix.md` that no proven claim backs; run by `notification-platform.yml`. There is no real-SMTP lane, and the matrix says so rather than implying one. | | File server platform | `app.fileserver-platform.enabled` / `APP_FILESERVER_PLATFORM_ENABLED`, `true` | yes | yes (one line: `runtimeOnly project(':composition:fileserver-platform')`, plus the persistence-jpa line) | yes | On when present; module-owned `config/module-defaults/fileserver.yml` also carries the servlet multipart ceiling. `app-bootstrap:integrationTest` → `FileserverCompositionIntegrationTest` (required by the strict lane), run by `integration-main.yml` → `integration-check` (`:integrationCheck`) | @@ -71,7 +71,7 @@ web 경로의 `W/`는 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adap 복구가 필요하면 표의 커밋에서 경로를 꺼낸다(`git show <커밋>:<경로>`). -리뷰 후속 작업(2026-09-25~28, `docs/superpowers/plans/2026-09-25-review-followup.md`)에서 지운 것은 마지막으로 존재한 커밋이 `6d27356e`인 행으로 표 끝에 이어 붙였다. +리뷰 후속 작업(2026-09-25~28, `docs/history/plans/2026-09-25-review-followup.md`)에서 지운 것은 마지막으로 존재한 커밋이 `6d27356e`인 행으로 표 끝에 이어 붙였다. | 대상 | 경로 | 마지막으로 존재한 커밋 | 이유 | | --- | --- | --- | --- | diff --git a/docs/ci-cd/boundary.md b/docs/ci-cd/boundary.md index 3869355f..1281e831 100644 --- a/docs/ci-cd/boundary.md +++ b/docs/ci-cd/boundary.md @@ -60,12 +60,10 @@ GitHub Actions 워크플로는 `kubectl apply`, `helm upgrade`, `argocd app sync | Argo CD Application 정의 | **없음.** GitOps 저장소에 둘 예정 | | CI에서의 클러스터 접근 | 없음 — 유일했던 `kubectl apply`는 제거됨 | -`release.yml`의 fileserver certification 잡(`fileserver-pvc-certification` 등, 예전 -`fileserver-certification.yml`)은 예외처럼 보이지만 아니다. PVC 매니페스트가 여전히 ReadWriteOnce를 -선언하는지 **파일만** 확인하고, 클러스터에는 아무것도 적용하지 않는다. 실제 클러스터에서의 인증은 -운영자가 `infra/fileserver/kubernetes/pvc-certification-job.yaml`을 직접 실행하고 -`docs/fileserver/storage-certification.md`에 기록한다. 잡 이름이 "release"가 아니라 "certification"인 -이유가 이것이다 — 이 잡은 릴리스하지 않는다. +PVC 매니페스트와 그 파일을 검사하던 `release.yml` 잡(`fileserver-pvc-certification`)은 2026-11-07에 +지웠다(소유자 결정: Kubernetes·프록시 설정은 이 repo 밖). 클러스터 인증은 배포하는 쪽이 +`docs/fileserver/storage-certification.md` 절차로 하고, volume 조건은 `docs/fileserver/operations.md` +「운영 환경이 지켜야 할 조건」에 있다. ## 규칙 diff --git a/docs/ci-cd/template-vs-consumer.md b/docs/ci-cd/template-vs-consumer.md index 964e2552..715189bc 100644 --- a/docs/ci-cd/template-vs-consumer.md +++ b/docs/ci-cd/template-vs-consumer.md @@ -4,8 +4,8 @@ 이 저장소에는 성격이 다른 두 종류의 검증이 섞여 있다. -1. **스켈레톤을 만드는 사람**에게 필요한 검증 — sample 모듈이 정말 제거 가능한가, optional 모듈 - 조합이 모두 빌드되는가, 레지스트리가 확장 가능한가. +1. **스켈레톤을 만드는 사람**에게 필요한 검증 — optional 모듈 조합이 모두 빌드되는가, 레지스트리가 + 확장 가능한가. 2. **스켈레톤을 가져다 서비스를 만드는 사람**에게 필요한 검증 — 내 애플리케이션의 테스트, 아키텍처 방향, 보안, 릴리스. @@ -16,10 +16,7 @@ | 대상 | 무엇을 지키는가 | | --- | --- | -| `:app-bootstrap:sampleOffTest`, `ci-quality-gates.yml`의 `sample-off` job | sample 픽스처를 지워도 애플리케이션이 빌드·부팅되는가 | -| `sample-portfolio` leaf 전체 | 참조 구현 | -| `Dockerfile.sample`, `docker-compose.*` 중 sample 관련 | 위와 동일 | -| `docs/superpowers/**` | 이 템플릿을 만든 과정의 설계/계획 기록 | +| `docs/design/**`, `docs/history/**` | 이 템플릿을 만든 과정의 설계서·계획서·납품 패키지·증거·학습 기록 | | `gradle/qualification/**` | 이 템플릿이 벤더링한 플랫폼(JPA, messaging)의 인증 체계 | | `*-certification.yml`, `*-qualification.yml`, `jpa-next-*.yml` | 템플릿이 광고하는 지원 매트릭스의 근거 | diff --git a/docs/superpowers/specs/2026-07-20-harness-policy-engine-design.md b/docs/design/2026-07-20-harness-policy-engine-design.md similarity index 94% rename from docs/superpowers/specs/2026-07-20-harness-policy-engine-design.md rename to docs/design/2026-07-20-harness-policy-engine-design.md index 7bec7e1e..de484796 100644 --- a/docs/superpowers/specs/2026-07-20-harness-policy-engine-design.md +++ b/docs/design/2026-07-20-harness-policy-engine-design.md @@ -1,3 +1,13 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 대체됨 +- 작성일: 2026-07-20 +- 요약: 중복된 하네스 규칙을 레지스트리 기반 정책 엔진으로 바꾸려던 설계다. +- 현재 정본: `src/config/architecture/modules.json` +- 대체됨: `docs/design/2026-07-25-harness-free-mode-b-amendment.md` + + > **SUPERSEDED — HISTORICAL PROVENANCE ONLY (2026-07-25):** The user-approved harness-free > Mode B amendment supersedes this design. Retain the body as historical provenance; it is not > executable instruction. diff --git a/docs/superpowers/specs/2026-07-25-application-outbox-failure-reporting-design.md b/docs/design/2026-07-25-application-outbox-failure-reporting-design.md similarity index 97% rename from docs/superpowers/specs/2026-07-25-application-outbox-failure-reporting-design.md rename to docs/design/2026-07-25-application-outbox-failure-reporting-design.md index ad582f0a..f74e9a57 100644 --- a/docs/superpowers/specs/2026-07-25-application-outbox-failure-reporting-design.md +++ b/docs/design/2026-07-25-application-outbox-failure-reporting-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-25 +- 요약: application-core에서 Spring·로깅 의존을 걷어내고 확정된 outbox 실패를 보고하는 방식을 정한 설계다. +- 현재 정본: `src/composition/outbox-relay/README.md` + + # Application Outbox Failure Reporting Refactoring Design - **Date:** 2026-07-25 diff --git a/docs/superpowers/specs/2026-07-25-application-outbox-failure-reporting-harness-free-design.md b/docs/design/2026-07-25-application-outbox-failure-reporting-harness-free-design.md similarity index 89% rename from docs/superpowers/specs/2026-07-25-application-outbox-failure-reporting-harness-free-design.md rename to docs/design/2026-07-25-application-outbox-failure-reporting-harness-free-design.md index 54f38f80..efb99afb 100644 --- a/docs/superpowers/specs/2026-07-25-application-outbox-failure-reporting-harness-free-design.md +++ b/docs/design/2026-07-25-application-outbox-failure-reporting-harness-free-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-25 +- 요약: 하네스 없이 application-core를 프레임워크·로깅 없이 두면서 outbox 실패를 구조화된 ERROR 한 줄로 남기는 설계다. +- 현재 정본: `src/composition/outbox-relay/README.md` + + # Application Outbox Failure Reporting — Harness-Free Design ## Context diff --git a/docs/superpowers/specs/2026-07-25-ci-control-plane-recovery-design.md b/docs/design/2026-07-25-ci-control-plane-recovery-design.md similarity index 97% rename from docs/superpowers/specs/2026-07-25-ci-control-plane-recovery-design.md rename to docs/design/2026-07-25-ci-control-plane-recovery-design.md index e34b294a..21d222ea 100644 --- a/docs/superpowers/specs/2026-07-25-ci-control-plane-recovery-design.md +++ b/docs/design/2026-07-25-ci-control-plane-recovery-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-25 +- 요약: 숨어 있던 CI 제어면을 저장소 안으로 되살려 Gradle·Docker 빌드와 의존성 자동화를 맞추는 설계다. +- 현재 정본: `docs/work/reference/gates.md` + + # CI Control Plane Recovery Design - **Date:** 2026-07-25 @@ -114,7 +123,7 @@ native provenance. **Mode B — controlled reconstruction.** The original source is unavailable or incomplete. The human records that fact and explicitly authorizes reconstruction from the approved [`2026-07-20-harness-policy-engine-design.md`](2026-07-20-harness-policy-engine-design.md), -[`2026-07-20-harness-policy-engine.md`](../plans/2026-07-20-harness-policy-engine.md), the tracked +[`2026-07-20-harness-policy-engine.md`](../history/plans/2026-07-20-harness-policy-engine.md), the tracked Gradle/module sources, and this design. Reconstructed artifacts receive new hashes and a `controlled-reconstruction` provenance record. Schema, renderer parity, mutation coverage, Gradle project discovery, and architecture dependency checks must pass before the new artifacts can act as diff --git a/docs/superpowers/specs/2026-07-25-harness-free-mode-b-amendment.md b/docs/design/2026-07-25-harness-free-mode-b-amendment.md similarity index 83% rename from docs/superpowers/specs/2026-07-25-harness-free-mode-b-amendment.md rename to docs/design/2026-07-25-harness-free-mode-b-amendment.md index 86c32ad5..f58fc5b9 100644 --- a/docs/superpowers/specs/2026-07-25-harness-free-mode-b-amendment.md +++ b/docs/design/2026-07-25-harness-free-mode-b-amendment.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-25 +- 요약: 하네스를 되살리지 않고 Gradle 부트스트랩과 의존 방향 검사를 복구하며 registry JSON을 정본으로 정한 범위 수정이다. +- 현재 정본: `src/config/architecture/modules.json` + + # Harness-Free Mode B Amendment - **Date:** 2026-07-25 diff --git a/docs/superpowers/specs/2026-07-25-harness-free-quality-security-ci-design.md b/docs/design/2026-07-25-harness-free-quality-security-ci-design.md similarity index 92% rename from docs/superpowers/specs/2026-07-25-harness-free-quality-security-ci-design.md rename to docs/design/2026-07-25-harness-free-quality-security-ci-design.md index e6b90784..b5a83880 100644 --- a/docs/superpowers/specs/2026-07-25-harness-free-quality-security-ci-design.md +++ b/docs/design/2026-07-25-harness-free-quality-security-ci-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-25 +- 요약: 하네스 없이 품질·의존성 보안 CI를 저장소 안에서 다시 세우는 설계다. +- 현재 정본: `docs/work/reference/gates.md` + + # Harness-Free Quality and Security CI Design - **Date:** 2026-07-25 diff --git a/docs/superpowers/specs/2026-07-25-module-gradle-hygiene-design.md b/docs/design/2026-07-25-module-gradle-hygiene-design.md similarity index 97% rename from docs/superpowers/specs/2026-07-25-module-gradle-hygiene-design.md rename to docs/design/2026-07-25-module-gradle-hygiene-design.md index 8e3e15ca..885c4ece 100644 --- a/docs/superpowers/specs/2026-07-25-module-gradle-hygiene-design.md +++ b/docs/design/2026-07-25-module-gradle-hygiene-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-25 +- 요약: leaf Gradle 의존 그래프를 Clean Architecture를 지키는 최소 모양으로 줄이는 정리 설계다. +- 현재 정본: `src/config/architecture/modules.json` + + # Module and Gradle Hygiene Refactoring Design - **Date:** 2026-07-25 diff --git a/docs/superpowers/specs/2026-07-25-module-gradle-hygiene-harness-free-design.md b/docs/design/2026-07-25-module-gradle-hygiene-harness-free-design.md similarity index 95% rename from docs/superpowers/specs/2026-07-25-module-gradle-hygiene-harness-free-design.md rename to docs/design/2026-07-25-module-gradle-hygiene-harness-free-design.md index a7a4435b..d043204a 100644 --- a/docs/superpowers/specs/2026-07-25-module-gradle-hygiene-harness-free-design.md +++ b/docs/design/2026-07-25-module-gradle-hygiene-harness-free-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-25 +- 요약: 같은 모듈·Gradle 정리를 하네스 없이 적용하는 설계다. +- 현재 정본: `src/config/architecture/modules.json` + + # Harness-Free Module and Gradle Hygiene Design - **Date:** 2026-07-25 diff --git a/docs/superpowers/specs/2026-07-26-fileserver-production-capability-design.md b/docs/design/2026-07-26-fileserver-production-capability-design.md similarity index 99% rename from docs/superpowers/specs/2026-07-26-fileserver-production-capability-design.md rename to docs/design/2026-07-26-fileserver-production-capability-design.md index fc0141c6..09b012fd 100644 --- a/docs/superpowers/specs/2026-07-26-fileserver-production-capability-design.md +++ b/docs/design/2026-07-26-fileserver-production-capability-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 폐기 +- 작성일: 2026-07-26 +- 요약: 파일 서버를 단계별로 운영 가능한 capability로 올리는 상세 설계다. 이 설계의 publication R1/R2 어댑터는 2026-09-25에 지웠다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver Production Capability Deep Design - 작성일: 2026-07-26 diff --git a/docs/superpowers/specs/2026-07-26-production-capability-platform-design.md b/docs/design/2026-07-26-production-capability-platform-design.md similarity index 98% rename from docs/superpowers/specs/2026-07-26-production-capability-platform-design.md rename to docs/design/2026-07-26-production-capability-platform-design.md index 2669121e..c80ca292 100644 --- a/docs/superpowers/specs/2026-07-26-production-capability-platform-design.md +++ b/docs/design/2026-07-26-production-capability-platform-design.md @@ -1,3 +1,13 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 대체됨 +- 작성일: 2026-07-26 +- 요약: 통합 지점 모음을 opt-in 운영 capability 플랫폼으로 키우는 전체 설계다. 스위치로 끄던 방식은 2026-09-25 capability 모듈 포장으로 바뀌었다. +- 현재 정본: `docs/capability-status.md` +- 대체됨: `docs/design/2026-09-25-capability-module-packaging-design.md` + + # Production Capability Platform Design - Date: 2026-07-26 @@ -952,7 +962,7 @@ and durable interfaces are explicit. The authoritative implementation-level design for this capability is [Object Storage Production Capability Deep Design](2026-07-28-objectstorage-production-capability-design.md). Its ordered RED–GREEN execution batches and promotion gates are in the -[Object Storage Production Capability Implementation Plan](../plans/2026-07-28-objectstorage-production-capability.md). +[Object Storage Production Capability Implementation Plan](../history/plans/2026-07-28-objectstorage-production-capability.md). This subsection is only the cross-capability baseline; the dedicated design governs when details differ. diff --git a/docs/superpowers/specs/2026-07-26-redis-production-capability-design.md b/docs/design/2026-07-26-redis-production-capability-design.md similarity index 99% rename from docs/superpowers/specs/2026-07-26-redis-production-capability-design.md rename to docs/design/2026-07-26-redis-production-capability-design.md index f43f6a66..3860ddcb 100644 --- a/docs/superpowers/specs/2026-07-26-redis-production-capability-design.md +++ b/docs/design/2026-07-26-redis-production-capability-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-26 +- 요약: Redis를 운영 가능한 capability로 올리는 단계별 상세 설계다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Production Capability Deep Design - Date: 2026-07-26 diff --git a/docs/superpowers/specs/2026-07-27-httpclient-production-capability-design.md b/docs/design/2026-07-27-httpclient-production-capability-design.md similarity index 99% rename from docs/superpowers/specs/2026-07-27-httpclient-production-capability-design.md rename to docs/design/2026-07-27-httpclient-production-capability-design.md index f70d714a..1b6e648e 100644 --- a/docs/superpowers/specs/2026-07-27-httpclient-production-capability-design.md +++ b/docs/design/2026-07-27-httpclient-production-capability-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-27 +- 요약: HTTP client를 운영 가능한 capability로 올리는 단계별 상세 설계다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + # HTTP Client Production Capability Deep Design - 작성일: 2026-07-27 diff --git a/docs/superpowers/specs/2026-07-28-fileserver-r2-control-plane-provider-selection-design.md b/docs/design/2026-07-28-fileserver-r2-control-plane-provider-selection-design.md similarity index 98% rename from docs/superpowers/specs/2026-07-28-fileserver-r2-control-plane-provider-selection-design.md rename to docs/design/2026-07-28-fileserver-r2-control-plane-provider-selection-design.md index 764d2b92..2c2b1bb8 100644 --- a/docs/superpowers/specs/2026-07-28-fileserver-r2-control-plane-provider-selection-design.md +++ b/docs/design/2026-07-28-fileserver-r2-control-plane-provider-selection-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 폐기 +- 작성일: 2026-07-28 +- 요약: 파일 서버 R2 제어면과 provider 선택을 정한 설계다. 이 R2 어댑터는 2026-09-25에 지웠다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver R2 Control Plane and Provider Selection Design - Date: 2026-07-28 diff --git a/docs/superpowers/specs/2026-07-28-jpa-production-capability-design.md b/docs/design/2026-07-28-jpa-production-capability-design.md similarity index 99% rename from docs/superpowers/specs/2026-07-28-jpa-production-capability-design.md rename to docs/design/2026-07-28-jpa-production-capability-design.md index d84ab5d9..8ac2384c 100644 --- a/docs/superpowers/specs/2026-07-28-jpa-production-capability-design.md +++ b/docs/design/2026-07-28-jpa-production-capability-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-28 +- 요약: JPA·PostgreSQL을 운영 가능한 capability로 올리는 상세 설계다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA/PostgreSQL Production Capability Deep Design - 작성일: 2026-07-28 diff --git a/docs/superpowers/specs/2026-07-28-messaging-production-capability-design.md b/docs/design/2026-07-28-messaging-production-capability-design.md similarity index 99% rename from docs/superpowers/specs/2026-07-28-messaging-production-capability-design.md rename to docs/design/2026-07-28-messaging-production-capability-design.md index 608c93f6..9d5f4759 100644 --- a/docs/superpowers/specs/2026-07-28-messaging-production-capability-design.md +++ b/docs/design/2026-07-28-messaging-production-capability-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-28 +- 요약: 메시징을 운영 가능한 capability로 올리는 상세 설계다. +- 현재 정본: `docs/messaging/support-matrix.md` + + # Messaging Production Capability Deep Design - 작성일: 2026-07-28 diff --git a/docs/superpowers/specs/2026-07-28-notification-production-capability-design.md b/docs/design/2026-07-28-notification-production-capability-design.md similarity index 99% rename from docs/superpowers/specs/2026-07-28-notification-production-capability-design.md rename to docs/design/2026-07-28-notification-production-capability-design.md index 956872d9..cf3e6165 100644 --- a/docs/superpowers/specs/2026-07-28-notification-production-capability-design.md +++ b/docs/design/2026-07-28-notification-production-capability-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-28 +- 요약: 알림을 운영 가능한 capability로 올리는 상세 설계다. +- 현재 정본: `docs/notification/support-matrix.md` + + # Notification Production Capability Deep Design - 작성일: 2026-07-28 @@ -15,7 +24,7 @@ 이 문서는 Notification capability의 승인된 상세 설계다. 2026-07-28에 §36의 다섯 gate를 사용자가 승인했으며, 실제 구현 순서는 -[Notification Production Capability Implementation Plan](../plans/2026-07-28-notification-production-capability.md)을 +[Notification Production Capability Implementation Plan](../history/plans/2026-07-28-notification-production-capability.md)을 정본으로 사용한다. 구현 및 production readiness는 아직 주장하지 않는다. 2026-07-28 현재 구현된 범위: @@ -4793,7 +4802,7 @@ COMPLETE 뒤 reverse가 필요하다면 canonical in-flight/intent backlog/provi inbound messaging/inbox architecture로 설계를 수정해야 한다. 사용자는 2026-07-28에 위 다섯 결정을 승인했다. 구현은 -[Notification Production Capability Implementation Plan](../plans/2026-07-28-notification-production-capability.md)의 +[Notification Production Capability Implementation Plan](../history/plans/2026-07-28-notification-production-capability.md)의 작은 TDD task, owner leaf, registry-derived Gradle path, focused test, architecture gate, real-provider evidence와 rollback point를 따른다. diff --git a/docs/superpowers/specs/2026-07-28-objectstorage-production-capability-design.md b/docs/design/2026-07-28-objectstorage-production-capability-design.md similarity index 99% rename from docs/superpowers/specs/2026-07-28-objectstorage-production-capability-design.md rename to docs/design/2026-07-28-objectstorage-production-capability-design.md index 2e805d4c..1846c917 100644 --- a/docs/superpowers/specs/2026-07-28-objectstorage-production-capability-design.md +++ b/docs/design/2026-07-28-objectstorage-production-capability-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-28 +- 요약: object storage를 운영 가능한 capability로 올리는 상세 설계와 batch 진행 기록이다. +- 현재 정본: `src/adapter/outbound/objectstorage/README.md` + + # Object Storage Production Capability Deep Design - 작성일: 2026-07-28 @@ -12,7 +21,7 @@ - 상위 문서: [Production Capability Platform Design](2026-07-26-production-capability-platform-design.md) - 구현 계획: - [Object Storage Production Capability Implementation Plan](../plans/2026-07-28-objectstorage-production-capability.md) + [Object Storage Production Capability Implementation Plan](../history/plans/2026-07-28-objectstorage-production-capability.md) - 참고 설계: [Redis Production Capability Deep Design](2026-07-26-redis-production-capability-design.md), [Fileserver Production Capability Deep Design](2026-07-26-fileserver-production-capability-design.md), @@ -78,11 +87,11 @@ create-only PUT/complete 조건을 무시하므로 managed/direct mutation profile을 `UNSUPPORTED`로 유지하며 readiness를 올리지 않는다. -증거는 [Batch A checkpoint](../../evidence/object-storage/batch-a-checkpoint.md), -[Batch B checkpoint](../../evidence/object-storage/batch-b-checkpoint.md), -[Batch C checkpoint](../../evidence/object-storage/batch-c-progress.md), -[Batch D checkpoint](../../evidence/object-storage/batch-d-checkpoint.md), -[Batch E pause checkpoint](../../evidence/object-storage/batch-e-pause-checkpoint.md)에 기록했다. +증거는 [Batch A checkpoint](../history/evidence/object-storage/batch-a-checkpoint.md), +[Batch B checkpoint](../history/evidence/object-storage/batch-b-checkpoint.md), +[Batch C checkpoint](../history/evidence/object-storage/batch-c-progress.md), +[Batch D checkpoint](../history/evidence/object-storage/batch-d-checkpoint.md), +[Batch E pause checkpoint](../history/evidence/object-storage/batch-e-pause-checkpoint.md)에 기록했다. 격리 브랜치에서는 private vault 경로를 잘못 선택해 capture가 차단됐지만, main 통합 작업은 사용자가 지정한 public vault의 @@ -4015,7 +4024,7 @@ authorization endpoint의 ephemeral response이며 stored object DTO에 영구 ## 37. 구현 계획 작성 전 확정 항목 정본 구현 순서와 아래 결정의 현재 freeze/approval gate는 -[Object Storage Production Capability Implementation Plan](../plans/2026-07-28-objectstorage-production-capability.md)에 +[Object Storage Production Capability Implementation Plan](../history/plans/2026-07-28-objectstorage-production-capability.md)에 기록한다. Tasks 1–24의 구현은 Batch E pause checkpoint까지 진행됐지만 Batch E 전체 combined/root gate는 아직 통과하지 않았다. Tasks 25–30은 미착수다. 이 구현 진행이나 계획 승인이 public API, scanner provider 또는 AWS/IaC 외부 변경 권한을 자동으로 부여하지 diff --git a/docs/superpowers/specs/2026-07-28-production-grade-test-architecture-environment-design.md b/docs/design/2026-07-28-production-grade-test-architecture-environment-design.md similarity index 99% rename from docs/superpowers/specs/2026-07-28-production-grade-test-architecture-environment-design.md rename to docs/design/2026-07-28-production-grade-test-architecture-environment-design.md index 50c570ca..51e4d1ef 100644 --- a/docs/superpowers/specs/2026-07-28-production-grade-test-architecture-environment-design.md +++ b/docs/design/2026-07-28-production-grade-test-architecture-environment-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 제안 +- 작성일: 2026-07-28 +- 요약: 운영 수준 테스트 구조와 테스트 환경(서비스 준비, 데이터 격리, CI·릴리스 환경)을 정하는 제안이다. +- 현재 정본: `docs/testing/TESTING_STRATEGY.md` + + # Production-grade test architecture and environment design - Status: proposed design; implementation not started diff --git a/docs/superpowers/specs/2026-07-28-redis-cache-resilience-design.md b/docs/design/2026-07-28-redis-cache-resilience-design.md similarity index 93% rename from docs/superpowers/specs/2026-07-28-redis-cache-resilience-design.md rename to docs/design/2026-07-28-redis-cache-resilience-design.md index dcadf83b..3edd97bb 100644 --- a/docs/superpowers/specs/2026-07-28-redis-cache-resilience-design.md +++ b/docs/design/2026-07-28-redis-cache-resilience-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-07-28 +- 요약: Redis 캐시에 cache-aside, 원본 보호, soft/hard TTL을 더하는 증분 설계다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Cache Resilience Increment Design **Status:** approved for implementation diff --git a/docs/superpowers/specs/2026-07-28-redis-distributed-rate-limit-design.md b/docs/design/2026-07-28-redis-distributed-rate-limit-design.md similarity index 92% rename from docs/superpowers/specs/2026-07-28-redis-distributed-rate-limit-design.md rename to docs/design/2026-07-28-redis-distributed-rate-limit-design.md index 4d2c42d6..9cfb040a 100644 --- a/docs/superpowers/specs/2026-07-28-redis-distributed-rate-limit-design.md +++ b/docs/design/2026-07-28-redis-distributed-rate-limit-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 구현됨 +- 작성일: 2026-07-28 +- 요약: Redis로 고를 수 있는 분산 rate-limit 알고리즘 셋을 제공하는 증분 설계다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Distributed Rate-Limit Increment Design **Status:** implemented as standalone R1 diff --git a/docs/superpowers/specs/2026-08-01-release-hygiene-refactoring-design.md b/docs/design/2026-08-01-release-hygiene-refactoring-design.md similarity index 94% rename from docs/superpowers/specs/2026-08-01-release-hygiene-refactoring-design.md rename to docs/design/2026-08-01-release-hygiene-refactoring-design.md index 3b564a4e..33dc50eb 100644 --- a/docs/superpowers/specs/2026-08-01-release-hygiene-refactoring-design.md +++ b/docs/design/2026-08-01-release-hygiene-refactoring-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-01 +- 요약: 릴리스 위생 경로(sample-off 게이트, wrapper 검증, Docker 캐시, SpotBugs)를 사실대로 맞추는 리팩터링 설계다. +- 현재 정본: `docs/work/reference/gates.md` + + # Release Hygiene Refactoring Design **Date:** 2026-08-01 diff --git a/docs/superpowers/specs/2026-08-02-client-safe-error-boundary-design.md b/docs/design/2026-08-02-client-safe-error-boundary-design.md similarity index 89% rename from docs/superpowers/specs/2026-08-02-client-safe-error-boundary-design.md rename to docs/design/2026-08-02-client-safe-error-boundary-design.md index 8ac709d1..b0807329 100644 --- a/docs/superpowers/specs/2026-08-02-client-safe-error-boundary-design.md +++ b/docs/design/2026-08-02-client-safe-error-boundary-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-02 +- 요약: 공개 HTTP 오류 응답에 허용한 문구와 안전한 값만 담게 하는 경계 설계다. +- 현재 정본: `docs/web/http-contract.md` + + # Client-Safe Error Boundary Design **Date:** 2026-08-02 diff --git a/docs/superpowers/specs/2026-08-02-conditional-inbound-transport-boundary-design.md b/docs/design/2026-08-02-conditional-inbound-transport-boundary-design.md similarity index 93% rename from docs/superpowers/specs/2026-08-02-conditional-inbound-transport-boundary-design.md rename to docs/design/2026-08-02-conditional-inbound-transport-boundary-design.md index e794e9e3..7d4cdba8 100644 --- a/docs/superpowers/specs/2026-08-02-conditional-inbound-transport-boundary-design.md +++ b/docs/design/2026-08-02-conditional-inbound-transport-boundary-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-02 +- 요약: GraphQL·gRPC·WebSocket 전송을 고를 때만 켜고 위험한 활성화는 실패시키는 경계 설계다. +- 현재 정본: `docs/web/http-contract.md` + + # Conditional Inbound Transport Boundary Design **Date:** 2026-08-02 diff --git a/docs/superpowers/specs/2026-08-02-p2-verification-governance-refactoring-design.md b/docs/design/2026-08-02-p2-verification-governance-refactoring-design.md similarity index 89% rename from docs/superpowers/specs/2026-08-02-p2-verification-governance-refactoring-design.md rename to docs/design/2026-08-02-p2-verification-governance-refactoring-design.md index 94d58c30..d6ba4b52 100644 --- a/docs/superpowers/specs/2026-08-02-p2-verification-governance-refactoring-design.md +++ b/docs/design/2026-08-02-p2-verification-governance-refactoring-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-02 +- 요약: 동작을 바꾸지 않고 남은 fail-open 검증 경로를 없애는 리팩터링 설계다. +- 현재 정본: `docs/work/reference/gates.md` + + # P2 Verification Governance Refactoring Design ## Goal diff --git a/docs/superpowers/specs/2026-08-02-redis-session-http-boundary-design.md b/docs/design/2026-08-02-redis-session-http-boundary-design.md similarity index 90% rename from docs/superpowers/specs/2026-08-02-redis-session-http-boundary-design.md rename to docs/design/2026-08-02-redis-session-http-boundary-design.md index 28d69df4..1f67bd7f 100644 --- a/docs/superpowers/specs/2026-08-02-redis-session-http-boundary-design.md +++ b/docs/design/2026-08-02-redis-session-http-boundary-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-02 +- 요약: Redis 세션과 HTTP 경계에서 브라우저 세션 보안이 유지되고 실패 시 닫히는지 증명하는 설계다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Session HTTP Boundary Design **Date:** 2026-08-02 diff --git a/docs/superpowers/specs/2026-08-02-verification-purity-refactoring-design.md b/docs/design/2026-08-02-verification-purity-refactoring-design.md similarity index 89% rename from docs/superpowers/specs/2026-08-02-verification-purity-refactoring-design.md rename to docs/design/2026-08-02-verification-purity-refactoring-design.md index dbc5c9be..8e8af585 100644 --- a/docs/superpowers/specs/2026-08-02-verification-purity-refactoring-design.md +++ b/docs/design/2026-08-02-verification-purity-refactoring-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-02 +- 요약: 파일을 고치던 검증 경로(stale JAR, 공개 경로)를 읽기 전용으로 바꾸는 설계다. +- 현재 정본: `docs/work/reference/gates.md` + + # Verification Purity Refactoring Design **Date:** 2026-08-02 diff --git a/docs/superpowers/specs/2026-08-02-warning-zero-build-design.md b/docs/design/2026-08-02-warning-zero-build-design.md similarity index 98% rename from docs/superpowers/specs/2026-08-02-warning-zero-build-design.md rename to docs/design/2026-08-02-warning-zero-build-design.md index 6c29407a..39c20254 100644 --- a/docs/superpowers/specs/2026-08-02-warning-zero-build-design.md +++ b/docs/design/2026-08-02-warning-zero-build-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-02 +- 요약: 컴파일러·정적 분석·테스트 출력 경고를 0으로 만드는 빌드 설계다. +- 현재 정본: `docs/work/reference/gates.md` + + # Warning-Zero Build Refactoring Design **Date:** 2026-08-02 diff --git a/docs/superpowers/specs/2026-08-02-web-security-boundary-design.md b/docs/design/2026-08-02-web-security-boundary-design.md similarity index 89% rename from docs/superpowers/specs/2026-08-02-web-security-boundary-design.md rename to docs/design/2026-08-02-web-security-boundary-design.md index 7f5849ed..c4c8a6c9 100644 --- a/docs/superpowers/specs/2026-08-02-web-security-boundary-design.md +++ b/docs/design/2026-08-02-web-security-boundary-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-02 +- 요약: JWT·JWKS와 CORS 필터 경계를 밀봉된 테스트와 릴리스 차단 검사로 고정하는 설계다. +- 현재 정본: `docs/web/http-contract.md` + + # Web Security Boundary Design **Date:** 2026-08-02 diff --git a/docs/superpowers/specs/2026-08-07-fileserver-platform-design.md b/docs/design/2026-08-07-fileserver-platform-design.md similarity index 99% rename from docs/superpowers/specs/2026-08-07-fileserver-platform-design.md rename to docs/design/2026-08-07-fileserver-platform-design.md index 4748d977..4fcc75dc 100644 --- a/docs/superpowers/specs/2026-08-07-fileserver-platform-design.md +++ b/docs/design/2026-08-07-fileserver-platform-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-07 +- 요약: 업로드·다운로드를 넘어 저장·게시·전송을 나눈 공통 파일 서비스 플랫폼 설계다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver Platform 설계서 **문서 상태:** 설계 확정안 diff --git a/docs/superpowers/specs/2026-08-07-redis-wrapper-typed-api-design.md b/docs/design/2026-08-07-redis-wrapper-typed-api-design.md similarity index 99% rename from docs/superpowers/specs/2026-08-07-redis-wrapper-typed-api-design.md rename to docs/design/2026-08-07-redis-wrapper-typed-api-design.md index 0d1fe53e..1d2b4fa2 100644 --- a/docs/superpowers/specs/2026-08-07-redis-wrapper-typed-api-design.md +++ b/docs/design/2026-08-07-redis-wrapper-typed-api-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-07 +- 요약: Redis 자료구조와 명령을 위험도에 따라 Typed API와 통제된 Raw Gateway로 나눠 제공하는 설계다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Wrapper 및 Typed API 설계서 - **상태:** 구현 기준선 확정 diff --git a/docs/superpowers/specs/2026-08-08-httpclient-platform-design.md b/docs/design/2026-08-08-httpclient-platform-design.md similarity index 99% rename from docs/superpowers/specs/2026-08-08-httpclient-platform-design.md rename to docs/design/2026-08-08-httpclient-platform-design.md index ef10f00a..ae4bb718 100644 --- a/docs/superpowers/specs/2026-08-08-httpclient-platform-design.md +++ b/docs/design/2026-08-08-httpclient-platform-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-08 +- 요약: 외부 HTTP 호출의 대상, 연결 자원, 시간 예산, 재시도 증거를 다루는 HTTP client 플랫폼 설계다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + # HTTP Client Platform 설계서 **문서 상태:** 구현 기준선 확정 diff --git a/docs/superpowers/specs/2026-08-10-messaging-platform-design.md b/docs/design/2026-08-10-messaging-platform-design.md similarity index 99% rename from docs/superpowers/specs/2026-08-10-messaging-platform-design.md rename to docs/design/2026-08-10-messaging-platform-design.md index af4a4587..2b281b94 100644 --- a/docs/superpowers/specs/2026-08-10-messaging-platform-design.md +++ b/docs/design/2026-08-10-messaging-platform-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-10 +- 요약: 메시지 생성부터 브로커 수락, 소비자 정산까지 증거로 다루는 메시징 플랫폼 설계다. +- 현재 정본: `docs/messaging/support-matrix.md` + + # Messaging Platform 설계서 - **상태:** 구현 승인용 기준 설계 diff --git a/docs/superpowers/specs/2026-08-10-notification-platform-design.md b/docs/design/2026-08-10-notification-platform-design.md similarity index 99% rename from docs/superpowers/specs/2026-08-10-notification-platform-design.md rename to docs/design/2026-08-10-notification-platform-design.md index 4637cab6..25f83125 100644 --- a/docs/superpowers/specs/2026-08-10-notification-platform-design.md +++ b/docs/design/2026-08-10-notification-platform-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-10 +- 요약: 요청·수신자·시도 수명주기와 provider 결과를 다루는 알림 전달 플랫폼 설계다. +- 현재 정본: `docs/notification/support-matrix.md` + + # Notification Delivery Platform 설계서 > 상태: 구현 기준 설계(Implementation-ready) diff --git a/docs/superpowers/specs/2026-08-11-jpa-persistence-platform-design.md b/docs/design/2026-08-11-jpa-persistence-platform-design.md similarity index 99% rename from docs/superpowers/specs/2026-08-11-jpa-persistence-platform-design.md rename to docs/design/2026-08-11-jpa-persistence-platform-design.md index a907c6b0..c52c39e8 100644 --- a/docs/superpowers/specs/2026-08-11-jpa-persistence-platform-design.md +++ b/docs/design/2026-08-11-jpa-persistence-platform-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-11 +- 요약: JPA 관계형 영속성 플랫폼의 공개 계약, 모듈 경계, 트랜잭션 의미론을 정한 설계다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA 관계형 영속성 플랫폼 설계서 - 문서 상태: 구현 기준 설계 diff --git a/docs/superpowers/specs/2026-08-11-mongodb-document-persistence-platform-design.md b/docs/design/2026-08-11-mongodb-document-persistence-platform-design.md similarity index 98% rename from docs/superpowers/specs/2026-08-11-mongodb-document-persistence-platform-design.md rename to docs/design/2026-08-11-mongodb-document-persistence-platform-design.md index e79ff9f3..29d31789 100644 --- a/docs/superpowers/specs/2026-08-11-mongodb-document-persistence-platform-design.md +++ b/docs/design/2026-08-11-mongodb-document-persistence-platform-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-11 +- 요약: 도메인이 MongoDB 문서와 repository를 소유하게 하는 문서 영속성 플랫폼 설계다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + # MongoDB 문서 영속성 플랫폼 설계서 - 문서 상태: 구현 기준 설계 diff --git a/docs/superpowers/specs/2026-08-12-graphql-api-execution-platform-design.md b/docs/design/2026-08-12-graphql-api-execution-platform-design.md similarity index 99% rename from docs/superpowers/specs/2026-08-12-graphql-api-execution-platform-design.md rename to docs/design/2026-08-12-graphql-api-execution-platform-design.md index 836c9d33..8047d655 100644 --- a/docs/superpowers/specs/2026-08-12-graphql-api-execution-platform-design.md +++ b/docs/design/2026-08-12-graphql-api-execution-platform-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-12 +- 요약: SDL 계약이 인증·제한·실행·오류 계약을 거쳐 유스케이스에 닿게 하는 GraphQL 실행 플랫폼 설계다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # GraphQL API 실행 플랫폼 설계서 - **문서 상태:** 구현 기준선 확정 diff --git a/docs/superpowers/specs/2026-08-15-five-adapter-runtime-remediation-review-design.md b/docs/design/2026-08-15-five-adapter-runtime-remediation-review-design.md similarity index 99% rename from docs/superpowers/specs/2026-08-15-five-adapter-runtime-remediation-review-design.md rename to docs/design/2026-08-15-five-adapter-runtime-remediation-review-design.md index 53c45211..676795a1 100644 --- a/docs/superpowers/specs/2026-08-15-five-adapter-runtime-remediation-review-design.md +++ b/docs/design/2026-08-15-five-adapter-runtime-remediation-review-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-15 +- 요약: 다섯 어댑터를 한 bootJar에서 켜고 끌 수 있게 고치는 통합 리뷰와 개선 설계다. +- 현재 정본: `docs/capability-status.md` + + # 다섯 Adapter 최종 통합 리뷰 및 개선 설계 - 기준 일자: 2026-08-15 diff --git a/docs/superpowers/specs/2026-08-30-grpc-platform-adaptation-design.md b/docs/design/2026-08-30-grpc-platform-adaptation-design.md similarity index 96% rename from docs/superpowers/specs/2026-08-30-grpc-platform-adaptation-design.md rename to docs/design/2026-08-30-grpc-platform-adaptation-design.md index c7f2c244..55b23bb0 100644 --- a/docs/superpowers/specs/2026-08-30-grpc-platform-adaptation-design.md +++ b/docs/design/2026-08-30-grpc-platform-adaptation-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-30 +- 요약: 타입 안전 gRPC 실행 플랫폼 계획을 이 저장소의 구조와 게이트에 맞춘 설계다. +- 현재 정본: `docs/compatibility/grpc-support-matrix.md` + + # 타입 안전 gRPC 실행 플랫폼 — 이 저장소 규약으로의 어댑팅 설계 두 계획 문서를 이 저장소(`ca-skeleton`)의 실제 구조·정책·빌드 게이트에 맞춰 실행 가능한 형태로 diff --git a/docs/superpowers/specs/2026-09-16-verification-surface-reduction-design.md b/docs/design/2026-09-16-verification-surface-reduction-design.md similarity index 97% rename from docs/superpowers/specs/2026-09-16-verification-surface-reduction-design.md rename to docs/design/2026-09-16-verification-surface-reduction-design.md index c53ad772..3b12bc99 100644 --- a/docs/superpowers/specs/2026-09-16-verification-surface-reduction-design.md +++ b/docs/design/2026-09-16-verification-surface-reduction-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-16 +- 요약: 스켈레톤을 qualification framework에서 되돌려 검증 표면을 줄이는 설계다. +- 현재 정본: `docs/work/reference/gates.md` + + # 검증 표면 축소 설계 — 스켈레톤을 qualification framework에서 되돌리기 날짜: 2026-09-16 diff --git a/docs/superpowers/specs/2026-09-17-jpa-evidence-gradle-model-decoupling-design.md b/docs/design/2026-09-17-jpa-evidence-gradle-model-decoupling-design.md similarity index 93% rename from docs/superpowers/specs/2026-09-17-jpa-evidence-gradle-model-decoupling-design.md rename to docs/design/2026-09-17-jpa-evidence-gradle-model-decoupling-design.md index 90a7ebe4..d8a38df9 100644 --- a/docs/superpowers/specs/2026-09-17-jpa-evidence-gradle-model-decoupling-design.md +++ b/docs/design/2026-09-17-jpa-evidence-gradle-model-decoupling-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-17 +- 요약: JPA 증거 생성이 실행 시점에 Gradle 모델을 읽지 않게 떼어 내는 설계다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA Evidence Gradle Model Decoupling Design ## Context diff --git a/docs/superpowers/specs/2026-09-18-bootstrap-structured-log-fields.md b/docs/design/2026-09-18-bootstrap-structured-log-fields.md similarity index 80% rename from docs/superpowers/specs/2026-09-18-bootstrap-structured-log-fields.md rename to docs/design/2026-09-18-bootstrap-structured-log-fields.md index b9451d4b..999f2b0f 100644 --- a/docs/superpowers/specs/2026-09-18-bootstrap-structured-log-fields.md +++ b/docs/design/2026-09-18-bootstrap-structured-log-fields.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: app-bootstrap 경고 로그를 구조화된 필드로 모으는 작은 설계다. +- 현재 정본: `docs/observability/log-fields.md` + + # Bootstrap Structured Log Fields ## Goal diff --git a/docs/superpowers/specs/2026-09-18-bootstrap-structured-runtime-logging.md b/docs/design/2026-09-18-bootstrap-structured-runtime-logging.md similarity index 84% rename from docs/superpowers/specs/2026-09-18-bootstrap-structured-runtime-logging.md rename to docs/design/2026-09-18-bootstrap-structured-runtime-logging.md index d4b80fa6..72ddaaf3 100644 --- a/docs/superpowers/specs/2026-09-18-bootstrap-structured-runtime-logging.md +++ b/docs/design/2026-09-18-bootstrap-structured-runtime-logging.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: app-bootstrap에 남은 비구조 운영 로그를 구조화하는 작은 설계다. +- 현재 정본: `docs/observability/log-fields.md` + + # Bootstrap Structured Runtime Logging ## Goal diff --git a/docs/superpowers/specs/2026-09-18-configuration-namespace-disposition.md b/docs/design/2026-09-18-configuration-namespace-disposition.md similarity index 83% rename from docs/superpowers/specs/2026-09-18-configuration-namespace-disposition.md rename to docs/design/2026-09-18-configuration-namespace-disposition.md index bf5ef95a..8ed316ea 100644 --- a/docs/superpowers/specs/2026-09-18-configuration-namespace-disposition.md +++ b/docs/design/2026-09-18-configuration-namespace-disposition.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: 설정 이름공간을 어디에 둘지 정리한 처분 기록이다. +- 현재 정본: `docs/registries/env-keys.yaml` + + BOOT-001 disposition ==================== diff --git a/docs/superpowers/specs/2026-09-18-deployment-composition-reachability-remediation.md b/docs/design/2026-09-18-deployment-composition-reachability-remediation.md similarity index 96% rename from docs/superpowers/specs/2026-09-18-deployment-composition-reachability-remediation.md rename to docs/design/2026-09-18-deployment-composition-reachability-remediation.md index f1d86c11..a8e92fda 100644 --- a/docs/superpowers/specs/2026-09-18-deployment-composition-reachability-remediation.md +++ b/docs/design/2026-09-18-deployment-composition-reachability-remediation.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: 배포 조립에서 닿지 않던 구성 요소를 고치는 설계다. +- 현재 정본: `docs/capability-status.md` + + # Deployment Composition Reachability Remediation ## Goal diff --git a/docs/superpowers/specs/2026-09-18-httpclient-capability-composition-ownership.md b/docs/design/2026-09-18-httpclient-capability-composition-ownership.md similarity index 83% rename from docs/superpowers/specs/2026-09-18-httpclient-capability-composition-ownership.md rename to docs/design/2026-09-18-httpclient-capability-composition-ownership.md index 233eb2c7..9706f444 100644 --- a/docs/superpowers/specs/2026-09-18-httpclient-capability-composition-ownership.md +++ b/docs/design/2026-09-18-httpclient-capability-composition-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: HTTP client 조립을 app-bootstrap에서 그 capability leaf로 옮기는 설계다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + # HTTP Client Capability Composition Ownership ## Goal diff --git a/docs/superpowers/specs/2026-09-18-jpa-capability-composition-ownership.md b/docs/design/2026-09-18-jpa-capability-composition-ownership.md similarity index 87% rename from docs/superpowers/specs/2026-09-18-jpa-capability-composition-ownership.md rename to docs/design/2026-09-18-jpa-capability-composition-ownership.md index 5d31943a..0842c8bc 100644 --- a/docs/superpowers/specs/2026-09-18-jpa-capability-composition-ownership.md +++ b/docs/design/2026-09-18-jpa-capability-composition-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: 관계형 영속성 조립을 app-bootstrap에서 persistence-jpa로 옮기는 설계다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA Capability Composition Ownership ## Goal diff --git a/docs/superpowers/specs/2026-09-18-jpa-runtime-master-switch.md b/docs/design/2026-09-18-jpa-runtime-master-switch.md similarity index 81% rename from docs/superpowers/specs/2026-09-18-jpa-runtime-master-switch.md rename to docs/design/2026-09-18-jpa-runtime-master-switch.md index d7f8062a..de89b53b 100644 --- a/docs/superpowers/specs/2026-09-18-jpa-runtime-master-switch.md +++ b/docs/design/2026-09-18-jpa-runtime-master-switch.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: JPA 조립 후보 둘이 같은 스위치를 따르게 하는 설계다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA Runtime Master Switch ## Problem diff --git a/docs/superpowers/specs/2026-09-18-messaging-platform-bridge-design.md b/docs/design/2026-09-18-messaging-platform-bridge-design.md similarity index 90% rename from docs/superpowers/specs/2026-09-18-messaging-platform-bridge-design.md rename to docs/design/2026-09-18-messaging-platform-bridge-design.md index 7db72d14..52051b27 100644 --- a/docs/superpowers/specs/2026-09-18-messaging-platform-bridge-design.md +++ b/docs/design/2026-09-18-messaging-platform-bridge-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: 애플리케이션 전용 브로커 이음매를 메시징 플랫폼으로 가는 bridge 하나로 바꾸는 설계다. +- 현재 정본: `docs/messaging/support-matrix.md` + + # Messaging Platform Bridge Design ## Goal diff --git a/docs/superpowers/specs/2026-09-18-mongo-health-composition-ownership.md b/docs/design/2026-09-18-mongo-health-composition-ownership.md similarity index 82% rename from docs/superpowers/specs/2026-09-18-mongo-health-composition-ownership.md rename to docs/design/2026-09-18-mongo-health-composition-ownership.md index 19b4d0e4..059cf9ca 100644 --- a/docs/superpowers/specs/2026-09-18-mongo-health-composition-ownership.md +++ b/docs/design/2026-09-18-mongo-health-composition-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: Mongo health 조립을 persistence-mongo leaf로 옮기는 설계다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + # Mongo Health Composition Ownership ## Goal diff --git a/docs/superpowers/specs/2026-09-18-notification-capability-composition-ownership.md b/docs/design/2026-09-18-notification-capability-composition-ownership.md similarity index 86% rename from docs/superpowers/specs/2026-09-18-notification-capability-composition-ownership.md rename to docs/design/2026-09-18-notification-capability-composition-ownership.md index 6e390448..522ea5cf 100644 --- a/docs/superpowers/specs/2026-09-18-notification-capability-composition-ownership.md +++ b/docs/design/2026-09-18-notification-capability-composition-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: 알림 provider·런타임 조립을 app-bootstrap에서 알림 capability로 옮기는 설계다. +- 현재 정본: `docs/notification/support-matrix.md` + + # Notification Capability Composition Ownership ## Goal diff --git a/docs/superpowers/specs/2026-09-18-outbox-transport-only-cutover-design.md b/docs/design/2026-09-18-outbox-transport-only-cutover-design.md similarity index 94% rename from docs/superpowers/specs/2026-09-18-outbox-transport-only-cutover-design.md rename to docs/design/2026-09-18-outbox-transport-only-cutover-design.md index 4e7b41cc..4bf0c391 100644 --- a/docs/superpowers/specs/2026-09-18-outbox-transport-only-cutover-design.md +++ b/docs/design/2026-09-18-outbox-transport-only-cutover-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-09-18 +- 요약: 기존 outbox 저장소는 두고 발행 전송만 메시징 플랫폼으로 넘기는 설계다. +- 현재 정본: `src/composition/outbox-relay/README.md` + + # Outbox Transport-Only Cutover Design ## Status diff --git a/docs/superpowers/specs/2026-09-18-outbox-v2-canonical-storage-alignment.md b/docs/design/2026-09-18-outbox-v2-canonical-storage-alignment.md similarity index 94% rename from docs/superpowers/specs/2026-09-18-outbox-v2-canonical-storage-alignment.md rename to docs/design/2026-09-18-outbox-v2-canonical-storage-alignment.md index 0e4131d7..381e47dc 100644 --- a/docs/superpowers/specs/2026-09-18-outbox-v2-canonical-storage-alignment.md +++ b/docs/design/2026-09-18-outbox-v2-canonical-storage-alignment.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 폐기 +- 작성일: 2026-09-18 +- 요약: outbox V2 저장소를 canonical 이벤트에 맞추는 설계다. V2 세대는 2026-09-25에 지웠다. +- 현재 정본: `docs/capability-status.md` + + # Outbox V2 Canonical Storage Alignment ## Status diff --git a/docs/superpowers/specs/2026-09-18-outbox-v2-one-record-publication-policy.md b/docs/design/2026-09-18-outbox-v2-one-record-publication-policy.md similarity index 88% rename from docs/superpowers/specs/2026-09-18-outbox-v2-one-record-publication-policy.md rename to docs/design/2026-09-18-outbox-v2-one-record-publication-policy.md index 3a440a78..7fd1e415 100644 --- a/docs/superpowers/specs/2026-09-18-outbox-v2-one-record-publication-policy.md +++ b/docs/design/2026-09-18-outbox-v2-one-record-publication-policy.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 폐기 +- 작성일: 2026-09-18 +- 요약: outbox V2에서 기록 하나를 한 번 발행하는 정책 설계다. V2 세대는 2026-09-25에 지웠다. +- 현재 정본: `docs/capability-status.md` + + # Outbox V2 One-Record Publication Policy ## Status diff --git a/docs/superpowers/specs/2026-09-18-postgresql-idempotency-composition-ownership.md b/docs/design/2026-09-18-postgresql-idempotency-composition-ownership.md similarity index 82% rename from docs/superpowers/specs/2026-09-18-postgresql-idempotency-composition-ownership.md rename to docs/design/2026-09-18-postgresql-idempotency-composition-ownership.md index 57d10f20..1c686ba0 100644 --- a/docs/superpowers/specs/2026-09-18-postgresql-idempotency-composition-ownership.md +++ b/docs/design/2026-09-18-postgresql-idempotency-composition-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: PostgreSQL 멱등성 저장소 조립을 app-bootstrap에서 persistence-jpa로 옮기는 설계다. +- 현재 정본: `src/composition/idempotency/README.md` + + # PostgreSQL Idempotency Composition Ownership ## Goal diff --git a/docs/superpowers/specs/2026-09-18-runtime-environment-tracing-ssot.md b/docs/design/2026-09-18-runtime-environment-tracing-ssot.md similarity index 86% rename from docs/superpowers/specs/2026-09-18-runtime-environment-tracing-ssot.md rename to docs/design/2026-09-18-runtime-environment-tracing-ssot.md index bf8e0b32..19d65ed3 100644 --- a/docs/superpowers/specs/2026-09-18-runtime-environment-tracing-ssot.md +++ b/docs/design/2026-09-18-runtime-environment-tracing-ssot.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: tracing과 capability 검증이 런타임 profile 어휘 하나를 쓰게 하는 설계다. +- 현재 정본: `src/app-bootstrap/README.md` + + # Runtime Environment and Tracing SSOT ## Goal diff --git a/docs/superpowers/specs/2026-09-18-secret-source-port-ownership.md b/docs/design/2026-09-18-secret-source-port-ownership.md similarity index 85% rename from docs/superpowers/specs/2026-09-18-secret-source-port-ownership.md rename to docs/design/2026-09-18-secret-source-port-ownership.md index 78a72696..510578d7 100644 --- a/docs/superpowers/specs/2026-09-18-secret-source-port-ownership.md +++ b/docs/design/2026-09-18-secret-source-port-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: 시크릿 출처 포트를 application이 소유하고 구현을 adapter로 옮기는 설계다. +- 현재 정본: `docs/registries/env-keys.yaml` + + # Secret Source Port Ownership ## Goal diff --git a/docs/superpowers/specs/2026-09-18-startup-failure-log-context-state.md b/docs/design/2026-09-18-startup-failure-log-context-state.md similarity index 81% rename from docs/superpowers/specs/2026-09-18-startup-failure-log-context-state.md rename to docs/design/2026-09-18-startup-failure-log-context-state.md index 5c75371d..957fd089 100644 --- a/docs/superpowers/specs/2026-09-18-startup-failure-log-context-state.md +++ b/docs/design/2026-09-18-startup-failure-log-context-state.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: 기동 실패 로그 상태를 프로세스 전역이 아닌 logger context에 두는 설계다. +- 현재 정본: `docs/observability/log-fields.md` + + # Startup Failure Log Context State ## Goal diff --git a/docs/superpowers/specs/2026-09-18-test-architecture-phase2-provider-ownership.md b/docs/design/2026-09-18-test-architecture-phase2-provider-ownership.md similarity index 88% rename from docs/superpowers/specs/2026-09-18-test-architecture-phase2-provider-ownership.md rename to docs/design/2026-09-18-test-architecture-phase2-provider-ownership.md index 682fa981..f6094075 100644 --- a/docs/superpowers/specs/2026-09-18-test-architecture-phase2-provider-ownership.md +++ b/docs/design/2026-09-18-test-architecture-phase2-provider-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: provider 증거 테스트의 소유 leaf를 정리하는 테스트 구조 2단계 설계다. +- 현재 정본: `docs/testing/TESTING_STRATEGY.md` + + # Test Architecture Phase 2 — Provider Ownership ## Goal diff --git a/docs/superpowers/specs/2026-09-18-test-taxonomy-ssot-alignment.md b/docs/design/2026-09-18-test-taxonomy-ssot-alignment.md similarity index 87% rename from docs/superpowers/specs/2026-09-18-test-taxonomy-ssot-alignment.md rename to docs/design/2026-09-18-test-taxonomy-ssot-alignment.md index 767e4a17..e30c4669 100644 --- a/docs/superpowers/specs/2026-09-18-test-taxonomy-ssot-alignment.md +++ b/docs/design/2026-09-18-test-taxonomy-ssot-alignment.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: 테스트 전략 문서를 테스트 분류 정본에 맞추는 설계다. +- 현재 정본: `docs/testing/TESTING_STRATEGY.md` + + # Test Taxonomy SSOT Alignment ## Goal diff --git a/docs/superpowers/specs/2026-09-19-build-release-review-remediation-design.md b/docs/design/2026-09-19-build-release-review-remediation-design.md similarity index 80% rename from docs/superpowers/specs/2026-09-19-build-release-review-remediation-design.md rename to docs/design/2026-09-19-build-release-review-remediation-design.md index 66a85a6e..09d1dd23 100644 --- a/docs/superpowers/specs/2026-09-19-build-release-review-remediation-design.md +++ b/docs/design/2026-09-19-build-release-review-remediation-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-19 +- 요약: 빌드·CI 리뷰가 찾은 조립 결함을 고치는 설계다. +- 현재 정본: `docs/work/reference/gates.md` + + # Build / Release Review Remediation Design ## Source diff --git a/docs/superpowers/specs/2026-09-19-capability-dependency-validation-context.md b/docs/design/2026-09-19-capability-dependency-validation-context.md similarity index 86% rename from docs/superpowers/specs/2026-09-19-capability-dependency-validation-context.md rename to docs/design/2026-09-19-capability-dependency-validation-context.md index 0c7e80d6..bb5877fd 100644 --- a/docs/superpowers/specs/2026-09-19-capability-dependency-validation-context.md +++ b/docs/design/2026-09-19-capability-dependency-validation-context.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 폐기 +- 작성일: 2026-09-19 +- 요약: capability 의존 검증을 StartupValidationContext로 옮기는 설계다. capability 의존 검증기는 2026-09-25에 지웠다. +- 현재 정본: `docs/capability-status.md` + + # Capability Dependency Validation Context ## Goal diff --git a/docs/superpowers/specs/2026-09-19-env-contract-verifier-truth-surface.md b/docs/design/2026-09-19-env-contract-verifier-truth-surface.md similarity index 89% rename from docs/superpowers/specs/2026-09-19-env-contract-verifier-truth-surface.md rename to docs/design/2026-09-19-env-contract-verifier-truth-surface.md index 1496ceee..aecc69f2 100644 --- a/docs/superpowers/specs/2026-09-19-env-contract-verifier-truth-surface.md +++ b/docs/design/2026-09-19-env-contract-verifier-truth-surface.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-19 +- 요약: env 키 검사가 선언과 실제 사용을 구분하게 하는 설계다. +- 현재 정본: `docs/registries/env-keys.yaml` + + # Env Contract Verifier Truth Surface ## Goal diff --git a/docs/superpowers/specs/2026-09-19-fileserver-composition-decomposition.md b/docs/design/2026-09-19-fileserver-composition-decomposition.md similarity index 91% rename from docs/superpowers/specs/2026-09-19-fileserver-composition-decomposition.md rename to docs/design/2026-09-19-fileserver-composition-decomposition.md index 0064b703..9ac265b4 100644 --- a/docs/superpowers/specs/2026-09-19-fileserver-composition-decomposition.md +++ b/docs/design/2026-09-19-fileserver-composition-decomposition.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-19 +- 요약: 파일 서버 조립을 관심사별 설정 다섯 개로 나누는 설계다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver Composition Decomposition ## Goal diff --git a/docs/superpowers/specs/2026-09-19-fileserver-verification-read-failure-remediation.md b/docs/design/2026-09-19-fileserver-verification-read-failure-remediation.md similarity index 81% rename from docs/superpowers/specs/2026-09-19-fileserver-verification-read-failure-remediation.md rename to docs/design/2026-09-19-fileserver-verification-read-failure-remediation.md index e7945cb7..c20b4d3f 100644 --- a/docs/superpowers/specs/2026-09-19-fileserver-verification-read-failure-remediation.md +++ b/docs/design/2026-09-19-fileserver-verification-read-failure-remediation.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-19 +- 요약: 파일 검증이 읽기 실패를 빈 내용으로 오인하지 않게 고치는 설계다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver Verification Read Failure Remediation ## Source diff --git a/docs/superpowers/specs/2026-09-19-mongo-client-runtime-review-remediation.md b/docs/design/2026-09-19-mongo-client-runtime-review-remediation.md similarity index 90% rename from docs/superpowers/specs/2026-09-19-mongo-client-runtime-review-remediation.md rename to docs/design/2026-09-19-mongo-client-runtime-review-remediation.md index 5bfcf0ea..1d7f68d4 100644 --- a/docs/superpowers/specs/2026-09-19-mongo-client-runtime-review-remediation.md +++ b/docs/design/2026-09-19-mongo-client-runtime-review-remediation.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-19 +- 요약: Mongo client 런타임 리뷰의 Critical 둘을 고치는 설계다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + # Mongo Client Runtime Review Remediation ## Source diff --git a/docs/superpowers/specs/2026-09-19-multi-instance-runtime-contract.md b/docs/design/2026-09-19-multi-instance-runtime-contract.md similarity index 88% rename from docs/superpowers/specs/2026-09-19-multi-instance-runtime-contract.md rename to docs/design/2026-09-19-multi-instance-runtime-contract.md index 6299c006..8dce6bf9 100644 --- a/docs/superpowers/specs/2026-09-19-multi-instance-runtime-contract.md +++ b/docs/design/2026-09-19-multi-instance-runtime-contract.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-19 +- 요약: 가짜 조정 bean 없이 다중 인스턴스 런타임 계약을 세우는 설계다. +- 현재 정본: `src/app-bootstrap/README.md` + + # Multi-instance Runtime Contract ## Goal diff --git a/docs/superpowers/specs/2026-09-19-prod-secret-consumer-alignment.md b/docs/design/2026-09-19-prod-secret-consumer-alignment.md similarity index 84% rename from docs/superpowers/specs/2026-09-19-prod-secret-consumer-alignment.md rename to docs/design/2026-09-19-prod-secret-consumer-alignment.md index a88b9183..28d2830d 100644 --- a/docs/superpowers/specs/2026-09-19-prod-secret-consumer-alignment.md +++ b/docs/design/2026-09-19-prod-secret-consumer-alignment.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-19 +- 요약: 운영 기동이 실제로 쓰는 시크릿만 요구하게 맞추는 설계다. +- 현재 정본: `docs/registries/env-keys.yaml` + + # Prod Secret Consumer Alignment ## Goal diff --git a/docs/superpowers/specs/2026-09-19-runtime-profile-access-boundary.md b/docs/design/2026-09-19-runtime-profile-access-boundary.md similarity index 82% rename from docs/superpowers/specs/2026-09-19-runtime-profile-access-boundary.md rename to docs/design/2026-09-19-runtime-profile-access-boundary.md index 8c894318..64c1a780 100644 --- a/docs/superpowers/specs/2026-09-19-runtime-profile-access-boundary.md +++ b/docs/design/2026-09-19-runtime-profile-access-boundary.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-19 +- 요약: 운영 코드가 Spring active profile을 직접 읽지 않게 하는 경계 설계다. +- 현재 정본: `src/app-bootstrap/README.md` + + # Runtime Profile Access Boundary ## Goal diff --git a/docs/superpowers/specs/2026-09-19-startup-order-contract.md b/docs/design/2026-09-19-startup-order-contract.md similarity index 80% rename from docs/superpowers/specs/2026-09-19-startup-order-contract.md rename to docs/design/2026-09-19-startup-order-contract.md index 7c87a89f..bb478264 100644 --- a/docs/superpowers/specs/2026-09-19-startup-order-contract.md +++ b/docs/design/2026-09-19-startup-order-contract.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-19 +- 요약: 기동 순서를 실행 가능한 계약 테스트로 고정하는 설계다. +- 현재 정본: `src/app-bootstrap/README.md` + + # Startup Order Contract ## Goal diff --git a/docs/superpowers/specs/2026-09-19-test-support-ownership-closure.md b/docs/design/2026-09-19-test-support-ownership-closure.md similarity index 79% rename from docs/superpowers/specs/2026-09-19-test-support-ownership-closure.md rename to docs/design/2026-09-19-test-support-ownership-closure.md index 0c7b7a63..e0032e8d 100644 --- a/docs/superpowers/specs/2026-09-19-test-support-ownership-closure.md +++ b/docs/design/2026-09-19-test-support-ownership-closure.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-19 +- 요약: 공유 테스트 지원 코드의 소유 위치를 마무리하는 설계다. +- 현재 정본: `docs/testing/TESTING_STRATEGY.md` + + # Test Support Ownership Closure ## Goal diff --git a/docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md b/docs/design/2026-09-25-capability-module-packaging-design.md similarity index 95% rename from docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md rename to docs/design/2026-09-25-capability-module-packaging-design.md index bb7e8833..01e50d49 100644 --- a/docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md +++ b/docs/design/2026-09-25-capability-module-packaging-design.md @@ -1,3 +1,12 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-09-25 +- 요약: 부가 기능을 붙이면 켜지고 떼면 사라지는 capability 모듈로 바꾸고 기본 조립을 web으로 줄인 설계다. +- 현재 정본: `docs/capability-status.md` + + # 부가 기능(capability) 제공 방식과 리뷰 후속 정리 — 설계 초안 - 상태: **확정** (2026-09-25 소유자 결정 2건 반영 — 10절). 실행 계획: `docs/superpowers/plans/2026-09-25-capability-module-packaging.md` diff --git a/docs/design/2026-11-06-error-code-log-level-design.md b/docs/design/2026-11-06-error-code-log-level-design.md new file mode 100644 index 00000000..33b909c4 --- /dev/null +++ b/docs/design/2026-11-06-error-code-log-level-design.md @@ -0,0 +1,254 @@ + +> **기록 · 설계서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-11-06 +- 요약: 오류 코드 레지스트리에 log_level 칸을 두지 않고 실패 종류·경로가 레벨을 정하게 한 설계 메모다. +- 현재 정본: `docs/registries/error-codes.yaml` + + +# `error-codes.yaml`의 `log_level` 칸 — 설계 메모 + +- 상태: **확정** (2026-11-06, 소유자 답 "권하는 안대로"). 결정은 10절이다. 아래 1~9절은 결정 전에 쓴 그대로 둔다. +- 기준 커밋: `06f520e6` (`refactor/maturity-review-2026-11`) +- 크기: 중간(brief). 이 메모가 고르는 안을 실제로 적용하는 일은 **큼**이다. 오류 코드 레지스트리는 공개 계약이라 + 파일 하나여도 큼이다(`docs/work/README.md` 2절). 그래서 이 메모는 대안 비교까지 하고 멈춘다. 코드와 yaml은 + 바꾸지 않았다. +- 요청(총괄 brief 원문): "`docs/registries/error-codes.yaml`의 `log_level` 칸은 읽는 코드가 없고, 값이 코드와 다른 + 곳이 있다(`IDEMPOTENCY_UNAVAILABLE`: 문서 WARN, 코드 ERROR). 이 칸을 어떻게 할지 설계 메모를 쓰고 소유자 결정을 + 묻는다." +- 처음 나온 곳: 재리뷰 round6이 "규범인지 판단하지 않았다"로 남긴 항목 + (`docs/reviews/2026-11-03-rereview/round6/02-idempotency-outbound.md:217`). + +## 1. 결론 + +권하는 안은 **A — 칸을 지운다**이다. 로그 레벨은 오류 코드 하나가 아니라 실패의 종류와 경로가 정하고, 그 규칙은 +이미 코드 한 곳(`ServerFailureLog`)에 있다. 레지스트리 머리말은 그 규칙을 가리키기만 한다. 칸 값을 증상으로 적은 +런북 2곳은 실제 로그 줄로 고친다. + +칸과 별개로 동작 질문이 둘 남는다. 보안 필터가 5xx 두 코드를 WARN으로 남기는 것(결정 2), 문서가 ERROR로 의도한 401 +세 코드(결정 3)다. + +## 2. 지금 어떻게 되어 있나 + +### 2.1 칸을 읽는 곳 + +- 스키마: `docs/registries/error-codes.yaml:18` `log_level: ERROR | WARN | INFO`. 60행 모두 값이 있다(ERROR 25, + WARN 26, INFO 9). +- 코드와 테스트: 읽는 곳이 없다. `src`·`scripts`의 java·py·gradle·sh에서 `log_level`·`logLevel` 검색 결과 0건이다. +- 테스트가 읽는 칸: `category`·`http_status`·`retryable`·`client_safe_message`·`runbook_link`·`owner_branch`· + `compatibility_impact`·`required_test`다(테스트 코드의 `get("<칸>")` 집계). `log_level`과 `owner_layer`만 + 아무도 읽지 않는다. +- 스키마 검사(`ContractRegistrySchemaGovernanceTest`, `RegistryGovernanceCatalog.java:217, 247-253`)는 필수 칸만 본다. + 모르는 칸을 막지 않는다. +- 값의 이력: `git log -S log_level`의 네 커밋(`821fe00c`, `9da00eb7`, `c4a066df`, `bbe944bd`)은 행을 넣거나 뺐다. + 있던 행의 레벨 값이 바뀐 적은 없다(커밋 사이 코드별 값 비교 결과 차이 0). +- 런북: 두 곳이 칸 값을 증상으로 적는다. + - `docs/runbooks/auth-token-invalid-signature.md:16`: "`log_level=ERROR` — may indicate forged tokens" + - `docs/runbooks/authz-tenant-mismatch.md:16`: "`log_level=ERROR`" +- 경보: `docs/registries/metrics.yaml`의 경보 기준은 모두 지표다(error_rate, p99 등). 로그 레벨을 세는 경보는 없다 + (`logback_events`·`level=error` 검색 0건). +- 파생 서비스 `tech-log-backend`(`a000f87`): 자기 `error-codes.yaml` 96행에 `log_level`을 채운다. 설계서가 새 행마다 + 이 칸을 채우라고 적는다(`docs/superpowers/specs/2026-08-18-techlog-studio-backend-design.md:382`). 그쪽에도 이 + 칸을 읽는 코드는 없다(`git grep log_level`, java·gradle·yaml·sh 0건). + +### 2.2 코드가 로그 레벨을 정하는 방식 + +레벨은 오류 코드가 아니라 **실패의 종류와 경로**가 정한다. + +```text +요청 실패 ─┬─ 보안 필터(401·403·JWKS·인증 설정) ─ AuthErrorResponseWriter ─────────── 늘 WARN + ├─ IllegalArgumentException ─────────── ServerFailureLog.refusedArgument ─── WARN + ├─ ApiErrorCarrier ─ ServerFailureLog.of ─┬─ PersistenceFailureException ── ERROR (상태 무관) + │ ├─ DependencyFailureException ── ERROR (상태 무관) + │ ├─ 그 밖의 5xx ───────────────── ERROR + │ └─ 4xx ───────────────────────── 남기지 않음 + ├─ Spring MVC 예외 ─ handleExceptionInternal ── 5xx면 ERROR, 4xx면 남기지 않음 + └─ 그 밖의 예외 ─ handleUnknown ── INTERNAL_ERROR로 답하고 ERROR +배경 작업 ─ outbox 실패 보고, executor 거절 ── ERROR +``` + +출처: + +- 규칙: `src/shared-contract/src/main/java/dev/caskeleton/shared/error/ServerFailureLog.java:54-79`. + 4xx를 남기지 않는 이유는 같은 파일 25행 "A client-side carrier is not logged: it is an answer, not an incident"다. + IAE WARN은 91-96행이다. +- 네 전송이 같은 줄을 쓴다. + - carrier ERROR: web `GlobalExceptionHandler.java:173-176`, gRPC `GrpcExceptionHandlingInterceptor.java:135-136`, + GraphQL `GraphQlWireErrorMapper.java:134-135`, STOMP `StompHandlerFailureLog.java:35-36` + - IAE WARN: web `GlobalExceptionHandler.java:96-97`, gRPC `:139-140`, GraphQL `:137-138`, STOMP `:40-41` +- 보안 필터: `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java:32` + `log.warn("security failure: code={} …")`. 인증 진입점과 접근 거부 처리기가 둘 다 이 writer를 쓴다. +- Spring MVC: `GlobalExceptionHandler.java:397-401`. 그 밖의 예외: 같은 파일 195-203행. +- 배경 작업: `Slf4jOutboxRelayFailureReportAdapter.java`의 `atError()`, `LoggingAbortPolicy.java:35`. +- 이 규칙은 리뷰를 거쳐 정한 설계다. 네 전송이 한 정책을 쓰게 했고(`ServerFailureLog` Javadoc 첫 문단), IAE를 네 + 전송에서 같은 WARN 한 줄로 남기게 했다(RR6-01-06, `docs/reviews/2026-11-03-rereview/README.md` 17절 r10-01). + +그래서 레벨은 오류 코드 하나에 값 하나로 떨어지지 않는다. + +- 같은 `BAD_PARAMETER`라도 IAE에서 오면 WARN이다. 타입 변환 실패에서 오면 남기지 않는다 + (`GlobalExceptionHandler.java:108-116`). +- 같은 409라도 영속성 실패면 ERROR다. 멱등 in-flight면 남기지 않는다. + +### 2.3 60행 대조 + +방법: 행마다 main 코드에서 그 코드를 내는 곳을 찾았다(`grep -rlw src --include='*.java'` 중 `/main/`). 그 경로에 +2.2의 규칙을 대어 레벨을 정했다. 코드를 읽은 결과이고, 실행 탐침은 돌리지 않았다(이유는 6절 가정 4). + +| 결과 | 행 | 코드 | +| --- | --- | --- | +| 같다 | 14 | WARN: `AUTH_TOKEN_MISSING`, `AUTH_TOKEN_MALFORMED`, `AUTH_TOKEN_EXPIRED`, `AUTH_KID_UNKNOWN`. ERROR: `DB_UNAVAILABLE`, `DB_IDLE_IN_TX_TIMEOUT`, `DB_COMPLETION_UNKNOWN`, `IDEMPOTENCY_COMPLETION_UNKNOWN`, `IDEMPOTENCY_RECOVERY_REQUIRED`, `ADAPTER_DISABLED`, `INTERNAL_ERROR`, `OUTBOX_PUBLISH_FAILED`, `OUTBOX_DEAD_LETTER`, `JOB_EXECUTOR_REJECTED` | +| 문서 ERROR, 코드 WARN | 5 | `AUTH_TOKEN_INVALID_SIGNATURE`, `AUTH_ISSUER_MISMATCH`, `AUTH_AUDIENCE_MISMATCH`(401), `AUTH_JWKS_UNAVAILABLE`(503), `INTERNAL_AUTH_MISCONFIGURATION`(500). 보안 필터가 모두 WARN으로 남긴다 | +| 문서 WARN, 코드 ERROR | 10 | `IDEMPOTENCY_UNAVAILABLE`(503 carrier). 영속성 실패 9개: `DB_SERIALIZATION_FAILURE`, `DB_DEADLOCK`, `DB_NULL_VIOLATION`, `DB_FK_VIOLATION`, `DB_UNIQUE_VIOLATION`, `DB_CHECK_VIOLATION`, `DB_OPTIMISTIC_CONFLICT`, `DB_LOCK_TIMEOUT`(409), `DB_QUERY_CANCELED`(503). JPA 예외는 모두 `PersistenceFailureException`의 하위 타입이다(`JpaPersistenceException.java:22`) | +| 문서는 레벨, 코드는 남기지 않음 | 15 | `IDEMPOTENT_IN_FLIGHT`, `IDEMPOTENT_REQUEST_MISMATCH`, `MAPPING_FAILED`, `VALIDATION_FAILED`, `PRECONDITION_FAILED`, `METHOD_NOT_ALLOWED`, `NOT_ACCEPTABLE`, `PAYLOAD_TOO_LARGE`, `URI_TOO_LONG`, `UNSUPPORTED_MEDIA_TYPE`, `ROUTE_NOT_FOUND`, `RATE_LIMIT_EXCEEDED`, `INVALID_TOKEN`, `FORBIDDEN`, `BATCH_PARTIAL_FAILURE` | +| 경로마다 다름 | 3 | `BAD_PARAMETER`(문서 INFO; IAE면 WARN, 타입 변환이면 없음). `AUTHZ_INSUFFICIENT_PERMISSION`(문서 WARN; 필터면 WARN, controller method security면 `handleForbidden`이라 없음). `UNAUTHENTICATED`(문서 WARN; web은 없음, gRPC는 인증 정책이 예외를 던질 때만 WARN — `GrpcAuthenticationInterceptor.java:55`) | +| 템플릿 main에 내는 곳 없음 | 13 | `AUTH_CLAIM_MAPPING_FAILED`, `AUTHZ_TENANT_MISMATCH`, `JVM_OOM`, `DEPENDENCY_TIMEOUT`, `DEPENDENCY_CONNECT_FAILED`, `DEPENDENCY_DNS_FAILED`, `DEPENDENCY_4XX_CLIENT`, `DEPENDENCY_5XX_SERVER`, `DEPENDENCY_CIRCUIT_OPEN`, `JOB_TIMEOUT`, `JOB_DEAD_LETTER`, `ACTUATOR_FORBIDDEN`, `LOCK_ACQUISITION_TIMEOUT` | + +- 내는 곳이 있는 47행 중 33행이 문서와 다르다. brief가 든 `IDEMPOTENCY_UNAVAILABLE`은 그중 하나다. +- `DEPENDENCY_*`: 파생 서비스의 어댑터가 `DependencyFailureException`으로 던지면 ERROR가 된다. 그때는 문서가 WARN인 + `DEPENDENCY_CIRCUIT_OPEN`도 어긋난다. +- `LOCK_ACQUISITION_TIMEOUT`은 레벨과 별개의 문제가 있다(9절). + +### 2.4 어긋남이 실제로 해를 끼치는 곳 + +- **런북 증상이 틀렸다.** `auth-token-invalid-signature.md`는 `log_level=ERROR`를 증상으로 적는다. 실제 줄은 + WARN `security failure: code=AUTH_TOKEN_INVALID_SIGNATURE …`다. ERROR로 거르는 운영자는 이 사건을 못 본다. +- **칸을 채우는 일이 헛수고다.** 새 코드를 만드는 사람이 칸을 채워도 동작이 바뀌지 않는다. 파생 서비스는 96행에 + 값을 골라 적었다. +- 경보는 로그 레벨을 쓰지 않는다. 그래서 이 어긋남으로 경보가 빠지지는 않는다. + +## 3. 선행 사례 + +| 출처 | 1차/2차 | 그들이 한 것 | 한계 | 가져올 것 | +| --- | --- | --- | --- | --- | +| 이 repo `client_safe_message` 칸 (`c4a066df`, 소유자 결정 11) | 1차 | 행마다 다르던 문구를 Category별 문구 표 하나(`ClientErrorMessages`)로 코드에 두었다. 칸은 그 값과 같아야 한다고 테스트로 고정했다(`OperationalErrorRegistryContractTest.everyRegistryClientMessageIsTheSharedCategoryMessage`) | 문구가 category만으로 정해져서 고정이 쉬웠다 | 코드가 원본이고 칸은 테스트가 고정한다. 레벨은 코드 하나로 정해지지 않는다는 점이 다르다(2.2) | +| 이 repo `category`·`http_status`·`retryable` | 1차 | enum이 원본이다. yaml을 enum과 테스트로 대조한다(`theEnumAndTheRegistryAgree`) | — | 레지스트리 칸은 코드가 읽거나 테스트가 고정한다는 이 repo의 관행 | +| 이 repo `env-keys.yaml`의 `required_when` (`0a6dd0e4`) | 1차 | 런타임이 강제한 적 없는 요구("app.redis.mode=sentinel")를 지우고 실제 동작에 맞췄다(`docs/registries/env-keys.yaml:2269-2273`) | — | 강제하지 않는 레지스트리 문장을 규범처럼 두지 않는다. 실제 동작으로 고친다 | +| JBoss Logging Tools (Hibernate·WildFly가 씀) | 1차, | 메시지 id와 레벨을 코드의 annotation 한 곳에 둔다(`@Message(id = …)`, `@LogMessage(level = ERROR)`). 보고서(id, 해결 문서 링크, 메시지, 레벨)는 annotation에서 만든다(AsciiDoc·XML) | 메시지마다 레벨이 하나인 모델이다. 경로마다 레벨이 다른 우리 설계에는 그대로 맞지 않는다 | 레벨을 문서로 보이고 싶으면 손으로 쓴 칸이 아니라 코드에서 뽑는다 | +| Spring Framework `AbstractHandlerExceptionResolver` | 1차, `spring-webmvc/src/main/java/org/springframework/web/servlet/handler/AbstractHandlerExceptionResolver.java`(main) | 예외 처리 로그는 처리기 코드가 정한다. 기본은 남기지 않고, `setWarnLogCategory`로 켜면 WARN 한 레벨로 남긴다 | 오류 코드별 레벨 표는 없다 | 처리된 클라이언트 오류는 기본으로 남기지 않는다. `ServerFailureLog`의 "4xx는 답이지 사건이 아니다"와 같은 판단이다 | + +## 4. 대안 + +### A. 칸을 지운다 + +- 머리말 스키마에서 `log_level` 줄을 뺀다. 대신 "로그 레벨은 오류 코드가 아니라 실패 종류와 경로가 정한다. 규칙은 + `ServerFailureLog` Javadoc과 `AuthErrorResponseWriter`"라고 적는다. +- 60행에서 `log_level:` 줄을 지운다. +- 런북 2곳의 증상 줄을 실제 로그 줄로 고친다. +- `docs/upgrade/`에 파생 서비스 안내를 한 줄 더한다. +- 선택(결정 1-b): 칸이 다시 생기지 않게 "행에 `log_level`이 없다"는 단언을 레지스트리 테스트에 둔다. 두면 파생 + 서비스도 자기 행에서 칸을 지워야 merge 뒤 테스트가 통과한다. + +### B. 칸을 남기고 코드에 맞춘 뒤 테스트로 고정한다 + +- 값 집합에 `NONE`(남기지 않음)과 `BY_PATH`(경로마다 다름)를 더한다. 60행을 2.3 표대로 고친다. +- 테스트는 `ServerFailureLog` 규칙을 다시 구현한 표(코드 → 기대 레벨)와 yaml을 대조한다. +- 문제: 레벨이 코드만으로 정해지지 않아서, 표가 규칙의 손 사본이 된다. 예외 종류(영속성·의존성 carrier)는 행에 + 없으므로, 테스트가 "`DB_*`면 ERROR"를 이름 접두어로 짐작해야 한다. 템플릿 main에 내는 곳이 없는 13행은 기대값을 + 정할 근거가 없다. + +### C. 칸을 규범으로 만들고 코드가 읽는다 + +- `ApiErrorCode`에 `logLevel()`을 더한다. `OperationalError`는 값을 갖고, 파생 enum은 default 메서드로 지금 규칙을 쓴다. +- 네 전송, 보안 필터, 배경 작업이 그 값으로 남긴다. yaml은 enum과 테스트로 대조한다. +- 동작이 바뀐다. 2.3의 33행이 지금과 다른 레벨이 된다. + - 문서가 INFO·WARN인 4xx 15행이 새로 로그를 남긴다. 404·400·429마다 한 줄씩이라, 스캐너·공격 트래픽이 로그 + 양을 정한다. + - 409 영속성 실패는 ERROR에서 WARN으로 내려간다. +- `ServerFailureLog`의 "4xx는 남기지 않는다"와 RR6-01-06 결정을 뒤집는다. 다시 열 조건(`docs/work/reference/decisions.md` + 1절)에 맞는 새 근거가 없다. +- `ApiErrorCode`는 shared-contract의 공개 인터페이스다. 파생 서비스의 enum이 영향을 받는다. + +### 버린 기준선: 주석만 달기 + +칸에 "참고용"이라 적고 `IDEMPOTENCY_UNAVAILABLE` 한 행만 고치는 안이다. 틀린 33행 중 1행만 고쳐지고 런북은 여전히 +틀린 증상을 적는다. 버린다. + +### 비교 + +| 대안 | 효과 | 비용 | 되돌리기 | 파생 서비스 영향 | 기존 결정과 충돌 | +| --- | --- | --- | --- | --- | --- | +| A 지움 | 틀린 값 33행과 틀린 런북 증상 2곳이 사라진다. 레벨의 원본이 코드 하나로 준다 | yaml 머리말·60줄, 런북 2곳, upgrade 1줄. 코드 변경 0 (1-b면 테스트 단언 1개) | 쉽다(revert) | 1-b 없으면 할 일 없음. 1-b면 자기 96행에서 칸을 지운다 | 없다. `client_safe_message`·`env-keys` 선례와 같은 방향 | +| B 맞추고 고정 | 칸이 맞는 값이 된다 | yaml 33행, 스키마, 새 테스트(규칙의 손 사본). 규칙을 바꿀 때마다 두 곳을 고친다 | 쉽다 | 같은 테스트가 파생 행도 읽으면 자기 행도 맞춰야 한다 | 없다. 다만 규칙 사본을 하나 더 만든다 | +| C 규범화 | 소유자가 코드마다 레벨을 고를 수 있다 | shared-contract 인터페이스, 전송 넷, 보안 필터, 배경 작업, 테스트. 로그 양이 는다 | 어렵다(공개 인터페이스, 운영 로그 모양) | `ApiErrorCode` 구현 enum, 로그 수집 규칙 | `ServerFailureLog` 설계, RR6-01-06 | + +## 5. 권하는 안: A + +- 이 칸이 담으려던 정보("이 코드가 얼마나 시끄러운가")는 코드가 이미 실패 종류로 정한다. 그 규칙은 리뷰를 거쳐 네 + 전송에 하나로 모였다. 코드별 칸은 그 규칙을 담을 모양이 아니다(2.2). +- B는 그 규칙의 손 사본을 테스트에 하나 더 만든다. 사본은 고칠 곳만 늘린다. 내는 곳이 없는 13행에는 고정할 값도 + 없다. +- C는 코드가 맞고 문서가 틀린 상황에서 코드를 문서에 맞춘다. 문서 값은 행을 처음 넣을 때 적은 뒤 한 번도 고친 적이 + 없다(2.1). 레벨을 따져 본 리뷰를 거친 쪽은 코드다. +- 이 repo의 관행은 "칸은 코드가 읽거나 테스트가 고정한다"이다. 이 관행에 맞는 길은 A와 B인데, B는 고정할 값이 + 없다. 그래서 A다. + +## 6. 반증할 수 있는 가정, 반론과 답 + +### 가정 + +1. **템플릿과 파생 서비스 밖에서 이 칸을 읽는 도구가 없다.** 틀렸다면: 로그 파이프라인이나 대시보드가 이 yaml을 + 읽고 있다면 칸 삭제가 그것을 깨뜨린다. 확인한 범위는 두 repo의 추적 파일이다. repo 밖 운영 도구는 모른다(결정 4). +2. **레벨은 오류 코드 하나로 정해지지 않는다.** 틀렸다면 B의 비용이 크게 준다. 확인: + `GlobalExceptionHandler.java:96-97`(IAE, WARN)과 `:108-116`(타입 변환, 로그 없음)가 같은 `BAD_PARAMETER`를 낸다. +3. **4xx를 남기지 않는 것은 의도다.** 틀렸다면, 즉 소유자가 4xx를 줄 단위로 추적하길 원하면 C가 맞다. 근거: + `ServerFailureLog.java:25`의 문장. 4xx 양은 `http.server.requests`의 `status=4xx` 지표로 이미 보인다 + (`metrics.yaml:18-40`). +4. **2.3 표는 코드 읽기로 충분하다.** 틀렸다면: 다른 경로가 같은 코드를 다른 레벨로 남기면 표 칸이 바뀐다. 결론 + ("대부분 다르다")은 33행 중 몇 행이 바뀌어도 유지된다. 탐침을 돌리지 않은 이유는 둘이다. + - 각 경로는 레벨을 바꾸는 분기가 없는 `log.error`/`log.warn` 한 줄이다. + - 기존 테스트가 같은 레벨을 고정한다: `GrpcExceptionHandlingInterceptorTest`·`StompHandlerFailureLogTest`· + `GraphQlWireErrorMapperTest`의 `Level.ERROR`/`Level.WARN` 단언, + `GlobalExceptionHandlerTest.anIllegalArgumentIsLoggedAtWarnByItsTypeWithoutItsMessage`. + +### 반론과 답 + +- **"레벨을 문서에서 한눈에 보는 가치가 있다."** 그 가치는 값이 맞을 때만 있다. 지금은 47행 중 33행이 틀렸다. + 꼭 보이고 싶다면 JBoss Logging처럼 코드에서 뽑아야 한다. 그것은 레벨이 코드별 값이 된 뒤(C)에나 가능하다. +- **"보안 쪽 ERROR(위조 토큰 의심)는 의도였다."** 의도는 런북 문장에 남아 있지만 구현된 적이 없다. 401 서명 실패를 + ERROR로 남기면 공격자가 ERROR 양을 정하게 된다. 감지가 필요하면 결정 3에서 따로 고른다. +- **"칸을 지우면 파생 서비스가 upstream merge 때 할 일이 생긴다."** 1-b를 두지 않으면 할 일이 없다. 1-b를 두면 + 지울 일이 생기지만, 같은 거짓 칸이 파생 서비스 96행에 남지 않는다. + +## 7. 소유자가 정할 것 + +| # | 항목 | 선택지 | 권하는 안과 이유 | 정할 사람 | +| --- | --- | --- | --- | --- | +| 1 | `log_level` 칸 | A 지움 / B 코드 규칙에 맞추고 테스트로 고정 / C 규범화(코드가 읽음) | **A**. 5절 | 소유자 | +| 1-b | A일 때 칸이 다시 생기는 것을 막는 단언 | 둔다(파생 서비스도 자기 행에서 지운다) / 두지 않는다 | **둔다**. 칸이 거짓인 것은 파생 서비스 행도 같다. upgrade 안내 "반드시 할 일"에 한 줄 | 소유자 | +| 2 | 보안 필터가 5xx 두 코드(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)를 WARN으로 남기는 것 | ERROR로 올림 / WARN 유지 | **ERROR로 올림**. 다른 모든 경로가 5xx를 ERROR로 남긴다. 둘 다 서버 쪽 고장(키 서버 장애, 설정 오류)이다. 1번과 관계없이 동작 변경이라 별도 개선 작업으로 한다 | 소유자 | +| 3 | 401 서명·issuer·audience 불일치(문서가 ERROR로 의도) | WARN 유지, 런북은 WARN 줄의 code로 찾게 고침 / ERROR로 올림 / WARN 유지 + 코드별 인증 실패 지표를 새로 둠 | **WARN 유지**. 클라이언트가 만드는 실패라 ERROR로 올리면 공격 트래픽이 ERROR 양을 정한다. 경보가 필요하면 세 번째 안이다. 지금은 코드별 인증 실패 지표가 없다(`metrics.yaml`) | 소유자 | +| 4 | repo 밖에서 이 칸을 읽는 도구 | 있음 / 없음 | **모름**. 두 repo의 추적 파일에는 없다. 있으면 A를 다시 본다 | 소유자 | + +## 8. 결정 뒤 할 일 (이 메모에서는 하지 않았다) + +- A를 고르면: `docs/registries/error-codes.yaml` 머리말과 60행, 런북 2곳, `docs/upgrade/` 안내 한 줄, (1-b면) + 레지스트리 테스트 단언. 공개 계약 변경이라 크기는 큼이고 `docs/work/improve.md`로 한다. 결정은 + `docs/work/reference/decisions.md`에 기록한다. +- 결정 2를 고르면: `AuthErrorResponseWriter`의 레벨 분기와 테스트(RED → GREEN). +- B나 C를 고르면 이 메모의 4절을 계획서로 옮겨 다시 크기를 잡는다. + +## 9. 이 조사 중 본 별개 문제 (범위 밖, 고치지 않았다) + +- `LockAcquisitionTimeoutException`은 `ApiErrorCarrier`를 구현하지 않는다 + (`src/application-core/src/main/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutException.java:13`). + inbound 어디에도 이 예외의 처리기가 없다(`grep -rln LockAcquisitionTimeoutException src`: persistence-jpa와 테스트뿐). + - Javadoc은 "The web adapter maps it to 409"라고 적는다. 하지만 web은 `handleUnknown`을 거쳐 `INTERNAL_ERROR` 500으로 + 답할 것으로 읽힌다(`GlobalExceptionHandler.java:195-203`). + - `LockAcquisitionTimeoutClassificationContractTest`가 막으려는 "500 INTERNAL로 뭉개기"(D7)와 같은 모양이다. 그 + 테스트는 enum과 레지스트리만 보고 전송 경로는 보지 않는다. + - 코드 읽기 결과이고 탐침은 돌리지 않았다. 결함 후보로 `docs/work/improve.md` 절차에 넘긴다. + +## 10. 결정 (2026-11-06) + +소유자 답은 "권하는 안대로"다(총괄 세션 전달, 2026-11-06). 7절 각 항목은 이렇게 정해졌다. + +| # | 결정 | 적용한 곳 | +| --- | --- | --- | +| 1 | A. `log_level` 칸을 지운다. 레지스트리 머리말이 레벨을 정하는 코드(`ServerFailureLog`, `AuthErrorResponseWriter`)를 가리킨다 | `docs/registries/error-codes.yaml` 머리말과 60행 | +| 1-b | 칸이 다시 생기지 않게 단언을 둔다. 파생 서비스는 자기 행에서도 지운다 | `OperationalErrorRegistryContractTest.noRegistryRowCarriesALogLevel`(태그 `document-contract`), `docs/upgrade/2026-11-maturity-review.md` 「반드시 할 일」 17·B-44 | +| 2 | 보안 필터는 5xx(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)를 ERROR로 남긴다 | `AuthErrorResponseWriter`(5xx ERROR, 4xx WARN), `EnvelopeAuthenticationEntryPointTest`, web README, 런북 2곳, upgrade 5절 | +| 3 | 401 서명·issuer·audience 불일치는 WARN으로 둔다. 런북은 WARN 줄의 `code=`로 찾게 고친다 | `docs/runbooks/auth-token-invalid-signature.md`, 서명 실패 WARN을 고정한 테스트 | +| 4 | repo 밖에서 이 칸을 읽는 도구는 없는 것으로 본다 | — | + +결정 색인: `docs/work/reference/decisions.md` 2.3절 「오류 코드 로그 레벨」. diff --git a/docs/fileserver/design-deviations.md b/docs/fileserver/design-deviations.md index 0bf0a744..0273e4a9 100644 --- a/docs/fileserver/design-deviations.md +++ b/docs/fileserver/design-deviations.md @@ -113,9 +113,8 @@ The metadata store, session store, quota service, queues, ledger, and staging lo `@ConditionalOnProperty(app.fileserver-platform.enabled)` even though the rest of `adapter:outbound:persistence-jpa` is unconditional. -Without the gate, every composition root that includes the persistence module built these beans — -including `sample-portfolio`, which has no Fileserver — and each of them needs collaborators only -the Fileserver configuration provides. That is the same rule the design states for the transport +게이트가 없으면 persistence 모듈을 포함한 조립 루트는 Fileserver를 쓰지 않아도 이 bean들을 만들고, 그 bean마다 +Fileserver 설정만 주는 협력 객체가 필요하다. That is the same rule the design states for the transport surface, applied to persistence: no surface appears merely because the dependency is present. `FileStateMachine` is bound alongside them, in `FileserverStorageConfiguration`. It had no diff --git a/docs/fileserver/operations.md b/docs/fileserver/operations.md index 33fd2cfb..f3930451 100644 --- a/docs/fileserver/operations.md +++ b/docs/fileserver/operations.md @@ -83,13 +83,13 @@ The volume was remounted somewhere the probe can no longer prove a required capa application refuses traffic rather than serving from storage it cannot publish to atomically. ```bash -kubectl apply -f infra/fileserver/kubernetes/pvc-certification-job.yaml -kubectl logs job/fileserver-pvc-certification +# staging과 content가 같은 파일 저장소(같은 장치 번호)인지 pod 안에서 본다 +kubectl exec -- stat -c %d /var/lib/backend/files/staging /var/lib/backend/files/content ``` -Compare the printed tuple with the certified one in `docs/fileserver/storage-certification.md`. A -mismatch in CSI driver, StorageClass, access mode, or mount options is the cause; the certification -does not carry across it. +`docs/fileserver/storage-certification.md`의 인증 절차로 지금 volume의 묶음(CSI driver, StorageClass, +접근 모드, backend, mount 옵션)을 다시 적고, 인증한 묶음과 비교한다. 하나라도 다르면 그것이 원인이다. +인증은 그 차이를 넘어 옮겨지지 않는다. ## Nginx delegation failure @@ -97,9 +97,9 @@ does not carry across it. The internal location is misconfigured, so the proxy cannot resolve the redirect it was handed. +프록시 설정의 내부 location(기본 `/__files/`)이 아래 「운영 환경이 지켜야 할 조건」을 지키는지 본다. + ```bash -# The internal prefix must resolve to the content root and must be marked `internal`. -grep -A5 '__files' infra/fileserver/nginx/nginx.conf curl -s $ADMIN/internal/fileserver/capabilities | jq '.capabilities.delegatedDownload' ``` @@ -110,6 +110,32 @@ slower but correct. app.fileserver-platform.nginx.enabled=false ``` +## 운영 환경이 지켜야 할 조건 + +이 repo는 프록시 설정 파일과 Kubernetes 매니페스트를 두지 않는다(2026-11-07 소유자 결정). 그 파일은 서비스를 +배포하는 쪽의 인프라 repo가 갖는다. 그 파일이 지켜야 할 조건은 아래다. + +**프런트 프록시(nginx `X-Accel-Redirect` 위임)** — `app.fileserver-platform.nginx.enabled=true`일 때 + +1. 내부 location(`app.fileserver-platform.nginx.internal-prefix`, 기본 `/__files/`)은 `internal`이다. 클라이언트가 + 그 경로를 직접 부르면 404이고 content 폴더에 닿지 않는다. 애플리케이션이 준 내부 redirect로만 닿는다. +2. 그 location의 `alias`는 저장 루트의 content 폴더다(기본 `/var/lib/backend/files/content/`). 애플리케이션은 + 절대 경로를 내보내지 않고 내부 접두사 아래 상대 URI만 내보낸다. 경로가 실제 위치가 되는 곳은 이 `alias`뿐이다. +3. 앱으로 넘기는 요청에서 클라이언트가 보낸 `X-Accel-Redirect` 헤더를 지운다. 남기면 호출자가 임의의 내부 + 객체를 가리킬 수 있다. +4. 업로드는 스트리밍으로 넘긴다(`proxy_request_buffering off`, 본문 크기 제한은 애플리케이션이 정하므로 프록시는 + 막지 않는다). 프록시가 큰 본문을 디스크에 버퍼링하면 쓰기가 두 번 일어난다. +5. 내부 location 응답에 `X-Content-Type-Options: nosniff`를 붙이고, 앱이 정한 `Content-Disposition`· + `Cache-Control`·`ETag`를 그대로 넘긴다. 올라온 내용이 자기 형식을 스스로 정하게 두지 않는다. + +**Kubernetes 저장 volume** + +1. PersistentVolumeClaim을 저장 루트(`/var/lib/backend/files`)에 마운트하고, 접근 모드는 `ReadWriteOnce`다. + `ReadWriteMany`(여러 노드의 동시 쓰기)는 인증하지 않았다(`support-matrix.md`). +2. pod `securityContext.fsGroup`을 이미지의 앱 그룹으로 둔다. 그래야 앱 계정이 volume에 쓸 수 있다. +3. 그 volume이 `storage-certification.md`의 인증 항목(같은 파일 저장소, 원자적 rename, `O_EXCL` 생성)을 + 통과해야 한다. 기동 때 `FileserverStartupValidator`도 같은 probe를 다시 돌린다. + ## Cleanup backlog **Signal** — `fileserver.cleanup{result="deferred"}` rising, or reclaimed bytes flat while deletes diff --git a/docs/fileserver/storage-certification.md b/docs/fileserver/storage-certification.md index b6788738..19117e1e 100644 --- a/docs/fileserver/storage-certification.md +++ b/docs/fileserver/storage-certification.md @@ -19,12 +19,15 @@ certification that does not name all five is not transferable. ## Running the certification -```bash -kubectl apply -f infra/fileserver/kubernetes/pvc-certification-job.yaml -kubectl logs job/fileserver-pvc-certification -``` +이 repo는 인증 job 매니페스트를 두지 않는다(2026-11-07 소유자 결정). 배포하는 쪽이 대상 volume을 저장 +루트(`/var/lib/backend/files`)에 마운트한 일회성 pod에서 아래를 차례로 확인한다. -The job writes a machine-readable result to the claim itself, carrying the full tuple: +1. `staging`과 `content` 폴더를 만들고, `staging`의 파일을 `content`로 `mv`해 원자적 rename이 되는지 본다. +2. 두 폴더의 장치 번호(`stat -c %d`)가 같은지 본다. 다르면 rename이 복사가 된다. +3. `set -o noclobber` 상태에서 같은 파일을 두 번 만들어 `O_EXCL` 생성이 막히는지 본다. +4. 결과와 함께 묶음(Kubernetes 버전, CSI driver, StorageClass, 접근 모드, backend, mount 옵션)을 기록한다. + +결과는 묶음 전체를 담은 기계가 읽는 형식으로 그 volume에 남긴다: ```json { @@ -40,13 +43,12 @@ The job writes a machine-readable result to the claim itself, carrying the full } ``` -The job fails closed: a volume whose staging and content areas are on different stores is not -certified, because its publish would silently degrade to a copy. +2번이 실패하면 인증하지 않는다. staging과 content가 다른 저장소인 volume은 게시가 소리 없이 복사로 바뀐다. ## Network filesystems ```bash -docker compose -f infra/fileserver/nfs/compose.yml up -d +docker compose -f src/adapter/outbound/fileserver/compose/nfs/compose.yml up -d FILESERVER_NFS_TESTS=true ./gradlew :adapter:outbound:fileserver:test ``` diff --git a/docs/fileserver/support-matrix.md b/docs/fileserver/support-matrix.md index d50f0db0..8e1c90ff 100644 --- a/docs/fileserver/support-matrix.md +++ b/docs/fileserver/support-matrix.md @@ -29,7 +29,6 @@ that does not exist, so a level can never outlive the test that justified it. | NFSv4 ambiguity handling | Beta | `fileserver-nfs-ambiguity` | | Large-file and slow-client performance | Beta | `fileserver-large-file-performance` | | Multi-instance writer lease | Beta | `fileserver-multi-instance-lease` | -| Kubernetes ReadWriteOnce PVC | Limited | `fileserver-pvc-certification` (manifest checks in CI; cluster run is operator-driven) | | Nginx `X-Accel-Redirect` delegation | Limited | `fileserver-http-contract` | | Telemetry sensitive-data suppression | Stable | `fileserver-sensitive-telemetry-scan` | | Documentation and support-claim coverage | Stable | `fileserver-documentation-gate` | @@ -46,10 +45,10 @@ leaf puts `DispatcherServlet` on the classpath, so Boot resolves SERVLET. These have no job, and therefore no claim: -- An automated Kubernetes cluster result. `fileserver-pvc-certification` validates the manifest on - every release and applies it only when a release cluster is configured; without one it warns and - records that nothing was certified. The cluster tuple is produced by an operator and read from - [storage-certification.md](storage-certification.md). +- Kubernetes PVC(ReadWriteOnce 포함). 이 repo는 클러스터 매니페스트와 그것을 검사하던 release job을 + 2026-11-07에 지웠다. volume이 지켜야 할 조건은 [operations.md](operations.md) 「운영 환경이 지켜야 할 + 조건」, 인증 절차는 [storage-certification.md](storage-certification.md)다. 클러스터 결과는 배포하는 쪽이 + 만든다. - Kubernetes ReadWriteMany PVC. Concurrent writers across nodes are not certified. - Windows NTFS as a production storage root. The filename policy strips the characters NTFS diff --git a/docs/evidence/object-storage/batch-a-checkpoint.md b/docs/history/evidence/object-storage/batch-a-checkpoint.md similarity index 89% rename from docs/evidence/object-storage/batch-a-checkpoint.md rename to docs/history/evidence/object-storage/batch-a-checkpoint.md index b350ee16..740b5eaa 100644 --- a/docs/evidence/object-storage/batch-a-checkpoint.md +++ b/docs/history/evidence/object-storage/batch-a-checkpoint.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-07-28 +- 요약: Object Storage 작업 Batch A의 체크포인트 기록이다. +- 현재 정본: `src/adapter/outbound/objectstorage/README.md` + + # Object Storage Batch A Checkpoint - Date: 2026-07-28 diff --git a/docs/evidence/object-storage/batch-b-checkpoint.md b/docs/history/evidence/object-storage/batch-b-checkpoint.md similarity index 93% rename from docs/evidence/object-storage/batch-b-checkpoint.md rename to docs/history/evidence/object-storage/batch-b-checkpoint.md index b7113d20..0bac6cd2 100644 --- a/docs/evidence/object-storage/batch-b-checkpoint.md +++ b/docs/history/evidence/object-storage/batch-b-checkpoint.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-07-28 +- 요약: Object Storage 작업 Batch B의 체크포인트 기록이다. +- 현재 정본: `src/adapter/outbound/objectstorage/README.md` + + # Object Storage Batch B Checkpoint - Date: 2026-07-28 diff --git a/docs/evidence/object-storage/batch-c-progress.md b/docs/history/evidence/object-storage/batch-c-progress.md similarity index 90% rename from docs/evidence/object-storage/batch-c-progress.md rename to docs/history/evidence/object-storage/batch-c-progress.md index 0a632d8d..95ee56f0 100644 --- a/docs/evidence/object-storage/batch-c-progress.md +++ b/docs/history/evidence/object-storage/batch-c-progress.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-07-28 +- 요약: Object Storage 작업 Batch C의 진행 기록이다. +- 현재 정본: `src/adapter/outbound/objectstorage/README.md` + + # Object Storage Batch C Checkpoint - Date: 2026-07-28 diff --git a/docs/evidence/object-storage/batch-d-checkpoint.md b/docs/history/evidence/object-storage/batch-d-checkpoint.md similarity index 91% rename from docs/evidence/object-storage/batch-d-checkpoint.md rename to docs/history/evidence/object-storage/batch-d-checkpoint.md index baa85bb2..cb48134c 100644 --- a/docs/evidence/object-storage/batch-d-checkpoint.md +++ b/docs/history/evidence/object-storage/batch-d-checkpoint.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-07-28 +- 요약: Object Storage 작업 Batch D의 체크포인트 기록이다. +- 현재 정본: `src/adapter/outbound/objectstorage/README.md` + + # Object Storage Batch D Checkpoint - Date: 2026-07-28 diff --git a/docs/evidence/object-storage/batch-e-pause-checkpoint.md b/docs/history/evidence/object-storage/batch-e-pause-checkpoint.md similarity index 90% rename from docs/evidence/object-storage/batch-e-pause-checkpoint.md rename to docs/history/evidence/object-storage/batch-e-pause-checkpoint.md index 914522cb..d5772fb5 100644 --- a/docs/evidence/object-storage/batch-e-pause-checkpoint.md +++ b/docs/history/evidence/object-storage/batch-e-pause-checkpoint.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-07-31 +- 요약: Object Storage 작업 Batch E를 멈춘 시점의 체크포인트 기록이다. +- 현재 정본: `src/adapter/outbound/objectstorage/README.md` + + # Object Storage Batch E Pause Checkpoint - Recorded: 2026-07-29 (Asia/Seoul) diff --git a/docs/evidence/object-storage/phase-0-inventory.md b/docs/history/evidence/object-storage/phase-0-inventory.md similarity index 90% rename from docs/evidence/object-storage/phase-0-inventory.md rename to docs/history/evidence/object-storage/phase-0-inventory.md index 9220594d..18645b9d 100644 --- a/docs/evidence/object-storage/phase-0-inventory.md +++ b/docs/history/evidence/object-storage/phase-0-inventory.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-07-31 +- 요약: Object Storage 작업을 시작하기 전 0단계 현황 조사다. +- 현재 정본: `src/adapter/outbound/objectstorage/README.md` + + # Object Storage Phase 0 Inventory - Captured: 2026-07-28 diff --git a/docs/superpowers/packages/fileserver/README.md b/docs/history/packages/fileserver/README.md similarity index 73% rename from docs/superpowers/packages/fileserver/README.md rename to docs/history/packages/fileserver/README.md index 95aca875..d483618e 100644 --- a/docs/superpowers/packages/fileserver/README.md +++ b/docs/history/packages/fileserver/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-11 +- 요약: 파일 서버 설계 패키지가 처음 납품됐을 때의 안내다. 본문 문서는 docs/design과 docs/history/plans에 있다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + > **보존 안내** — 이 파일은 저장소 루트 `fileserver-superpowers-package/` 에 있던 납품 패키지의 README다. > 2026-08-15 문서 정리에서 설계서·계획서는 `docs/superpowers/specs/` 와 `docs/superpowers/plans/` 로 통합했고, > 실행 불가 상태였던 `validate_fileserver_docs.py` 는 제거했다. diff --git a/docs/superpowers/packages/fileserver/VALIDATION.md b/docs/history/packages/fileserver/VALIDATION.md similarity index 83% rename from docs/superpowers/packages/fileserver/VALIDATION.md rename to docs/history/packages/fileserver/VALIDATION.md index 0b19a1d4..b4bdb35a 100644 --- a/docs/superpowers/packages/fileserver/VALIDATION.md +++ b/docs/history/packages/fileserver/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-11 +- 요약: 파일 서버 설계 패키지를 받을 때 한 정적 검증 결과다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver Superpowers 문서 검증 **결과:** PASS diff --git a/docs/graphql-superpowers-package/MANIFEST.sha256 b/docs/history/packages/graphql-superpowers-package/MANIFEST.sha256 similarity index 100% rename from docs/graphql-superpowers-package/MANIFEST.sha256 rename to docs/history/packages/graphql-superpowers-package/MANIFEST.sha256 diff --git a/docs/graphql-superpowers-package/README.md b/docs/history/packages/graphql-superpowers-package/README.md similarity index 74% rename from docs/graphql-superpowers-package/README.md rename to docs/history/packages/graphql-superpowers-package/README.md index 4eff19b3..adaf6d8b 100644 --- a/docs/graphql-superpowers-package/README.md +++ b/docs/history/packages/graphql-superpowers-package/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: GraphQL 설계 패키지 묶음의 안내다. 안의 MANIFEST.sha256는 머리 블록을 달기 전 납품 바이트의 해시다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # GraphQL Superpowers 설계 패키지 이 패키지는 `GraphQL API 실행 플랫폼 심층 리서치`를 구현 기준선으로 변환한 설계서와 실행 계획서다. diff --git a/docs/superpowers/packages/graphql/VALIDATION.md b/docs/history/packages/graphql-superpowers-package/VALIDATION.md similarity index 88% rename from docs/superpowers/packages/graphql/VALIDATION.md rename to docs/history/packages/graphql-superpowers-package/VALIDATION.md index 725a4b2a..30ab0b52 100644 --- a/docs/superpowers/packages/graphql/VALIDATION.md +++ b/docs/history/packages/graphql-superpowers-package/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: GraphQL 설계 패키지 묶음을 받을 때 한 정적 검증 결과다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # GraphQL Superpowers 문서 정적 검증 결과 - **검증 시각 기준:** 2026-08-12 diff --git a/docs/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md b/docs/history/packages/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md similarity index 99% rename from docs/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md rename to docs/history/packages/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md index 904319ae..eddb4a19 100644 --- a/docs/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md +++ b/docs/history/packages/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-12 +- 요약: GraphQL 실행 계획의 납품 원본이다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # GraphQL Advanced Capability Expansion Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md b/docs/history/packages/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md similarity index 99% rename from docs/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md rename to docs/history/packages/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md index 2f5204e1..7cb7e168 100644 --- a/docs/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md +++ b/docs/history/packages/graphql-superpowers-package/docs/superpowers/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-12 +- 요약: GraphQL 실행 계획의 납품 원본이다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # GraphQL API 실행 플랫폼 Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/graphql-superpowers-package/docs/superpowers/specs/2026-08-12-graphql-api-execution-platform-design.md b/docs/history/packages/graphql-superpowers-package/docs/superpowers/specs/2026-08-12-graphql-api-execution-platform-design.md similarity index 99% rename from docs/graphql-superpowers-package/docs/superpowers/specs/2026-08-12-graphql-api-execution-platform-design.md rename to docs/history/packages/graphql-superpowers-package/docs/superpowers/specs/2026-08-12-graphql-api-execution-platform-design.md index 836c9d33..93a40c8a 100644 --- a/docs/graphql-superpowers-package/docs/superpowers/specs/2026-08-12-graphql-api-execution-platform-design.md +++ b/docs/history/packages/graphql-superpowers-package/docs/superpowers/specs/2026-08-12-graphql-api-execution-platform-design.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-12 +- 요약: GraphQL 설계서의 납품 원본이다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # GraphQL API 실행 플랫폼 설계서 - **문서 상태:** 구현 기준선 확정 diff --git a/docs/graphql-superpowers-package/validate_graphql_docs.py b/docs/history/packages/graphql-superpowers-package/validate_graphql_docs.py similarity index 100% rename from docs/graphql-superpowers-package/validate_graphql_docs.py rename to docs/history/packages/graphql-superpowers-package/validate_graphql_docs.py diff --git a/docs/superpowers/packages/graphql/README.md b/docs/history/packages/graphql/README.md similarity index 79% rename from docs/superpowers/packages/graphql/README.md rename to docs/history/packages/graphql/README.md index 2a0e7212..6a8549b7 100644 --- a/docs/superpowers/packages/graphql/README.md +++ b/docs/history/packages/graphql/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: GraphQL 설계 패키지가 처음 납품됐을 때의 안내다. 본문 문서는 docs/design과 docs/history/plans에 있다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + > **보존 안내** — 이 파일은 저장소 루트 `graphql-superpowers-package/` 에 있던 납품 패키지의 README다. > 2026-08-15 문서 정리에서 설계서·계획서는 `docs/superpowers/specs/` 와 `docs/superpowers/plans/` 로 통합했고, > `validate_graphql_docs.py` 와 `MANIFEST.sha256` 은 제거했다. diff --git a/docs/graphql-superpowers-package/VALIDATION.md b/docs/history/packages/graphql/VALIDATION.md similarity index 88% rename from docs/graphql-superpowers-package/VALIDATION.md rename to docs/history/packages/graphql/VALIDATION.md index 725a4b2a..c080bdb3 100644 --- a/docs/graphql-superpowers-package/VALIDATION.md +++ b/docs/history/packages/graphql/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: GraphQL 설계 패키지를 받을 때 한 정적 검증 결과다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # GraphQL Superpowers 문서 정적 검증 결과 - **검증 시각 기준:** 2026-08-12 diff --git a/docs/superpowers/packages/httpclient/README.md b/docs/history/packages/httpclient/README.md similarity index 73% rename from docs/superpowers/packages/httpclient/README.md rename to docs/history/packages/httpclient/README.md index 3dbc997e..f371910a 100644 --- a/docs/superpowers/packages/httpclient/README.md +++ b/docs/history/packages/httpclient/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-11 +- 요약: HTTP client 설계 패키지가 처음 납품됐을 때의 안내다. 본문 문서는 docs/design과 docs/history/plans에 있다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + > **보존 안내** — 이 파일은 저장소 루트 `httpclient-superpowers-package/` 에 있던 납품 패키지의 README다. > 2026-08-15 문서 정리에서 설계서·계획서는 `docs/superpowers/specs/` 와 `docs/superpowers/plans/` 로 통합했고, > 실행 불가 상태였던 `validate_httpclient_docs.py` 는 제거했다. diff --git a/docs/superpowers/packages/httpclient/VALIDATION.md b/docs/history/packages/httpclient/VALIDATION.md similarity index 72% rename from docs/superpowers/packages/httpclient/VALIDATION.md rename to docs/history/packages/httpclient/VALIDATION.md index 4f534975..cf624b1d 100644 --- a/docs/superpowers/packages/httpclient/VALIDATION.md +++ b/docs/history/packages/httpclient/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-11 +- 요약: HTTP client 설계 패키지를 받을 때 한 정적 검증 결과다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + # HTTP Client Superpowers 문서 검증 **검증 결과:** PASS diff --git a/docs/superpowers/packages/jpa/README.md b/docs/history/packages/jpa/README.md similarity index 85% rename from docs/superpowers/packages/jpa/README.md rename to docs/history/packages/jpa/README.md index 20aed5ea..6064d255 100644 --- a/docs/superpowers/packages/jpa/README.md +++ b/docs/history/packages/jpa/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: JPA 설계 패키지가 처음 납품됐을 때의 안내다. 본문 문서는 docs/design과 docs/history/plans에 있다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + > **보존 안내** — 이 파일은 저장소 루트 `jpa-superpowers-package/` 에 있던 납품 패키지의 README다. > 2026-08-15 문서 정리에서 설계서·계획서는 `docs/superpowers/specs/` 와 `docs/superpowers/plans/` 로 통합했고, > `validate_jpa_docs.py` 와 `MANIFEST.sha256` 은 제거했다. diff --git a/docs/superpowers/packages/jpa/VALIDATION.md b/docs/history/packages/jpa/VALIDATION.md similarity index 99% rename from docs/superpowers/packages/jpa/VALIDATION.md rename to docs/history/packages/jpa/VALIDATION.md index e8d0b2fb..32bf2ac6 100644 --- a/docs/superpowers/packages/jpa/VALIDATION.md +++ b/docs/history/packages/jpa/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: JPA 설계 패키지를 받을 때 한 정적 검증 결과다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA Superpowers 문서 정적 검증 - 결과: **PASS** diff --git a/docs/superpowers/packages/messaging/README.md b/docs/history/packages/messaging/README.md similarity index 85% rename from docs/superpowers/packages/messaging/README.md rename to docs/history/packages/messaging/README.md index 627adc1b..f35c7a44 100644 --- a/docs/superpowers/packages/messaging/README.md +++ b/docs/history/packages/messaging/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: 메시징 설계 패키지가 처음 납품됐을 때의 안내다. 본문 문서는 docs/design과 docs/history/plans에 있다. +- 현재 정본: `docs/messaging/support-matrix.md` + + > **보존 안내** — 이 파일은 저장소 루트 `messaging-superpowers-package/` 에 있던 납품 패키지의 README다. > 2026-08-15 문서 정리에서 설계서·계획서는 `docs/superpowers/specs/` 와 `docs/superpowers/plans/` 로 통합했고, > `validate_messaging_docs.py` 와 `MANIFEST.sha256` 은 제거했다. diff --git a/docs/superpowers/packages/messaging/VALIDATION.md b/docs/history/packages/messaging/VALIDATION.md similarity index 97% rename from docs/superpowers/packages/messaging/VALIDATION.md rename to docs/history/packages/messaging/VALIDATION.md index d7029704..3ccec775 100644 --- a/docs/superpowers/packages/messaging/VALIDATION.md +++ b/docs/history/packages/messaging/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: 메시징 설계 패키지를 받을 때 한 정적 검증 결과다. +- 현재 정본: `docs/messaging/support-matrix.md` + + # Messaging Superpowers 문서 정적 검증 - 설계서: `messaging-platform-design.md` — 2,608행, 74,649 bytes diff --git a/docs/superpowers/packages/mongodb/README.md b/docs/history/packages/mongodb/README.md similarity index 78% rename from docs/superpowers/packages/mongodb/README.md rename to docs/history/packages/mongodb/README.md index 96bb42df..cb7bda75 100644 --- a/docs/superpowers/packages/mongodb/README.md +++ b/docs/history/packages/mongodb/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: MongoDB 설계 패키지가 처음 납품됐을 때의 안내다. 본문 문서는 docs/design과 docs/history/plans에 있다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + > **보존 안내** — 이 파일은 저장소 루트 `mongodb-superpowers-package/` 에 있던 납품 패키지의 README다. > 2026-08-15 문서 정리에서 설계서·계획서는 `docs/superpowers/specs/` 와 `docs/superpowers/plans/` 로 통합했고, > `validate_mongodb_docs.py` 와 `MANIFEST.sha256` 은 제거했다. diff --git a/docs/superpowers/packages/mongodb/VALIDATION.md b/docs/history/packages/mongodb/VALIDATION.md similarity index 98% rename from docs/superpowers/packages/mongodb/VALIDATION.md rename to docs/history/packages/mongodb/VALIDATION.md index 041c890f..1e534206 100644 --- a/docs/superpowers/packages/mongodb/VALIDATION.md +++ b/docs/history/packages/mongodb/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: MongoDB 설계 패키지를 받을 때 한 정적 검증 결과다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + # MongoDB Superpowers 문서 정적 검증 결과 ## 결과 diff --git a/docs/superpowers/packages/notification/README.md b/docs/history/packages/notification/README.md similarity index 85% rename from docs/superpowers/packages/notification/README.md rename to docs/history/packages/notification/README.md index 85dbebd2..c93d7311 100644 --- a/docs/superpowers/packages/notification/README.md +++ b/docs/history/packages/notification/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: 알림 설계 패키지가 처음 납품됐을 때의 안내다. 본문 문서는 docs/design과 docs/history/plans에 있다. +- 현재 정본: `docs/notification/support-matrix.md` + + > **보존 안내** — 이 파일은 저장소 루트 `notification-superpowers-package/` 에 있던 납품 패키지의 README다. > 2026-08-15 문서 정리에서 설계서·계획서는 `docs/superpowers/specs/` 와 `docs/superpowers/plans/` 로 통합했고, > 실행 불가 상태였던 `validate_notification_docs.py` 와 `MANIFEST.sha256` 은 제거했다. diff --git a/docs/superpowers/packages/notification/VALIDATION.md b/docs/history/packages/notification/VALIDATION.md similarity index 98% rename from docs/superpowers/packages/notification/VALIDATION.md rename to docs/history/packages/notification/VALIDATION.md index c063263f..1faf2ab7 100644 --- a/docs/superpowers/packages/notification/VALIDATION.md +++ b/docs/history/packages/notification/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: 알림 설계 패키지를 받을 때 한 정적 검증 결과다. +- 현재 정본: `docs/notification/support-matrix.md` + + # Notification Superpowers 문서 정적 검증 - 결과: **PASS** diff --git a/docs/superpowers/packages/redis/README.md b/docs/history/packages/redis/README.md similarity index 85% rename from docs/superpowers/packages/redis/README.md rename to docs/history/packages/redis/README.md index 17c31e58..8b41b5e0 100644 --- a/docs/superpowers/packages/redis/README.md +++ b/docs/history/packages/redis/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-11 +- 요약: Redis 설계 패키지가 처음 납품됐을 때의 안내다. 본문 문서는 docs/design과 docs/history/plans에 있다. +- 현재 정본: `docs/redis/support-matrix.md` + + > **보존 안내** — 이 파일은 저장소 루트 `redis-superpowers-package/` 에 있던 납품 패키지의 README다. > 2026-08-15 문서 정리에서 설계서·계획서는 `docs/superpowers/specs/` 와 `docs/superpowers/plans/` 로 통합했고, > 이 패키지에는 검증 스크립트가 없었다. diff --git a/docs/superpowers/packages/redis/VALIDATION.md b/docs/history/packages/redis/VALIDATION.md similarity index 82% rename from docs/superpowers/packages/redis/VALIDATION.md rename to docs/history/packages/redis/VALIDATION.md index a11631b0..826e364b 100644 --- a/docs/superpowers/packages/redis/VALIDATION.md +++ b/docs/history/packages/redis/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-11 +- 요약: Redis 설계 패키지를 받을 때 한 정적 검증 결과다. +- 현재 정본: `docs/redis/support-matrix.md` + + # 정적 검증 결과 - **결과:** PASS diff --git a/docs/web-superpowers-package/MANIFEST.sha256 b/docs/history/packages/web-superpowers-package/MANIFEST.sha256 similarity index 100% rename from docs/web-superpowers-package/MANIFEST.sha256 rename to docs/history/packages/web-superpowers-package/MANIFEST.sha256 diff --git a/docs/web-superpowers-package/README.md b/docs/history/packages/web-superpowers-package/README.md similarity index 78% rename from docs/web-superpowers-package/README.md rename to docs/history/packages/web-superpowers-package/README.md index 46fbdb8d..3063c885 100644 --- a/docs/web-superpowers-package/README.md +++ b/docs/history/packages/web-superpowers-package/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-28 +- 요약: 웹 inbound HTTP 설계 패키지 묶음의 안내다. 안의 MANIFEST.sha256는 머리 블록을 달기 전 납품 바이트의 해시다. +- 현재 정본: `docs/web/http-contract.md` + + # Web Superpowers Package Spring Boot 기반 **인바운드 HTTP API 실행 플랫폼 `web`**의 설계, Stable 구현 계획, Advanced 확장 계획, 원본 심층 리서치, 정적 검증 도구를 묶은 패키지입니다. diff --git a/docs/web-superpowers-package/VALIDATION.md b/docs/history/packages/web-superpowers-package/VALIDATION.md similarity index 91% rename from docs/web-superpowers-package/VALIDATION.md rename to docs/history/packages/web-superpowers-package/VALIDATION.md index 27a0f631..dcf2dc40 100644 --- a/docs/web-superpowers-package/VALIDATION.md +++ b/docs/history/packages/web-superpowers-package/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-28 +- 요약: 웹 inbound HTTP 설계 패키지 묶음을 받을 때 한 정적 검증 결과다. +- 현재 정본: `docs/web/http-contract.md` + + # Web Superpowers 문서 정적 검증 결과 검증 기준일: 2026-08-13 diff --git a/docs/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-advanced-capabilities-expansion-plan.md b/docs/history/packages/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-advanced-capabilities-expansion-plan.md similarity index 99% rename from docs/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-advanced-capabilities-expansion-plan.md rename to docs/history/packages/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-advanced-capabilities-expansion-plan.md index ee777f6a..a9f6dc6d 100644 --- a/docs/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-advanced-capabilities-expansion-plan.md +++ b/docs/history/packages/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-advanced-capabilities-expansion-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: 웹 inbound HTTP 실행 계획의 납품 원본이다. +- 현재 정본: `docs/web/http-contract.md` + + # 인바운드 HTTP API 실행 플랫폼 `web` Advanced Capability 확장 계획서 > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-inbound-http-api-execution-platform-implementation-plan.md b/docs/history/packages/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-inbound-http-api-execution-platform-implementation-plan.md similarity index 99% rename from docs/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-inbound-http-api-execution-platform-implementation-plan.md rename to docs/history/packages/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-inbound-http-api-execution-platform-implementation-plan.md index 9e19b680..c0e9dfb8 100644 --- a/docs/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-inbound-http-api-execution-platform-implementation-plan.md +++ b/docs/history/packages/web-superpowers-package/docs/superpowers/plans/2026-08-13-web-inbound-http-api-execution-platform-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: 웹 inbound HTTP 실행 계획의 납품 원본이다. +- 현재 정본: `docs/web/http-contract.md` + + # 인바운드 HTTP API 실행 플랫폼 `web` 구현 계획서 > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/web-superpowers-package/docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design.md b/docs/history/packages/web-superpowers-package/docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design.md similarity index 98% rename from docs/web-superpowers-package/docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design.md rename to docs/history/packages/web-superpowers-package/docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design.md index 9a1dce60..e67d614f 100644 --- a/docs/web-superpowers-package/docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design.md +++ b/docs/history/packages/web-superpowers-package/docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-13 +- 요약: 웹 inbound HTTP 설계서의 납품 원본이다. +- 현재 정본: `docs/web/http-contract.md` + + # 인바운드 HTTP API 실행 플랫폼 `web` 설계서 > 기준일: 2026-08-13 diff --git a/docs/web-superpowers-package/research/source-web-deep-research.md b/docs/history/packages/web-superpowers-package/research/source-web-deep-research.md similarity index 99% rename from docs/web-superpowers-package/research/source-web-deep-research.md rename to docs/history/packages/web-superpowers-package/research/source-web-deep-research.md index a270ca2b..fe16866a 100644 --- a/docs/web-superpowers-package/research/source-web-deep-research.md +++ b/docs/history/packages/web-superpowers-package/research/source-web-deep-research.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-28 +- 요약: 웹 inbound HTTP 설계의 입력이 된 심층 조사 원문이다. +- 현재 정본: `docs/web/http-contract.md` + + # 인바운드 HTTP API 실행 플랫폼 `web` 심층 리서치 본 조사에서 `web`은 Spring MVC 설정 묶음이나 공통 `ControllerAdvice`가 아니라, **HTTP 요청이 신뢰 경계를 통과해 Application Use Case에 진입하고, 그 실행 결과가 HTTP 의미론으로 다시 외부에 노출되는 전 과정을 통제하는 플랫폼**으로 정의하는 것이 적절합니다. diff --git a/docs/web-superpowers-package/validate_web_docs.py b/docs/history/packages/web-superpowers-package/validate_web_docs.py similarity index 100% rename from docs/web-superpowers-package/validate_web_docs.py rename to docs/history/packages/web-superpowers-package/validate_web_docs.py diff --git a/docs/websocket-superpowers-package/MANIFEST.sha256 b/docs/history/packages/websocket-superpowers-package/MANIFEST.sha256 similarity index 100% rename from docs/websocket-superpowers-package/MANIFEST.sha256 rename to docs/history/packages/websocket-superpowers-package/MANIFEST.sha256 diff --git a/docs/websocket-superpowers-package/README.md b/docs/history/packages/websocket-superpowers-package/README.md similarity index 65% rename from docs/websocket-superpowers-package/README.md rename to docs/history/packages/websocket-superpowers-package/README.md index 3cc4a682..86e828c7 100644 --- a/docs/websocket-superpowers-package/README.md +++ b/docs/history/packages/websocket-superpowers-package/README.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-28 +- 요약: WebSocket 설계 패키지 묶음의 안내다. 안의 MANIFEST.sha256는 머리 블록을 달기 전 납품 바이트의 해시다. +- 현재 정본: `src/adapter/inbound/websocket/README.md` + + # WebSocket Superpowers Package 이 패키지는 WebSocket 실시간 양방향 연결 실행 플랫폼의 설계서, Stable 구현 계획, Advanced 확장 계획, 요구사항 원본과 정적 검증 도구를 포함한다. diff --git a/docs/websocket-superpowers-package/VALIDATION.md b/docs/history/packages/websocket-superpowers-package/VALIDATION.md similarity index 78% rename from docs/websocket-superpowers-package/VALIDATION.md rename to docs/history/packages/websocket-superpowers-package/VALIDATION.md index b1980389..dafaaf07 100644 --- a/docs/websocket-superpowers-package/VALIDATION.md +++ b/docs/history/packages/websocket-superpowers-package/VALIDATION.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-28 +- 요약: WebSocket 설계 패키지 묶음을 받을 때 한 정적 검증 결과다. +- 현재 정본: `src/adapter/inbound/websocket/README.md` + + # WebSocket Superpowers 문서 정적 검증 결과 - **검증일:** 2026-08-14 diff --git a/docs/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-advanced-capabilities-expansion-plan.md b/docs/history/packages/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-advanced-capabilities-expansion-plan.md similarity index 99% rename from docs/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-advanced-capabilities-expansion-plan.md rename to docs/history/packages/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-advanced-capabilities-expansion-plan.md index 2680dd4a..a30e1e74 100644 --- a/docs/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-advanced-capabilities-expansion-plan.md +++ b/docs/history/packages/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-advanced-capabilities-expansion-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-14 +- 요약: WebSocket 실행 계획의 납품 원본이다. +- 현재 정본: `src/adapter/inbound/websocket/README.md` + + # WebSocket Advanced Capability Expansion Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-realtime-connection-platform-implementation-plan.md b/docs/history/packages/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-realtime-connection-platform-implementation-plan.md similarity index 99% rename from docs/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-realtime-connection-platform-implementation-plan.md rename to docs/history/packages/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-realtime-connection-platform-implementation-plan.md index 6ee91e05..51d0fa4b 100644 --- a/docs/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-realtime-connection-platform-implementation-plan.md +++ b/docs/history/packages/websocket-superpowers-package/docs/superpowers/plans/2026-08-14-websocket-realtime-connection-platform-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-14 +- 요약: WebSocket 실행 계획의 납품 원본이다. +- 현재 정본: `src/adapter/inbound/websocket/README.md` + + # WebSocket 실시간 양방향 연결 실행 플랫폼 Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/websocket-superpowers-package/docs/superpowers/specs/2026-08-14-websocket-realtime-connection-platform-design.md b/docs/history/packages/websocket-superpowers-package/docs/superpowers/specs/2026-08-14-websocket-realtime-connection-platform-design.md similarity index 99% rename from docs/websocket-superpowers-package/docs/superpowers/specs/2026-08-14-websocket-realtime-connection-platform-design.md rename to docs/history/packages/websocket-superpowers-package/docs/superpowers/specs/2026-08-14-websocket-realtime-connection-platform-design.md index 09edbef4..6c9115f8 100644 --- a/docs/websocket-superpowers-package/docs/superpowers/specs/2026-08-14-websocket-realtime-connection-platform-design.md +++ b/docs/history/packages/websocket-superpowers-package/docs/superpowers/specs/2026-08-14-websocket-realtime-connection-platform-design.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-14 +- 요약: WebSocket 설계서의 납품 원본이다. +- 현재 정본: `src/adapter/inbound/websocket/README.md` + + # WebSocket 실시간 양방향 연결 실행 플랫폼 설계서 - **문서 상태:** 구현 기준선 확정 diff --git a/docs/websocket-superpowers-package/research/source-websocket-deep-research.md b/docs/history/packages/websocket-superpowers-package/research/source-websocket-deep-research.md similarity index 99% rename from docs/websocket-superpowers-package/research/source-websocket-deep-research.md rename to docs/history/packages/websocket-superpowers-package/research/source-websocket-deep-research.md index 5be010bd..d60eb5d1 100644 --- a/docs/websocket-superpowers-package/research/source-websocket-deep-research.md +++ b/docs/history/packages/websocket-superpowers-package/research/source-websocket-deep-research.md @@ -1,3 +1,12 @@ + +> **기록 · 납품 패키지** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-28 +- 요약: WebSocket 설계의 입력이 된 심층 조사 원문이다. +- 현재 정본: `src/adapter/inbound/websocket/README.md` + + # WebSocket 실시간 양방향 연결 실행 플랫폼 심층 리서치 ## 결론과 기술 기준선 diff --git a/docs/websocket-superpowers-package/validate_websocket_docs.py b/docs/history/packages/websocket-superpowers-package/validate_websocket_docs.py similarity index 100% rename from docs/websocket-superpowers-package/validate_websocket_docs.py rename to docs/history/packages/websocket-superpowers-package/validate_websocket_docs.py diff --git a/docs/superpowers/plans/2026-07-20-harness-policy-engine.md b/docs/history/plans/2026-07-20-harness-policy-engine.md similarity index 91% rename from docs/superpowers/plans/2026-07-20-harness-policy-engine.md rename to docs/history/plans/2026-07-20-harness-policy-engine.md index 40535a51..7352cf64 100644 --- a/docs/superpowers/plans/2026-07-20-harness-policy-engine.md +++ b/docs/history/plans/2026-07-20-harness-policy-engine.md @@ -1,3 +1,13 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 대체됨 +- 작성일: 2026-07-20 +- 요약: 하네스 규칙을 레지스트리 기반 정책 엔진으로 바꾸려던 실행 계획이다. +- 현재 정본: `src/config/architecture/modules.json` +- 대체됨: `docs/history/plans/2026-07-25-harness-free-mode-b-amendment.md` + + > **SUPERSEDED — HISTORICAL PROVENANCE ONLY (2026-07-25):** The user-approved harness-free > Mode B amendment supersedes this plan. Retain the body as historical provenance; it is not > executable instruction. diff --git a/docs/superpowers/plans/2026-07-25-application-outbox-failure-reporting-harness-free.md b/docs/history/plans/2026-07-25-application-outbox-failure-reporting-harness-free.md similarity index 93% rename from docs/superpowers/plans/2026-07-25-application-outbox-failure-reporting-harness-free.md rename to docs/history/plans/2026-07-25-application-outbox-failure-reporting-harness-free.md index 91d1f8f0..5977f41a 100644 --- a/docs/superpowers/plans/2026-07-25-application-outbox-failure-reporting-harness-free.md +++ b/docs/history/plans/2026-07-25-application-outbox-failure-reporting-harness-free.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-25 +- 요약: 하네스 없이 application-core의 outbox 실패 보고를 프레임워크 없이 만드는 실행 계획이다. +- 현재 정본: `src/composition/outbox-relay/README.md` + + # Application Outbox Failure Reporting Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development diff --git a/docs/superpowers/plans/2026-07-25-application-outbox-failure-reporting.md b/docs/history/plans/2026-07-25-application-outbox-failure-reporting.md similarity index 99% rename from docs/superpowers/plans/2026-07-25-application-outbox-failure-reporting.md rename to docs/history/plans/2026-07-25-application-outbox-failure-reporting.md index a985e2e0..9417cd11 100644 --- a/docs/superpowers/plans/2026-07-25-application-outbox-failure-reporting.md +++ b/docs/history/plans/2026-07-25-application-outbox-failure-reporting.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-25 +- 요약: application-core에서 Spring·로깅 결합을 걷어내고 outbox 실패를 보고하는 실행 계획이다. +- 현재 정본: `src/composition/outbox-relay/README.md` + + # Application Outbox Failure Reporting Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-07-25-ci-control-plane-recovery.md b/docs/history/plans/2026-07-25-ci-control-plane-recovery.md similarity index 99% rename from docs/superpowers/plans/2026-07-25-ci-control-plane-recovery.md rename to docs/history/plans/2026-07-25-ci-control-plane-recovery.md index 9ba0c491..66fc2666 100644 --- a/docs/superpowers/plans/2026-07-25-ci-control-plane-recovery.md +++ b/docs/history/plans/2026-07-25-ci-control-plane-recovery.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-25 +- 요약: CI 제어면을 되살려 Gradle·Docker 빌드를 맞추는 실행 계획이다. +- 현재 정본: `docs/work/reference/gates.md` + + # CI Control Plane Recovery Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-07-25-harness-free-mode-b-amendment.md b/docs/history/plans/2026-07-25-harness-free-mode-b-amendment.md similarity index 89% rename from docs/superpowers/plans/2026-07-25-harness-free-mode-b-amendment.md rename to docs/history/plans/2026-07-25-harness-free-mode-b-amendment.md index b4da4907..252dbc9b 100644 --- a/docs/superpowers/plans/2026-07-25-harness-free-mode-b-amendment.md +++ b/docs/history/plans/2026-07-25-harness-free-mode-b-amendment.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-25 +- 요약: 하네스 없이 Gradle 부트스트랩과 의존 방향 검사를 되살리는 실행 계획이다. +- 현재 정본: `src/config/architecture/modules.json` + + # Harness-Free Mode B Amendment Implementation Plan > **For agentic workers:** Execute this plan task-by-task with diff --git a/docs/superpowers/plans/2026-07-25-harness-free-quality-security-ci.md b/docs/history/plans/2026-07-25-harness-free-quality-security-ci.md similarity index 92% rename from docs/superpowers/plans/2026-07-25-harness-free-quality-security-ci.md rename to docs/history/plans/2026-07-25-harness-free-quality-security-ci.md index eb6d6c70..221815ee 100644 --- a/docs/superpowers/plans/2026-07-25-harness-free-quality-security-ci.md +++ b/docs/history/plans/2026-07-25-harness-free-quality-security-ci.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-25 +- 요약: 하네스 없는 품질·의존성 보안 CI를 다시 세우는 실행 계획이다. +- 현재 정본: `docs/work/reference/gates.md` + + # Harness-Free Quality and Security CI Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use `superpowers:executing-plans` to implement this diff --git a/docs/superpowers/plans/2026-07-25-module-gradle-hygiene-harness-free.md b/docs/history/plans/2026-07-25-module-gradle-hygiene-harness-free.md similarity index 92% rename from docs/superpowers/plans/2026-07-25-module-gradle-hygiene-harness-free.md rename to docs/history/plans/2026-07-25-module-gradle-hygiene-harness-free.md index 411ac783..d7056358 100644 --- a/docs/superpowers/plans/2026-07-25-module-gradle-hygiene-harness-free.md +++ b/docs/history/plans/2026-07-25-module-gradle-hygiene-harness-free.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-25 +- 요약: 하네스 없이 leaf 의존·경계 정리를 적용하는 실행 계획이다. +- 현재 정본: `src/config/architecture/modules.json` + + # Harness-Free Module and Gradle Hygiene Implementation Plan **Goal:** Apply the approved 19-leaf dependency and boundary cleanup without `.harness`. diff --git a/docs/superpowers/plans/2026-07-25-module-gradle-hygiene.md b/docs/history/plans/2026-07-25-module-gradle-hygiene.md similarity index 99% rename from docs/superpowers/plans/2026-07-25-module-gradle-hygiene.md rename to docs/history/plans/2026-07-25-module-gradle-hygiene.md index a95af829..806cc850 100644 --- a/docs/superpowers/plans/2026-07-25-module-gradle-hygiene.md +++ b/docs/history/plans/2026-07-25-module-gradle-hygiene.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-25 +- 요약: leaf Gradle 그래프를 최소로 줄이는 리팩터링 실행 계획이다. +- 현재 정본: `src/config/architecture/modules.json` + + # Module and Gradle Hygiene Refactoring Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-07-28-fileserver-durable-recovery.md b/docs/history/plans/2026-07-28-fileserver-durable-recovery.md similarity index 88% rename from docs/superpowers/plans/2026-07-28-fileserver-durable-recovery.md rename to docs/history/plans/2026-07-28-fileserver-durable-recovery.md index 5b1ed10d..acc73a4d 100644 --- a/docs/superpowers/plans/2026-07-28-fileserver-durable-recovery.md +++ b/docs/history/plans/2026-07-28-fileserver-durable-recovery.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-07-28 +- 요약: 파일 서버 로컬 publication provider가 재시작에도 완료·봉인 상태를 지키게 하는 실행 계획이다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver Durable Recovery Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this diff --git a/docs/superpowers/plans/2026-07-28-fileserver-production-capability-foundation.md b/docs/history/plans/2026-07-28-fileserver-production-capability-foundation.md similarity index 95% rename from docs/superpowers/plans/2026-07-28-fileserver-production-capability-foundation.md rename to docs/history/plans/2026-07-28-fileserver-production-capability-foundation.md index 6750df8d..72110157 100644 --- a/docs/superpowers/plans/2026-07-28-fileserver-production-capability-foundation.md +++ b/docs/history/plans/2026-07-28-fileserver-production-capability-foundation.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-28 +- 요약: 파일 서버 CSV 예제를 프레임워크 없는 publication 계약과 단계형 로컬 provider로 바꾸는 실행 계획이다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver Production Capability Foundation Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-07-28-fileserver-r2-control-plane-provider-selection.md b/docs/history/plans/2026-07-28-fileserver-r2-control-plane-provider-selection.md similarity index 98% rename from docs/superpowers/plans/2026-07-28-fileserver-r2-control-plane-provider-selection.md rename to docs/history/plans/2026-07-28-fileserver-r2-control-plane-provider-selection.md index 801794c9..945e425a 100644 --- a/docs/superpowers/plans/2026-07-28-fileserver-r2-control-plane-provider-selection.md +++ b/docs/history/plans/2026-07-28-fileserver-r2-control-plane-provider-selection.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-07-28 +- 요약: 파일 서버 R2 제어면과 provider 선택을 넣는 실행 계획이다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver R2 Control Plane and Provider Selection Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use diff --git a/docs/superpowers/plans/2026-07-28-httpclient-canonical-zero-binding.md b/docs/history/plans/2026-07-28-httpclient-canonical-zero-binding.md similarity index 93% rename from docs/superpowers/plans/2026-07-28-httpclient-canonical-zero-binding.md rename to docs/history/plans/2026-07-28-httpclient-canonical-zero-binding.md index 8b129d76..5f90a26d 100644 --- a/docs/superpowers/plans/2026-07-28-httpclient-canonical-zero-binding.md +++ b/docs/history/plans/2026-07-28-httpclient-canonical-zero-binding.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-07-28 +- 요약: HTTP client 활성화를 명시적인 조립 결정으로 만드는 실행 계획이다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + # HTTP Client Canonical Zero-Binding Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use diff --git a/docs/superpowers/plans/2026-07-28-httpclient-production-capability-foundation.md b/docs/history/plans/2026-07-28-httpclient-production-capability-foundation.md similarity index 91% rename from docs/superpowers/plans/2026-07-28-httpclient-production-capability-foundation.md rename to docs/history/plans/2026-07-28-httpclient-production-capability-foundation.md index 18cd7483..5d61060a 100644 --- a/docs/superpowers/plans/2026-07-28-httpclient-production-capability-foundation.md +++ b/docs/history/plans/2026-07-28-httpclient-production-capability-foundation.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-07-28 +- 요약: HTTP client의 호출 예산과 typed operation·target 기반을 세우는 실행 계획이다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + # HTTP Client Production Capability Foundation Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development diff --git a/docs/superpowers/plans/2026-07-28-httpclient-total-deadline.md b/docs/history/plans/2026-07-28-httpclient-total-deadline.md similarity index 87% rename from docs/superpowers/plans/2026-07-28-httpclient-total-deadline.md rename to docs/history/plans/2026-07-28-httpclient-total-deadline.md index 40e0d080..2f88342c 100644 --- a/docs/superpowers/plans/2026-07-28-httpclient-total-deadline.md +++ b/docs/history/plans/2026-07-28-httpclient-total-deadline.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-07-28 +- 요약: HTTP 논리 호출 전체(재시도 대기 포함)에 호출 예산을 강제하는 실행 계획이다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + # HTTP Client Total Deadline Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this diff --git a/docs/superpowers/plans/2026-07-28-jpa-production-capability.md b/docs/history/plans/2026-07-28-jpa-production-capability.md similarity index 97% rename from docs/superpowers/plans/2026-07-28-jpa-production-capability.md rename to docs/history/plans/2026-07-28-jpa-production-capability.md index b3024afd..16e890b5 100644 --- a/docs/superpowers/plans/2026-07-28-jpa-production-capability.md +++ b/docs/history/plans/2026-07-28-jpa-production-capability.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-28 +- 요약: JPA·PostgreSQL을 운영 capability로 올리는 실행 계획이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA/PostgreSQL Production Capability Implementation Plan > 상태: Phase 0~3 기반과 Phase 4의 idempotency/outbox polling/inbox 후보 구현 및 전체 diff --git a/docs/superpowers/plans/2026-07-28-messaging-first-r2-polling-producer.md b/docs/history/plans/2026-07-28-messaging-first-r2-polling-producer.md similarity index 99% rename from docs/superpowers/plans/2026-07-28-messaging-first-r2-polling-producer.md rename to docs/history/plans/2026-07-28-messaging-first-r2-polling-producer.md index a28aa914..3516ae5a 100644 --- a/docs/superpowers/plans/2026-07-28-messaging-first-r2-polling-producer.md +++ b/docs/history/plans/2026-07-28-messaging-first-r2-polling-producer.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-28 +- 요약: typed 통합 이벤트에서 시작하는 첫 운영 기준 메시징 경로(R2 polling producer)를 만드는 실행 계획이다. +- 현재 정본: `docs/messaging/support-matrix.md` + + # Messaging First R2 Polling Producer Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use @@ -26,7 +35,7 @@ Testcontainers Kafka/PostgreSQL, Micrometer. - 작성일: 2026-07-28 - 상태: 실행 계획 작성·독립 검토 완료, 모든 task 미착수 - 설계 정본: - [Messaging Production Capability Deep Design](../specs/2026-07-28-messaging-production-capability-design.md) + [Messaging Production Capability Deep Design](../../design/2026-07-28-messaging-production-capability-design.md) - 구현 범위: P0–P4의 first R2 polling producer tuple - 명시적 비범위: inbound Kafka consumer, inbox, retry topic, DLT/replay, Kafka EOS, Debezium/Kafka Connect CDC, Avro/Protobuf/schema registry, alternate broker, multi-cluster diff --git a/docs/superpowers/plans/2026-07-28-notification-production-capability.md b/docs/history/plans/2026-07-28-notification-production-capability.md similarity index 99% rename from docs/superpowers/plans/2026-07-28-notification-production-capability.md rename to docs/history/plans/2026-07-28-notification-production-capability.md index 3266922d..0eaac617 100644 --- a/docs/superpowers/plans/2026-07-28-notification-production-capability.md +++ b/docs/history/plans/2026-07-28-notification-production-capability.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-28 +- 요약: 알림을 운영 capability로 올리는 실행 계획이다. +- 현재 정본: `docs/notification/support-matrix.md` + + # Notification Production Capability Implementation Plan > **Execution workflow:** 구현 시 `superpowers:subagent-driven-development`, @@ -15,7 +24,7 @@ provider/runtime 범위는 미착수다. 아래 isolated-worktree 검증 기록과 main 통합 검증 결과는 서로 다른 증거로 구분한다. - 설계 정본: - [Notification Production Capability Deep Design](../specs/2026-07-28-notification-production-capability-design.md) + [Notification Production Capability Deep Design](../../design/2026-07-28-notification-production-capability-design.md) - 비교한 실행 계획: [Redis Foundation](2026-07-28-redis-production-capability-foundation.md), [Redis Runtime](2026-07-28-redis-runtime-cache.md), diff --git a/docs/superpowers/plans/2026-07-28-objectstorage-production-capability.md b/docs/history/plans/2026-07-28-objectstorage-production-capability.md similarity index 99% rename from docs/superpowers/plans/2026-07-28-objectstorage-production-capability.md rename to docs/history/plans/2026-07-28-objectstorage-production-capability.md index f6b61b94..d1011294 100644 --- a/docs/superpowers/plans/2026-07-28-objectstorage-production-capability.md +++ b/docs/history/plans/2026-07-28-objectstorage-production-capability.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-28 +- 요약: 호출자 키·byte[] 예제를 프레임워크 없는 object storage 계약으로 바꾸는 실행 계획이다. +- 현재 정본: `src/adapter/outbound/objectstorage/README.md` + + # Object Storage Production Capability Implementation Plan - 작성일: 2026-07-28 @@ -32,7 +41,7 @@ multi-module verification, JUnit 5, AssertJ, jqwik `1.9.1`, AWS SDK for Java v2 Toxiproxy, PostgreSQL/Flyway for the sample workflow, Micrometer/Actuator. **Authoritative design:** -[Object Storage Production Capability Deep Design](../specs/2026-07-28-objectstorage-production-capability-design.md). +[Object Storage Production Capability Deep Design](../../design/2026-07-28-objectstorage-production-capability-design.md). When this plan and that design differ, stop and amend the design before implementing. Module edges remain governed only by `src/config/architecture/modules.json`. @@ -51,13 +60,13 @@ single upload/download cards remain R1; every direct, multipart, quarantine, ret production reconciliation card remains R0. The exhaustive R2 fault/race matrices named by unchecked steps remain follow-up evidence, not implied completion. The legacy provider and Poster consumer remain isolated behind explicit sample-local/test activation. Evidence: -[Batch A](../../evidence/object-storage/batch-a-checkpoint.md), -[Batch B](../../evidence/object-storage/batch-b-checkpoint.md), and -[Batch C](../../evidence/object-storage/batch-c-progress.md), -[Batch D](../../evidence/object-storage/batch-d-checkpoint.md). +[Batch A](../evidence/object-storage/batch-a-checkpoint.md), +[Batch B](../evidence/object-storage/batch-b-checkpoint.md), and +[Batch C](../evidence/object-storage/batch-c-progress.md), +[Batch D](../evidence/object-storage/batch-d-checkpoint.md). Batch E의 개별 focused fix 증거는 -[Batch E pause checkpoint](../../evidence/object-storage/batch-e-pause-checkpoint.md)에 기록됐다. +[Batch E pause checkpoint](../evidence/object-storage/batch-e-pause-checkpoint.md)에 기록됐다. 당시 Batch E combined/root gate는 재실행되지 않았으므로 Batch E 전체 완료나 R2를 주장하지 않는다. 격리 브랜치에서 잘못 선택했던 private vault 경로 대신, main 통합 작업은 사용자가 캡처했다. diff --git a/docs/superpowers/plans/2026-07-28-redis-cache-resilience.md b/docs/history/plans/2026-07-28-redis-cache-resilience.md similarity index 82% rename from docs/superpowers/plans/2026-07-28-redis-cache-resilience.md rename to docs/history/plans/2026-07-28-redis-cache-resilience.md index fd4974fe..8e187285 100644 --- a/docs/superpowers/plans/2026-07-28-redis-cache-resilience.md +++ b/docs/history/plans/2026-07-28-redis-cache-resilience.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-28 +- 요약: Redis 캐시 회복력(cache-aside, 원본 보호, TTL) 설계를 구현하는 실행 계획이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Cache Resilience Implementation Plan > Repository commit policy is human-only. Do not stage, commit, amend or push. diff --git a/docs/superpowers/plans/2026-07-28-redis-distributed-rate-limit.md b/docs/history/plans/2026-07-28-redis-distributed-rate-limit.md similarity index 83% rename from docs/superpowers/plans/2026-07-28-redis-distributed-rate-limit.md rename to docs/history/plans/2026-07-28-redis-distributed-rate-limit.md index ddb47b89..87a0e9f9 100644 --- a/docs/superpowers/plans/2026-07-28-redis-distributed-rate-limit.md +++ b/docs/history/plans/2026-07-28-redis-distributed-rate-limit.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-28 +- 요약: Redis 분산 rate-limit 알고리즘을 구현하는 실행 계획이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Distributed Rate-Limit Implementation Plan > Repository commit policy is human-only. Do not stage, commit, amend or push. diff --git a/docs/superpowers/plans/2026-07-28-redis-production-capability-foundation.md b/docs/history/plans/2026-07-28-redis-production-capability-foundation.md similarity index 92% rename from docs/superpowers/plans/2026-07-28-redis-production-capability-foundation.md rename to docs/history/plans/2026-07-28-redis-production-capability-foundation.md index 03cef9c0..93352bc8 100644 --- a/docs/superpowers/plans/2026-07-28-redis-production-capability-foundation.md +++ b/docs/history/plans/2026-07-28-redis-production-capability-foundation.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-07-28 +- 요약: Redis 캐시 이음매를 프레임워크 없는 의미 캐시 계약으로 바꾸는 실행 계획이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Production Capability Foundation Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development diff --git a/docs/superpowers/plans/2026-07-28-redis-runtime-cache.md b/docs/history/plans/2026-07-28-redis-runtime-cache.md similarity index 89% rename from docs/superpowers/plans/2026-07-28-redis-runtime-cache.md rename to docs/history/plans/2026-07-28-redis-runtime-cache.md index ef4b8943..4c5b2ac1 100644 --- a/docs/superpowers/plans/2026-07-28-redis-runtime-cache.md +++ b/docs/history/plans/2026-07-28-redis-runtime-cache.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-07-28 +- 요약: opt-in Lettuce 런타임과 Lua 기반 의미 캐시를 넣는 실행 계획이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Runtime And Semantic Cache Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this diff --git a/docs/superpowers/plans/2026-07-29-redis-production-capability-completion.md b/docs/history/plans/2026-07-29-redis-production-capability-completion.md similarity index 98% rename from docs/superpowers/plans/2026-07-29-redis-production-capability-completion.md rename to docs/history/plans/2026-07-29-redis-production-capability-completion.md index 480d9344..9a3250d0 100644 --- a/docs/superpowers/plans/2026-07-29-redis-production-capability-completion.md +++ b/docs/history/plans/2026-07-29-redis-production-capability-completion.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-07-29 +- 요약: Redis 운영 capability 설계의 1~5단계를 capability별로 마무리하는 계획이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Production Capability Completion Plan > **Scope:** Redis를 먼저 완료한다. 현재 실행 단위는 deep design Phase 5 전체가 아니라 diff --git a/docs/superpowers/plans/2026-07-30-redis-lab-strict-kubeconfig-renderer.md b/docs/history/plans/2026-07-30-redis-lab-strict-kubeconfig-renderer.md similarity index 95% rename from docs/superpowers/plans/2026-07-30-redis-lab-strict-kubeconfig-renderer.md rename to docs/history/plans/2026-07-30-redis-lab-strict-kubeconfig-renderer.md index 1021b1a6..76a47efa 100644 --- a/docs/superpowers/plans/2026-07-30-redis-lab-strict-kubeconfig-renderer.md +++ b/docs/history/plans/2026-07-30-redis-lab-strict-kubeconfig-renderer.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-07-30 +- 요약: Redis 실험 환경의 kubeconfig를 엄격한 렌더러로 만드는 실행 계획이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Lab Strict Kubeconfig Renderer Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use diff --git a/docs/superpowers/plans/2026-08-01-release-hygiene-refactoring.md b/docs/history/plans/2026-08-01-release-hygiene-refactoring.md similarity index 98% rename from docs/superpowers/plans/2026-08-01-release-hygiene-refactoring.md rename to docs/history/plans/2026-08-01-release-hygiene-refactoring.md index c15722da..4878e2a7 100644 --- a/docs/superpowers/plans/2026-08-01-release-hygiene-refactoring.md +++ b/docs/history/plans/2026-08-01-release-hygiene-refactoring.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-01 +- 요약: 릴리스 위생 경로를 사실대로 맞추는 리팩터링 실행 계획이다. +- 현재 정본: `docs/work/reference/gates.md` + + # Release Hygiene Refactoring Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-02-client-safe-error-boundary.md b/docs/history/plans/2026-08-02-client-safe-error-boundary.md similarity index 90% rename from docs/superpowers/plans/2026-08-02-client-safe-error-boundary.md rename to docs/history/plans/2026-08-02-client-safe-error-boundary.md index d1c02c5b..16b63143 100644 --- a/docs/superpowers/plans/2026-08-02-client-safe-error-boundary.md +++ b/docs/history/plans/2026-08-02-client-safe-error-boundary.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-08-02 +- 요약: 공개 HTTP 오류 응답에 허용 문구만 담게 하는 실행 계획이다. +- 현재 정본: `docs/web/http-contract.md` + + # Client-Safe Error Boundary Implementation Plan > **Execution:** Follow `superpowers:test-driven-development`; request an independent code review diff --git a/docs/superpowers/plans/2026-08-02-conditional-inbound-transport-boundary.md b/docs/history/plans/2026-08-02-conditional-inbound-transport-boundary.md similarity index 90% rename from docs/superpowers/plans/2026-08-02-conditional-inbound-transport-boundary.md rename to docs/history/plans/2026-08-02-conditional-inbound-transport-boundary.md index 49f9f44a..a1749094 100644 --- a/docs/superpowers/plans/2026-08-02-conditional-inbound-transport-boundary.md +++ b/docs/history/plans/2026-08-02-conditional-inbound-transport-boundary.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-02 +- 요약: GraphQL·gRPC·WebSocket을 고를 때만 켜고 위험한 활성화를 막는 실행 계획이다. +- 현재 정본: `docs/web/http-contract.md` + + # Conditional Inbound Transport Boundary Implementation Plan > **Execution:** Apply TDD independently per transport, then run exact no-skip qualification and an diff --git a/docs/superpowers/plans/2026-08-02-p2-verification-governance-refactoring.md b/docs/history/plans/2026-08-02-p2-verification-governance-refactoring.md similarity index 97% rename from docs/superpowers/plans/2026-08-02-p2-verification-governance-refactoring.md rename to docs/history/plans/2026-08-02-p2-verification-governance-refactoring.md index 74fdd3cc..d0d32b58 100644 --- a/docs/superpowers/plans/2026-08-02-p2-verification-governance-refactoring.md +++ b/docs/history/plans/2026-08-02-p2-verification-governance-refactoring.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-02 +- 요약: 남은 fail-open 검증 경로를 없애는 리팩터링 계획이다. +- 현재 정본: `docs/work/reference/gates.md` + + # P2 Verification Governance Refactoring Plan ## Batch 1 — strict owner-local qualification diff --git a/docs/superpowers/plans/2026-08-02-redis-session-http-boundary.md b/docs/history/plans/2026-08-02-redis-session-http-boundary.md similarity index 89% rename from docs/superpowers/plans/2026-08-02-redis-session-http-boundary.md rename to docs/history/plans/2026-08-02-redis-session-http-boundary.md index b3e11cb2..1f81cffb 100644 --- a/docs/superpowers/plans/2026-08-02-redis-session-http-boundary.md +++ b/docs/history/plans/2026-08-02-redis-session-http-boundary.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-08-02 +- 요약: Redis 세션과 HTTP 경계의 보안을 실제 Spring Session으로 증명하는 실행 계획이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Session HTTP Boundary Implementation Plan > **Execution:** Follow test-driven development and request an independent read-only review before diff --git a/docs/superpowers/plans/2026-08-02-verification-purity-refactoring.md b/docs/history/plans/2026-08-02-verification-purity-refactoring.md similarity index 92% rename from docs/superpowers/plans/2026-08-02-verification-purity-refactoring.md rename to docs/history/plans/2026-08-02-verification-purity-refactoring.md index de4d0504..fec243af 100644 --- a/docs/superpowers/plans/2026-08-02-verification-purity-refactoring.md +++ b/docs/history/plans/2026-08-02-verification-purity-refactoring.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-08-02 +- 요약: 검증 경로를 읽기 전용으로 바꾸는 실행 계획이다. +- 현재 정본: `docs/work/reference/gates.md` + + # Verification Purity Refactoring Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-02-warning-zero-build-refactoring.md b/docs/history/plans/2026-08-02-warning-zero-build-refactoring.md similarity index 98% rename from docs/superpowers/plans/2026-08-02-warning-zero-build-refactoring.md rename to docs/history/plans/2026-08-02-warning-zero-build-refactoring.md index 62626953..3ec33f4c 100644 --- a/docs/superpowers/plans/2026-08-02-warning-zero-build-refactoring.md +++ b/docs/history/plans/2026-08-02-warning-zero-build-refactoring.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-02 +- 요약: 빌드 경고를 0으로 만드는 리팩터링 실행 계획이다. +- 현재 정본: `docs/work/reference/gates.md` + + # Warning-Zero Build Refactoring Implementation Plan > **For Codex:** REQUIRED SUB-SKILLS: use `superpowers:subagent-driven-development` for the diff --git a/docs/superpowers/plans/2026-08-02-web-security-boundary.md b/docs/history/plans/2026-08-02-web-security-boundary.md similarity index 87% rename from docs/superpowers/plans/2026-08-02-web-security-boundary.md rename to docs/history/plans/2026-08-02-web-security-boundary.md index 1b6f8a21..a8e4fa09 100644 --- a/docs/superpowers/plans/2026-08-02-web-security-boundary.md +++ b/docs/history/plans/2026-08-02-web-security-boundary.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-08-02 +- 요약: JWT·JWKS·CORS 필터 경계를 밀봉 테스트로 고정하는 실행 계획이다. +- 현재 정본: `docs/web/http-contract.md` + + # Web Security Boundary Implementation Plan > **Execution:** Follow test-driven development and request an independent read-only review before diff --git a/docs/superpowers/plans/2026-08-07-fileserver-platform-implementation-plan.md b/docs/history/plans/2026-08-07-fileserver-platform-implementation-plan.md similarity index 99% rename from docs/superpowers/plans/2026-08-07-fileserver-platform-implementation-plan.md rename to docs/history/plans/2026-08-07-fileserver-platform-implementation-plan.md index 93932a62..730de6aa 100644 --- a/docs/superpowers/plans/2026-08-07-fileserver-platform-implementation-plan.md +++ b/docs/history/plans/2026-08-07-fileserver-platform-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-07 +- 요약: 파일 서버 플랫폼(streaming 업로드, 상태 기반 게시, Range 다운로드, tus)을 만드는 실행 계획이다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver Platform Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-implementation-plan.md b/docs/history/plans/2026-08-07-redis-wrapper-typed-api-implementation-plan.md similarity index 99% rename from docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-implementation-plan.md rename to docs/history/plans/2026-08-07-redis-wrapper-typed-api-implementation-plan.md index dfb103bd..f1389891 100644 --- a/docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-implementation-plan.md +++ b/docs/history/plans/2026-08-07-redis-wrapper-typed-api-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-07 +- 요약: Redis 자료구조 전체를 Typed API와 Raw Gateway로 제공하는 SDK 실행 계획이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Wrapper and Typed API Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-status.md b/docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md similarity index 99% rename from docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-status.md rename to docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md index 28ac923e..ca1b5738 100644 --- a/docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-status.md +++ b/docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-07 +- 요약: Redis Wrapper·Typed API를 이 저장소에 맞춘 방법과 납품 상태 기록이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Wrapper and Typed API — repository adaptation and delivery status - **Design:** `docs/superpowers/specs/2026-08-07-redis-wrapper-typed-api-design.md` diff --git a/docs/superpowers/plans/2026-08-08-httpclient-platform-implementation-plan.md b/docs/history/plans/2026-08-08-httpclient-platform-implementation-plan.md similarity index 99% rename from docs/superpowers/plans/2026-08-08-httpclient-platform-implementation-plan.md rename to docs/history/plans/2026-08-08-httpclient-platform-implementation-plan.md index d00adfa8..1345a332 100644 --- a/docs/superpowers/plans/2026-08-08-httpclient-platform-implementation-plan.md +++ b/docs/history/plans/2026-08-08-httpclient-platform-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-08 +- 요약: HTTP client 플랫폼(Typed Service Client, 재시도, OAuth2·TLS, SSRF 방어)을 만드는 실행 계획이다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + # HTTP Client Platform Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-10-httpclient-platform-activation-and-env-ssot.md b/docs/history/plans/2026-08-10-httpclient-platform-activation-and-env-ssot.md similarity index 99% rename from docs/superpowers/plans/2026-08-10-httpclient-platform-activation-and-env-ssot.md rename to docs/history/plans/2026-08-10-httpclient-platform-activation-and-env-ssot.md index e6172474..d5fd6336 100644 --- a/docs/superpowers/plans/2026-08-10-httpclient-platform-activation-and-env-ssot.md +++ b/docs/history/plans/2026-08-10-httpclient-platform-activation-and-env-ssot.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-10 +- 요약: HTTP client 플랫폼을 켤 때만 있는 capability로 만들고 env 정본을 정하는 실행 계획이다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + # HTTP Client Platform — Activation Boundary and ENV SSOT Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-10-messaging-platform-implementation-plan.md b/docs/history/plans/2026-08-10-messaging-platform-implementation-plan.md similarity index 99% rename from docs/superpowers/plans/2026-08-10-messaging-platform-implementation-plan.md rename to docs/history/plans/2026-08-10-messaging-platform-implementation-plan.md index 56cd6f22..0ebc3715 100644 --- a/docs/superpowers/plans/2026-08-10-messaging-platform-implementation-plan.md +++ b/docs/history/plans/2026-08-10-messaging-platform-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-10 +- 요약: 메시징 플랫폼(증거 기반 발행, 중복 안전 소비, Kafka·RabbitMQ, outbox·inbox)을 만드는 실행 계획이다. +- 현재 정본: `docs/messaging/support-matrix.md` + + # Messaging Platform Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-10-notification-platform-implementation-plan.md b/docs/history/plans/2026-08-10-notification-platform-implementation-plan.md similarity index 99% rename from docs/superpowers/plans/2026-08-10-notification-platform-implementation-plan.md rename to docs/history/plans/2026-08-10-notification-platform-implementation-plan.md index d79ae00a..07c44362 100644 --- a/docs/superpowers/plans/2026-08-10-notification-platform-implementation-plan.md +++ b/docs/history/plans/2026-08-10-notification-platform-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-10 +- 요약: 알림 전달 플랫폼(수명주기, provider 결과, 예약, callback 원장, 채널 어댑터)을 만드는 실행 계획이다. +- 현재 정본: `docs/notification/support-matrix.md` + + # Notification Delivery Platform Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-10-redis-optionality-and-composition.md b/docs/history/plans/2026-08-10-redis-optionality-and-composition.md similarity index 97% rename from docs/superpowers/plans/2026-08-10-redis-optionality-and-composition.md rename to docs/history/plans/2026-08-10-redis-optionality-and-composition.md index 260eec6b..ccfdc7a1 100644 --- a/docs/superpowers/plans/2026-08-10-redis-optionality-and-composition.md +++ b/docs/history/plans/2026-08-10-redis-optionality-and-composition.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-10 +- 요약: Redis를 끄면 정말 아무것도 싣지 않게 하는 선택성·조립 실행 계획이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Optionality and Composition Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development diff --git a/docs/superpowers/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md b/docs/history/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md similarity index 98% rename from docs/superpowers/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md rename to docs/history/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md index bc9c1ae1..5e43c356 100644 --- a/docs/superpowers/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md +++ b/docs/history/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-11 +- 요약: Stable JPA 플랫폼을 건드리지 않고 multi-tenancy·RLS·read replica 등 실험 기능을 더하는 계획이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA Experimental Expansion Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md b/docs/history/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md similarity index 99% rename from docs/superpowers/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md rename to docs/history/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md index 43d000df..2816b2a6 100644 --- a/docs/superpowers/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md +++ b/docs/history/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-11 +- 요약: JPA 관계형 영속성 플랫폼을 만드는 실행 계획이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA 관계형 영속성 플랫폼 Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-11-mongodb-advanced-capabilities-expansion-plan.md b/docs/history/plans/2026-08-11-mongodb-advanced-capabilities-expansion-plan.md similarity index 99% rename from docs/superpowers/plans/2026-08-11-mongodb-advanced-capabilities-expansion-plan.md rename to docs/history/plans/2026-08-11-mongodb-advanced-capabilities-expansion-plan.md index 3990a179..0d731a20 100644 --- a/docs/superpowers/plans/2026-08-11-mongodb-advanced-capabilities-expansion-plan.md +++ b/docs/history/plans/2026-08-11-mongodb-advanced-capabilities-expansion-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-11 +- 요약: MongoDB 문서 영속성 플랫폼에 sharding·암호화·검색 등 고급 기능을 더하는 계획이다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + # MongoDB Advanced Capabilities Expansion Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-11-mongodb-document-persistence-platform-implementation-plan.md b/docs/history/plans/2026-08-11-mongodb-document-persistence-platform-implementation-plan.md similarity index 99% rename from docs/superpowers/plans/2026-08-11-mongodb-document-persistence-platform-implementation-plan.md rename to docs/history/plans/2026-08-11-mongodb-document-persistence-platform-implementation-plan.md index 76f6399b..711366a7 100644 --- a/docs/superpowers/plans/2026-08-11-mongodb-document-persistence-platform-implementation-plan.md +++ b/docs/history/plans/2026-08-11-mongodb-document-persistence-platform-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-11 +- 요약: MongoDB 문서 영속성 플랫폼을 만드는 실행 계획이다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + # MongoDB 문서 영속성 플랫폼 Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md b/docs/history/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md similarity index 99% rename from docs/superpowers/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md rename to docs/history/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md index 904319ae..cd5b86e2 100644 --- a/docs/superpowers/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md +++ b/docs/history/plans/2026-08-12-graphql-advanced-capabilities-expansion-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-12 +- 요약: GraphQL 실행 플랫폼에 persisted operation·subscription·federation 등을 더하는 계획이다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # GraphQL Advanced Capability Expansion Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md b/docs/history/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md similarity index 99% rename from docs/superpowers/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md rename to docs/history/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md index 2f5204e1..17ef84f0 100644 --- a/docs/superpowers/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md +++ b/docs/history/plans/2026-08-12-graphql-api-execution-platform-implementation-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-12 +- 요약: GraphQL API 실행 플랫폼을 만드는 실행 계획이다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # GraphQL API 실행 플랫폼 Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-08-15-five-adapter-runtime-remediation-index.md b/docs/history/plans/2026-08-15-five-adapter-runtime-remediation-index.md similarity index 97% rename from docs/superpowers/plans/2026-08-15-five-adapter-runtime-remediation-index.md rename to docs/history/plans/2026-08-15-five-adapter-runtime-remediation-index.md index 35341719..36b98c51 100644 --- a/docs/superpowers/plans/2026-08-15-five-adapter-runtime-remediation-index.md +++ b/docs/history/plans/2026-08-15-five-adapter-runtime-remediation-index.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-15 +- 요약: 다섯 어댑터 런타임 개선 계획 묶음의 목차다. +- 현재 정본: `docs/capability-status.md` + + # Five-Adapter Runtime Remediation — Plan Index > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development @@ -25,7 +34,7 @@ dependency closure and fail closed at startup rather than at first request. JUnit 5 + AssertJ, ArchUnit 1.3.0, Testcontainers, Flyway, PostgreSQL 16–18, MongoDB, Kafka/RabbitMQ, Keycloak, MinIO, Docker Compose 5.4.0 (spec floor: 2.24.4). -**Spec:** [`docs/superpowers/specs/2026-08-15-five-adapter-runtime-remediation-review-design.md`](../specs/2026-08-15-five-adapter-runtime-remediation-review-design.md) +**Spec:** [`docs/superpowers/specs/2026-08-15-five-adapter-runtime-remediation-review-design.md`](../../design/2026-08-15-five-adapter-runtime-remediation-review-design.md) --- diff --git a/docs/superpowers/plans/2026-08-15-wave0-red-baseline.md b/docs/history/plans/2026-08-15-wave0-red-baseline.md similarity index 99% rename from docs/superpowers/plans/2026-08-15-wave0-red-baseline.md rename to docs/history/plans/2026-08-15-wave0-red-baseline.md index 3655e44c..6ad30ceb 100644 --- a/docs/superpowers/plans/2026-08-15-wave0-red-baseline.md +++ b/docs/history/plans/2026-08-15-wave0-red-baseline.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-15 +- 요약: 개선 설계가 지목한 실패를 먼저 실패하는 테스트로 고정하는 0단계 계획이다. +- 현재 정본: `docs/capability-status.md` + + # Wave 0 — Red Baseline and Evidence Pinning Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development @@ -22,7 +31,7 @@ report the exact remaining red set at any point during Waves 1–4. + `SpringApplication` process harness, Gradle 9 custom `Test` lanes, `docker compose config` as a subprocess. -**Spec:** [`docs/superpowers/specs/2026-08-15-five-adapter-runtime-remediation-review-design.md`](../specs/2026-08-15-five-adapter-runtime-remediation-review-design.md) +**Spec:** [`docs/superpowers/specs/2026-08-15-five-adapter-runtime-remediation-review-design.md`](../../design/2026-08-15-five-adapter-runtime-remediation-review-design.md) (§2, §3.1, §4, §11 Wave 0, §12.2) --- diff --git a/docs/superpowers/plans/2026-08-15-wave1-activation-ssot.md b/docs/history/plans/2026-08-15-wave1-activation-ssot.md similarity index 99% rename from docs/superpowers/plans/2026-08-15-wave1-activation-ssot.md rename to docs/history/plans/2026-08-15-wave1-activation-ssot.md index 2ee6ec62..6d46a217 100644 --- a/docs/superpowers/plans/2026-08-15-wave1-activation-ssot.md +++ b/docs/history/plans/2026-08-15-wave1-activation-ssot.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-15 +- 요약: 어댑터마다 활성화 정본 하나와 classpath를 정하는 1단계 계획이다. +- 현재 정본: `docs/capability-status.md` + + # Wave 1 — Activation SSOT and Classpath Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development @@ -28,7 +37,7 @@ capability roots whose conditions are computed from the same dependency closure. `AutoConfigurationImportFilter`, `EnvironmentPostProcessor`), Gradle 9 project dependencies, the architecture registry, JUnit 5 + `ApplicationContextRunner` + `@SpringBootTest`. -**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../specs/2026-08-15-five-adapter-runtime-remediation-review-design.md) +**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../../design/2026-08-15-five-adapter-runtime-remediation-review-design.md) (§4, §5, §6.1 JPA-INT-001/004, §6.2 MNG-INT-001/005, §6.3 MSG-INT-001, §6.4 NTF-INT-005, §6.5 GQL-INT-001, §11 Wave 1) diff --git a/docs/superpowers/plans/2026-08-15-wave2-module-on-path.md b/docs/history/plans/2026-08-15-wave2-module-on-path.md similarity index 98% rename from docs/superpowers/plans/2026-08-15-wave2-module-on-path.md rename to docs/history/plans/2026-08-15-wave2-module-on-path.md index edbf7aae..f9f1f87b 100644 --- a/docs/superpowers/plans/2026-08-15-wave2-module-on-path.md +++ b/docs/history/plans/2026-08-15-wave2-module-on-path.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-15 +- 요약: 스위치를 켜면 실제로 동작하게 모듈별 막힘을 푸는 2단계 계획이다. +- 현재 정본: `docs/capability-status.md` + + # Wave 2 — Module On-Path Blockers Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development @@ -22,7 +31,7 @@ through the real request path. **Tech Stack:** Testcontainers (PostgreSQL 16/17/18, MongoDB replica set, Kafka, RabbitMQ, Mailpit), Spring GraphQL, Spring Security OAuth2 resource server, Flyway, Micrometer. -**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../specs/2026-08-15-five-adapter-runtime-remediation-review-design.md) +**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../../design/2026-08-15-five-adapter-runtime-remediation-review-design.md) (§6 in full, §11 Wave 2, §12.2, §12.3) --- diff --git a/docs/superpowers/plans/2026-08-15-wave3-environment-and-infra.md b/docs/history/plans/2026-08-15-wave3-environment-and-infra.md similarity index 97% rename from docs/superpowers/plans/2026-08-15-wave3-environment-and-infra.md rename to docs/history/plans/2026-08-15-wave3-environment-and-infra.md index c0393113..ad67ff3a 100644 --- a/docs/superpowers/plans/2026-08-15-wave3-environment-and-infra.md +++ b/docs/history/plans/2026-08-15-wave3-environment-and-infra.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-15 +- 요약: 예제 설정과 운영 입력을 나누고 인프라 smoke를 세우는 3단계 계획이다. +- 현재 정본: `docs/capability-status.md` + + # Wave 3 — Environment Separation and Infrastructure Smoke Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development @@ -24,7 +33,7 @@ secret files, sanitized evidence, and a `trap`-driven teardown scoped to that pr **Tech Stack:** Docker Compose ≥ 2.24.4 (this machine: 5.4.0), PostgreSQL 16 with TLS, MongoDB replica set, Kafka, Mailpit, MinIO + `mc`, Keycloak with `--import-realm`, Bash. -**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../specs/2026-08-15-five-adapter-runtime-remediation-review-design.md) +**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../../design/2026-08-15-five-adapter-runtime-remediation-review-design.md) (§7 in full, §11 Wave 3, §12.4) --- diff --git a/docs/superpowers/plans/2026-08-15-wave4-warning-zero.md b/docs/history/plans/2026-08-15-wave4-warning-zero.md similarity index 96% rename from docs/superpowers/plans/2026-08-15-wave4-warning-zero.md rename to docs/history/plans/2026-08-15-wave4-warning-zero.md index 1374c4b5..a3486487 100644 --- a/docs/superpowers/plans/2026-08-15-wave4-warning-zero.md +++ b/docs/history/plans/2026-08-15-wave4-warning-zero.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-15 +- 요약: local·dev·prod 기동 로그의 WARN·ERROR를 0으로 만드는 4단계 계획이다. +- 현재 정본: `docs/capability-status.md` + + # Wave 4 — Runtime Warning and IDE Error Zero Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development @@ -21,7 +30,7 @@ warning gate itself is the Wave 0 recorder, promoted from characterization to a **Tech Stack:** Micrometer `MeterRegistryCustomizer`/`MeterFilter`, Spring `ObjectProvider`, Logback `springProfile`, Eclipse JDT preferences, Spring Tools LS settings. -**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../specs/2026-08-15-five-adapter-runtime-remediation-review-design.md) +**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../../design/2026-08-15-five-adapter-runtime-remediation-review-design.md) (§9 in full, §11 Wave 4) --- diff --git a/docs/superpowers/plans/2026-08-15-wave5-gradle-build-logic.md b/docs/history/plans/2026-08-15-wave5-gradle-build-logic.md similarity index 95% rename from docs/superpowers/plans/2026-08-15-wave5-gradle-build-logic.md rename to docs/history/plans/2026-08-15-wave5-gradle-build-logic.md index 9f177163..7d7ae9a4 100644 --- a/docs/superpowers/plans/2026-08-15-wave5-gradle-build-logic.md +++ b/docs/history/plans/2026-08-15-wave5-gradle-build-logic.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-15 +- 요약: 중복된 Gradle 빌드 로직을 convention으로 뽑는 5단계 계획이다. +- 현재 정본: `docs/capability-status.md` + + # Wave 5 — Gradle Build Logic Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development @@ -21,7 +30,7 @@ reporting green for work it no longer does. **Tech Stack:** Gradle 9 included builds, precompiled script plugins (`build-logic/src/main/groovy`), Gradle TestKit. -**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../specs/2026-08-15-five-adapter-runtime-remediation-review-design.md) +**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../../design/2026-08-15-five-adapter-runtime-remediation-review-design.md) (§10 in full, §11 Wave 5, §14 closing paragraph) --- diff --git a/docs/superpowers/plans/2026-08-15-wave6-final-qualification.md b/docs/history/plans/2026-08-15-wave6-final-qualification.md similarity index 95% rename from docs/superpowers/plans/2026-08-15-wave6-final-qualification.md rename to docs/history/plans/2026-08-15-wave6-final-qualification.md index 5d0d11a2..b0cead3e 100644 --- a/docs/superpowers/plans/2026-08-15-wave6-final-qualification.md +++ b/docs/history/plans/2026-08-15-wave6-final-qualification.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-08-15 +- 요약: 모든 차단 게이트와 활성화 매트릭스, 환경 smoke를 돌리는 마지막 단계 계획이다. +- 현재 정본: `docs/capability-status.md` + + # Wave 6 — Final Qualification and Documentation Sync Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans (this wave is @@ -15,7 +24,7 @@ backed by a command and its output stored under `docs/superpowers/plans/evidence/2026-08-15-wave6-final/`. A checkbox without attached evidence stays unticked, and a gate that could not run is reported as not-run with its reason — never as passing. -**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../specs/2026-08-15-five-adapter-runtime-remediation-review-design.md) +**Spec:** [`2026-08-15-five-adapter-runtime-remediation-review-design.md`](../../design/2026-08-15-five-adapter-runtime-remediation-review-design.md) (§12 in full, §13, §11 Wave 6) --- diff --git a/docs/superpowers/plans/2026-08-30-grpc-platform-implementation.md b/docs/history/plans/2026-08-30-grpc-platform-implementation.md similarity index 93% rename from docs/superpowers/plans/2026-08-30-grpc-platform-implementation.md rename to docs/history/plans/2026-08-30-grpc-platform-implementation.md index cee058e1..e30b43b1 100644 --- a/docs/superpowers/plans/2026-08-30-grpc-platform-implementation.md +++ b/docs/history/plans/2026-08-30-grpc-platform-implementation.md @@ -1,6 +1,15 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-08-30 +- 요약: 타입 안전 gRPC 실행 플랫폼의 실행 계획과 실행 결과다. +- 현재 정본: `docs/compatibility/grpc-support-matrix.md` + + # 타입 안전 gRPC 실행 플랫폼 — 실행 계획과 실행 결과 -설계 SSOT: [docs/superpowers/specs/2026-08-30-grpc-platform-adaptation-design.md](../specs/2026-08-30-grpc-platform-adaptation-design.md) +설계 SSOT: [docs/superpowers/specs/2026-08-30-grpc-platform-adaptation-design.md](../../design/2026-08-30-grpc-platform-adaptation-design.md) 원본: - `docs/2026-08-13-grpc-type-safe-rpc-platform-implementation-plan.md` (Stable, Task 1–53) diff --git a/docs/superpowers/plans/2026-09-16-ci-stage-separation.md b/docs/history/plans/2026-09-16-ci-stage-separation.md similarity index 96% rename from docs/superpowers/plans/2026-09-16-ci-stage-separation.md rename to docs/history/plans/2026-09-16-ci-stage-separation.md index 6071e627..6c93273e 100644 --- a/docs/superpowers/plans/2026-09-16-ci-stage-separation.md +++ b/docs/history/plans/2026-09-16-ci-stage-separation.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-16 +- 요약: CI를 단계별로 나누고 컨테이너 릴리스를 들여오는 계획이다. +- 현재 정본: `docs/work/reference/gates.md` + + # CI 단계 분리 + 컨테이너 릴리스 도입 - 작성: 2026-09-16 diff --git a/docs/superpowers/plans/2026-09-17-jpa-evidence-gradle-model-decoupling.md b/docs/history/plans/2026-09-17-jpa-evidence-gradle-model-decoupling.md similarity index 92% rename from docs/superpowers/plans/2026-09-17-jpa-evidence-gradle-model-decoupling.md rename to docs/history/plans/2026-09-17-jpa-evidence-gradle-model-decoupling.md index 76a13192..e4294732 100644 --- a/docs/superpowers/plans/2026-09-17-jpa-evidence-gradle-model-decoupling.md +++ b/docs/history/plans/2026-09-17-jpa-evidence-gradle-model-decoupling.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-17 +- 요약: JPA 증거 생성에서 실행 시점 Gradle 모델 접근을 없애는 실행 계획이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA Evidence Gradle Model Decoupling Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-09-17-jpa-leaf-verification-java.md b/docs/history/plans/2026-09-17-jpa-leaf-verification-java.md similarity index 86% rename from docs/superpowers/plans/2026-09-17-jpa-leaf-verification-java.md rename to docs/history/plans/2026-09-17-jpa-leaf-verification-java.md index 443ecb1a..d118144f 100644 --- a/docs/superpowers/plans/2026-09-17-jpa-leaf-verification-java.md +++ b/docs/history/plans/2026-09-17-jpa-leaf-verification-java.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-17 +- 요약: JPA leaf 검증 로직을 Groovy에서 Java로 옮기는 실행 계획이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA Leaf Verification Java Migration Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-09-17-jpa-test-lanes-java.md b/docs/history/plans/2026-09-17-jpa-test-lanes-java.md similarity index 73% rename from docs/superpowers/plans/2026-09-17-jpa-test-lanes-java.md rename to docs/history/plans/2026-09-17-jpa-test-lanes-java.md index 503cddc1..304a61b1 100644 --- a/docs/superpowers/plans/2026-09-17-jpa-test-lanes-java.md +++ b/docs/history/plans/2026-09-17-jpa-test-lanes-java.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-17 +- 요약: JPA 테스트 lane 정의를 Java record convention으로 옮기는 계획이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA Test Lanes Java Convention Plan **Goal:** Remove the remaining Map-driven JPA lane factories from Groovy and make lane metadata compile-time checked Java records. diff --git a/docs/superpowers/plans/2026-09-17-mongo-gradle-verification-java.md b/docs/history/plans/2026-09-17-mongo-gradle-verification-java.md similarity index 90% rename from docs/superpowers/plans/2026-09-17-mongo-gradle-verification-java.md rename to docs/history/plans/2026-09-17-mongo-gradle-verification-java.md index a6aa6758..478f7c55 100644 --- a/docs/superpowers/plans/2026-09-17-mongo-gradle-verification-java.md +++ b/docs/history/plans/2026-09-17-mongo-gradle-verification-java.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-17 +- 요약: Mongo 빌드 검증 알고리즘을 Groovy에서 Java 빌드 도구로 옮기는 실행 계획이다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + # Mongo Gradle Verification Java Migration Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-09-17-redis-topology-lane-java.md b/docs/history/plans/2026-09-17-redis-topology-lane-java.md similarity index 80% rename from docs/superpowers/plans/2026-09-17-redis-topology-lane-java.md rename to docs/history/plans/2026-09-17-redis-topology-lane-java.md index c04763e0..aacbfec2 100644 --- a/docs/superpowers/plans/2026-09-17-redis-topology-lane-java.md +++ b/docs/history/plans/2026-09-17-redis-topology-lane-java.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-17 +- 요약: Redis topology 검증 lane을 Java convention plugin으로 옮기는 실행 계획이다. +- 현재 정본: `docs/redis/support-matrix.md` + + # Redis Topology Lane Java Migration Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. diff --git a/docs/superpowers/plans/2026-09-18-bootstrap-structured-log-fields.md b/docs/history/plans/2026-09-18-bootstrap-structured-log-fields.md similarity index 60% rename from docs/superpowers/plans/2026-09-18-bootstrap-structured-log-fields.md rename to docs/history/plans/2026-09-18-bootstrap-structured-log-fields.md index f242c41d..916bbade 100644 --- a/docs/superpowers/plans/2026-09-18-bootstrap-structured-log-fields.md +++ b/docs/history/plans/2026-09-18-bootstrap-structured-log-fields.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: app-bootstrap 경고 로그를 구조화 필드로 모으는 계획이다. +- 현재 정본: `docs/observability/log-fields.md` + + # Bootstrap Structured Log Fields — Plan - [x] Centralize meter/fallback warning shapes in RuntimeWarnings diff --git a/docs/superpowers/plans/2026-09-18-bootstrap-structured-runtime-logging.md b/docs/history/plans/2026-09-18-bootstrap-structured-runtime-logging.md similarity index 58% rename from docs/superpowers/plans/2026-09-18-bootstrap-structured-runtime-logging.md rename to docs/history/plans/2026-09-18-bootstrap-structured-runtime-logging.md index 4420bc87..36285e86 100644 --- a/docs/superpowers/plans/2026-09-18-bootstrap-structured-runtime-logging.md +++ b/docs/history/plans/2026-09-18-bootstrap-structured-runtime-logging.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: app-bootstrap의 남은 운영 로그를 구조화하는 계획이다. +- 현재 정본: `docs/observability/log-fields.md` + + # Bootstrap Structured Runtime Logging — Plan - [x] Add structured fields to FileserverCleanupWorker success/failure logs diff --git a/docs/superpowers/plans/2026-09-18-deployment-composition-reachability-remediation.md b/docs/history/plans/2026-09-18-deployment-composition-reachability-remediation.md similarity index 83% rename from docs/superpowers/plans/2026-09-18-deployment-composition-reachability-remediation.md rename to docs/history/plans/2026-09-18-deployment-composition-reachability-remediation.md index e2e22b2f..b715ce17 100644 --- a/docs/superpowers/plans/2026-09-18-deployment-composition-reachability-remediation.md +++ b/docs/history/plans/2026-09-18-deployment-composition-reachability-remediation.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: 배포 조립에서 닿지 않던 구성 요소를 고치는 계획이다. +- 현재 정본: `docs/capability-status.md` + + # Deployment Composition Reachability Remediation — Plan ## Stage 0 — global Clock diff --git a/docs/superpowers/plans/2026-09-18-httpclient-capability-composition-ownership.md b/docs/history/plans/2026-09-18-httpclient-capability-composition-ownership.md similarity index 70% rename from docs/superpowers/plans/2026-09-18-httpclient-capability-composition-ownership.md rename to docs/history/plans/2026-09-18-httpclient-capability-composition-ownership.md index 637e1c83..527e80d5 100644 --- a/docs/superpowers/plans/2026-09-18-httpclient-capability-composition-ownership.md +++ b/docs/history/plans/2026-09-18-httpclient-capability-composition-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: HTTP client 조립을 capability leaf로 옮기는 계획이다. +- 현재 정본: `docs/httpclient/support-matrix.md` + + # HTTP Client Capability Composition Ownership — Plan - [x] Add generic capability startup-validation failure support and reporter coverage diff --git a/docs/superpowers/plans/2026-09-18-jpa-capability-composition-ownership.md b/docs/history/plans/2026-09-18-jpa-capability-composition-ownership.md similarity index 78% rename from docs/superpowers/plans/2026-09-18-jpa-capability-composition-ownership.md rename to docs/history/plans/2026-09-18-jpa-capability-composition-ownership.md index 9f499c49..7725ec70 100644 --- a/docs/superpowers/plans/2026-09-18-jpa-capability-composition-ownership.md +++ b/docs/history/plans/2026-09-18-jpa-capability-composition-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: 관계형 영속성 조립을 persistence-jpa로 옮기는 계획이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA Capability Composition Ownership — Plan - [x] Add package-private leaf Boot roots under the JPA master switch diff --git a/docs/superpowers/plans/2026-09-18-jpa-runtime-master-switch.md b/docs/history/plans/2026-09-18-jpa-runtime-master-switch.md similarity index 56% rename from docs/superpowers/plans/2026-09-18-jpa-runtime-master-switch.md rename to docs/history/plans/2026-09-18-jpa-runtime-master-switch.md index 2f666ff7..511c55cb 100644 --- a/docs/superpowers/plans/2026-09-18-jpa-runtime-master-switch.md +++ b/docs/history/plans/2026-09-18-jpa-runtime-master-switch.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: JPA 조립 후보가 같은 스위치를 따르게 하는 계획이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # JPA Runtime Master Switch — Plan - [x] Change the focused runtime fixture so normal runtime tests explicitly enable JPA diff --git a/docs/superpowers/plans/2026-09-18-messaging-platform-bridge.md b/docs/history/plans/2026-09-18-messaging-platform-bridge.md similarity index 91% rename from docs/superpowers/plans/2026-09-18-messaging-platform-bridge.md rename to docs/history/plans/2026-09-18-messaging-platform-bridge.md index 7a562665..51c669a2 100644 --- a/docs/superpowers/plans/2026-09-18-messaging-platform-bridge.md +++ b/docs/history/plans/2026-09-18-messaging-platform-bridge.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: 통합 이벤트 발행 경계를 메시징 플랫폼 bridge에 잇는 실행 계획이다. +- 현재 정본: `docs/messaging/support-matrix.md` + + # Messaging Platform Bridge Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-09-18-mongo-health-composition-ownership.md b/docs/history/plans/2026-09-18-mongo-health-composition-ownership.md similarity index 62% rename from docs/superpowers/plans/2026-09-18-mongo-health-composition-ownership.md rename to docs/history/plans/2026-09-18-mongo-health-composition-ownership.md index 83c12524..33c35ff5 100644 --- a/docs/superpowers/plans/2026-09-18-mongo-health-composition-ownership.md +++ b/docs/history/plans/2026-09-18-mongo-health-composition-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: Mongo health 조립을 persistence-mongo로 옮기는 계획이다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + # Mongo Health Composition Ownership — Plan - [x] Add spring-boot-health to persistence-mongo diff --git a/docs/superpowers/plans/2026-09-18-notification-capability-composition-ownership.md b/docs/history/plans/2026-09-18-notification-capability-composition-ownership.md similarity index 78% rename from docs/superpowers/plans/2026-09-18-notification-capability-composition-ownership.md rename to docs/history/plans/2026-09-18-notification-capability-composition-ownership.md index 3038684b..010adffb 100644 --- a/docs/superpowers/plans/2026-09-18-notification-capability-composition-ownership.md +++ b/docs/history/plans/2026-09-18-notification-capability-composition-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: 알림 조립을 알림 capability로 옮기는 계획이다. +- 현재 정본: `docs/notification/support-matrix.md` + + # Notification Capability Composition Ownership — Plan - [x] Replace bootstrap StartupFailures dependency in notification secrets with capability startup validation diff --git a/docs/superpowers/plans/2026-09-18-outbox-transport-only-cutover.md b/docs/history/plans/2026-09-18-outbox-transport-only-cutover.md similarity index 91% rename from docs/superpowers/plans/2026-09-18-outbox-transport-only-cutover.md rename to docs/history/plans/2026-09-18-outbox-transport-only-cutover.md index 9b13bc4b..85a7b9e6 100644 --- a/docs/superpowers/plans/2026-09-18-outbox-transport-only-cutover.md +++ b/docs/history/plans/2026-09-18-outbox-transport-only-cutover.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: outbox 저장소는 두고 발행 전송만 메시징 플랫폼으로 넘기는 실행 계획이다. +- 현재 정본: `src/composition/outbox-relay/README.md` + + # Outbox Transport-Only Cutover Implementation Plan **Goal:** Preserve canonical integration-event bytes and metadata inside the existing legacy `outbox_event` authority, then route canonical claimed rows through the messaging platform while legacy rows keep the current broker path. diff --git a/docs/superpowers/plans/2026-09-18-outbox-v2-canonical-storage-alignment.md b/docs/history/plans/2026-09-18-outbox-v2-canonical-storage-alignment.md similarity index 81% rename from docs/superpowers/plans/2026-09-18-outbox-v2-canonical-storage-alignment.md rename to docs/history/plans/2026-09-18-outbox-v2-canonical-storage-alignment.md index 4b53ff43..b1171c53 100644 --- a/docs/superpowers/plans/2026-09-18-outbox-v2-canonical-storage-alignment.md +++ b/docs/history/plans/2026-09-18-outbox-v2-canonical-storage-alignment.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: outbox V2 저장소를 canonical 이벤트에 맞추는 계획이다. V2 세대는 2026-09-25에 지웠다. +- 현재 정본: `docs/capability-status.md` + + # Outbox V2 Canonical Storage Alignment — Plan - [x] Make NewOutboxEventV2 wrap ValidatedIntegrationEvent only diff --git a/docs/superpowers/plans/2026-09-18-outbox-v2-one-record-publication-policy.md b/docs/history/plans/2026-09-18-outbox-v2-one-record-publication-policy.md similarity index 72% rename from docs/superpowers/plans/2026-09-18-outbox-v2-one-record-publication-policy.md rename to docs/history/plans/2026-09-18-outbox-v2-one-record-publication-policy.md index e1db876f..e09af053 100644 --- a/docs/superpowers/plans/2026-09-18-outbox-v2-one-record-publication-policy.md +++ b/docs/history/plans/2026-09-18-outbox-v2-one-record-publication-policy.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-18 +- 요약: outbox V2 기록 하나를 한 번 발행하는 정책 계획이다. V2 세대는 2026-09-25에 지웠다. +- 현재 정본: `docs/capability-status.md` + + # Outbox V2 One-Record Publication Policy — Plan - [ ] Add DB event/delivery created-at facts to ClaimedOutboxDelivery diff --git a/docs/superpowers/plans/2026-09-18-postgresql-idempotency-composition-ownership.md b/docs/history/plans/2026-09-18-postgresql-idempotency-composition-ownership.md similarity index 64% rename from docs/superpowers/plans/2026-09-18-postgresql-idempotency-composition-ownership.md rename to docs/history/plans/2026-09-18-postgresql-idempotency-composition-ownership.md index 9b4a976b..e820456d 100644 --- a/docs/superpowers/plans/2026-09-18-postgresql-idempotency-composition-ownership.md +++ b/docs/history/plans/2026-09-18-postgresql-idempotency-composition-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: PostgreSQL 멱등성 저장소 조립을 persistence-jpa로 옮기는 계획이다. +- 현재 정본: `src/composition/idempotency/README.md` + + # PostgreSQL Idempotency Composition Ownership — Plan - [x] Add package-private PostgreSQL idempotency store composition to persistence-jpa diff --git a/docs/superpowers/plans/2026-09-18-runtime-environment-tracing-ssot.md b/docs/history/plans/2026-09-18-runtime-environment-tracing-ssot.md similarity index 64% rename from docs/superpowers/plans/2026-09-18-runtime-environment-tracing-ssot.md rename to docs/history/plans/2026-09-18-runtime-environment-tracing-ssot.md index 15cc2f9e..a4e76b03 100644 --- a/docs/superpowers/plans/2026-09-18-runtime-environment-tracing-ssot.md +++ b/docs/history/plans/2026-09-18-runtime-environment-tracing-ssot.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: tracing과 capability 검증이 런타임 profile 어휘 하나를 쓰게 하는 계획이다. +- 현재 정본: `src/app-bootstrap/README.md` + + # Runtime Environment and Tracing SSOT — Plan - [x] Make TracingSampleRateResolver depend on RuntimeEnvironment, not string switch literals diff --git a/docs/superpowers/plans/2026-09-18-secret-source-port-ownership.md b/docs/history/plans/2026-09-18-secret-source-port-ownership.md similarity index 67% rename from docs/superpowers/plans/2026-09-18-secret-source-port-ownership.md rename to docs/history/plans/2026-09-18-secret-source-port-ownership.md index f71b429a..39d76e5d 100644 --- a/docs/superpowers/plans/2026-09-18-secret-source-port-ownership.md +++ b/docs/history/plans/2026-09-18-secret-source-port-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: 시크릿 출처 포트를 application으로 옮기는 계획이다. +- 현재 정본: `docs/registries/env-keys.yaml` + + # Secret Source Port Ownership — Plan - [x] Add application-owned SecretSourcePort under application.outbound diff --git a/docs/superpowers/plans/2026-09-18-startup-failure-log-context-state.md b/docs/history/plans/2026-09-18-startup-failure-log-context-state.md similarity index 57% rename from docs/superpowers/plans/2026-09-18-startup-failure-log-context-state.md rename to docs/history/plans/2026-09-18-startup-failure-log-context-state.md index af97c610..47deec54 100644 --- a/docs/superpowers/plans/2026-09-18-startup-failure-log-context-state.md +++ b/docs/history/plans/2026-09-18-startup-failure-log-context-state.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: 기동 실패 로그 상태를 logger context로 옮기는 계획이다. +- 현재 정본: `docs/observability/log-fields.md` + + # Startup Failure Log Context State — Plan - [x] Replace static AtomicBoolean with LoggerContext object-map state diff --git a/docs/superpowers/plans/2026-09-18-test-architecture-phase2-provider-ownership.md b/docs/history/plans/2026-09-18-test-architecture-phase2-provider-ownership.md similarity index 80% rename from docs/superpowers/plans/2026-09-18-test-architecture-phase2-provider-ownership.md rename to docs/history/plans/2026-09-18-test-architecture-phase2-provider-ownership.md index c166ed41..675f2cd0 100644 --- a/docs/superpowers/plans/2026-09-18-test-architecture-phase2-provider-ownership.md +++ b/docs/history/plans/2026-09-18-test-architecture-phase2-provider-ownership.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: provider 증거 테스트를 소유 leaf로 옮기는 실행 계획이다. +- 현재 정본: `docs/testing/TESTING_STRATEGY.md` + + # Test Architecture Phase 2 Provider Ownership — Implementation Plan ## Slice A — PostgreSQL migration/idempotency ownership diff --git a/docs/superpowers/plans/2026-09-18-test-taxonomy-ssot-alignment.md b/docs/history/plans/2026-09-18-test-taxonomy-ssot-alignment.md similarity index 65% rename from docs/superpowers/plans/2026-09-18-test-taxonomy-ssot-alignment.md rename to docs/history/plans/2026-09-18-test-taxonomy-ssot-alignment.md index f48bba0f..fa75b6bc 100644 --- a/docs/superpowers/plans/2026-09-18-test-taxonomy-ssot-alignment.md +++ b/docs/history/plans/2026-09-18-test-taxonomy-ssot-alignment.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-18 +- 요약: 테스트 전략 문서를 테스트 분류 정본에 맞추는 계획이다. +- 현재 정본: `docs/testing/TESTING_STRATEGY.md` + + # Test Taxonomy SSOT Alignment — Plan - [x] Rewrite TESTING_STRATEGY around TEST / INTEGRATION / SYSTEM / ARCHITECTURE / PERFORMANCE diff --git a/docs/superpowers/plans/2026-09-19-build-release-review-remediation.md b/docs/history/plans/2026-09-19-build-release-review-remediation.md similarity index 89% rename from docs/superpowers/plans/2026-09-19-build-release-review-remediation.md rename to docs/history/plans/2026-09-19-build-release-review-remediation.md index 41c9f75f..16b9252e 100644 --- a/docs/superpowers/plans/2026-09-19-build-release-review-remediation.md +++ b/docs/history/plans/2026-09-19-build-release-review-remediation.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: 빌드·CI 리뷰의 조립 결함을 고치는 실행 계획이다. +- 현재 정본: `docs/work/reference/gates.md` + + # Build / Release Review Remediation Implementation Plan > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [x]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-09-19-capability-dependency-validation-context.md b/docs/history/plans/2026-09-19-capability-dependency-validation-context.md similarity index 60% rename from docs/superpowers/plans/2026-09-19-capability-dependency-validation-context.md rename to docs/history/plans/2026-09-19-capability-dependency-validation-context.md index c7ebf75a..833cf066 100644 --- a/docs/superpowers/plans/2026-09-19-capability-dependency-validation-context.md +++ b/docs/history/plans/2026-09-19-capability-dependency-validation-context.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: capability 의존 검증을 StartupValidationContext로 옮기는 계획이다. +- 현재 정본: `docs/capability-status.md` + + # Capability Dependency Validation Context — Plan - [x] Replace raw capability dependency ArrayList with StartupValidationContext diff --git a/docs/superpowers/plans/2026-09-19-env-contract-verifier-truth-surface.md b/docs/history/plans/2026-09-19-env-contract-verifier-truth-surface.md similarity index 67% rename from docs/superpowers/plans/2026-09-19-env-contract-verifier-truth-surface.md rename to docs/history/plans/2026-09-19-env-contract-verifier-truth-surface.md index 315ee494..136f3b8c 100644 --- a/docs/superpowers/plans/2026-09-19-env-contract-verifier-truth-surface.md +++ b/docs/history/plans/2026-09-19-env-contract-verifier-truth-surface.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: env 키 검사가 선언과 사용을 구분하게 하는 계획이다. +- 현재 정본: `docs/registries/env-keys.yaml` + + # Env Contract Verifier Truth Surface — Plan - [x] Add RED test: .env.example presence does not make an untyped Redis key consumed diff --git a/docs/superpowers/plans/2026-09-19-fileserver-composition-decomposition.md b/docs/history/plans/2026-09-19-fileserver-composition-decomposition.md similarity index 66% rename from docs/superpowers/plans/2026-09-19-fileserver-composition-decomposition.md rename to docs/history/plans/2026-09-19-fileserver-composition-decomposition.md index bfb0ec20..545bc1d0 100644 --- a/docs/superpowers/plans/2026-09-19-fileserver-composition-decomposition.md +++ b/docs/history/plans/2026-09-19-fileserver-composition-decomposition.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: 파일 서버 조립을 관심사별로 나누는 계획이다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver Composition Decomposition — Plan - [x] Split platform bean families into five package-private concern configurations diff --git a/docs/superpowers/plans/2026-09-19-fileserver-verification-read-failure-remediation.md b/docs/history/plans/2026-09-19-fileserver-verification-read-failure-remediation.md similarity index 59% rename from docs/superpowers/plans/2026-09-19-fileserver-verification-read-failure-remediation.md rename to docs/history/plans/2026-09-19-fileserver-verification-read-failure-remediation.md index 6902dd64..3a818fb7 100644 --- a/docs/superpowers/plans/2026-09-19-fileserver-verification-read-failure-remediation.md +++ b/docs/history/plans/2026-09-19-fileserver-verification-read-failure-remediation.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: 파일 검증의 읽기 실패 처리를 고치는 계획이다. +- 현재 정본: `docs/fileserver/support-matrix.md` + + # Fileserver Verification Read Failure Remediation — Plan - [x] Add RED production-reader test: missing staging content must not look like empty content diff --git a/docs/superpowers/plans/2026-09-19-mongo-client-runtime-review-remediation.md b/docs/history/plans/2026-09-19-mongo-client-runtime-review-remediation.md similarity index 67% rename from docs/superpowers/plans/2026-09-19-mongo-client-runtime-review-remediation.md rename to docs/history/plans/2026-09-19-mongo-client-runtime-review-remediation.md index eb0dfbef..0c9d6b43 100644 --- a/docs/superpowers/plans/2026-09-19-mongo-client-runtime-review-remediation.md +++ b/docs/history/plans/2026-09-19-mongo-client-runtime-review-remediation.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: Mongo client 런타임 리뷰 결함을 고치는 계획이다. +- 현재 정본: `docs/mongodb/repository-adaptation.md` + + # Mongo Client Runtime Review Remediation — Plan - [x] Add RED startup dependency tests for missing Mongo connection source diff --git a/docs/superpowers/plans/2026-09-19-multi-instance-runtime-contract.md b/docs/history/plans/2026-09-19-multi-instance-runtime-contract.md similarity index 63% rename from docs/superpowers/plans/2026-09-19-multi-instance-runtime-contract.md rename to docs/history/plans/2026-09-19-multi-instance-runtime-contract.md index 9f3964ca..3660fa20 100644 --- a/docs/superpowers/plans/2026-09-19-multi-instance-runtime-contract.md +++ b/docs/history/plans/2026-09-19-multi-instance-runtime-contract.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: 다중 인스턴스 런타임 계약을 세우는 계획이다. +- 현재 정본: `src/app-bootstrap/README.md` + + # Multi-instance Runtime Contract — Plan - [x] Make shipped distributed-lock system proof RED by removing fake sibling coordination beans diff --git a/docs/superpowers/plans/2026-09-19-prod-secret-consumer-alignment.md b/docs/history/plans/2026-09-19-prod-secret-consumer-alignment.md similarity index 59% rename from docs/superpowers/plans/2026-09-19-prod-secret-consumer-alignment.md rename to docs/history/plans/2026-09-19-prod-secret-consumer-alignment.md index f0ed3a08..4879ca7b 100644 --- a/docs/superpowers/plans/2026-09-19-prod-secret-consumer-alignment.md +++ b/docs/history/plans/2026-09-19-prod-secret-consumer-alignment.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: 운영 기동이 쓰는 시크릿만 요구하게 하는 계획이다. +- 현재 정본: `docs/registries/env-keys.yaml` + + # Prod Secret Consumer Alignment — Plan - [x] Remove three consumerless secrets from REQUIRED_PROD_SECRETS diff --git a/docs/superpowers/plans/2026-09-19-runtime-profile-access-boundary.md b/docs/history/plans/2026-09-19-runtime-profile-access-boundary.md similarity index 59% rename from docs/superpowers/plans/2026-09-19-runtime-profile-access-boundary.md rename to docs/history/plans/2026-09-19-runtime-profile-access-boundary.md index ffa9f293..2e6e432e 100644 --- a/docs/superpowers/plans/2026-09-19-runtime-profile-access-boundary.md +++ b/docs/history/plans/2026-09-19-runtime-profile-access-boundary.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: 운영 코드가 active profile을 직접 읽지 않게 하는 계획이다. +- 현재 정본: `src/app-bootstrap/README.md` + + # Runtime Profile Access Boundary — Plan - [x] Add immutable Spring-aware RuntimeProfileSnapshot diff --git a/docs/history/plans/2026-09-19-startup-order-contract.md b/docs/history/plans/2026-09-19-startup-order-contract.md new file mode 100644 index 00000000..0f923341 --- /dev/null +++ b/docs/history/plans/2026-09-19-startup-order-contract.md @@ -0,0 +1,18 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: 기동 순서를 계약 테스트로 고정하는 계획이다. +- 현재 정본: `src/app-bootstrap/README.md` + + +# Startup Order Contract — Plan + +- [x] Add spring.factories-driven EnvironmentPostProcessor ordering test +- [x] Prove every registered processor implements Ordered +- [x] Pin each shipped processor to its StartupOrder constant +- [x] Prove readiness and validator/defaulting bands are strictly ordered +- [x] Run focused ordering test +- [x] Run app-bootstrap full TEST/ARCHITECTURE regressions +- [x] git diff --check diff --git a/docs/history/plans/2026-09-19-test-support-ownership-closure.md b/docs/history/plans/2026-09-19-test-support-ownership-closure.md new file mode 100644 index 00000000..58af9af9 --- /dev/null +++ b/docs/history/plans/2026-09-19-test-support-ownership-closure.md @@ -0,0 +1,18 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-19 +- 요약: 공유 테스트 지원 코드의 위치를 마무리하는 계획이다. +- 현재 정본: `docs/testing/TESTING_STRATEGY.md` + + +# Test Support Ownership Closure — Plan + +- [x] Move AdapterActivationInventory from test to systemTest +- [x] Prove no TEST source consumes AdapterActivationInventory +- [x] Prove custom testkit publisher/source-set declarations are absent +- [x] Preserve taxonomy positive-control fixture placement +- [x] Run systemTest compile/focused consumers +- [x] Run app-bootstrap TEST and ARCHITECTURE regressions +- [x] git diff --check diff --git a/docs/superpowers/plans/2026-09-23-app-bootstrap-build-composition-plan.md b/docs/history/plans/2026-09-23-app-bootstrap-build-composition-plan.md similarity index 97% rename from docs/superpowers/plans/2026-09-23-app-bootstrap-build-composition-plan.md rename to docs/history/plans/2026-09-23-app-bootstrap-build-composition-plan.md index 33520ffa..2f2cd183 100644 --- a/docs/superpowers/plans/2026-09-23-app-bootstrap-build-composition-plan.md +++ b/docs/history/plans/2026-09-23-app-bootstrap-build-composition-plan.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-23 +- 요약: app-bootstrap 빌드 조립을 정리하는 실행 계획이다. +- 현재 정본: `src/app-bootstrap/README.md` + + # App Bootstrap Build Composition — implementation plan Design authority: the 2026-09-23 "App Bootstrap Build Composition 설계 작업 문서". diff --git a/docs/superpowers/plans/2026-09-25-capability-module-packaging.md b/docs/history/plans/2026-09-25-capability-module-packaging.md similarity index 99% rename from docs/superpowers/plans/2026-09-25-capability-module-packaging.md rename to docs/history/plans/2026-09-25-capability-module-packaging.md index 419f3174..3f224e04 100644 --- a/docs/superpowers/plans/2026-09-25-capability-module-packaging.md +++ b/docs/history/plans/2026-09-25-capability-module-packaging.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 끝남 +- 작성일: 2026-09-25 +- 요약: 부가 기능을 capability 모듈로 포장하고 기본 조립을 web으로 줄이는 실행 계획이다. +- 현재 정본: `docs/capability-status.md` + + # 부가 기능(capability) 모듈 포장 — 실행 계획 > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/2026-09-25-review-followup-tools/agent-brief.md b/docs/history/plans/2026-09-25-review-followup-tools/agent-brief.md similarity index 93% rename from docs/superpowers/plans/2026-09-25-review-followup-tools/agent-brief.md rename to docs/history/plans/2026-09-25-review-followup-tools/agent-brief.md index 175fba54..3777b14b 100644 --- a/docs/superpowers/plans/2026-09-25-review-followup-tools/agent-brief.md +++ b/docs/history/plans/2026-09-25-review-followup-tools/agent-brief.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-25 +- 요약: 리뷰 후속 작업에서 구현 에이전트에게 준 공통 지시다. +- 현재 정본: `docs/work/delegate.md` + + # 구현 에이전트 공통 지시 (리뷰 후속) 당신은 구현 에이전트다. 프롬프트가 지정한 묶음(`P<번호>`)을 끝까지 구현·검증·커밋한다. diff --git a/docs/superpowers/plans/2026-09-25-review-followup-tools/apply_results.py b/docs/history/plans/2026-09-25-review-followup-tools/apply_results.py similarity index 100% rename from docs/superpowers/plans/2026-09-25-review-followup-tools/apply_results.py rename to docs/history/plans/2026-09-25-review-followup-tools/apply_results.py diff --git a/docs/superpowers/plans/2026-09-25-review-followup-tools/by_area.py b/docs/history/plans/2026-09-25-review-followup-tools/by_area.py similarity index 100% rename from docs/superpowers/plans/2026-09-25-review-followup-tools/by_area.py rename to docs/history/plans/2026-09-25-review-followup-tools/by_area.py diff --git a/docs/superpowers/plans/2026-09-25-review-followup.md b/docs/history/plans/2026-09-25-review-followup.md similarity index 98% rename from docs/superpowers/plans/2026-09-25-review-followup.md rename to docs/history/plans/2026-09-25-review-followup.md index c508cbd5..aa0c01fe 100644 --- a/docs/superpowers/plans/2026-09-25-review-followup.md +++ b/docs/history/plans/2026-09-25-review-followup.md @@ -1,3 +1,12 @@ + +> **기록 · 계획서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 확인 안 함 +- 작성일: 2026-09-25 +- 요약: 2026-09-24 리뷰의 남은 항목을 모두 닫는 실행 계획이다. +- 현재 정본: `docs/reviews/2026-09-25-review-followup-status.md` + + # 2026-09-24 리뷰 남은 항목 전부 반영 — 실행 계획 > **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave0-baseline.md b/docs/history/plans/evidence/2026-08-15-wave0-baseline.md similarity index 98% rename from docs/superpowers/plans/evidence/2026-08-15-wave0-baseline.md rename to docs/history/plans/evidence/2026-08-15-wave0-baseline.md index a6e141e6..4505f2ef 100644 --- a/docs/superpowers/plans/evidence/2026-08-15-wave0-baseline.md +++ b/docs/history/plans/evidence/2026-08-15-wave0-baseline.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-15 +- 요약: 개선 0단계에서 실패 기준선을 잡은 증거다. +- 현재 정본: `docs/capability-status.md` + + # Wave 0 — Red Baseline Evidence - Repository HEAD at capture: `2f5d2fc21954286213c1474d19935f571ef896ea` diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave2-decisions.md b/docs/history/plans/evidence/2026-08-15-wave2-decisions.md similarity index 99% rename from docs/superpowers/plans/evidence/2026-08-15-wave2-decisions.md rename to docs/history/plans/evidence/2026-08-15-wave2-decisions.md index 2fc843eb..f6ce58fa 100644 --- a/docs/superpowers/plans/evidence/2026-08-15-wave2-decisions.md +++ b/docs/history/plans/evidence/2026-08-15-wave2-decisions.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-15 +- 요약: 개선 2단계에서 고른 선택과 그 증거다. +- 현재 정본: `docs/capability-status.md` + + # Wave 2 — decisions and evidence Required by the Wave 2 exit criteria. One entry per task that made a choice a reader could diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-architecture-gates.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task1-architecture-gates.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-architecture-gates.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task1-architecture-gates.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-check.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task1-check.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-check.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task1-check.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-compile.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task1-compile.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-compile.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task1-compile.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-test.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task1-test.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-test.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task1-test.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-wave0-red-set.md b/docs/history/plans/evidence/2026-08-15-wave6-final/task1-wave0-red-set.md similarity index 85% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-wave0-red-set.md rename to docs/history/plans/evidence/2026-08-15-wave6-final/task1-wave0-red-set.md index 8e562c96..73889497 100644 --- a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-wave0-red-set.md +++ b/docs/history/plans/evidence/2026-08-15-wave6-final/task1-wave0-red-set.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-15 +- 요약: 0단계 실패 묶음이 비었고 그 lane을 지웠다는 증거다. +- 현재 정본: `docs/capability-status.md` + + # Task 1 — the Wave 0 red set is empty, and the lanes are removed ## Command diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-wave0RedReport.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task1-wave0RedReport.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task1-wave0RedReport.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task1-wave0RedReport.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-b5-ghost-release-lanes.md b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-b5-ghost-release-lanes.md similarity index 86% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-b5-ghost-release-lanes.md rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-b5-ghost-release-lanes.md index c8c47be3..6cd8f93b 100644 --- a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-b5-ghost-release-lanes.md +++ b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-b5-ghost-release-lanes.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-15 +- 요약: 실체 없던 Mongo 릴리스 lane 셋을 처리한 증거다. +- 현재 정본: `docs/capability-status.md` + + # Task 2 — Wave 2 Task B5, the three ghost release lanes Wave 2 offered two outcomes for `mongoShardedTest`, `mongoAtlasTest` and `mongoKmsTest`: implement diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-focused-module-tests.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-focused-module-tests.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-focused-module-tests.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-focused-module-tests.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-graphql-runtime-qualification-NOT-RUN.md b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-graphql-runtime-qualification-NOT-RUN.md similarity index 87% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-graphql-runtime-qualification-NOT-RUN.md rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-graphql-runtime-qualification-NOT-RUN.md index 86942f93..62de081b 100644 --- a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-graphql-runtime-qualification-NOT-RUN.md +++ b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-graphql-runtime-qualification-NOT-RUN.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-15 +- 요약: GraphQL bootJar JWT 검증을 돌리지 못한 이유를 남긴 기록이다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # NOT RUN — the GraphQL bootJar JWT qualification Recorded as not-run with its reason, per this wave's rule that a gate which could not run is never diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-graphql-runtime-qualification.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-graphql-runtime-qualification.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-graphql-runtime-qualification.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-graphql-runtime-qualification.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-graphql-stable-and-transport.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-graphql-stable-and-transport.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-graphql-stable-and-transport.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-graphql-stable-and-transport.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-first-run-failed.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-first-run-failed.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-first-run-failed.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-first-run-failed.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg16.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg16.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg16.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg16.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg17.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg17.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg17.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg17.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg18.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg18.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg18.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate-pg18.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-jpa-release-gate.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-messaging-certification.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-messaging-certification.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-messaging-certification.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-messaging-certification.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-messaging-live-broker.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-messaging-live-broker.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-messaging-live-broker.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-messaging-live-broker.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-compatibility.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-compatibility.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-compatibility.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-compatibility.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-failover.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-failover.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-failover.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-failover.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-lanes-first-run-failed.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-lanes-first-run-failed.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-lanes-first-run-failed.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-lanes-first-run-failed.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-lanes.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-lanes.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-lanes.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-lanes.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-migration.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-migration.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-migration.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-migration.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-performance.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-performance.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-performance.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-performance.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-replicaset.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-replicaset.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-replicaset.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-replicaset.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-security.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-security.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-mongo-security.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-mongo-security.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-release-manifest-arbiter.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task2-release-manifest-arbiter.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task2-release-manifest-arbiter.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task2-release-manifest-arbiter.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task3-activation-matrix.md b/docs/history/plans/evidence/2026-08-15-wave6-final/task3-activation-matrix.md similarity index 93% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task3-activation-matrix.md rename to docs/history/plans/evidence/2026-08-15-wave6-final/task3-activation-matrix.md index 6478f7f7..d7f4fe09 100644 --- a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task3-activation-matrix.md +++ b/docs/history/plans/evidence/2026-08-15-wave6-final/task3-activation-matrix.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-15 +- 요약: 활성화 매트릭스 열 줄과 각 줄의 증거 위치다. +- 현재 정본: `docs/capability-status.md` + + # Task 3 — the ten-row activation matrix Every row below names where its evidence is, and nothing is ticked from reasoning about the code. diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task3-matrix-to-lane-map.md b/docs/history/plans/evidence/2026-08-15-wave6-final/task3-matrix-to-lane-map.md similarity index 82% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task3-matrix-to-lane-map.md rename to docs/history/plans/evidence/2026-08-15-wave6-final/task3-matrix-to-lane-map.md index 1f47c6a8..0d96463e 100644 --- a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task3-matrix-to-lane-map.md +++ b/docs/history/plans/evidence/2026-08-15-wave6-final/task3-matrix-to-lane-map.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-15 +- 요약: 활성화 매트릭스 줄이 어느 lane의 증거로 이어지는지 적은 표다. +- 현재 정본: `docs/capability-status.md` + + # Task 3 — the activation matrix, and where each row's evidence comes from The plan's matrix is ten rows; the Compose contract is fifteen lanes; the in-process activation diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task3-row8-dependency-error.log b/docs/history/plans/evidence/2026-08-15-wave6-final/task3-row8-dependency-error.log similarity index 100% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task3-row8-dependency-error.log rename to docs/history/plans/evidence/2026-08-15-wave6-final/task3-row8-dependency-error.log diff --git a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task6-p0-reconciliation.md b/docs/history/plans/evidence/2026-08-15-wave6-final/task6-p0-reconciliation.md similarity index 96% rename from docs/superpowers/plans/evidence/2026-08-15-wave6-final/task6-p0-reconciliation.md rename to docs/history/plans/evidence/2026-08-15-wave6-final/task6-p0-reconciliation.md index af9bc2eb..131e75ef 100644 --- a/docs/superpowers/plans/evidence/2026-08-15-wave6-final/task6-p0-reconciliation.md +++ b/docs/history/plans/evidence/2026-08-15-wave6-final/task6-p0-reconciliation.md @@ -1,3 +1,12 @@ + +> **기록 · 증거** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-15 +- 요약: 다섯 리뷰의 P0 발견을 맞춰 본 결과다. +- 현재 정본: `docs/capability-status.md` + + # Task 6 — the five reviews' P0 findings, reconciled The remediation design this wave executed never referenced a review id (`grep -c` over it: zero). diff --git a/docs/study/graphql-walkthrough.ko.md b/docs/history/study/graphql-walkthrough.ko.md similarity index 99% rename from docs/study/graphql-walkthrough.ko.md rename to docs/history/study/graphql-walkthrough.ko.md index b8b7f532..bf0df1d1 100644 --- a/docs/study/graphql-walkthrough.ko.md +++ b/docs/history/study/graphql-walkthrough.ko.md @@ -1,3 +1,12 @@ + +> **기록 · 학습 문서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-09-16 +- 요약: GraphQL 기능을 쓴 때의 코드로 따라 읽은 학습 기록이다. 2026-09-25 이후 지운 코드를 설명하는 절이 있다. +- 현재 정본: `src/adapter/inbound/graphql/README.md` + + # GraphQL 인바운드 모듈 완전 해부 > **2026-09-25 이후 달라진 점**: `moduleboundary/`, `architecture/`, `compat/`, `release/`, @@ -15,9 +24,9 @@ > 되어 있는가"를 정리한 글이다. > > SSOT는 여전히 `src/config/architecture/modules.json`, 모듈 -> [CLAUDE.md](../../src/adapter/inbound/graphql/CLAUDE.md), -> [README.md](../../src/adapter/inbound/graphql/README.md), -> [ADR-GQL-001](../adr/ADR-GQL-001-graphql-context-and-storage-ownership.md)이다. +> [CLAUDE.md](../../../src/adapter/inbound/graphql/CLAUDE.md), +> [README.md](../../../src/adapter/inbound/graphql/README.md), +> [ADR-GQL-001](../../adr/ADR-GQL-001-graphql-context-and-storage-ownership.md)이다. > 이 문서와 그것들이 어긋나면 그쪽이 맞다 — **단, §28에 적은 것들은 예외다. 거기 적힌 것은 > 문서 쪽이 코드와 어긋나 있는 항목이고, 코드가 맞다.** > diff --git a/docs/study/postgresql-jpa-walkthrough.ko.md b/docs/history/study/postgresql-jpa-walkthrough.ko.md similarity index 97% rename from docs/study/postgresql-jpa-walkthrough.ko.md rename to docs/history/study/postgresql-jpa-walkthrough.ko.md index 6e74af3d..e48f504c 100644 --- a/docs/study/postgresql-jpa-walkthrough.ko.md +++ b/docs/history/study/postgresql-jpa-walkthrough.ko.md @@ -1,3 +1,12 @@ + +> **기록 · 학습 문서** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 보관 +- 작성일: 2026-08-24 +- 요약: PostgreSQL·JPA 기능을 쓴 때의 코드로 따라 읽은 학습 기록이다. +- 현재 정본: `docs/jpa/repository-adaptation.md` + + # PostgreSQL / JPA 모듈 완전 해부 > **성격**: 정책 문서가 아니라 **읽기 기록**이다. `adapter:outbound:persistence-jpa` leaf와 @@ -1337,15 +1346,22 @@ startup 동작으로는 절대 아니다. ### 8.2 `ConcurrentIndexMigrationInspector` PostgreSQL은 `CREATE INDEX CONCURRENTLY`·`DROP INDEX CONCURRENTLY`·`REINDEX … CONCURRENTLY`를 -트랜잭션 블록 안에서 거부한다. Flyway 11은 `CREATE`/`DROP INDEX CONCURRENTLY`가 든 파일을 **스스로 -트랜잭션 밖에서** 돌린다. `REINDEX … CONCURRENTLY`는 모른다. 그 파일은 트랜잭션 안에서 돌고, 배포 때 -PostgreSQL이 거부한다. 그래서 검사기는 동시 인덱스 문장이 있으면 `.sql.conf`에 -`executeInTransaction=false`를 적으라고 요구한다. Flyway가 알아서 빼 주는 문장에도 적는다. 파일이 -자기에게 필요한 것을 스스로 말하게 하려는 것이다. +트랜잭션 블록 안에서 거부한다. Flyway 11은 `CREATE`/`DROP INDEX CONCURRENTLY`나 +`REINDEX SCHEMA|DATABASE`(`CONCURRENTLY`가 있든 없든)가 든 파일을 **스스로 트랜잭션 밖에서** 돌린다. +`REINDEX INDEX|TABLE … CONCURRENTLY`(`REINDEX (CONCURRENTLY) TABLE` 포함)는 모른다. 그 파일은 +트랜잭션 안에서 돌고, 배포 때 PostgreSQL이 거부한다. 다섯 형태를 실제 PostgreSQL에서 돌린 결과는 +`PostgreSqlMigrationLockWaitIntegrationTest`에 있다. 그래서 검사기는 동시 인덱스 문장이 있으면 +`.sql.conf`에 `executeInTransaction=false`를 적으라고 요구한다. Flyway가 알아서 빼 주는 문장에도 +적는다. 파일이 자기에게 필요한 것을 스스로 말하게 하려는 것이다. -> 다른 문장과 섞인 파일은 Flyway가 기본값(`mixed=false`)에서 **아무것도 실행하기 전에 거부**한다. -> 부분 적용은 일어나지 않는다. 그래도 한 파일에 하나만 두는 이유는 아래 `requireIsolatedStatement`의 -> 복구 때문이다. +> 다른 문장과 섞인 파일은 설정에 따라 결과가 다르다. +> +> - `.sql.conf`가 없으면 Flyway가 기본값(`mixed=false`)에서 **아무것도 실행하기 전에 거부**한다. +> - 검사기가 요구하는 `executeInTransaction=false`를 붙이면 Flyway가 **문장마다 따로 커밋**한다. +> 동시 빌드가 실패해도 그 앞 문장은 **이미 적용돼 남는다**(부분 적용). +> +> 그래서 동시 인덱스 문장은 한 파일에 하나만 둔다. 두 경우 모두 +> `PostgreSqlConcurrentIndexMigrationIntegrationTest`가 실제 PostgreSQL에서 보여 준다. 트랜잭션 밖에서도 동시 빌드는 **자기보다 먼저 시작한 트랜잭션이 모두 끝나기를 기다린다.** @@ -1366,18 +1382,38 @@ Flyway 기본값: 잠금 트랜잭션(열린 채) ──기다림──▶ 마 검사 대상: `CREATE [UNIQUE] INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY`, `REINDEX … CONCURRENTLY` (`REINDEX (CONCURRENTLY) TABLE` 같은 괄호 옵션 포함). -`requireIsolatedStatement`도 있다 — concurrent 빌드가 실패하면 invalid index가 남고, 그 -복구는 마이그레이션이 다른 걸 아무것도 안 했으면 `DROP INDEX` 하나지만 뭔가 했으면 부분 -상태를 손으로 재구성해야 한다. +`requireIsolatedStatement`도 있다 — concurrent 문장이 실패하면 invalid index와 그 버전의 +**실패 이력 행**(`success = false`)이 남는다. Flyway는 그 행이 있는 한 다음 배포를 validate에서 거부한다. +그래서 인덱스만 지우고 다시 배포하면 또 멈춘다. -`FailedConcurrentIndexRecovery`가 `pg_index.indisvalid = false`를 조회해서 리포트한다. -**자동으로 지우지 않는다.** +``` +실패한 동시 인덱스 문장 → invalid index + 실패 이력 행 + → 빌드가 아직 도는지 확인 → 원인 정리(중복 행, 붙잡던 열린 트랜잭션) + → 빌드·재빌드가 남긴 invalid index를 DROP INDEX CONCURRENTLY + → 그 버전의 실패 이력 행만 DELETE → 다시 배포 +``` + +- 원인 정리가 먼저다. 운영자의 `DROP INDEX CONCURRENTLY`도 그 테이블을 잡은 열린 트랜잭션을 기다린다. +- 실패한 문장이 `DROP INDEX CONCURRENTLY`면 남은 invalid index는 그 마이그레이션이 지우려던 인덱스다. + 손으로 지우지 않는다. 다시 배포한 같은 문장이 지운다. 먼저 지우면 그 문장이 없는 인덱스(`42704`)로 또 실패한다. + +- 절차와 SQL은 `docs/runbooks/migration-failed.md` "Recover a failed concurrent index migration"에 있다. + `PostgreSqlConcurrentIndexMigrationIntegrationTest`가 그 SQL을 runbook에서 읽어 세 문장(중복으로 실패한 unique 빌드, + 열린 트랜잭션을 기다리다 취소된 재빌드와 drop)마다 실제 PostgreSQL에서 돌린다. +- 실패 이력 행을 지우는 것은 "이력을 고치지 않는다"의 하나뿐인 예외다(소유자 결정 2026-11-06). + 실패 행은 적용되지 않은 버전의 기록이라, 지워도 성공한 버전의 순서와 checksum은 그대로다. +- `flyway repair`는 여전히 쓰지 않는다. 남은 행의 checksum·설명까지 디스크의 스크립트에 맞춰 다시 쓰기 때문이다. +- 마이그레이션이 다른 문장도 담고 있었으면 그 문장은 이미 커밋돼 있다. 부분 상태를 손으로 재구성해야 한다. + +invalid index를 찾는 쿼리는 `docs/jpa/runbooks.md` "An invalid index exists"에 있다(예전의 +`FailedConcurrentIndexRecovery` 클래스는 호출자가 없어 지웠고, 이 쿼리가 대신한다). +플랫폼은 invalid index를 **자동으로 지우지 않는다.** > invalid index는 **빌드가 아직 돌고 있다**는 뜻일 수도 있고, 카탈로그만으로는 둘을 구별할 수 > 없다. 자동 drop은 곧 끝나려던 concurrent 빌드와 경주하게 되고, rolling deploy의 모든 > 인스턴스에서 동시에 그렇게 한다. -리포트는 운영자가 돌릴 statement를 준다(그 자체가 non-transactional인 `DROP INDEX CONCURRENTLY`). +지우는 문장은 운영자가 직접 돌린다(그 자체가 트랜잭션 밖에서만 도는 `DROP INDEX CONCURRENTLY`). ### 8.3 실제 마이그레이션 트리 — 8개 독립 스트림 diff --git a/docs/httpclient/performance-baseline.md b/docs/httpclient/performance-baseline.md index 7335d020..0a1ee87e 100644 --- a/docs/httpclient/performance-baseline.md +++ b/docs/httpclient/performance-baseline.md @@ -8,19 +8,20 @@ from an explicit profile setting. ## How to run ```bash -# structural bounds only (default; still executes every test) +# every bound, structural and machine-dependent ./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest --console=plain -# full certification, including machine-dependent bounds -./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest \ - -Pperformance.assertions.enabled=true --console=plain - -# JMH benchmarks +# JMH benchmarks: numbers only, never a gate ./gradlew :adapter:outbound:httpclient:jmh --console=plain ``` -Machine-dependent assertions are reported as explicitly skipped when the flag is absent — the lane -never silently degrades into a pass. +The lane asserts every bound in every run. There is no switch that turns the machine-dependent one +off: the strict-lane convention fails a performance lane before it runs when the build sets +`performance.assertions.enabled` to anything but `true`, and fails it when one of its tests is +skipped. The same command is what `integration-main.yml` (`:performanceCheck`) and `release.yml` +run. Every run prints the measured heap increase (`[httpclient-performance] streaming download heap +increase … bytes, bound … bytes`) to the test output and report, and a bound that fails repeats the +value in its assertion message; for numbers without a verdict, use JMH. ## Certified bounds diff --git a/docs/httpclient/release-checklist.md b/docs/httpclient/release-checklist.md index 6b21cf41..a11e0f7f 100644 --- a/docs/httpclient/release-checklist.md +++ b/docs/httpclient/release-checklist.md @@ -9,11 +9,10 @@ cd src ./gradlew :adapter:outbound:httpclient:test --console=plain ./gradlew :adapter:outbound:httpclient:httpClientStableContractTest --console=plain ./gradlew :adapter:outbound:httpclient:httpClientSecurityTest --console=plain -./gradlew :adapter:outbound:httpclient:spring62CompatibilityTest --console=plain +./gradlew :adapter:outbound:httpclient:spring62ApiSurfaceScan --console=plain ./gradlew :adapter:outbound:httpclient:spring70CompatibilityTest --console=plain ./gradlew :adapter:outbound:httpclient:httpClientFailureInjectionTest --console=plain # needs Docker -./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest \ - -Pperformance.assertions.enabled=true --console=plain +./gradlew :adapter:outbound:httpclient:httpClientPerformanceTest --console=plain # every bound asserted ./gradlew verifyCleanArchitectureDependencies --console=plain ./gradlew :app-bootstrap:architectureTest --console=plain python3 ../scripts/verify-httpclient-docs.py diff --git a/docs/httpclient/repository-adaptation.md b/docs/httpclient/repository-adaptation.md index 95c397a3..4b7c9476 100644 --- a/docs/httpclient/repository-adaptation.md +++ b/docs/httpclient/repository-adaptation.md @@ -1,7 +1,7 @@ # HTTP Client Platform — Repository Adaptation Contract -**Design source:** `docs/superpowers/specs/2026-08-08-httpclient-platform-design.md` -**Plan source:** `docs/superpowers/plans/2026-08-08-httpclient-platform-implementation-plan.md` +**Design source:** `docs/design/2026-08-08-httpclient-platform-design.md` +**Plan source:** `docs/history/plans/2026-08-08-httpclient-platform-implementation-plan.md` The design package states its own adaptation rule: diff --git a/docs/httpclient/support-matrix.md b/docs/httpclient/support-matrix.md index 7d3966c1..a253cfd9 100644 --- a/docs/httpclient/support-matrix.md +++ b/docs/httpclient/support-matrix.md @@ -57,19 +57,19 @@ gives route-scoped pooling and Dynamic Target pinning, JDK gives HTTP/2. | Profile | Frequency | Release gate | Task | |---|---|---|---| -| Spring Framework 7.0 (repository baseline) | every PR | required | `spring70CompatibilityTest` | -| Spring Framework 6.2 API surface | every PR | required | `spring62CompatibilityTest` | -| Apache HC5 + RestClient | every PR | required | `httpClientStableContractTest -Phttpclient.contract.transports=apache` | -| JDK HttpClient + RestClient | every PR | required | `httpClientStableContractTest -Phttpclient.contract.transports=jdk` | -| SSRF / cardinality suite | every PR | required | `httpClientSecurityTest` | -| Toxiproxy fault suite | nightly, release | required | `httpClientFailureInjectionTest` | -| Performance certification | nightly, release | required | `httpClientPerformanceTest -Pperformance.assertions.enabled=true` | -| Jetty HTTP/3 | nightly | Experimental, non-blocking | `test -Phttp3.tests.enabled=true` | +| Spring Framework 7.0 (repository baseline) | PR touching this leaf, main push, release | required | `spring70CompatibilityTest` | +| Spring Framework 6.2 API surface | every PR (`check`), release | required | `spring62ApiSurfaceScan` | +| Apache HC5 + RestClient | PR touching this leaf (both transports together on every PR through `check`), release | required | `httpClientStableContractTest -Phttpclient.contract.transports=apache` | +| JDK HttpClient + RestClient | PR touching this leaf (both transports together on every PR through `check`), release | required | `httpClientStableContractTest -Phttpclient.contract.transports=jdk` | +| SSRF / cardinality suite | every PR (`check`), release | required | `httpClientSecurityTest` | +| Toxiproxy fault suite | main push, nightly (`integrationCheck`), release | required | `httpClientFailureInjectionTest` | +| Performance certification | main push, nightly (`performanceCheck`), release | required | `httpClientPerformanceTest` (every bound asserted; no switch turns them off) | +| Jetty HTTP/3 | main push, nightly | Experimental, non-blocking | `test -Phttp3.tests.enabled=true` | ### Known limitation of the Spring 6.2 lane This repository's Spring Boot 4.0 baseline pins Spring Framework 7, so a real 6.2 runtime cannot be -resolved here. `spring62CompatibilityTest` therefore verifies the **API surface**: the common +resolved here. `spring62ApiSurfaceScan` therefore verifies the **API surface**: the common packages must not reference any Spring 7-only type, and no class uses `org.springframework.web.service.registry`. Executing the suite against an actual 6.2 distribution requires a host project on that line. This limitation is stated rather than hidden behind a passing @@ -83,5 +83,5 @@ Stated so the matrix is read as a measurement rather than an aspiration. | Gap | Why | What is proven instead | |---|---|---| | HTTP/2 frame injection (`REFUSED_STREAM`, arbitrary `GOAWAY`) | The fixture server exposes no frame-level control, and a purpose-built h2 server is a larger dependency than the guarantee is worth here | `Http2EvidenceMapperTest` proves the frame → evidence mapping, and `NegotiatedProtocolContractTest` proves h2 is really negotiated | -| Spring 6.2 runtime | This repository's Boot 4.0 baseline pins Spring 7 | `spring62CompatibilityTest` confines the common packages to the 6.2 API surface | -| Performance latency baseline | Numbers measured on a build agent are not a certification | `httpClientPerformanceTest` asserts structural bounds unconditionally; latency and heap bounds run under `-Pperformance.assertions.enabled=true` | +| Spring 6.2 runtime | This repository's Boot 4.0 baseline pins Spring 7 | `spring62ApiSurfaceScan` confines the common packages to the 6.2 API surface | +| Performance latency baseline | Numbers measured on a build agent are not a certification | `httpClientPerformanceTest` asserts its structural bounds and the streaming heap bound in every run; it asserts no latency figure | diff --git a/docs/jpa/entity-mapping-guide.md b/docs/jpa/entity-mapping-guide.md index 2a09c7d5..aae8772c 100644 --- a/docs/jpa/entity-mapping-guide.md +++ b/docs/jpa/entity-mapping-guide.md @@ -96,8 +96,8 @@ second `UPDATE`, and the entity graph is a cycle. Keep the association on one si an ID or a query (re-review round 2, RR-02-15). A class that links to itself is a pair only when a second member points back the other way (`@ManyToOne parent` with `@OneToMany children`); two `@ManyToOne` links of a class to itself (a manager and a mentor) pass, because both keys point into -the one table and there are no two tables to order. `JpaProductionArchitectureTest` (app-bootstrap -`architectureTest`) runs it over the production graph and `SampleArchitectureTest` over the sample. +the one table and there are no two tables to order. 이 규칙은 `JpaProductionArchitectureTest`(app-bootstrap +`architectureTest`)가 운영 그래프 전체에 건다. The failure message names the fields and these alternatives. Chosen and rejected: diff --git a/docs/jpa/migration-guide.md b/docs/jpa/migration-guide.md index e42b7ed1..0a6b3e61 100644 --- a/docs/jpa/migration-guide.md +++ b/docs/jpa/migration-guide.md @@ -20,7 +20,10 @@ older than itself, Flyway's own included — the deploy stops with no error and defaults (`config/module-defaults/persistence-jpa.yml`, `spring.flyway.postgresql.transactional-lock: false`) for the one Spring Boot builds at startup, and `FlywaySchemaPolicy.configure()` for every stream it builds itself — a service's own stream starts from it too, and `JpaProductionArchitectureTest` -refuses production code that calls `Flyway.configure()` directly. The deployment-owned migration of +refuses production code that builds a Flyway any other way: calling `Flyway.configure()`, or +constructing a configuration itself (`new FluentConfiguration()`, `new ClassicConfiguration()`, a +subclass of either, or `FluentConfiguration::new`). `new Flyway(...)` over the policy's configuration +is allowed. The deployment-owned migration of staging and prod is outside this repository: give its tool the same value (`FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false`, or the key above in its configuration file). @@ -47,6 +50,10 @@ applied one, and the interesting question is which change is missing from this d makes that question unaskable. It exists only as an explicit admin operation with an operator, a reason, and an approval (design §8.4). +The one change to the history an operator makes is narrower than repair: after a concurrent index +migration fails, the failed row of that one version is deleted so that the version can run again +("Concurrent index builds" below). Every applied row, and its checksum, stays as it was. + Only Flyway's structured error codes reach the exception. Its messages embed the script path and part of the failing statement. @@ -84,7 +91,9 @@ Flyway's list: Flyway runs it in the transaction, PostgreSQL refuses it there, a `VACUUM FULL`, a non-concurrent `REINDEX SCHEMA|DATABASE|SYSTEM` — can never be bounded this way and does not belong in a migration: run it by hand as an operations step, outside a deploy, in a psql session that sets `SET lock_timeout = '5s';` first (the session ends with the step, so the plain -`SET` is the bound there). +`SET` is the bound there). A `.sql.conf` with `executeInTransaction=true` does not change that: it +keeps the statement and its `SET LOCAL` in the transaction only for PostgreSQL to refuse it at +deploy, and the inspector below refuses it as well. Enforced, not remembered: `LockWaitMigrationInspector` (persistence-jpa testkit) reads a script — and the `.sql.conf` beside it, as Flyway reads it (a properties file, `false` in any case), and @@ -94,10 +103,9 @@ from its list that lock an existing table with no bound in force: `ALTER TABLE`, FULL`; `REFERENCES` on the table it references, in a new table as much as in an `ALTER TABLE` (a foreign key locks its parent against writes while it is added); `CREATE TRIGGER` and `DROP TRIGGER` on their table; `UPDATE` and `DELETE`. It reads text, so a statement outside the list is not -checked. `MigrationLockWaitTest` runs it over every tree this leaf's database runs, -`SampleMigrationLockWaitTest` over the sample's stream; a service stream copies the latter with its -own directory. Both find the migrations the way Flyway does, decimal versions (`V22_1__`) included -(`VersionedMigrationFiles`, testkit). The migrations released before the rule wait unbounded and +checked. `MigrationLockWaitTest`는 이 leaf의 데이터베이스가 돌리는 모든 트리에 이 검사를 건다. 서비스 +스트림은 이 테스트를 복사해 자기 폴더를 넣는다. 이 테스트는 Flyway와 같은 방식으로 마이그레이션을 찾고, 소수 +버전(`V22_1__`)도 포함한다(`VersionedMigrationFiles`, testkit). The migrations released before the rule wait unbounded and stay that way (they are applied, and applied files are never edited); the test lists them and refuses any new one. `PostgreSqlMigrationLockWaitIntegrationTest` (`postgresqlMigrationLockWaitIntegrationTest`) shows on real PostgreSQL that a bounded migration @@ -112,18 +120,25 @@ optional build, which cannot depend on the testkit: its `GrpcOperationLedgerMigr runs every ledger migration after V001, read from the tree, against a held ledger instead, so its next migration is checked on real PostgreSQL. It finds and orders that tree with the testkit's own `VersionedMigrationFiles`, which the ledger's `build.gradle` copies into its integration-test sources -at build time (`sharedMigrationFileSources`), so both builds read one definition. The rule came from -V21 having the bound and V22, in the same commit, not having it (re-review 2026-11-03 round 2, +at build time (`sharedMigrationFileSources`), so both builds read one definition. A concurrent index +build in that tree runs outside a transaction and is no case for a held ledger: it goes in the +test's `RUN_OUTSIDE_A_TRANSACTION` with its reason, and the same test holds each file listed there to +`ConcurrentIndexMigrationInspector`, copied the same way ("Concurrent index builds"). Every ledger +lane applies the tree one file at a time, as Flyway does, so such a file is not refused inside the +implicit transaction of one string holding many. The rule came +from V21 having the bound and V22, in the same commit, not having it (re-review 2026-11-03 round 2, RR-02-09; round 3, RR3-02-01, RR3-02-03, RR3-02-04; round 4, RR4-02-01; round 6, RR6-03-02, -RR6-03-03). +RR6-03-03; round 7, RR7-03-01). ## Concurrent index builds `CREATE INDEX CONCURRENTLY`, `DROP INDEX CONCURRENTLY` and `REINDEX … CONCURRENTLY` cannot run -inside a transaction block. Flyway recognizes `CREATE`/`DROP INDEX CONCURRENTLY` and runs such a -script outside a transaction on its own (above), but not `REINDEX … CONCURRENTLY`, which it runs in -the transaction for PostgreSQL to refuse. Write the companion configuration for every concurrent -statement anyway, so the file says what it needs and no reader has to know Flyway's list: +inside a transaction block. Flyway runs a script outside a transaction on its own when it holds +`CREATE`/`DROP INDEX CONCURRENTLY` or `REINDEX SCHEMA|DATABASE`, with or without `CONCURRENTLY` +(above). It runs `REINDEX INDEX|TABLE … CONCURRENTLY` — `REINDEX (CONCURRENTLY) TABLE` included — in +the transaction, where PostgreSQL refuses it. `PostgreSqlMigrationLockWaitIntegrationTest` shows the +five forms on real PostgreSQL. Write the companion configuration for every concurrent statement +anyway, so the file says what it needs and no reader has to know Flyway's list: ```conf # V42__order_index.sql.conf @@ -136,17 +151,33 @@ transaction Flyway itself keeps open, and Flyway waits for the build in turn: th and the table's other DDL and autovacuum queue behind the build meanwhile. The template's Flyway holds its lock for the session instead ("Who may change the schema"), so the build waits only for other transactions; a deployment tool left on Flyway's default stops on the first such migration. -`DROP INDEX CONCURRENTLY` does not wait that way. `PostgreSqlConcurrentIndexMigrationIntegrationTest` +`DROP INDEX CONCURRENTLY` does not wait that way: it waits only for the transactions that hold a +lock on its table. `PostgreSqlConcurrentIndexMigrationIntegrationTest` (`postgresqlConcurrentIndexMigrationIntegrationTest`) applies both builds as a second deploy, with the Flyway Spring Boot builds from the module defaults and with `FlywaySchemaPolicy.configure()`, on real PostgreSQL. The other transactions still count: a long one an operator or a report keeps -open holds the build, and a file run outside a transaction cannot bound that wait with `SET LOCAL`. -Look for old transactions (`pg_stat_activity.xact_start`) before deploying one. +open holds the build, and the drop too once it has touched the table, and a file run outside a +transaction cannot bound that wait with `SET LOCAL`. Look for old transactions +(`pg_stat_activity.xact_start`) before deploying one. The testkit's `ConcurrentIndexMigrationInspector` checks a script for this in a migration test -(nothing checks it at startup), and additionally requires the migration to contain nothing else. A failed concurrent build leaves an invalid index behind; -recovering is a single `DROP INDEX` when the migration did nothing else, and a manual reconstruction -of partial state when it did. +(nothing checks it at startup), and additionally requires the migration to contain nothing else. +Next to another statement, a concurrent one makes Flyway refuse the file before any of it runs when +nothing configures it; with `executeInTransaction=false` Flyway commits each statement on its own, +and a failed build leaves the statements before it applied — state to reconstruct by hand. + +Alone, a failed statement leaves an invalid index and a history row with `success = false` for its +version, and Flyway refuses every later deploy ("Detected failed migration to version …") until that +row is gone: dropping the index is not enough. The recovery is +[migration-failed.md](../runbooks/migration-failed.md) "Recover a failed concurrent index migration": +confirm no build is running, remove the cause, drop the invalid index a failed build or rebuild +left, delete that version's failed row and nothing else, deploy again. A failed `DROP INDEX +CONCURRENTLY` leaves invalid the index it was dropping; the runbook leaves that one for the deploy +again to drop, since dropped by hand it makes the same statement fail. It is not `flyway repair`, +which would also rewrite the remaining rows' checksums. `PostgreSqlConcurrentIndexMigrationIntegrationTest` +(`postgresqlConcurrentIndexMigrationIntegrationTest`) runs the runbook's SQL, read from the runbook, +after a unique build that failed on a duplicate and after a rebuild and a drop cancelled while they +waited for an open transaction, and shows both mixed files above. An invalid index is not merely useless — the planner ignores it while every write still maintains it. [runbooks.md](runbooks.md) has the query that finds them. Nothing drops them automatically: an diff --git a/docs/jpa/repository-adaptation.md b/docs/jpa/repository-adaptation.md index 4e6973b0..c0b3a490 100644 --- a/docs/jpa/repository-adaptation.md +++ b/docs/jpa/repository-adaptation.md @@ -1,8 +1,8 @@ # JPA Relational Persistence Platform — Repository Adaptation Contract -**Design source:** `docs/superpowers/specs/2026-08-11-jpa-persistence-platform-design.md` -**Stable plan source:** `docs/superpowers/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md` -**Experimental plan source:** `docs/superpowers/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md` +**Design source:** `docs/design/2026-08-11-jpa-persistence-platform-design.md` +**Stable plan source:** `docs/history/plans/2026-08-11-jpa-persistence-platform-implementation-plan.md` +**Experimental plan source:** `docs/history/plans/2026-08-11-jpa-persistence-experimental-expansion-plan.md` The design package states its own adaptation rule (§3.2): the assumed package paths and Gradle structure are explicit implementation *assumptions* made because the real Backend Skeleton @@ -100,9 +100,9 @@ Docker-dependent lanes fail closed rather than skipping, matching the existing | Hibernate ORM 7.4 is the Stable provider | Boot 4.0.0 resolves `org.hibernate.orm:hibernate-core:7.1.8.Final` | The *declared* Stable provider baseline of the design stays 7.4 in `HibernateProviderPolicy`; the runtime provider version is read from Hibernate itself and reported. The collection-fetch-pagination gate runs against whatever provider the BOM resolves, and `HibernateProviderPolicy.driftsFromDeclaredBaseline()` makes the difference visible instead of hiding it behind a green check. | | PostgreSQL 16·17·18 Stable matrix | This leaf's existing evidence image is `postgres:16-alpine` | `PostgreSqlVersion` declares exactly PG 16, 17, 18. The default lane runs the repository's existing 16 image; 17 and 18 are selected by `-Pjpa.matrix.versions=16,17,18`, and an unknown or empty selection is an error rather than a skip. | | `settings.gradle.kts` module registration | Fail-closed 19-leaf registry | No registry change: leaf identity, Gradle path, allowed dependencies, and runtime memberships are unchanged. | -| `infra/jpa/{postgres,roles,toxiproxy}` | Repository already owns `infra/` | Created at the same repository-relative paths. | +| `infra/jpa/{postgres,roles,toxiproxy}` | 이 repo는 운영 인프라 파일을 두지 않는다(2026-11-07 소유자 결정) | 2026-11-07에 지웠다(쓰는 곳이 없거나 운영 인프라 파일). 운영 DB 조건은 `docs/jpa/security.md`로 옮겼다. | | `docs/jpa/**`, `docs/adr/ADR-JPA-*`, `.github/workflows/jpa-*.yml` | Repository already owns `docs/` and `.github/workflows/` | Created at the same repository-relative paths. | -| release blocking aggregate | `jpaReleaseQualification` (persistence-jpa `build.gradle`) over `config/jpa/release-registry.json`, run per PostgreSQL major by the `jpa-release-gate` job in `.github/workflows/release.yml` | The registry names the blocking lanes; Gradle defines how each lane runs; CI only schedules the matrix. | | +| release blocking aggregate | `jpaReleaseQualification` (persistence-jpa `build.gradle`) over `persistence-jpa/release/release-registry.json`, run per PostgreSQL major by the `jpa-release-gate` job in `.github/workflows/release.yml` | The registry names the blocking lanes; Gradle defines how each lane runs; CI only schedules the matrix. | | | Per-task `git add` + `git commit` | `AGENTS.md`: commit policy is `human-only`; agents do not stage, commit, amend, or push | Implementation is delivered unstaged. This is the only plan step intentionally not executed, and it is recorded here. | | Querydsl as an optional module dependency | Querydsl is not part of this repository's dependency set | `querydsl` is implemented against the plan's contracts with the Querydsl types kept behind `compileOnly`, so the Stable runtime classpath never carries Querydsl and a deployment opting in adds the artifact itself. | | Hibernate Envers as a module dependency | Envers is not part of this repository's dependency set | Same treatment as Querydsl: `compileOnly` + explicit opt-in, matching the plan's "Envers is opt-in and never enabled by a global base class". | diff --git a/docs/jpa/runbooks.md b/docs/jpa/runbooks.md index ad14f251..6e954dc7 100644 --- a/docs/jpa/runbooks.md +++ b/docs/jpa/runbooks.md @@ -69,11 +69,19 @@ join pg_namespace n on n.oid = i.relnamespace where not x.indisvalid; ``` -A concurrent build failed. The index is ignored by the planner and maintained by every write. +A concurrent build, rebuild or drop failed. The index is ignored by the planner and maintained by +every write. 1. Confirm no build is currently running. An in-progress build looks identical in the catalog. -2. Run `DROP INDEX CONCURRENTLY IF EXISTS ;` outside a migration. -3. Re-apply the index migration. +2. If a migration was building, rebuilding or dropping it, Flyway recorded that version as failed + (`success = false`) and refuses every later deploy until that row is gone: dropping the index + does not clear it. Follow [migration-failed.md](../runbooks/migration-failed.md) "Recover a + failed concurrent index migration" instead of the next step. It removes the cause, drops the + index a failed build or rebuild left, and deletes that one row. It leaves the index a failed + `DROP INDEX CONCURRENTLY` left, for the deploy again to drop: dropped by hand, that statement + finds no index and fails again. +3. Otherwise run `DROP INDEX CONCURRENTLY IF EXISTS ;` outside a migration, and + re-apply the index migration. The platform does not drop these automatically: on a rolling deploy every instance would race to drop an index another instance was about to finish building. @@ -83,6 +91,6 @@ drop an index another instance was about to finish building. Startup refused because the runtime credential holds `CREATE`, or `search_path` contains an unapproved schema. -This is not a false positive to be worked around. Re-provision from -`infra/jpa/roles/runtime-roles.sql`; the application's credential having DDL is the condition that -makes every other schema guarantee unenforceable. +This is not a false positive to be worked around. `docs/jpa/security.md` 「역할과 권한 — 운영 DB가 +갖춰야 할 것」대로 권한을 다시 맞춘다. 애플리케이션 자격 증명이 DDL을 가지면 다른 schema 보장을 하나도 +지킬 수 없다. diff --git a/docs/jpa/security.md b/docs/jpa/security.md index 2d0813f4..dbf5fa92 100644 --- a/docs/jpa/security.md +++ b/docs/jpa/security.md @@ -14,7 +14,41 @@ The separation is what makes "Flyway owns schema change" enforceable rather than the application's own credential cannot execute DDL, then no code path, no library, and no injected statement can alter the schema at runtime, regardless of what the application intended. -`infra/jpa/roles/runtime-roles.sql` provisions them. +### 역할과 권한 — 운영 DB가 갖춰야 할 것 + +이 repo는 역할을 만드는 SQL 파일을 두지 않는다(2026-11-07 소유자 결정. 운영 DB 준비는 배포하는 쪽의 +일이다). 운영 DB는 아래 조건을 지켜야 한다. 기동 때 `PostgreSqlRuntimeRoleVerifier`가 그중 런타임 역할의 +`CREATE` 권한과 `search_path`를 다시 본다. + +1. 애플리케이션 schema(예: `app`)는 migration 역할이 소유한다. 런타임 역할이 소유하지 않는다. +2. `PUBLIC`에서 데이터베이스 권한 전체와 `public` schema의 `CREATE`를 거둔다. PostgreSQL 15 전에는 + `PUBLIC`이 `public` schema에 `CREATE`를 가져, 권한 없는 역할이 `search_path`로 진짜 객체를 가리는 + 객체를 만들 수 있었다. +3. 런타임 역할에는 `CONNECT`, 애플리케이션 schema의 `USAGE`, 그 schema 테이블의 + `SELECT`·`INSERT`·`UPDATE`·`DELETE`, sequence의 `USAGE`·`SELECT`만 준다. +4. migration 역할이 앞으로 만들 테이블·sequence에도 같은 권한이 가도록 `ALTER DEFAULT PRIVILEGES`를 + 건다. 빠뜨리면 새 테이블을 더한 첫 배포가 런타임 권한 오류로 실패한다. +5. 런타임 역할에서 schema와 데이터베이스의 `CREATE`를 명시적으로 거둔다. 기동 검사가 보는 두 권한이다. +6. 관리 역할(COPY·backfill·정비용)은 런타임 역할과 같은 행 권한을 갖되 schema를 소유하지 않는다. 요청 + 경로는 이 역할을 쓰지 않는다. +7. 런타임·관리 역할의 `search_path`를 `app, pg_catalog`처럼 고정한다. + +비밀번호는 배포 환경의 비밀 저장소에서 넣는다. repo에 두지 않는다. + +### 서버 설정 — 플랫폼의 보장이 기대는 것 + +계약 테스트는 자기 컨테이너를 띄우므로(`PostgreSqlContainerFactory`) 이 설정이 필요 없다. 운영 DB에서 +플랫폼의 보장이 성립하려면 아래 설정이 있어야 한다. 값은 출발점이다. 가장 느린 정상 쿼리를 재 보고 정한다. + +| 설정 | 출발 값 | 왜 필요한가 | +| --- | --- | --- | +| `statement_timeout` | `30s` | 트랜잭션 안의 문장 하나가 요청보다 오래 사는 것을 막는 마지막 상한 | +| `idle_in_transaction_session_timeout` | `60s` | 열어 둔 채 쉬는 트랜잭션이 잠금과 snapshot을 붙잡아 쓰기와 vacuum을 막는 시간을 줄인다 | +| `lock_timeout` | `10s` | `PostgreSqlLockOptions`의 요청별 잠금 상한 아래에 까는 바닥 | +| `max_connections` | 배포 수에 맞춤 | 모든 인스턴스의 pool 합과, `REQUIRES_NEW`가 두 번째 연결을 잡는 경우를 함께 견딘다 | +| `default_transaction_isolation` | `read committed` | 바꾸면 격리 수준을 고르지 않은 모든 트랜잭션이 조용히 달라진다 | + +확장(extension)은 필요 없다. JSONB, 배열, 범위, `SKIP LOCKED`, `ON CONFLICT`는 모두 PostgreSQL 본체 기능이다. ## Startup verification diff --git a/docs/jpa/support-matrix.md b/docs/jpa/support-matrix.md index 1de1114b..258fa1fa 100644 --- a/docs/jpa/support-matrix.md +++ b/docs/jpa/support-matrix.md @@ -1,7 +1,7 @@ # JPA Persistence Platform — Support Matrix **This document is a rendering. The machine-readable source is -[`src/config/jpa/release-registry.json`](../../src/config/jpa/release-registry.json).** +[`src/adapter/outbound/persistence-jpa/release/release-registry.json`](../../src/adapter/outbound/persistence-jpa/release/release-registry.json).** `JpaReleaseManifest` used to parse this file with regular expressions: every `PostgreSQL NN` it mentioned became a supported version, whatever table or sentence produced the match. An Experimental @@ -118,8 +118,8 @@ Each row is a way the platform could pass its tests and still be wrong in produc ### The audit mechanism `audit/AuditableEntity` is the only one: `created_*`/`updated_*`, a 256-character actor, stamped -explicitly by the repository adapter. It is what the sample entities extend and what the migrations -were written for. A second, Spring Data listener-based mechanism (`auditing/AuditMetadata`) was never +explicitly by the repository adapter. 서비스의 엔티티는 이것을 상속하고, 마이그레이션도 이 열에 +맞춰 썼다. A second, Spring Data listener-based mechanism (`auditing/AuditMetadata`) was never composed and has been removed; `JpaAuditMechanismRule.entitiesUseExactlyOneAuditMechanism` keeps it from coming back on an entity. diff --git a/docs/manual/02-new-feature.md b/docs/manual/02-new-feature.md index 8bdf7814..0f36708c 100644 --- a/docs/manual/02-new-feature.md +++ b/docs/manual/02-new-feature.md @@ -12,8 +12,8 @@ ``` 바깥 계층은 안쪽을 알지만 안쪽은 바깥을 모른다. 그래서 안쪽부터 만들면 각 단계가 앞 단계만 보고 -컴파일된다. 한 단계가 다른 leaf나 계층을 고쳐야 하면 거기서 멈추고 설계를 다시 본다(`CLAUDE.md` -Layer workflow). +컴파일된다. 한 단계가 다른 leaf나 계층을 고쳐야 하면 거기서 멈추고 설계를 다시 본다 +([새 기능 playbook](../work/new-feature.md) 「하지 말 것」). ## 0단계 — 배치를 정한다 @@ -35,7 +35,7 @@ Layer workflow). - **기본값**: 서버가 만든다. domain `XIdFactory extends IdFactory` + `adapter:outbound:identifier` 구현. 문법은 id 값 객체 생성자에서 검사한다. - **예외**: 클라이언트가 자연 키(주문번호 등)를 주는 기능은 그 키를 id로 쓴다. 이때 중복은 DB 유일성 - 제약이 막는다(04장). UUIDv7이 필요하면 `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/identifier/UuidWorkLogIdFactory.java`처럼 바꾼다. + 제약이 막는다(04장). UUIDv7이 필요하면 `src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactory.java`처럼 바꾼다. ### 판단: 불변식을 어디 두나 diff --git a/docs/manual/03-placement.md b/docs/manual/03-placement.md index 01ecf57a..395780c9 100644 --- a/docs/manual/03-placement.md +++ b/docs/manual/03-placement.md @@ -2,9 +2,9 @@ ## 핵심 -새 기능을 두는 모양은 셋이다. **업무 기능의 기본은 ① 계층 leaf 안 `` 패키지**다. -선택해서 켜고 끄는 플랫폼 기능만 ② 별도 `application-*` leaf로 만든다. ③ 한 leaf 수직 슬라이스는 -지울 수 있는 샘플 전용이다. 생성 명령은 ①만 만든다. +새 기능을 두는 모양은 둘이다. **업무 기능의 기본은 ① 계층 leaf 안 `` 패키지**다. +선택해서 켜고 끄는 플랫폼 기능만 ② 별도 `application-*` leaf로 만든다. 한 leaf에 모든 계층을 두는 +수직 슬라이스는 쓰지 않는다. 생성 명령은 ①만 만든다. ```text ① 계층 leaf 안 패키지 (기본) @@ -13,21 +13,18 @@ ② 기능 전용 leaf (capability) application- -> persistence-, adapter:outbound:, adapter:inbound:web- -> composition:-platform app-bootstrap/build.gradle 에 runtimeOnly 한 줄 - -③ 한 leaf 수직 슬라이스 (샘플 전용) - sample-portfolio = domain + application + adapter + bootstrap 패키지 ``` ## 기준표 -| 질문 | ① 계층 leaf 패키지 | ② 기능 leaf | ③ 수직 슬라이스 | -| --- | --- | --- | --- | -| 서비스마다 켜고 끌 수 있어야 하나 | 아니오 | **예** | — | -| 다른 서비스가 같은 기능을 라이브러리로 받나 | 아니오 | **예** | 아니오 | -| 한 줄 지워 기능을 통째로 빼야 하나 | 아니오(패키지 삭제) | **예**(`runtimeOnly` 한 줄) | 예(leaf 삭제) | -| leaf 단위 의존 방향 검사가 기능 안에도 걸리나 | 예(계층이 leaf) | 예 | **아니오**(ArchUnit 패키지 규칙에만 기댐) | -| 고칠 공용 파일 | 없음(+ imports 한 줄) | `modules.json`, `settings.gradle` 매핑, `app-bootstrap/build.gradle`, lockfile | `modules.json` | -| 예시 | 생성 명령 출력, `application-core/.../operation` | `application-notification`, `application-fileserver`, `application-objectstorage` | `sample-portfolio` | +| 질문 | ① 계층 leaf 패키지 | ② 기능 leaf | +| --- | --- | --- | +| 서비스마다 켜고 끌 수 있어야 하나 | 아니오 | **예** | +| 다른 서비스가 같은 기능을 라이브러리로 받나 | 아니오 | **예** | +| 한 줄 지워 기능을 통째로 빼야 하나 | 아니오(패키지 삭제) | **예**(`runtimeOnly` 한 줄) | +| leaf 단위 의존 방향 검사가 기능 안에도 걸리나 | 예(계층이 leaf) | 예 | +| 고칠 공용 파일 | 없음(+ imports 한 줄) | `modules.json`, `settings.gradle` 매핑, `app-bootstrap/build.gradle`, lockfile | +| 예시 | 생성 명령 출력, `application-core/.../operation` | `application-notification`, `application-fileserver`, `application-objectstorage` | ### 판단: ①과 ② 중 무엇인가 @@ -37,21 +34,20 @@ - **예외**: ② — 여러 서비스가 쓰는 플랫폼 기능, 배포마다 켜고 끄는 기능, 자기 설정 prefix와 자기 저장소를 가진 기능. 이때는 capability 완료 기준 7개를 모두 지킨다(`AGENTS.md`, 10장). - **다시 볼 조건**: 파생 서비스가 둘 이상 생겨 같은 업무 기능을 공유하거나, application-core 컴파일·테스트 - 시간이 문제가 되면 ①을 ②로 옮긴다(리뷰 01 영역 5.2절). + 시간이 문제가 되면 ①을 ②로 옮긴다. -### 판단: ③을 써도 되나 +### 판단: 한 leaf 수직 슬라이스를 써도 되나 -- **기본값**: 쓰지 않는다. ③은 leaf 하나가 모든 계층에 의존해서 leaf 단위 방향 검사가 기능 안에서는 +- **기본값**: 쓰지 않는다. leaf 하나가 모든 계층에 의존해서 leaf 단위 방향 검사가 기능 안에서는 아무것도 막지 못한다. -- **예외**: 통째로 지울 수 있어야 하는 샘플·데모. `sample-portfolio`가 그 예다. 샘플을 계층 leaf로 쪼개지 - 않는 이유는 "leaf 하나 지우면 끝"이라는 성질을 지키려는 것이다. +- **예외**: 없다. 이 모양이던 샘플 모듈은 매뉴얼과 생성 명령이 예시를 맡아 2026-11-07에 지웠다. ## ① 안의 패키지 규칙 | 계층 | 패키지 | 하위 패키지 | | --- | --- | --- | | domain | `dev.caskeleton.domain.` | fake·계약은 testFixtures `dev.caskeleton.domain..testkit` | -| application | `dev.caskeleton.application.` | 종류별 하위 패키지(`command`, `usecase`, `port`)를 만들지 않는다. 기능별 한 패키지(sample P30 결정과 같다) | +| application | `dev.caskeleton.application.` | 종류별 하위 패키지(`command`, `usecase`, `port`)를 만들지 않는다. 기능별 한 패키지 | | outbound | `dev.caskeleton.adapter.outbound..` | | | inbound | `dev.caskeleton.adapter.inbound.web.` | | | bootstrap | `dev.caskeleton.bootstrap.autoconfigure.` | `@AutoConfiguration`만(`BOOTSTRAP_AUTOCONFIGURE_STEREOTYPES_ARE_AUTO_CONFIGURATIONS`) | @@ -73,4 +69,3 @@ - 업무 기능 = ① 계층 leaf 패키지. 생성 명령이 이 모양을 만든다. - 켜고 끄는 플랫폼 기능 = ② 별도 leaf, capability 기준 7개. -- sample-portfolio는 기법 참고용이지 배치 예시가 아니다. diff --git a/docs/manual/04-persistence.md b/docs/manual/04-persistence.md index f009b847..cf10e492 100644 --- a/docs/manual/04-persistence.md +++ b/docs/manual/04-persistence.md @@ -31,7 +31,7 @@ use case ── tx.inWrite ──▶ XRepository (domain 포트) adapter는 호출자 트랜잭션 밖의 호출을 거부하므로(아래 「트랜잭션 안에서만 쓴다」), 계약의 `inTransaction(Supplier)`을 재정의해 거기서 트랜잭션을 열고 커밋한다. 계약은 모든 저장소 호출을 그 hook으로 부른다. fake는 기본값(그냥 실행)을 쓴다. - 예: `src/sample-portfolio/src/integrationTest/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/WorkLogRepositoryAdapterContractTest.java`. + 예: `src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/operation/JpaDurableOperationStoreContractTest.java`. 5. adapter를 bean으로 등록하는 자동 설정을 쓰고, 기능의 `XConfig`에 `afterName`으로 그 순서를 적는다. ## 판단: 저장 adapter를 둘 leaf @@ -44,7 +44,6 @@ use case ── tx.inWrite ──▶ XRepository (domain 포트) ("모듈을 아는 곳은 모듈 자신뿐")을 어기고, ② 그 leaf의 공개 API 기준선 (`docs/architecture/jpa-api-surface.txt`)과 엔티티 scan 목록(`PersistenceJpaConfig`, `PersistenceEntityScanCoverageTest`)을 고쳐야 하며, ③ upstream 병합 충돌 면이 넓어진다. - sample은 자기 leaf 안에 adapter를 둔다(③ 수직 슬라이스라서). - 새 leaf는 `modules.json` 등록, lockfile 생성, `app-bootstrap/build.gradle` 한 줄이 필요하다(10장). ## 엔티티 매핑 @@ -80,22 +79,22 @@ store는 자기 트랜잭션을 열지 않는다. 유스케이스가 연 트랜 - 중복 금지 → 유일성 제약/인덱스. 유스케이스의 사전 조회(`existsBy…`)는 빠른 거절일 뿐이다. READ COMMITTED에서 두 요청이 모두 "없음"을 보고 둘 다 insert한다. - adapter가 그 **이름 붙은 제약**의 위반만 잡아 기능 예외로 바꾼다. 다른 제약 위반은 그대로 둔다. - 예: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/outbound/persistence/repository/PosterRepositoryAdapter.java` - (`DataIntegrityViolationException` → 제약 이름 확인 → `PosterTitleAlreadyExistsException` 409), - 제약은 `src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql`. + 순서는 `DataIntegrityViolationException`을 잡는다 → 원인의 제약 이름이 그 제약인지 본다 → 맞으면 + 기능 예외(예: `TitleAlreadyExistsException`, 409)를 던지고, 아니면 다시 던진다. 템플릿 코드에는 이 + 모양의 예가 없다. 확인은 아래 공유 계약 테스트와 동시성 테스트로 한다. - **충돌을 바꾸는 곳은 하나다.** 업무 규칙 충돌(같은 제목)은 포트 옆 domain 패키지의 예외 타입이고, 포트가 `@throws`로 선언하고 adapter가 던진다. 유스케이스의 사전 조회도 같은 타입을 던져 두 경로가 같은 409가 된다. application 예외를 domain 포트가 Javadoc으로만 가리키면 fake·mock은 그 약속을 지킬 수 없다. 기술 충돌(버전 불일치·교착)은 adapter가 프레임워크 예외 그대로 두고 아래 `PersistenceExceptionTranslator`가 - `DB_*` 코드로 바꾼다(WorkLog의 `ObjectOptimisticLockingFailureException` → `DB_OPTIMISTIC_CONFLICT`). + `DB_*` 코드로 바꾼다(`ObjectOptimisticLockingFailureException` → `DB_OPTIMISTIC_CONFLICT`). - 그 약속은 포트 소유자 testFixtures의 공유 계약 테스트로 고정한다. fake와 adapter가 같은 계약을 상속한다. - 예: `PosterRepositoryContract`(`InMemoryPosterRepository`, `PosterRepositoryAdapterContractTest`). + 예: `DurableOperationStoreContract`(`InMemoryDurableOperationStore`, `JpaDurableOperationStoreContractTest`). - 여러 인스턴스가 집는 작업 → `FOR UPDATE SKIP LOCKED`는 **트랜잭션 안에서**, 그리고 lease(만료 시각)와 fence 값을 함께 저장한다. 예: `ReconciliationJobStorePort.claimDue`(application-notification), gRPC operation ledger의 claim. - - 수정 충돌 → 버전 열(낙관적 잠금). 예: `UpdateWorkLogUseCase`의 version 비교와 `@Version`. + - 수정 충돌 → 버전 열(낙관적 잠금). 예: `DurableOperationEntity`(persistence-jpa)의 `@Version` 열 `row_version`. - **예외**: DB가 볼 수 없는 규칙(외부 시스템 상태)은 분산 락(`DistributedLockPort`)이나 멱등성 키(05장). -- 동시성 테스트는 실 DB lane에서 동시 요청 N개 → 행 1개를 단언한다(sample `integrationTest` 참고). +- 동시성 테스트는 실 DB lane에서 동시 요청 N개 → 행 1개를 단언한다. ## 기술 실패는 공통 코드로 나간다 @@ -110,37 +109,35 @@ SQLState 표를 복사하지 않는다. ```text 템플릿 운영 스트림 classpath:db/migration/postgresql V1 … V19 … (upstream이 계속 늘린다) capability 스트림 db/migration/jpa/ 각자 history table -샘플 스트림 db/sample-migration flyway_sample_schema_history 서비스 스트림(권장) db/migration/ flyway__schema_history ``` - **고르는 기준**: upstream 템플릿을 계속 받을 것인가. - **기본값**: 서비스 마이그레이션은 **자기 위치 + 자기 history table** 스트림에 둔다. 모양은 - `SamplePostgreSqlPersistenceConfig.sampleMigrationStrategy` - (`src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/bootstrap/persistence/SamplePostgreSqlPersistenceConfig.java`)와 `NotificationSchemaStream`(persistence-notification). 그러면 번호가 템플릿 스트림과 독립이라 V1부터 쓴다. 자기 스트림의 Flyway는 `Flyway.configure()`가 아니라 `FlywaySchemaPolicy.configure()`(persistence-jpa)로 - 만든다. Flyway의 PostgreSQL 잠금을 세션에 두어야 `CREATE INDEX CONCURRENTLY` 마이그레이션이 끝나고, - 직접 부르면 `:app-bootstrap:architectureTest`가 실패한다(`docs/jpa/migration-guide.md` "Who may change the schema"). + 만든다. Flyway의 PostgreSQL 잠금을 세션에 두어야 `CREATE INDEX CONCURRENTLY` 마이그레이션이 끝난다. + `Flyway.configure()`를 직접 부르거나 설정 객체를 직접 만들면(`new FluentConfiguration()`, + `new ClassicConfiguration()`, 그 하위 클래스) `:app-bootstrap:architectureTest`가 실패한다 + (`docs/jpa/migration-guide.md` "Who may change the schema"). - **예외**: 템플릿 운영 스트림(`db/migration/postgresql`)에 직접 넣으면 upstream이 다음에 쓸 번호와 겹친다. 어쩔 수 없으면 upstream이 쓰지 않을 큰 번호대를 정해 문서에 적는다. - 이미 적용된 파일은 고치지 않는다. 고치면 체크섬 불일치로 기동이 멈추고, `repair`는 쓰지 않는다 (`docs/jpa/migration-guide.md`). -- 같은 스트림 안에서 기존 두 버전 사이에 끼워야 하면 소수 버전(`V8_1`)을 쓴다. 샘플 테스트 일부가 운영 - 스트림과 샘플 스트림을 한 목록으로 합치는데, 정수 V9 이상은 운영이 이미 쓰고 있어서 `V8_1`을 골랐다 - (리뷰 README 13.2, 09-02). -- 기존 데이터가 새 제약을 어기면 마이그레이션이 이유를 남기고 멈추게 쓴다(`V8_1`의 `DO $$` 블록). 조용히 +- 같은 스트림 안에서 기존 두 버전 사이에 끼워야 하면 소수 버전(`V8_1`)을 쓴다. 두 스트림을 한 목록으로 + 합쳐 검사하는 테스트가 있으면, 다른 스트림이 이미 쓴 정수 번호를 피하려고 이렇게 끼운다. +- 기존 데이터가 새 제약을 어기면 마이그레이션이 이유를 남기고 멈추게 쓴다(`DO $$` 블록의 `RAISE EXCEPTION`). 조용히 지우지 않는다. - 운영 중인 테이블을 잠그는 문장(`ALTER TABLE`, `CONCURRENTLY` 없는 `CREATE INDEX`, `UPDATE`·`DELETE`, 기존 테이블을 가리키는 `REFERENCES`, trigger 만들기·지우기 등 — 전체 목록은 `docs/jpa/migration-guide.md`)이 있으면 - 그 앞에 `SET LOCAL lock_timeout = '5s';`를 둔다(`V8_1`, `V22`). 값은 0이 아니어야 하고, + 그 앞에 `SET LOCAL lock_timeout = '5s';`를 둔다(`V22`). 값은 0이 아니어야 하고, `executeInTransaction=false` 마이그레이션에서는 `SET LOCAL`이 효과가 없으니 잠그는 문장을 거기 두지 않는다. Flyway가 스스로 트랜잭션 밖에서 돌리는 문장(`VACUUM`, `CREATE INDEX CONCURRENTLY` 등 — 목록은 같은 가이드)이 하나라도 있는 파일도 트랜잭션 밖에서 돌므로, 그런 문장은 따로 한 파일에 둔다. `VACUUM FULL`처럼 트랜잭션 안에서 돌 수 없는 잠금 문장은 상한을 걸 수 없으니 마이그레이션에 두지 않고 운영 절차로 돌린다. 상한이 없으면 그 테이블을 건드린 열린 트랜잭션 하나(`ALTER TABLE`이면 읽기만 한 것도) 뒤에서 마이그레이션이 끝없이 기다리고, 그동안 뒤에 온 그 테이블의 쓰기(`ALTER TABLE`이면 읽기까지)가 모두 마이그레이션 뒤에 줄을 선다. 상한이 있으면 5초 뒤 실패·롤백되고 새 버전이 뜨지 않을 뿐이다. 자기 스트림에도 - `SampleMigrationLockWaitTest`처럼 `LockWaitMigrationInspector`(persistence-jpa testkit) 검사를 둔다 + `MigrationLockWaitTest`(persistence-jpa)처럼 `LockWaitMigrationInspector`(persistence-jpa testkit) 검사를 둔다 (`docs/jpa/migration-guide.md` "Bound the lock wait"). ## 지금 이해하면 되는 것 diff --git a/docs/manual/05-idempotency.md b/docs/manual/05-idempotency.md index a076b5a4..25280c6c 100644 --- a/docs/manual/05-idempotency.md +++ b/docs/manual/05-idempotency.md @@ -40,8 +40,9 @@ DB 커밋 중 연결 끊김 ───────────────── 5. 저장소 provider를 고른다: `app.capabilities.idempotency.provider` = `postgresql` 또는 `redis` (기본 `disabled`). 운영에서 in-memory 금지. -예: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/` 의 -`PosterImagePublicationController`(키 헤더 검증), 유스케이스 쪽은 sample `application/posterimage`. +예: 키 헤더 검증은 `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/http/IdempotencyKeyHeader.java`, +executor 조립과 실제 PostgreSQL 저장소 왕복은 `PostgreSqlIdempotencyProviderIntegrationTest`(app-bootstrap +`integrationTest`)다. KEYED 유스케이스를 HTTP부터 끝까지 이은 업무 기능 예는 템플릿에 없다. ## 클라이언트에게 무엇을 약속하나 @@ -54,7 +55,7 @@ DB 커밋 중 연결 끊김 ───────────────── | 500 `IDEMPOTENCY_RECOVERY_REQUIRED` | 이전 시도 효과를 증명 못함 | 자동 재시도 안 함. 같은 키 재전송은 안전(재생·실행·다시 500을 서버가 판정, 다시 돌리지 않음). 업무 데이터로 확인하고, 효과가 없다고 확인된 뒤에만 운영 절차에 따라 새 키 | | 500 `DB_COMPLETION_UNKNOWN`, `retryable=false` | DB 커밋 중 연결 끊김. 커밋됐을 수도 있음 | 키 없이 재시도 금지. KEYED면 같은 키로 재전송하면 서버가 판정 | -같은 키 재전송이 무엇을 막는지는 저장소마다 다르다(재리뷰 2026-11-04 RR5-01-05, 라운드6 RR6-02-05, 정본 +같은 키 재전송이 무엇을 막는지는 저장소마다 다르다(정본 `docs/web/http-contract.md` 2절). Redis 저장소에서 같은 키 재전송은 효과가 있었을 수 있는 작업을 다시 돌리지 않는다. PostgreSQL 저장소를 템플릿처럼 쓰기 트랜잭션 하나로 쓰면 실패한 요청의 기록은 롤백되어 다음 같은 키 요청이 다시 실행한다. 그래서 트랜잭션 밖 효과는 따로 멱등하게 만든다. 첫 시도가 processing lease(기본 30s)보다 @@ -74,24 +75,24 @@ DB 커밋 중 연결 끊김 ───────────────── claim의 lease가 작업 시작 전에 끝나면 두 저장소 모두 시작을 거절하고(`LEASE_EXPIRED`), executor는 작업을 돌리지 않은 채 503 `IDEMPOTENCY_UNAVAILABLE`로 답한다. 다음 같은 키 요청이 그 claim을 넘겨받아 실행한다. -`IdempotencyClaimAttempt`를 재시도 사이에 들고 있다가 같은 attempt로 다시 부르는 호출자도 넘겨받는다(라운드6 -RR6-02-01. 전에는 같은 claim을 재생받아 시작을 다시 거절당해 기록이 사라질 때까지 503이었다). 같은 attempt를 -두 호출이 동시에 쓰면 서버가 가려내지 못하므로, 재시도는 앞 호출이 돌아온 뒤에 한다. +`IdempotencyClaimAttempt`를 재시도 사이에 들고 있다가 같은 attempt로 다시 부르는 호출자도 넘겨받는다(2026-11-05 +확인 리뷰가 찾아 고쳤다. 전에는 같은 claim을 재생받아 시작을 다시 거절당해 기록이 사라질 때까지 503이었다). +같은 attempt를 두 호출이 동시에 쓰면 서버가 가려내지 못하므로, 재시도는 앞 호출이 돌아온 뒤에 한다. 기록은 lease + `replay-ttl` 동안 남고, `replay-ttl`이 lease보다 짧으면 기동이 실패한다 -(`IdempotencyStoreContract`, 재리뷰 2026-11-04 RR-01-11·RR-03-11). 작업이 실패로 끝나 executor가 포기나 +(`IdempotencyStoreContract`). 작업이 실패로 끝나 executor가 포기나 재시도 가능으로 표시한 기록은 표시한 때부터 `failure-retention`(기본 24h) 동안 남는다(PostgreSQL을 트랜잭션 하나로 쓰면 위처럼 롤백과 함께 사라진다). `failure-retention`이 `replay-ttl`보다 짧으면 기동이 실패한다. -짧으면 효과 불명으로 포기한 기록이 먼저 사라져 같은 키 재전송이 작업을 다시 돌리기 때문이다(RR3-03-02, -2026-11-04 소유자 결정). 거꾸로 말하면 `replay-ttl`(`APP_IDEMPOTENCY_TTL`)은 lease 이상, `failure-retention` +짧으면 효과 불명으로 포기한 기록이 먼저 사라져 같은 키 재전송이 작업을 다시 돌리기 때문이다(2026-11-04 +소유자 결정). 거꾸로 말하면 `replay-ttl`(`APP_IDEMPOTENCY_TTL`)은 lease 이상, `failure-retention` 이하로 둔다. -409를 `retryable=true`로 바꾼 이유(리뷰 02-01 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시 +409를 `retryable=true`로 바꾼 이유(2026-11-01 소유자 결정): 같은 키 재전송은 서버가 안전하게 판정하므로 다시 보내는 것이 맞고, 새 키로 보내면 서버가 막지 못한다. 짝 프론트 분류기도 이 표를 따른다. ## 결과 불명을 만드는 곳마다 같은 규칙 -리뷰가 찾은 반복 원인 1번이 "결과 불명을 확실함으로 기록"이었다(05-01, 04-01, 06-01). 새 경계를 -만들 때 아래 질문에 답한다. +2026-11-01 성숙도 리뷰가 찾은 반복 원인 첫째가 "결과 불명을 확실함으로 기록"이었다. 알림 발송·DB +커밋·메시지 relay 세 경계에서 같은 실수가 나왔다. 새 경계를 만들 때 아래 질문에 답한다. - **고르는 기준**: 실패한 호출이 **상대편에서 이미 효과를 냈을 수 있는가**. - **기본값**: 그럴 수 있으면 "결과 불명"으로 분류한다. 재시도 가능(`retryable=true`)으로 분류하지 @@ -101,7 +102,8 @@ RR6-02-01. 전에는 같은 claim을 재생받아 시작을 다시 거절당해 - 메시지 발행 응답 없음 → `OutboxPublishAmbiguousException`(application-core `outbox`) - 알림 발송 시작 뒤 crash → 재발송하지 않고 reconcile(application-notification evidence 모델) - **예외**: 요청이 상대에게 **도달하기 전**에 실패한 것이 증명되면(연결 수립 실패, 실행 전 거부) - 재시도 가능이다. 반대 방향 실수(확실히 안 간 것을 불명으로)도 결함이다(리뷰 05-17). + 재시도 가능이다. 반대 방향 실수(확실히 안 간 것을 불명으로)도 결함이다(2026-11-01 성숙도 리뷰가 + Redis 연결 수립 실패에서 찾았다). - 불명 상태를 푸는 방법(reconcile, 키 재전송, 운영자 확인)을 runbook에 적는다(`docs/runbooks/`). ## 지금 이해하면 되는 것 diff --git a/docs/manual/06-errors.md b/docs/manual/06-errors.md index d80efb4b..5f59d9f5 100644 --- a/docs/manual/06-errors.md +++ b/docs/manual/06-errors.md @@ -26,9 +26,7 @@ gRPC/GraphQL/WebSocket: 같은 ApiErrorCarrier를 자기 status 모양으로 - **기본값**: application 기능 패키지의 `XErrorCode implements ApiErrorCode` enum + 예외가 `ApiErrorCarrier` 구현. 전송마다 핸들러를 만들 필요가 없다. 생성 명령 출력이 이 모양이다 (`ErrorCode`, `NotFoundException`, `RejectedException`). -- **예외**: 한 전송에서만 의미가 있는 실패(HTTP 헤더 형식 등)는 그 전송 adapter에 둔다. sample은 기능 - 코드를 web 패키지(`PortfolioErrorCode`, `DomainExceptionHandler`)에 두는데, 한 leaf 수직 샘플이라 - 가능한 모양이다. 따라 하지 않는다. +- **예외**: 한 전송에서만 의미가 있는 실패(HTTP 헤더 형식 등)는 그 전송 adapter에 둔다. ## 판단: 어떤 예외 타입으로 던지나 @@ -42,8 +40,8 @@ gRPC/GraphQL/WebSocket: 같은 ApiErrorCarrier를 자기 status 모양으로 | DB·외부 의존 실패 | adapter가 shared-contract carrier(`PersistenceFailureException`, `DependencyFailureException`)로 | 분류표대로(04·05장) | - `IllegalArgumentException`을 "서버 조립이 틀렸다"에 쓰지 않는다. web은 그것을 400으로 바꾸고 WARN - 한 줄만 남긴다(`GlobalExceptionHandler`). 서버 결함이 클라이언트 오류 통계에 섞여 경보가 울리지 않는다 - (리뷰 01-04). 서버 쪽 잘못은 `IllegalStateException`(500, 로그)이다. + 한 줄만 남긴다(`GlobalExceptionHandler`). 서버 결함이 클라이언트 오류 통계에 섞여 경보가 울리지 않는다. + 서버 쪽 잘못은 `IllegalStateException`(500, 로그)이다. - 메시지는 로그용이다. 클라이언트에는 코드와 category별 고정 문구(`ClientErrorMessages`)만 간다. 메시지에 SQLState·내부 경로·토큰을 넣어도 클라이언트에 새지 않지만, 로그 정책은 지킨다. @@ -58,8 +56,8 @@ gRPC/GraphQL/WebSocket: 같은 ApiErrorCarrier를 자기 status 모양으로 - 템플릿 운영 코드: `OperationalError` + `docs/registries/error-codes.yaml`을 같은 변경에서 고친다. `ErrorCodeRegistryMappingTest`(app-bootstrap)가 status 일치를 검사한다. - 서비스 기능 코드: 그 registry에 넣지 않는다(registry 머리말 "Product/fork ApiErrorCode enums own local - registries"). 서비스 자기 registry를 만들고 같은 모양의 대조 테스트를 둔다. 예: - `src/sample-portfolio/src/test/java/dev/caskeleton/sample/portfolio/adapter/inbound/web/error/PortfolioErrorCodeRegistryMappingTest.java`. + registries"). 서비스 자기 registry를 만들고 같은 모양의 대조 테스트를 둔다. 모양은 위 + `ErrorCodeRegistryMappingTest`(`src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/ErrorCodeRegistryMappingTest.java`)다. ## 지금 이해하면 되는 것 diff --git a/docs/manual/07-authorization.md b/docs/manual/07-authorization.md index 468f0901..4f56ff53 100644 --- a/docs/manual/07-authorization.md +++ b/docs/manual/07-authorization.md @@ -25,7 +25,8 @@ | 프록시 가능 | `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/authz/RequiresPermissionProxyabilityTest.java` | 검사 자동 설정은 인증 체인(`WebSecurityAutoConfiguration`)과 **분리**되어 있다. 서비스가 자기 인증 -방식으로 인증 체인을 바꿔도 권한 검사는 꺼지지 않는다(1라운드 07-03 수정). +방식으로 인증 체인을 바꿔도 권한 검사는 꺼지지 않는다(2026-11-01부터. 전에는 인증 체인 자동 설정을 빼면 +권한 검사도 함께 빠졌다). ### 지켜야 할 것 셋 @@ -48,8 +49,8 @@ ### 역할은 어디서 오나 JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `resource_access..roles`만 -읽는다. audience는 필수다(1라운드 02-03 수정). 같은 issuer의 다른 client가 같은 이름의 역할을 정의해도 -이 서비스 권한이 되지 않는다(`JwtToAuthenticatedPrincipalConverter`, `docs/runbooks/auth-audience-mismatch.md`). +읽는다. audience는 필수다(2026-11-01부터. 전에는 비어 있으면 검증을 건너뛰었다). 같은 issuer의 다른 +client가 같은 이름의 역할을 정의해도 이 서비스 권한이 되지 않는다(`JwtToAuthenticatedPrincipalConverter`, `docs/runbooks/auth-audience-mismatch.md`). ## 객체 단위 권한 @@ -80,7 +81,8 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re 어디서든 ─▶ @SystemInvoked 유스케이스를 bean으로 등록 ──✗ (기동 실패) ``` -- 사용자 전송: 사용자가 보낸 요청이 들어오는 inbound adapter다(web·GraphQL·gRPC·WebSocket). +- 사용자 전송: 사용자가 보낸 요청이 들어오는 inbound adapter다(web·GraphQL·gRPC·WebSocket). STOMP + 클라이언트가 보낸 프레임마다 도는 inbound channel interceptor도 여기에 든다. - 시스템 호출자: broker 전달이나 시간(tick)이 깨우는 코드다. 사용자 요청은 여기로 들어오지 않는다. 시스템 호출자가 `@SystemInvoked` 유스케이스를 얻는 길은 아래 셋뿐이다. 이 표가 정본이고, 다른 문서는 이 @@ -95,25 +97,32 @@ JWT의 `realm_access.roles`와 **자기 client**(`app.security.audience`)의 `re 예약 작업은 controller와 같은 leaf에 놓이기 쉽다. 그때 "지금 실행" endpoint가 작업 bean을 주입받아 부르면 권한 검사 없는 쓰기를 사용자가 부르게 된다. 아래 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`가 이것을 빌드에서 막는다. 사용자도 같은 일을 시켜야 하면 `@RequiresPermission`을 단 사용자용 유스케이스를 따로 -만든다(아래 D4 문단). +만든다(아래 권한 선언 검사 문단). | 규칙 | 무엇을 막나 | 어디 | | --- | --- | --- | | bean 금지 | `@SystemInvoked` 유스케이스가 bean이면 기동 실패. 호출자가 `new`로 만들어 혼자 들고 있는 것만 허용한다 | `src/composition/service-runtime/src/main/java/dev/caskeleton/composition/runtime/authorization/PermissionEnforcementGuard.java` | | 시스템 호출자만 | inbound adapter가 그 클래스에 의존하면 빌드 실패. `@SystemCaller(reason = "...")`를 단 클래스와 그 안에 중첩된 클래스만 예외 | `ONLY_SYSTEM_CALLERS_REACH_SYSTEM_INVOKED_USE_CASES`(`ApplicationBoundaryArchitectureTest`) | -| 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) | -| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등)에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 셋이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`)과 그 안에 중첩된 클래스 가운데 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor` 등)에 의존하는 것. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. ③ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·controller bean을 함께 만들어도 걸리지 않지만, 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 직접 쓰면 걸린다. 요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | +| 표시 검사 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스는 `..adapter.inbound.messaging..`·`..adapter.inbound.scheduler..`에만 있고, 사용자 전송 타입(controller·JAX-RS·GraphQL·STOMP mapping과 channel interceptor·gRPC·servlet)에 의존하지 않는다 | `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`(같은 파일) | +| 전송 → 시스템 호출자 금지 | 사용자 전송 클래스가 `@SystemCaller`나, 그 클래스가 구현·상속하는 프로젝트 타입(작업의 인터페이스 등)에 의존하면 빌드 실패. 중간 클래스를 거쳐도 잡는다. 사용자 전송 클래스는 넷이다. ① 사용자 전송 패키지에 있는 클래스. ② 설정(`@Configuration`·`@AutoConfiguration`) 클래스 자신이 요청 처리기 타입(함수형 `RouterFunction`·`HandlerFunction`, `@RestController`·`@RequestMapping`, servlet·`Filter`·`HandlerInterceptor`, `WebSocketHandler`, GraphQL `DataFetcher`·`RuntimeWiringConfigurer`, gRPC `BindableService`·`ServerInterceptor`, STOMP `ChannelInterceptor`·`ExecutorChannelInterceptor` 등)에 의존하는 것. 요청 처리 코드를 설정에 직접 쓴 경우와 등록만 한 경우가 모두 든다. channel interceptor를 구현한 설정은 프레임마다 자기 메서드가 돈다. interceptor를 `@Bean`으로 내놓는 설정은 route를 등록하는 설정과 같다. 함수형 route나 data fetcher를 람다로 쓰면 그 코드가 설정 클래스의 메서드로 컴파일되어 설정이 곧 endpoint다. 처리 코드를 다른 클래스에 두고 메서드 참조로 등록만 해도(`route().GET("/orders", orders::list)`) 설정은 route builder에 의존한다. 클래스 의존으로는 등록과 처리 코드를 가를 수 없어서 둘 다 사용자 전송으로 센다. ③ 설정 안에 중첩된 클래스 가운데 사용자 전송 타입에 의존하는 것. 중첩된 JAX-RS 자원·`@ServerEndpoint`, `configureClientInboundChannel`에서 등록하는 STOMP channel interceptor(익명 클래스여도, STOMP 헤더를 읽지 않아도)도 여기서 잡힌다. 설정용 타입(`WebMvcConfigurer`·`WebSocketConfigurer`·STOMP broker 설정과 그 registry, CORS 설정, `RequestMethod`)에만 의존하는 중첩 클래스는 설정의 일부로 본다. inbound channel의 thread 수만 정하는 설정도 설정용이다. ④ 그 밖의 클래스 가운데 사용자 전송 타입에 의존하는 것. 사용자 전송 패키지 밖에 둔 channel interceptor가 여기에 든다. 그래서 handler를 bean으로 등록하는 설정은 같은 클래스에서 `WebMvcConfigurer`(설정 필드를 읽는 익명 클래스여도)·CORS 설정·controller bean을 함께 만들어도 걸리지 않는다. 같은 클래스에 "지금 실행" route·data fetcher·interceptor를 쓰거나, route를 등록하거나, 안에 중첩한 endpoint가 작업을 부르면(설정의 메서드를 거쳐 불러도) 걸린다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. 설정이 만드는 controller는 controller 자신이 검사받는다 | `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`(같은 파일) | | 프로젝트 밖 상위 타입 금지 | `@SystemCaller` 클래스와 그 안에 중첩된 클래스(익명·지역 클래스와 예외 제외)는 프로젝트(`dev.caskeleton..`) 밖의 클래스·인터페이스를 상속·구현하지 않는다. `Runnable`은 누구나 의존하는 타입이라, endpoint가 작업을 `Runnable`로 주입받아도 위 규칙이 다른 사용과 구별하지 못하기 때문이다. 메시지 handler의 `MessageHandler`는 프로젝트 타입이라 된다. record·enum은 언어가 붙이는 상위 타입(`Record`, `Enum`과 `Enum`이 구현하는 `Comparable`·`Serializable`·`Constable`)만은 가져도 된다. 그래서 handler 안의 파싱 결과 record, 결과 enum, 독(poison) 메시지 예외, record로 쓴 handler는 통과하고, `Runnable`을 구현한 record는 걸린다 | `SYSTEM_CALLERS_HAVE_ONLY_PROJECT_SUPERTYPES`(같은 파일) | 규칙은 "누가 닿으면 안 되나"가 아니라 "누가 닿아도 되나"를 적는다. 이 성질은 **패키지** 쪽에서만 온다. 패키지는 허용 목록이라, 나중에 새 전송 패키지가 생겨도 따로 고치지 않아도 막힌다. 사용자 전송 **타입** 쪽은 나열 목록이다(`ARE_USER_TRANSPORT_TYPES`). 시스템 패키지 안에 놓인 endpoint를 알아보는 데 쓰는 목록이라, 목록에 없는 전송 라이브러리로 만든 endpoint는 전송으로 보이지 않는다. 새 전송 라이브러리를 -들이면 그 패키지를 이 목록에 더한다. 설정 안의 요청 처리 코드를 알아보는 요청 처리기 타입 -(`ARE_REQUEST_HANDLER_TYPES`)도 나열 목록이라, 새 전송 라이브러리의 handler 타입을 함께 더한다. +들이면 그 패키지를 이 목록에 더한다. 들인 라이브러리에서 사용자 요청이 지나는 타입을 새로 쓸 때도 같다. +STOMP는 `org.springframework.messaging` 가운데 `simp` 패키지, `@MessageMapping`, inbound channel +interceptor 두 타입(`ChannelInterceptor`·`ExecutorChannelInterceptor`)만 목록에 있다. 같은 라이브러리의 +broker listener용 `@Payload`·`@Header`는 시스템 쪽이라 넣지 않는다. 설정 클래스 자신을 판정하는 요청 처리기 +타입(`ARE_REQUEST_HANDLER_TYPES`)도 나열 목록이라, 새 전송 라이브러리의 handler 타입을 함께 더한다. 요청 처리기 +타입은 모두 사용자 전송 타입이어야 하고, 설정용 타입(`ARE_TRANSPORT_SETUP_TYPES`)은 요청 처리기 타입을 덮지 +않아야 한다. `UserTransportTypeListsTest`가 둘을 검사한다. 설정용 타입 목록에 없는 configurer 타입을 쓰는 중첩 +클래스는 사용자 전송으로 읽혀, 설정 필드를 읽으면 빌드가 실패한다. 그 타입이 요청마다 도는 코드가 아니라 기동 때 +한 번 도는 설정용 타입이면 설정용 타입 목록에 더한다. -D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표시를 쓰지 않는다. 사용자가 부르는 -쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다 +쓰기 유스케이스의 권한 선언 검사(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`) 실패를 끄려고 이 표시를 +쓰지 않는다. 사용자가 부르는 쓰기라면 권한을 선언하고 역할에 매핑한다. 같은 쓰기를 사용자도 시스템도 부르면 유스케이스를 둘로 나눈다 (사용자용 `@RequiresPermission`, 시스템용 `@SystemInvoked`). 업무 규칙은 domain에 두고 둘이 같이 쓴다. ### 규칙이 못 보는 길 @@ -123,10 +132,13 @@ D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표 - 이름이나 `Object`로 bean을 찾는 코드: `getBean("nightlyJob")`, `Map` 주입 뒤 reflection 호출. - 설정이 사용자 전송에 작업을 감싼 함수를 넘기는 코드: `new RunNowController(job::run)`처럼 controller는 - `Runnable`만 받는다. 의존은 설정 → 작업 쪽에만 있고, 요청 처리 코드를 직접 갖지 않은 설정은 사용자 전송이 + `Runnable`만 받는다. 의존은 설정 → 작업 쪽에만 있고, 요청 처리기 타입에 의존하지 않는 설정은 사용자 전송이 아니다. -- 설정 안의 요청 처리 코드가 요청 처리기 타입 목록(`ARE_REQUEST_HANDLER_TYPES`)에 없는 타입으로 쓰인 경우. - 목록 방식이라, 목록에 없는 endpoint 타입으로 설정 안에 쓴 endpoint는 사용자 전송으로 보이지 않는다. +- 설정 클래스 자신에 쓴 요청 처리 코드가 요청 처리기 타입 목록(`ARE_REQUEST_HANDLER_TYPES`)에 없는 타입으로 + 쓰인 경우. 목록 방식이라, 목록에 없는 endpoint 타입으로 설정 클래스에 직접 쓴 endpoint는 사용자 전송으로 + 보이지 않는다. 설정 안에 중첩한 클래스는 더 넓은 사용자 전송 타입 목록으로 보므로 여기에 들지 않는다. 다만 + 그 목록도 나열 목록이라, 그 목록에 없는 타입으로 만든 endpoint는 어디에 두든 보이지 않는다. 그런 타입을 + 쓰게 되면 앞 절의 사용자 전송 타입 목록 문단대로 목록에 더한다. 이 길을 막는 것은 ArchUnit 규칙이 아니라 다음 셋이다. @@ -137,13 +149,13 @@ D4 실패(`MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`)를 끄려고 이 표 못 한다. 예약 작업은 서비스 자기 leaf에 있어서 같은 leaf의 controller와 사이에는 이 게이트가 없다. 그래서 위 길들은 사실상 controller와 작업이 같은 leaf에 있을 때, 또는 둘을 모두 보는 설정에서 생긴다. - 리뷰: 설정에서 시스템 호출자를 함수로 감싸 다른 bean에 넘기거나, 사용자 전송이 bean을 이름으로 찾거나, 목록에 - 없는 타입으로 설정 안에 endpoint를 쓰는 코드는 리뷰에서 거절한다. 사용자도 같은 일을 시켜야 하면 위 문단대로 + 없는 타입으로 설정 클래스에 endpoint를 쓰는 코드는 리뷰에서 거절한다. 사용자도 같은 일을 시켜야 하면 위 문단대로 사용자용 유스케이스를 따로 만든다. ## web 없는 조립 web이 빠진 조립(gRPC 전용·배치 전용)에는 `@RequiresPermission`을 검사할 advisor가 없다. 그런 조립에 -권한을 선언한 bean이 있으면 `PermissionEnforcementGuard`가 기동을 실패시킨다(리뷰 01-06). web 없이 +권한을 선언한 bean이 있으면 `PermissionEnforcementGuard`가 기동을 실패시킨다. web 없이 조립하는 서비스는 자기 전송에 맞는 검사 advisor를 함께 넣어야 기동한다. ## 지금 이해하면 되는 것 diff --git a/docs/manual/08-testing.md b/docs/manual/08-testing.md index 631d0af7..ae0560a5 100644 --- a/docs/manual/08-testing.md +++ b/docs/manual/08-testing.md @@ -35,7 +35,7 @@ fake와 실제 adapter가 **같은 계약**을 통과해야 fake 위의 유스 1. 이름은 lowerCamelCase 행동 문장. 이름이 말한 성질을 단언한다. 예: 이름에 "트랜잭션 전에"를 넣었으면 트랜잭션이 없었다는 것도 단언하거나, 이름에서 뺀다. 2. `@DisplayName`은 메서드 이름으로 못 쓰는 내용(숫자, 기호, 이유)이 있을 때만, **한국어**로 - (소유자 결정 5). 예: `@DisplayName("이름이 NAME_MAX_LENGTH + 1자이면 거절한다")`. + (2026-09-25 소유자 결정). 예: `@DisplayName("이름이 NAME_MAX_LENGTH + 1자이면 거절한다")`. 3. 본문 3문장 이상이면 `// given` `// when` `// then`. `// when`은 하나. 예외는 `catchThrowable`로 분리. 4. then은 when의 결과 하나만. 예외는 타입과 reason/code를 함께. 5. 포트 대역은 hand-rolled fake 하나, **포트 소유 leaf의 testFixtures**에. Mockito는 프레임워크 경계와 @@ -46,7 +46,8 @@ fake와 실제 adapter가 **같은 계약**을 통과해야 fake 위의 유스 - **고르는 기준**: 포트 인터페이스가 어느 leaf에 있나. - **기본값**: 그 leaf의 `src/testFixtures/java/...//testkit/`. domain 포트면 domain-core, application 포트면 application-core. 소비 leaf는 `testImplementation testFixtures(project(':'))`. -- **예외**: 없다. 테스트 안 private fake는 계약 밖에 있어 실제와 갈라진다(리뷰 01-05의 lock fake). +- **예외**: 없다. 테스트 안 private fake는 계약 밖에 있어 실제와 갈라진다(2026-11-01 성숙도 리뷰가 + 분산 lock 포트 계약 테스트 안의 fake에서 찾았다). ## lane과 단계 @@ -61,7 +62,7 @@ lane으로 선언하고 단계를 지정한다. 선언은 `ca.strict-test-lane`( | 성능·부하 | performance 범주 | `performanceCheck` | | 외부 입력 필요(자격증명 등) | `explicitOnly(reason)` | 어떤 집계에도 안 들어가고 이유가 출력된다 | -예: `src/sample-portfolio/build.gradle`의 `strictTestLanes { lane('integrationTest') { integration() … } }`, +예: `src/app-bootstrap/build.gradle`의 `strictTestLanes { lane('integrationTest') { integration() … } }`, `src/app-bootstrap/build.gradle`의 `publicPathSnapshotTest`(`mainStage()`). ### 판단: 새 테스트를 어느 lane에 @@ -71,7 +72,8 @@ lane으로 선언하고 단계를 지정한다. 선언은 `ca.strict-test-lane`( - **예외**: 반드시 실행돼야 하는 소수 테스트(계약 자격 검사)는 `requires(클래스)` + `rejectSkipped = true`로 이름을 박는다. 이름이 바뀌거나 지워지면 lane이 실패한다. - 새 lane이 어떤 단계에도 속하지 않으면 PR 게이트의 `verifyStrictLaneStages --dry-run`이 실패한다 - (1라운드 08-01). 단계는 집계 태스크(`integrationCheck` 등)를 통해 붙고, workflow 파일을 고치지 않는다. + (2026-11-01부터. 전에는 어떤 workflow도 돌리지 않는 strict lane이 14개 있었다). 단계는 집계 + 태스크(`integrationCheck` 등)를 통해 붙고, workflow 파일을 고치지 않는다. ## 지금 이해하면 되는 것 diff --git a/docs/manual/09-outbox-events.md b/docs/manual/09-outbox-events.md index 61b75b94..68affbe9 100644 --- a/docs/manual/09-outbox-events.md +++ b/docs/manual/09-outbox-events.md @@ -23,19 +23,19 @@ DB 저장과 broker 발행을 따로 하면(dual write) 둘 중 하나만 성공 ## 순서 1. 계약을 정한다: 계약 id(`..`), 버전, payload record, JSON schema 파일과 해시. - 예: `src/sample-portfolio/src/main/java/dev/caskeleton/sample/portfolio/application/worklog/WorkLogReservedContractContribution.java`, - `src/sample-portfolio/src/main/resources/contracts/messaging/portfolio.worklog.reserved/v1.schema.json`(+ `.sha256`). + 예: `src/application-core/src/main/java/dev/caskeleton/application/operation/DurableOperationSubmittedContract.java`, + `src/application-core/src/main/resources/contracts/messaging/durable-operation.submitted/v1.schema.json`(해시는 계약 클래스 안). 2. payload record(`IntegrationPayload`)를 만든다. 3. 유스케이스의 `tx.inWrite` 안에서 저장 뒤 draft → encode → append. 예: - `CreateWorkLogUseCase`(sample)와 그 헬퍼 `PortfolioEventOutbox`. + `SubmitDurableOperationUseCase`(application-core `operation`). 4. 계약 contribution을 조립에서 `@Bean`으로 등록한다. encoder는 컨텍스트의 계약 bean으로 만들어진다. 등록을 빠뜨리면 append 때 실패한다. 예: `DurableOperationAutoConfiguration.durableOperationSubmittedContract()`. 5. 테스트: 계약 contribution 테스트(해시 고정), 유스케이스가 append했는지(`InMemoryOutboxStore`), - 소비자 중복 제거 계약(sample `WorkLogReservedConsumerDedupeContractTest`). + 소비자가 있으면 같은 event id를 두 번 받아도 효과가 한 번인지 보는 중복 제거 계약. 6. schema를 출시한다: `src/test/resources/contracts/released-payload-schemas.sha256`에 새 version 파일의 해시를 한 줄 더한다. 출시한 version 파일은 고치지 않는다 — 바뀌면 `ReleasedPayloadSchemaContract` 테스트가 실패한다. 필드를 바꾸는 변경은 새 version으로 낸다. 절차: `src/application-core/README.md` - "payload version 올리기"(리뷰 06-10). + "payload version 올리기". ## 판단 지점 @@ -44,7 +44,7 @@ DB 저장과 broker 발행을 따로 하면(dual write) 둘 중 하나만 성공 - **고르는 기준**: 같은 서비스 안에서 이 사실에 반응하는 코드가 있는가. - **기본값**: 통합 이벤트만. 유스케이스가 저장 뒤 바로 payload를 만든다. - **예외**: aggregate 안에서 일어난 사실을 여러 유스케이스가 같은 방식으로 내보내면 domain - `@DomainEvent` record를 두고 유스케이스가 그것을 payload로 옮긴다(sample `WorkLogReserved`). + `@DomainEvent` record를 두고 유스케이스가 그것을 payload로 옮긴다. ### payload에 무엇을 넣나 @@ -57,11 +57,11 @@ draft는 `IntegrationEventDrafts.draft(contract, eventId, aggregate, order, occu 만든다(`src/application-core/src/main/java/dev/caskeleton/application/messaging/event/IntegrationEventDrafts.java`). 계약 id·payload 버전·목적지는 계약에서 오고, 기능이 정하는 것은 aggregate·순서·payload뿐이다. `new IntegrationEventDraft<>(…)`를 직접 쓰면 빌드가 막는다(`INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`). -예: sample `PortfolioEventOutbox`, `SubmitDurableOperationUseCase`. +예: `SubmitDurableOperationUseCase`. - event id: 정규 소문자 UUIDv7, 소비자 중복 제거 키. draft(`IntegrationEventDraft`)가 다른 값(대문자, v4, `event-1` 같은 문자열)을 거부하므로 업무 쓰기에서 바로 실패한다 — 커밋된 뒤 relay에서 DEAD가 되지 - 않는다(리뷰 06-06). 같은 작업의 재시도가 같은 event id를 내야 하면(durable operation) 작업 id를 쓰고, + 않는다. 같은 작업의 재시도가 같은 event id를 내야 하면(durable operation) 작업 id를 쓰고, 작업 id가 UUIDv7이 아니면 작업 id와 접수 시각에서 UUIDv7을 파생한다. - correlation: 헬퍼가 정한다. 요청의 correlation id가 `IntegrationIdentity` 문법·길이에 맞으면 그것, 아니면 event id. 문법 밖 헤더가 업무 쓰기를 실패시키지 않는다. 값을 미리 검사해야 하면 문법을 베끼지 @@ -70,12 +70,12 @@ draft는 `IntegrationEventDrafts.draft(contract, eventId, aggregate, order, occu - tenant 범위: tenant가 없는 기능은 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`). - aggregate 순서: `OutboxAggregateSequencePort.nextSequence(aggregate)`로 같은 `tx.inWrite` 안에서 받는다(V21 카운터, 커밋 순서를 따른다). 이벤트가 하나뿐인 aggregate는 `AggregateOrder.first()`. 발생 - 시각(벽시계)은 쓰지 않는다 — 서버 시계가 어긋나면 순서가 뒤집힌다(리뷰 06-07). 벽시계 번호를 쓰던 + 시각(벽시계)은 쓰지 않는다 — 서버 시계가 어긋나면 순서가 뒤집힌다. 벽시계 번호를 쓰던 서비스가 포트로 옮기면 V21 floor 덕분에 새 번호는 옛 번호 뒤에서 시작한다. 그래서 첫 번호가 1이 아니라 약 1.7×10¹⁵일 수 있다. 소비자는 번호를 "마지막으로 본 값보다 큰가"로만 비교하고 연속성을 가정하지 않는다. 비교는 aggregate identity(tenant scope 포함) 단위다. tenant scope를 바꾸는 배포는 옛 버전 인스턴스를 모두 멈춘 뒤 새 버전을 띄운다 — 섞여 돌면 새 scope의 번호가 옛 버전이 방금 쓴 번호보다 - 작을 수 있다(runbook `outbox-dead-letter.md` §8, 재리뷰 2차 RR-02-10). + 작을 수 있다(runbook `outbox-dead-letter.md` §8). ## relay와 실패 @@ -83,10 +83,10 @@ draft는 `IntegrationEventDrafts.draft(contract, eventId, aggregate, order, occu 선언이 없어서, bean이 되면 전송 계층이 **권한 검사 없이** 닿는다. 그래서 bean으로 등록하면 `PermissionEnforcementGuard`가 기동을 실패시킨다(07장 「시스템이 부르는 쓰기」). - broker의 **재시도 가능한** 거부와 응답 없음은 DEAD가 아니라 backoff 재시도다. broker가 멈춰도 대량 - DEAD가 되지 않는다(1라운드 06-01·06-03). 대신 끝이 없다: 진짜 인증 오류, Kafka adapter가 이름을 모르는 - broker 거부도 영원히 재시도된다. 행의 `last_failure_code`와 로그의 `error.reason`이 원인 코드를 남기고, + DEAD가 되지 않는다(2026-11-01부터. 전에는 broker가 몇 분만 멈춰도 행이 대량으로 DEAD가 됐다). 대신 + 끝이 없다: 진짜 인증 오류, Kafka adapter가 이름을 모르는 broker 거부도 영원히 재시도된다. 행의 `last_failure_code`와 로그의 `error.reason`이 원인 코드를 남기고, `outbox.retry.long.size`가 오래 재시도 중인 행을 센다. 처분(보류·재개·skip)은 publish-failed runbook - §4.1이다(재리뷰 RR-05-03). + §4.1이다. - 발행 응답을 못 받으면 결과 불명(`OutboxPublishAmbiguousException`) — 05장 규칙과 같다. - 운영: `docs/runbooks/outbox-dead-letter.md`, `docs/runbooks/outbox-publish-failed.md`. diff --git a/docs/manual/10-capabilities.md b/docs/manual/10-capabilities.md index e5c20061..31140b5c 100644 --- a/docs/manual/10-capabilities.md +++ b/docs/manual/10-capabilities.md @@ -18,7 +18,7 @@ app-bootstrap/build.gradle ``` 정본: `AGENTS.md` 「부가 기능(capability) 모듈 규칙」(완료 기준 7개), -`docs/superpowers/specs/2026-09-25-capability-module-packaging-design.md`, 현황은 `docs/capability-status.md`. +`docs/design/2026-09-25-capability-module-packaging-design.md`, 현황은 `docs/capability-status.md`. ## 켜기 diff --git a/docs/manual/README.md b/docs/manual/README.md index d5216db7..47d7cc38 100644 --- a/docs/manual/README.md +++ b/docs/manual/README.md @@ -4,6 +4,9 @@ 무엇을 기준으로 고르는지를 적는다. 규칙의 정본은 따로 있다. 이 매뉴얼은 그 정본을 **가리키고** 작업 순서로 엮을 뿐, 규칙을 다시 쓰지 않는다(아래 「정본 위치」). +입구는 작업 매뉴얼의 [새 기능 playbook](../work/new-feature.md)이다. 일의 크기, 완료 기준, 하지 말 것은 +거기에 있다. 새 기능이 아닌 일(개선, 조사·설계, 문서, 운영)은 [docs/work/](../work/README.md)가 맡는다. + 판단 지점은 모두 같은 틀로 적는다. - **고르는 기준** — 무엇을 보고 고르는가 @@ -37,7 +40,7 @@ | 무엇 | 정본 | | --- | --- | -| 계층 경계·금지 규칙·테스트 작성 규칙 | `AGENTS.md`(요약은 `CLAUDE.md`) | +| 계층 경계·금지 규칙·테스트 작성 규칙 | `AGENTS.md`(작업 지도는 `CLAUDE.md`) | | leaf 목록·허용 의존 | `src/config/architecture/modules.json` | | 이름 규칙(유스케이스·포트·command·query) | `src/application-core/CLAUDE.md` 「Naming convention」. 기계 검사는 `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/NamingConventionTest.java`와 `ApplicationBoundaryArchitectureTest.java` | | 유스케이스 모양·트랜잭션 모양 | `src/application-core/CLAUDE.md` 「Canonical use case shape」「Allowed transactional shapes」 | @@ -52,31 +55,31 @@ ## 따라 할 예시는 하나 -예시가 셋(sample-portfolio 수직, onboarding fixture, durable operation)이라 어느 것을 베끼느냐에 따라 -배치가 달라졌다(리뷰 2026-11-01 01-01·07-09). 이제 **새 업무 기능의 예시는 생성 명령의 출력 하나**다. +예시가 셋(한 leaf에 모든 계층을 둔 샘플 모듈, onboarding fixture, durable operation)이라 어느 것을 베끼느냐에 따라 +배치가 달라졌다(2026-11-01 성숙도 리뷰). 이제 **새 업무 기능의 예시는 생성 명령의 출력 하나**다. 샘플 모듈은 +2026-11-07에 지웠다. | 코드 | 역할 | 따라 하나 | | --- | --- | --- | | `scripts/new-feature.sh` 출력 | 계층 leaf에 나눈 업무 기능 | **이것을 따른다** | -| `src/sample-portfolio` | 한 leaf에 모든 계층을 둔 지울 수 있는 샘플. 개별 기법(조건부 PATCH, 페이지, outbox, DB 유일성 제약)의 참고 | 기법만 본다. 배치는 따르지 않는다 | | `src/app-bootstrap/src/test/java/dev/caskeleton/onboarding/**` | ArchUnit 규칙이 새 기능 모양에 적용되는지 확인하는 테스트 fixture | 따르지 않는다 | | `application-core/.../operation` + `DurableOperationAutoConfiguration`(composition:durable-operation) | 템플릿 플랫폼 기능 | 조립 모양(`@ConditionalOnBean` + 유스케이스 `@Bean`)만 본다 | -## 1라운드 수정으로 생긴 패턴 (리뷰 README 13절) +## 리뷰 뒤 첫 수정으로 생긴 패턴 -리뷰 뒤 1라운드에서 굳은 모양이다. 각 장에 반영했다. +2026-11-01 성숙도 리뷰 뒤 같은 날 한 첫 수정에서 굳은 모양이다. 각 장에 반영했다. | 패턴 | 근거 코드 | 장 | | --- | --- | --- | | Envelope는 null 필드를 내보내지 않는다 | `docs/web/http-contract.md` 1절 | 06 | | 처리 중 409 `IDEMPOTENT_IN_FLIGHT`는 `retryable=true` + `Retry-After: 2`, 같은 키로 재전송 | `docs/web/http-contract.md` 2절 | 05 | | 커밋 중 연결이 끊기면 재시도 가능이 아니라 결과 불명(`DB_COMPLETION_UNKNOWN`, 500) | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/failure/PersistenceExceptionTranslator.java`, `docs/adr/ADR-JPA-003-completion-unknown.md` | 05 | -| 중복 규칙은 조회 후 insert가 아니라 DB 유일성 제약, 위반은 같은 409로 변환 | `src/sample-portfolio/src/main/resources/db/sample-migration/V8_1__poster_title_unique.sql`, `PosterRepositoryAdapter` | 04 | +| 중복 규칙은 조회 후 insert가 아니라 DB 유일성 제약, 위반은 같은 409로 변환 | 04장 「중복·경쟁은 DB가 막는다」(템플릿 코드에 예 없음) | 04 | | 여러 인스턴스가 집는 작업은 lease 있는 claim | `ReconciliationJobStorePort.claimDue`(application-notification) | 04 | | 양방향 연관관계 금지를 ArchUnit으로 | `JpaArchitectureRules.associationsAreMappedFromOneSideOnly()` | 04 | | store는 호출자 트랜잭션을 요구한다 | `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/transaction/CallerTransaction.java` | 04 | | `@RequiresPermission` 검사는 인증 체인과 분리된 자동 설정 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebMethodSecurityAutoConfiguration.java` | 07 | | JWT audience 필수, 자기 client role만 | `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/JwtDecoderConfig.java`, `docs/runbooks/auth-audience-mismatch.md` | 07 | | strict lane은 반드시 어떤 단계에 속한다 | `verifyStrictLaneStages`(`src/build.gradle` `strictLaneStages`) | 08 | -| 샘플 마이그레이션은 별도 history table, 번호는 운영과 겹치지 않게 | `SamplePostgreSqlPersistenceConfig`, `V8_1__…` | 04 | +| 서비스 마이그레이션은 별도 history table, 번호는 운영과 겹치지 않게 | `NotificationSchemaStream`(persistence-notification) | 04 | | 재시도 가능한 broker 거부는 DEAD가 아니라 재시도 | `docs/runbooks/outbox-dead-letter.md` | 09 | diff --git a/docs/messaging/security.md b/docs/messaging/security.md index a8472055..16e8359b 100644 --- a/docs/messaging/security.md +++ b/docs/messaging/security.md @@ -21,6 +21,10 @@ runtime이 admin 자격 증명을 아예 보유하지 않으므로, 침해된 ha - broker authentication 활성 - topology auto-create 비활성 +broker 인증서는 `subjectAltName`에 접속 이름을 가져야 한다. hostname verification은 SAN을 보므로, SAN이 +없는 인증서는 실패하는 것이 맞다. 검사를 끄지 않는다. 키와 인증서는 배포 환경의 PKI가 발급해 실행 때 +마운트하고, repo에 두지 않는다. + Kafka는 추가로 `enable.idempotence=true`, `acks=all`, `max.in.flight.requests.per.connection <= 5`, consumer auto-commit 금지. diff --git a/docs/messaging/support-matrix.md b/docs/messaging/support-matrix.md index bd3164cd..1a2e72c9 100644 --- a/docs/messaging/support-matrix.md +++ b/docs/messaging/support-matrix.md @@ -27,7 +27,7 @@ > `modules.json`은 messaging leaf의 `gradle_path`와 허용 의존성을 관리하지만 > `runtime_memberships` 필드는 없다. 실제 런타임 편입은 `app-bootstrap`의 Gradle 의존성과 starter / > auto-configuration 경로가 결정한다. 아래 등급은 "무엇이 증명되었는가"를 말하며 런타임 편입 여부와 -> 같은 축이 아니다. 자세한 composition/cutover 상태는 `src/messaging/CLAUDE.md`가 소유한다. +> 같은 축이 아니다. 자세한 composition/cutover 상태는 `src/platforms/messaging/CLAUDE.md`가 소유한다. ## 브로커 등급 diff --git a/docs/mongodb/advanced/sharding.md b/docs/mongodb/advanced/sharding.md index 2987a243..2f308936 100644 --- a/docs/mongodb/advanced/sharding.md +++ b/docs/mongodb/advanced/sharding.md @@ -13,7 +13,7 @@ enables the capability; construction is refused otherwise. | Topology | A real sharded cluster. A replica set cannot exercise routing. | | Server | MongoDB 7.0 or 8.0. | | Privilege | `MongoPrincipalRole.SHARD_ADMIN` for the admin plane; the application role is unchanged. | -| Gate | **Not promoted.** No `mongoShardedTest` lane is registered, and a sharded cluster is not an environment this repository stands up. Listed under `experimental_contracts` in `src/config/mongodb/release-contracts.json`; promoting it needs the lane, its required class, and protected-environment evidence to exist first. | +| Gate | **Not promoted.** No `mongoShardedTest` lane is registered, and a sharded cluster is not an environment this repository stands up. Listed under `experimental_contracts` in `src/adapter/outbound/persistence-mongo/release/release-contracts.json`; promoting it needs the lane, its required class, and protected-environment evidence to exist first. | ## Shard key diff --git a/docs/mongodb/repository-adaptation.md b/docs/mongodb/repository-adaptation.md index 9061ff42..e50c4795 100644 --- a/docs/mongodb/repository-adaptation.md +++ b/docs/mongodb/repository-adaptation.md @@ -1,8 +1,8 @@ # MongoDB Document Persistence Platform — Repository Adaptation Contract -**Design source:** `docs/superpowers/specs/2026-08-11-mongodb-document-persistence-platform-design.md` -**Stable plan:** `docs/superpowers/plans/2026-08-11-mongodb-document-persistence-platform-implementation-plan.md` -**Advanced plan:** `docs/superpowers/plans/2026-08-11-mongodb-advanced-capabilities-expansion-plan.md` +**Design source:** `docs/design/2026-08-11-mongodb-document-persistence-platform-design.md` +**Stable plan:** `docs/history/plans/2026-08-11-mongodb-document-persistence-platform-implementation-plan.md` +**Advanced plan:** `docs/history/plans/2026-08-11-mongodb-advanced-capabilities-expansion-plan.md` The design package declares its own module root (`modules/mongodb`) and root package (`io.backend.skeleton.mongodb`) as *implementation assumptions*, not as contract. This file is the diff --git a/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md b/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md index e3d6e92c..fb7d5f2f 100644 --- a/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md +++ b/docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-14 +- 요약: 알림 submit()은 영속적으로 받아들였다는 뜻이라는 결정이다. +- 현재 정본: `docs/notification/support-matrix.md` + + # NOTIF-ADR-001 — `submit()` means durable acceptance ## Status diff --git a/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md b/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md index c7d990e7..67afe419 100644 --- a/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md +++ b/docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-14 +- 요약: 알림 상태를 덧붙이기만 하는 이벤트 원장과 채널별 projector로 둔다는 결정이다. +- 현재 정본: `docs/notification/support-matrix.md` + + # NOTIF-ADR-002 — append-only event ledger with channel projectors ## Status diff --git a/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md b/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md index 71730392..c38e6184 100644 --- a/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md +++ b/docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-14 +- 요약: 결과가 모호한 제출을 정식 상태로 둔다는 결정이다. +- 현재 정본: `docs/notification/support-matrix.md` + + # NOTIF-ADR-003 — ambiguous submission is a first-class state ## Status diff --git a/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md b/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md index dd6bc2b1..e7b84c67 100644 --- a/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md +++ b/docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택 +- 작성일: 2026-08-14 +- 요약: FCM 대상은 installation id를 먼저 쓴다는 결정이다. +- 현재 정본: `docs/notification/provider-runbooks.md` + + # NOTIF-ADR-004 — FCM installation id is the primary target ## Status diff --git a/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md b/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md index 41e11c10..299363ac 100644 --- a/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md +++ b/docs/notification/adr/NOTIF-ADR-005-canonical-namespace.md @@ -1,3 +1,12 @@ + +> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다. + +- 상태: 채택(보완) +- 작성일: 2026-08-15 +- 요약: 어느 알림 API가 canonical인지 정한 결정이다. R1 타입은 2026-09-25에 지웠다. +- 현재 정본: `docs/notification/module-mapping.md` + + # NOTIF-ADR-005 — 어느 notification API가 canonical인가 ## 상태 diff --git a/docs/notification/module-mapping.md b/docs/notification/module-mapping.md index ba7edb5e..13dd4e5e 100644 --- a/docs/notification/module-mapping.md +++ b/docs/notification/module-mapping.md @@ -1,8 +1,8 @@ # Notification Delivery Platform — module mapping -> Source design: `docs/superpowers/specs/2026-08-10-notification-platform-design.md` +> Source design: `docs/design/2026-08-10-notification-platform-design.md` > -> Source plan: `docs/superpowers/plans/2026-08-10-notification-platform-implementation-plan.md` +> Source plan: `docs/history/plans/2026-08-10-notification-platform-implementation-plan.md` ## Why a mapping exists diff --git a/docs/redis/support-matrix.md b/docs/redis/support-matrix.md index f90fcfe8..9a7bb58a 100644 --- a/docs/redis/support-matrix.md +++ b/docs/redis/support-matrix.md @@ -4,8 +4,8 @@ This file is a gate, not a summary. `RedisSupportMatrixTest` parses the tables b the SDK grows a package or a capability that is not listed, so a module cannot ship without someone stating its minimum version, its topology support, and what it does not do. -Design: `docs/superpowers/specs/2026-08-07-redis-wrapper-typed-api-design.md`. -Delivery status and the decisions behind each module: `docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-status.md`. +Design: `docs/design/2026-08-07-redis-wrapper-typed-api-design.md`. +Delivery status and the decisions behind each module: `docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md`. ## Modules @@ -68,7 +68,7 @@ nothing in this repository has executed against 7.2 or 8.2. ### What the standalone ACL run established -`RedisTopologyContractTest` runs the four accounts in `infra/redis-sdk/acl` against a live server and +`RedisTopologyContractTest` runs the four accounts in `compose/redis/acl` against a live server and asserts that each `CommandAccess` level grants exactly what the command policy catalog says it may issue. Writing it found five defects that no amount of reading the files would have surfaced: diff --git a/docs/redis/upgrade-guide.md b/docs/redis/upgrade-guide.md index a2c5d21c..07144bd0 100644 --- a/docs/redis/upgrade-guide.md +++ b/docs/redis/upgrade-guide.md @@ -42,7 +42,7 @@ actually run. ## 5. Topology suite -Run the standalone, Sentinel, and Cluster lanes declared in `infra/redis-sdk/`. A version is +Run the standalone, Sentinel, and Cluster lanes declared in `src/adapter/outbound/redis-sdk/compose/`. A version is certified by the lane passing, not by the version number being newer. *Why:* failover certainty and cross-slot behaviour are the two things the in-memory fixture cannot diff --git a/docs/registries/env-keys.yaml b/docs/registries/env-keys.yaml index 954205da..6536d1ae 100644 --- a/docs/registries/env-keys.yaml +++ b/docs/registries/env-keys.yaml @@ -2031,7 +2031,7 @@ env_keys: # secret://@/ form as the application reference. Unset, scripts run # as the application account and startup logs a warning saying so. The Compose Redis lanes use # secret://ca-skeleton-application-advanced@environment/REDIS_LANE_ADVANCED_PASSWORD, a fixture - # account of infra/redis-sdk/acl/lane-fixture-accounts.acl. + # account of compose/redis/acl/lane-fixture-accounts.acl. property: app.redis.authentication.advanced-credential-reference owner_module: adapter-outbound-cache-redis type: string @@ -2074,7 +2074,7 @@ env_keys: # . Without the account part the client authenticates as `default`, which a hardened # Redis turns off. The Compose Redis lanes use # secret://ca-skeleton-application@environment/REDIS_LANE_APPLICATION_PASSWORD, a fixture - # account of infra/redis-sdk/acl/lane-fixture-accounts.acl. + # account of compose/redis/acl/lane-fixture-accounts.acl. property: app.redis.authentication.credential-reference owner_module: adapter-outbound-cache-redis type: string @@ -2631,8 +2631,8 @@ env_keys: required_test: cache-contract:redis-soft-hard-ttl-order - name: APP_CACHE_REDIS_TTL_JITTER - # DEPRECATED 2026-11-02: no settings class binds it. Its only reader was a block in - # sample-portfolio's application.yml that nothing bound either (07-10), removed with it. + # DEPRECATED 2026-11-02: no settings class binds it. Its only reader was a block in the + # sample module's application.yml that nothing bound either (07-10), removed with it. # Kept so a deployment still setting it is told it does nothing. deprecated_orphaned: true removal_deadline: 2027-02-28 diff --git a/docs/registries/error-codes.yaml b/docs/registries/error-codes.yaml index d569b16b..821c32c1 100644 --- a/docs/registries/error-codes.yaml +++ b/docs/registries/error-codes.yaml @@ -1,7 +1,7 @@ # Registry: Error Codes # Schema owner: feature-contract-registry-governance # Category enum owner: feature-operational-error-observability-foundation -# Last updated: 2026-09-28 +# Last updated: 2026-11-06 # Scope: skeleton-wide OperationalError SSOT. Product/fork ApiErrorCode enums own local registries/contracts. # # Schema (per row): @@ -15,7 +15,6 @@ # owner_layer: presentation | application | domain | infrastructure | crosscut # client_safe_message: = shared-contract ClientErrorMessages.of(category) — category별 한국어 문구 표 # 하나(소유자 결정 11). no token / no principal raw / no internal path / no stack trace -# log_level: ERROR | WARN | INFO # runbook_link: runbook://area/scenario OR null (client-error만 null 허용) # compatibility_impact: none | additive | behavior-change | breaking # required_test: owning contract test identifier @@ -25,6 +24,13 @@ # TRANSIENT_DEPENDENCY, PERMANENT_DEPENDENCY} ⇒ runbook_link 필수. # VALIDATION/NOT_FOUND/CONFLICT/DATA_INTEGRITY는 client-error로 runbook 면제 가능. # retryable=true 인 모든 row는 runbook_link 필수. +# +# 로그 레벨은 행의 칸이 아니다. 레벨은 오류 코드가 아니라 실패의 종류와 경로가 정한다. +# shared-contract ServerFailureLog — 모든 전송이 쓴다. 영속성·의존성 carrier와 5xx carrier는 ERROR, +# 4xx carrier는 남기지 않는다. IllegalArgumentException(BAD_PARAMETER)은 WARN. +# web AuthErrorResponseWriter — 보안 필터. 5xx는 ERROR, 4xx는 WARN. +# 행에 log_level을 두면 OperationalErrorRegistryContractTest가 실패한다. +# 결정: docs/design/2026-11-06-error-code-log-level-design.md 7·10절. errors: @@ -41,7 +47,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/token-missing" compatibility_impact: none required_test: contract-verification:auth-category @@ -55,7 +60,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/token-malformed" compatibility_impact: none required_test: contract-verification:auth-category @@ -69,7 +73,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/token-expired" compatibility_impact: none required_test: contract-verification:auth-category @@ -83,7 +86,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: ERROR runbook_link: "runbook://auth/token-invalid-signature" compatibility_impact: none required_test: contract-verification:auth-category @@ -97,7 +99,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: ERROR runbook_link: "runbook://auth/issuer-mismatch" compatibility_impact: none required_test: contract-verification:auth-category @@ -111,7 +112,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: ERROR runbook_link: "runbook://auth/audience-mismatch" compatibility_impact: none required_test: contract-verification:auth-category @@ -126,7 +126,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/kid-unknown" compatibility_impact: none required_test: contract-verification:auth-category @@ -140,7 +139,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://auth/jwks-unavailable" compatibility_impact: none required_test: contract-verification:auth-category @@ -154,7 +152,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: ERROR runbook_link: "runbook://auth/claim-mapping-failed" compatibility_impact: none required_test: contract-verification:auth-category @@ -172,7 +169,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "이 작업을 수행할 권한이 없습니다." - log_level: WARN runbook_link: "runbook://authz/insufficient-permission" compatibility_impact: none required_test: contract-verification:authz-category @@ -186,7 +182,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: presentation client_safe_message: "이 작업을 수행할 권한이 없습니다." - log_level: ERROR runbook_link: "runbook://authz/tenant-mismatch" compatibility_impact: none required_test: contract-verification:authz-category @@ -204,7 +199,6 @@ errors: owner_branch: feature-security-operational-baseline owner_layer: crosscut client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://auth/public-path-misconfiguration" compatibility_impact: none required_test: contract-verification:auth-category @@ -218,7 +212,6 @@ errors: owner_branch: feature-container-runtime-contract owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://runtime/jvm-oom" compatibility_impact: none required_test: contract-verification:container-runtime-oom @@ -236,7 +229,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://db/unavailable" compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -250,7 +242,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: "runbook://db/serialization-failure" compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -264,7 +255,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: "runbook://db/deadlock" compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -278,7 +268,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -292,7 +281,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -306,7 +294,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -320,7 +307,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -334,7 +320,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://db/idle-in-tx-timeout" compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -348,7 +333,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: WARN runbook_link: "runbook://db/query-canceled" compatibility_impact: none required_test: contract-verification:persistence-mapping @@ -362,7 +346,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: additive required_test: persistence-jpa:JpaPersistenceExceptionCodeTest @@ -376,7 +359,6 @@ errors: owner_branch: feature-persistence-failure-baseline owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: null compatibility_impact: additive required_test: persistence-jpa:JpaPersistenceExceptionCodeTest @@ -394,7 +376,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: presentation client_safe_message: "요청이 너무 잦습니다. 잠시 후 다시 시도해 주세요." - log_level: WARN runbook_link: "runbook://rate-limit/exceeded" compatibility_impact: none required_test: contract-verification:rate-limit @@ -412,7 +393,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: INFO runbook_link: null compatibility_impact: behavior-change required_test: contract-verification:idempotency @@ -426,7 +406,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "요청 값이 올바르지 않습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:idempotency @@ -440,7 +419,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: WARN runbook_link: "runbook://idempotency/unavailable" compatibility_impact: additive required_test: contract-verification:idempotency @@ -456,7 +434,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://idempotency/unavailable" compatibility_impact: additive required_test: contract-verification:idempotency @@ -470,7 +447,6 @@ errors: owner_branch: feature-rate-limit-idempotency-contract owner_layer: application client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://idempotency/unavailable" compatibility_impact: additive required_test: contract-verification:idempotency @@ -498,7 +474,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -512,7 +487,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -526,7 +500,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: INFO runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -540,7 +513,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -557,7 +529,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: WARN runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -571,7 +542,6 @@ errors: owner_branch: feature-api-contract-baseline owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: none required_test: contract-verification:api-contract-status-mapping @@ -609,7 +579,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://dependency/timeout" compatibility_impact: none required_test: contract-verification:outbound-http @@ -623,7 +592,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://dependency/connect-failed" compatibility_impact: none required_test: contract-verification:outbound-http @@ -637,7 +605,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://dependency/dns-failed" compatibility_impact: none required_test: contract-verification:outbound-http @@ -651,7 +618,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://dependency/4xx-client" compatibility_impact: none required_test: contract-verification:outbound-http @@ -665,7 +631,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://dependency/5xx-server" compatibility_impact: none required_test: contract-verification:outbound-http @@ -679,7 +644,6 @@ errors: owner_branch: feature-outbound-http-client-baseline owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: WARN runbook_link: "runbook://dependency/circuit-open" compatibility_impact: none required_test: contract-verification:outbound-http @@ -697,7 +661,6 @@ errors: owner_branch: feature-domain-event-outbox-contract owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://outbox/publish-failed" compatibility_impact: none required_test: contract-verification:outbox-publish @@ -711,7 +674,6 @@ errors: owner_branch: feature-domain-event-outbox-contract owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://outbox/dead-letter" compatibility_impact: none required_test: contract-verification:outbox-dlq @@ -729,7 +691,6 @@ errors: owner_branch: feature-background-job-async-contract owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://job/executor-rejected" compatibility_impact: none required_test: contract-verification:async-saturation @@ -743,7 +704,6 @@ errors: owner_branch: feature-background-job-async-contract owner_layer: infrastructure client_safe_message: "일시적인 오류입니다. 잠시 후 다시 시도해 주세요." - log_level: ERROR runbook_link: "runbook://job/timeout" compatibility_impact: none required_test: contract-verification:async-timeout @@ -757,7 +717,6 @@ errors: owner_branch: feature-background-job-async-contract owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://job/dead-letter" compatibility_impact: none required_test: contract-verification:async-dlq @@ -782,7 +741,6 @@ errors: owner_branch: feature-distributed-lock-contract owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: "runbook://lock/acquisition-timeout" compatibility_impact: none required_test: contract-verification:lock-acquisition-timeout @@ -800,7 +758,6 @@ errors: owner_branch: feature-integration-adapter-templates owner_layer: infrastructure client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://adapter/adapter-disabled" compatibility_impact: none required_test: adapter-contract:adapter-disabled-runtime-call @@ -819,7 +776,6 @@ errors: owner_branch: feature-management-actuator-security-contract owner_layer: presentation client_safe_message: "이 작업을 수행할 권한이 없습니다." - log_level: WARN runbook_link: "runbook://management/actuator-forbidden" compatibility_impact: none required_test: contract-verification:management-actuator @@ -838,7 +794,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: application client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -851,7 +806,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -864,7 +818,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "요청 값이 올바르지 않습니다." - log_level: INFO runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -877,7 +830,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: application client_safe_message: "요청 값이 올바르지 않습니다." - log_level: WARN runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -890,7 +842,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: crosscut client_safe_message: "요청을 처리할 수 없습니다." - log_level: ERROR runbook_link: "runbook://internal/error-spike" compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -903,7 +854,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/token-missing" compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -916,7 +866,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "인증이 필요합니다." - log_level: WARN runbook_link: "runbook://auth/token-malformed" compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -929,7 +878,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "이 작업을 수행할 권한이 없습니다." - log_level: WARN runbook_link: "runbook://authz/insufficient-permission" compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -942,7 +890,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: presentation client_safe_message: "요청한 리소스를 찾을 수 없습니다." - log_level: INFO runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry @@ -955,7 +902,6 @@ errors: owner_branch: 2026-09-21-core-web-review-remediation owner_layer: infrastructure client_safe_message: "현재 상태에서는 요청을 처리할 수 없습니다." - log_level: WARN runbook_link: null compatibility_impact: additive required_test: contract-verification:operational-error-registry diff --git a/docs/registries/secrets-classification.yaml b/docs/registries/secrets-classification.yaml index e6b4e67f..bddb0aeb 100644 --- a/docs/registries/secrets-classification.yaml +++ b/docs/registries/secrets-classification.yaml @@ -11,7 +11,7 @@ # - prod profile에서 `__LOCAL_DEV_` prefix 발견 시 startup fail # (feature-secrets-config-source-contract 2026-05-22). # - prod profile에서 비밀값이 `fixture-`로 시작하면(이 저장소에 적힌 lane fixture 비밀번호 — -# infra/redis-sdk/acl, compose lane의 REDIS_LANE_*) 같은 이유로 startup fail (review 2026-11-03 +# compose/redis/acl, compose lane의 REDIS_LANE_*) 같은 이유로 startup fail (review 2026-11-03 # RR-07-04). 비밀값만 본다: 이 파일의 `secret` 행(SecretSourceValidator.CLASSIFIED_SECRETS, # SecretsClassificationRegistryTest가 1:1로 묶음), 모듈이 기여한 비밀, `secret://…/` 참조가 # 가리키는 변수. HOSTNAME·앱 이름 같은 비밀이 아닌 값은 보지 않는다 (review 2026-11-04 RR2-04-01). diff --git a/docs/reviews/2026-11-03-rereview/README.md b/docs/reviews/2026-11-03-rereview/README.md index 84e7b67c..7dcd79f9 100644 --- a/docs/reviews/2026-11-03-rereview/README.md +++ b/docs/reviews/2026-11-03-rereview/README.md @@ -403,3 +403,570 @@ Minor 중 RR5-01-01(`IDEMPOTENCY_RECOVERY_REQUIRED`의 클라이언트 안내가 - GREEN: 03 동시 인덱스 검사기(`ConcurrentIndexMigrationInspectorTest`)와 손 포맷(persistence-jpa `spotlessCheck`), 01 `architectureTest` 228·`spotbugsArchitectureTest`(A5 최종본), optional ledger `check`를 게이트 전에 따로 돌렸다(1분 50초, rc=0). - 게이트 안에서 확인한 보고서 항목: `:app-bootstrap:documentContractTest` 65, `verifyEnvKeys`, `verifyJpaApiSurface`, `redisContainerContractTest` 78, `jpaPlatformContractTest` 407, `jpaPlatformMigrationTest` 45, 새 lane `postgresqlConcurrentIndexMigrationIntegrationTest` 4(`integrationCheck`에서 실행), `postgresqlMigrationLockWaitIntegrationTest` 36, `postgresqlNotificationSchemaActivationIntegrationTest` 8, `postgresqlIdempotencyIntegrationTest` 10, `messagingInboxRedeliveryIntegrationTest` 3, app-bootstrap `integrationTest` 10(`PostgreSqlIdempotencyProviderIntegrationTest` 포함), sample `integrationTest` 63(`SampleIdempotencyReplayIntegrationTest`·`SampleMigrationStreamIsolationTest` 포함), ledger `integrationTest` 46. 모두 실패 0. in-memory fake 계약의 skip 19는 시간 케이스(설계). - 다시 돌리지 않은 것: 각 묶음이 로컬에서 이미 확인한 RED(01의 gRPC·STOMP·GraphQL·shared-contract·shared 규칙, 02 표, 03, 04). r10-03 보고서가 적은 `:adapter:outbound:persistence-jpa:documentContractTest`는 없는 태스크다(그 lane은 app-bootstrap에만 있다). + +## 18. r10 확인 리뷰 round7 (2026-11-06) + +`6e992970`(r10)만 봤다. 기준 커밋 `06f520e6`(브랜치 `refactor/maturity-review-2026-11` 위, 그 사이 커밋은 문서·성능 lane이라 리뷰한 +파일을 바꾸지 않았다). 리뷰어 1명이 영역을 차례로 봤다. 영역 문서는 `round7/01~05`다. + +커밋 하나가 +5,143줄이라 확인 리뷰 상한(추가 1,500줄, `docs/work/improve.md` 4.4절)을 넘는다. 영역 pathspec으로 나눴다. 정확한 +pathspec은 각 영역 문서 「범위」에 있다. + +같은 날 2차로 총괄이 세 가지를 더 맡겼다: 같은 커밋을 따로 본 리뷰의 발견 중 겹치지 않는 것(18.2절), 다른 세션이 코드 읽기로 찾은 결함 +후보 하나(RR7-01-04), round6 「Declined to judge」 30건 판정(18.5절). 2차 결함은 각 영역 문서의 「2차 추가 결함」 절에 있다. + +| 영역 | 대상 | `git diff --shortstat` | +|---|---|---| +| [01 core·inbound](round7/01-core-inbound.md) | shared-contract, inbound web·GraphQL·gRPC·WebSocket, app-bootstrap(Flyway 규칙 제외), 매뉴얼 07, runbook | 33 파일, +1056 −137 | +| [02 멱등성·outbound](round7/02-idempotency-outbound.md) | application-core, cache-redis, redis-runtime, PG 멱등성 store, 매뉴얼 05 | 15 파일, +407 −458 | +| [03 persistence](round7/03-persistence.md) | persistence-jpa(멱등성·lockfile 제외), persistence-notification, inbound messaging, grpc ledger, sample, Flyway 규칙, `docs/jpa`·매뉴얼 04·study | 28 파일, +877 −113 | +| [04 build-logic 셸 판독](round7/04-build-logic-shell.md) | `ShellScript`, `StrictLaneStagesPlugin`, TestKit 테스트, build-logic `build.gradle`·README | 5 파일, +659 −100 | +| [05 build-logic workflow 판독](round7/05-build-logic-workflow.md) | `WorkflowGradleInvocations`와 그 테스트, `GradleCommandLineTest`, AGENTS.md·CLAUDE.md·`src/README.md` | 6 파일, +1288 −101 | +| 공통 문서(영역마다 자기 행을 읽음) | `docs/upgrade/`, `docs/testing/`, 2026-11-01 README | 3 파일, +25 −14 | +| 보지 않음 | 리뷰 기록 `round6/*`·이 README 17절(+829), lockfile 2줄 | — | + +### 18.1 결과 + +Critical 0, Important 2, Minor 13, 회귀 1. 결함 15건: 이번 수정이 만든 것 5건, 섞임 2건(이전부터 있던 것을 이번 수정이 넓히거나 새로 +약속함), 이전부터 8건. 그중 RR7-02-02·RR7-03-06 두 건은 2026-11-07 1차 「Declined to judge」 판정(18.5절)에서 올렸다. 처리는 18.7절이다. + +| ID | 심각도 | 내용 | 이번 수정 / 이전부터 | 출처 | 증거 | +|---|---|---|---|---|---| +| RR7-01-01 | Minor(회귀) | 설정에 중첩된 JAX-RS 자원·`@ServerEndpoint`가 `@SystemCaller`를 불러도 잡히지 않는다. r9는 잡았다 | 이번 수정 | 이 리뷰(다른 리뷰도 같은 결함) | E2 | +| RR7-01-02 | Minor | 메서드 참조로 route만 등록한 설정도 사용자 전송이라 handler bean과 같이 두면 거짓 실패. Javadoc·매뉴얼 07·B-16 안내와 다르다 | 이번 수정 | 이 리뷰 | E2 | +| RR7-01-03 | Minor | gRPC가 IAE를 원인으로 든 raw status를 던지면 `INTERNAL`·ERROR(메시지 첨부), `onError`로 넘기면 `BAD_PARAMETER`·WARN | 이전부터 | 다른 리뷰 | E2 | +| RR7-01-04 | Important | `LockAcquisitionTimeoutException`이 carrier가 아니고 처리기도 없어 409(재시도 가능) 대신 500 `INTERNAL_ERROR`(재시도 불가) | 이전부터 | 총괄 전달 후보 | E2 | +| RR7-01-05 | Minor | 감싼 carrier를 web·GraphQL·STOMP는 못 보고 gRPC만 찾아 응답 코드·로그가 전송마다 다르다 | 이전부터 | round6 01 Declined | E1 | +| RR7-01-06 | Minor | STOMP payload 변환·검증 실패를 ERROR와 예외 메시지(입력 조각)로 남긴다 | 이전부터 | round6 01 Declined | E1 | +| RR7-02-01 | Minor | httpclient `ClientRuntimeRegistry.close()`가 interrupt 상태면 drain 스레드 종료를 확인하지 않고 정상 반환 | 이전부터 | round6 02 Declined | E1 | +| RR7-02-02 | Minor | in-memory fake가 시작을 적용한 같은 핸들의 재시작(응답 유실)에 `NOT_OWNER` — 두 저장소·포트 Javadoc은 `ALREADY_STARTED_SAME_OPERATION` | 이전부터 | 이 리뷰 1차 02 Declined | E1 | +| RR7-03-01 | Minor | ledger 잠금 대기 IT가 "예외로 적으라"고 안내하지만 예외를 적을 곳이 없다 | 이번 수정 | 이 리뷰 | E1 | +| RR7-03-02 | Minor | "Flyway는 `REINDEX … CONCURRENTLY`를 트랜잭션 안에서 돌린다"가 `SCHEMA`·`DATABASE` 형태에서 틀린다 | 섞임 | 이 리뷰 | E3 | +| RR7-03-03 | Important | 실패한 동시 인덱스 복구를 "`DROP INDEX` 하나"로 안내하지만 `success=false` 이력 행이 다음 배포를 막고 runbook은 그 행 삭제를 금지 | 이전부터 | 다른 리뷰 | E3 | +| RR7-03-04 | Minor | "섞인 파일은 부분 적용되지 않는다"가 `.sql.conf`(`executeInTransaction=false`)를 붙이면 틀린다 | 이번 수정 | 다른 리뷰 | E3 | +| RR7-03-05 | Minor | 잠금 대기 검사기 Javadoc은 `VACUUM FULL`을 늘 거부한다지만 `executeInTransaction=true` 설정 파일에서는 통과 | 이전부터 | round6 03 Declined | E1 | +| RR7-03-06 | Minor | "코드로 만드는 Flyway는 모두 `FlywaySchemaPolicy.configure()`에서" 규칙을 ArchUnit이 `Flyway.configure()` 호출로만 지켜 `new FluentConfiguration()`·`new ClassicConfiguration()`이 빠진다 | 이번 수정 | 이 리뷰 1차 03 Declined | E1 | +| RR7-05-01 | Minor | 메시지·B-36은 "매 push·PR·schedule"을 요구하지만 판독기는 `paths:` 필터 workflow도 센다 | 섞임 | 이 리뷰(round6 04 Declined와 같음) | E2 | + +r10이 고쳤다고 한 항목의 재확인(영역 문서 「항목 재확인」): + +- 닫힘: RR6-01-01~09, RR6-02-01~05, RR6-03-01~04, RR6-04-01~06. +- 부분: RR6-03-05(설명을 고치며 RR7-03-01·02·04가 생김). + +색인 보완: 이 README가 ID 대신 내용으로만 적은 지난 발견 둘을 이름으로 적는다(`docs/work/evidence.md` 7절). RR-05-10(06 영역 발견 5건의 +색인 누락)은 1절 정정과 6.1절이, RR-07-05(CSRF 제외 규칙의 이유)는 6절 r4-f 행의 "RR-06-05+07-05"가 다룬다. + +### 18.2 출처 리뷰와 ID 대응 + +같은 커밋 `6e992970`을 다른 리뷰어가 따로 리뷰했다: 브랜치 `claude/t1-baseline-7d623a`, 커밋 `3add4917`, 파일 +`docs/reviews/2026-11-03-rereview/round7/review.md`(그 브랜치에만 있음), 매뉴얼 `docs/improvement/` 기준. 그 리뷰도 `RR7-NN-MM`을 썼고 번호가 +이 리뷰와 겹치지만 뜻이 다르다. 넘겨받은 발견은 그쪽 근거를 확인한 뒤 이 리뷰의 기준 커밋에서 탐침을 다시 돌렸다. + +| 다른 리뷰 ID | 이 리뷰 ID | 처리 | +|---|---|---| +| RR7-01-01 | RR7-01-01 | 같은 결함. 하나로 센다(01 문서 RR7-01-01에 한 줄) | +| RR7-01-02 | RR7-01-03 | 넘겨받음. 명령 B3으로 재현 | +| RR7-03-01 | RR7-03-04 | 넘겨받음. 명령 B4로 재현 | +| RR7-03-02(Important) | RR7-03-03(Important) | 넘겨받음. 명령 B4로 재현, 고치는 법의 SQL도 확인 | + +- 그 리뷰의 「Declined to judge」 중 경로 필터는 RR7-05-01, `new FluentConfiguration()` 경로·같은 owner token의 다른 operation id는 이 리뷰 + 1차 Declined(03·02 문서)와 같다. "설정이 `@CrossOrigin`·`RequestMethod`·`HttpServletRequest`를 쓰면 거짓 실패"는 RR7-01-02와 같은 모양이라 + 01 문서 RR7-01-02에 한 줄로 더했다. +- 두 리뷰 문서를 한 브랜치에 합치면 같은 ID가 다른 결함을 가리켜 색인 검사가 중복으로 보고한다. `round7/review.md`는 그대로 합치지 말고, + 출처 기록으로 그 브랜치에 두거나 위 표대로 번호를 바꿔 합친다. + +### 18.3 실행 (2026-11-06, desktop) + +임시 worktree `~/workspace/t1-r10-review`(`06f520e6`)와 `~/workspace/t1-r10-review-r9`(`45d2a478`, r9 비교용)에 탐침을 얹어 +`flock /tmp/claude-gates/heavy.lock` 아래에서 차례로 돌렸다. 로그 `~/t1-r10-review-logs/`(desktop, `summary.txt`). 탐침 코드와 결과는 공유 노트 +폴더 `rr7-probes/`(1차)·`rr7-probes/pass2/`(2차)에 있어 고칠 때 fixture로 옮겨 쓸 수 있다. 1차·2차 모두 끝나고 worktree를 지웠다. + +| # | 명령 | 대상 | 결과 | 시간 | 직전 부하(1분) | +|---|---|---|---|---|---| +| A1 | `:app-bootstrap:architectureTest --tests …Rr7ProbeTest` | `06f520e6` | rc=0(탐침 P1·P2 위반 없음, P3 위반) | 21초 | 4.58 | +| A2 | 같은 명령 | `45d2a478` | rc=0(P1·P2 위반, P3 위반 없음) | 20초 | 4.89 | +| A3 | `-p build-logic test --tests …Rr7WorkflowProbeTest` | `06f520e6` | rc=0(경로 필터 workflow를 셈) | 2초 | 4.66 | +| A4 | `:adapter:outbound:persistence-jpa:rr7ReindexProbe`(임시 lane, 실 PostgreSQL) | `06f520e6` | rc=0(REINDEX 다섯 형태 중 SCHEMA·DATABASE만 적용) | 19초 | 4.28 | +| A5 | `:shared-contract:test :application-core:test :adapter:outbound:redis-runtime:test :adapter:outbound:cache-redis:test :adapter:outbound:persistence-jpa:test :adapter:outbound:persistence-notification:test :adapter:inbound:messaging:test :adapter:inbound:web:test :adapter:inbound:grpc:test :adapter:inbound:graphql:test :adapter:inbound:websocket:test :app-bootstrap:architectureTest --rerun --continue` | `06f520e6` + 탐침 | rc=0. 실행: persistence-jpa `test` 664건, `architectureTest` 229건(탐침 1건 포함), 실패 0. 나머지 10개 `test`는 FROM-CACHE(같은 입력의 이전 실행 결과) | 47초 | 4.46 | +| A6 | `-p build-logic test --rerun` | `06f520e6` + 탐침 | rc=0, 169건 실패 0 skip 0(탐침 1건 포함) | 40초 | 3.69 | +| B1 | `:adapter:inbound:web:test --tests …Rr7LockTimeoutWebProbeTest` | `06f520e6` | rc=0(500 `INTERNAL_ERROR` `retryable=false`) | 9초 | 1.32 | +| B2 | `:adapter:inbound:graphql:test --tests …Rr7LockTimeoutGraphQlProbeTest` | `06f520e6` | rc=0(`INTERNAL_ERROR`) | 8초 | 1.73 | +| B3 | `:adapter:inbound:grpc:test --tests "…GrpcExceptionHandlingInterceptorTest.rr7probe*"` | `06f520e6` | rc=0(던짐 `INTERNAL`·ERROR+메시지, 넘김 `INVALID_ARGUMENT`·WARN) | 4초 | 2.01 | +| B4 | `:adapter:outbound:persistence-jpa:rr7CicProbe`(임시 lane, 실 PostgreSQL) | `06f520e6` | 첫 실행 rc=1(내 탐침 컴파일 오류), 고친 뒤 rc=0(섞임·복구 네 경우, 03 문서 표) | 3초 / 15초 | 2.01 / 2.66 | + +다시 돌리지 않은 것: 라운드 끝 게이트(`ci`, `mainCheck`, `integrationCheck`, `-p optional-platforms …`, compose)와 실 Redis·실 PG 계약 +lane. 마지막 실행은 17.2절의 `2c692554`다(이 리뷰에는 E0). + +### 18.4 결정이 필요한 것 + +| 항목 | 선택지 | 권하는 안과 이유 | 정할 사람 | 소유자 답 | +|---|---|---|---|---| +| RR7-05-01(= round6 04 Declined ①) 경로 필터 workflow를 단계 실행으로 셀지 | (a) `paths:`·`paths-ignore:` trigger만으로는 세지 않는다 (b) 세고, 메시지·B-36의 "매 변경" 약속을 고친다 | (a). 단계 검사는 "모든 변경이 이 lane을 지난다"를 보장하려는 것이고 경로 필터는 그 보장을 깬다. 이 repo의 단계 명령은 필터 없는 workflow에 있어 판정이 바뀌지 않는다 | 소유자 | (a), 2026-11-06. 결정 색인 2.7절 「경로 필터 workflow와 단계 검사」 | +| RR7-03-03 실패한 동시 인덱스 마이그레이션의 복구 절차 | (a) runbook에 "그 버전의 실패 이력 행만 지운다" 예외와 SQL(`DELETE FROM WHERE version = '' AND NOT success`)을 둔다 (b) 이 경우 `flyway repair`를 허용한다 (c) 동시 인덱스 마이그레이션을 금지하고 운영 절차로 돌린다 | (a). 실패 행은 적용되지 않은 버전의 기록이라 지워도 성공한 마이그레이션의 순서·checksum은 그대로다(명령 B4 넷째 경우로 재배포 성공 확인). (b)의 repair는 checksum·설명까지 다시 맞춰 가이드가 막으려는 불일치를 지운다. (c)는 r10이 이미 버린 대안이다(큰 테이블 인덱스 추가가 번거로워짐). "이력을 고치지 않는다" 정책의 예외라 소유자 확인이 필요하다 | 소유자 | (a), 2026-11-06. 결정 색인 2.5절 「실패한 동시 인덱스 마이그레이션 복구」 | +| RR7-01-05(= round6 01 Declined ①) 감싼 carrier를 전송이 어떻게 볼지 | (a) 네 전송 모두 원인 사슬의 첫 carrier를 본다 — web·GraphQL·STOMP에서 감싼 carrier의 응답이 500 → carrier 코드로 바뀐다 (b) 네 전송 모두 맨 위만 본다 — gRPC 응답이 carrier 코드 → `INTERNAL`로 바뀐다 (c) 차이를 두고 문서화한다 | (a). use case가 뜻한 코드로 답하고, persistence 실패의 SQL 원인이 어느 전송 로그에도 남지 않는다. gRPC가 이미 그렇게 해서 바뀌는 쪽이 셋이지만, 바뀌는 응답은 지금 500 `INTERNAL_ERROR`로 뭉개지는 경우뿐이다. 응답 코드가 바뀌는 수정이라 고치기 전에 확인받는다(`docs/work/improve.md` 7절) | 소유자 | (a), 2026-11-06. 결정 색인 2.3절 「감싼 carrier를 전송이 읽는 법」 | +| round7 05 Declined ①: 태그·릴리스 trigger만 있는 workflow를 단계 실행으로 셀지 | (a) `push`에 `tags:`만 있거나(`branches`·`paths` 없이) `release` trigger만 있는 workflow는 `releaseCheck` 단계에만 센다 (b) 지금처럼 모든 단계에 센다(릴리스 흐름도 변경 흐름의 일부)고 메시지·B-36에 적는다 | (a). 결정 「경로 필터 workflow와 단계 검사」와 같은 원칙이다 — 태그 push는 매 변경에 돌지 않는다. `releaseCheck`는 정의가 "tag 전용 검사"(`src/README.md`)라 예외로 둔다. 이 repo는 `release.yml`(`push: tags: [v*]`)이 `:releaseCheck`·`-p optional-platforms releaseCheck` 말고도 `-p optional-platforms integrationCheck`를 돌리지만, 같은 단계를 `integration-main.yml`(main push·nightly)도 돌려 판정이 바뀌지 않는다 | 소유자 | (a), 2026-11-07. 결정 색인 2.7절 「태그·릴리스 workflow와 단계 검사」 | + +네 건 모두 소유자가 권하는 안 (a)로 정했다. 적용한 커밋은 18.7절이다. + +### 18.5 round6 「Declined to judge」 30건 판정 (2026-11-06) + +(a) 실제 결함 → round7 발견으로 넣음, (b) 결함 아님 → 닫음, (c) 소유자 결정 필요 → 18.4절. 번호는 round6 각 영역 문서 「Declined to judge」의 +순서다. 결과: (a) 4건(그중 1건은 RR7-01-01에 합침), (b) 24건, (c) 2건. + +| 영역 | # | 항목 | 판정 | 근거 | +|---|---|---|---|---| +| 01 | ① | 감싼 carrier를 전송마다 다르게 봄 | (c) → RR7-01-05 | 같은 규칙이 전송마다 갈라졌다(A1). 고치는 방향이 응답 코드를 바꿔 18.4절 | +| 01 | ② | dependency·5xx carrier를 원인 사슬째 남김 | (b) | 서버 실패를 원인과 함께 남기는 것이 정한 설계다(`ServerFailureLog.of`가 dependency·5xx carrier에 예외를 붙임). A8이 막는 것은 SQL 원인과 입력값이다. 자격 증명이 실리는 구체적 경로를 세우지 못했다 | +| 01 | ③ | GraphQL이 실패한 필드마다 한 줄 | (b) | 필드 단위 오류 설계의 결과다. 약속 위반이 없다 | +| 01 | ④ | 업그레이드 B-34가 템플릿 패키지 이름을 다시 나열 | (b) | 업그레이드 안내는 그 릴리스의 변경 기록이다. 정본은 `src/application-core/CLAUDE.md` 표이고 `TemplatePackageOwnershipDocumentTest`가 코드 사본과 대조한다 | +| 01 | ⑤ | STOMP 변환·검증 실패 ERROR | (a) → RR7-01-06 | 클라이언트 탓 실패를 ERROR와 입력 조각으로 남겨 A8을 어긴다 | +| 01 | ⑥ | RR6-01-01 고치는 법의 endpoint 목록 완전성 | (a) → RR7-01-01에 합침 | 목록이 사용자 전송 타입 목록보다 좁아 r9가 잡던 중첩 endpoint를 놓친다 | +| 01 | ⑦ | 규칙 탐침이 정적 `@ArchTest`만 돌림 | (b) | 방법 메모이고 결함 주장이 아니다. 메서드형 `@ArchTest`는 지금도 없다(architectureTest 전체 grep, `@ArchTest` 뒤 메서드 0) | +| 02 | ① | watchdog 스레드의 `inheritedAccessControlContext` | (b) | 템플릿은 실행 jar로 배포해 class loader가 하나다. 스레드는 마지막 예약 60초 뒤 끝난다. 공유 부모 loader 배포는 지원하는 형태가 아니다 | +| 02 | ② | `ClientRuntimeRegistry.close()`의 interrupt 처리 | (a) → RR7-02-01 | "돌아오면 스레드가 없다"는 Javadoc 약속이 interrupt 경로에서 확인 없이 깨진다(A14) | +| 02 | ③ | 배포 중 섞인 버전의 lease 지난 시작 | (b) | 배포 동안만이고 중복 실행이 없다(새 인스턴스는 옛 인스턴스가 시작한 기록을 넘겨받지 않는다) | +| 02 | ④ | `error-codes.yaml` `IDEMPOTENCY_UNAVAILABLE` `log_level` | (b) 다른 세션 처리, 닫힘 | `claude/t3-error-codes-loglevel-fcf427`에서 고쳤고 리뷰 브랜치에 합쳐졌다(`ddf174cd`). 합친 트리 `2c8a359d`에서 행에 `log_level`이 없고, 두면 `OperationalErrorRegistryContractTest`가 실패한다(`docs/registries/error-codes.yaml` 머리 주석) | +| 02 | ⑤ | 시작 호출의 operation id가 claim과 다를 때 저장소 답이 다름 | (b) 다른 세션 처리, 닫힘 | `claude/t5-idempotency-operation-id-9bd973`(`200019aa`)이 고쳤고 리뷰 브랜치에 합쳐졌다(`0fa01019`). 합친 트리 `2c8a359d`에서 PostgreSQL 시작도 `namesAnotherOperation` → `OPERATION_CONFLICT`로 Redis와 같다 | +| 02 | ⑥ | in-memory fake가 lease를 모델링하지 않음 | (b) | RR-01-06 결정의 설계다(시간 케이스는 skip으로 보고). executor의 `LEASE_EXPIRED` → 503 매핑은 단위 테스트가 본다 | +| 03 | ① | 검사기의 10단어 셈이 Flyway와 다름 | (b) | 결과가 달라지는 입력이 없다(판정 단어가 첫 4개 키워드 안, 앞 괄호는 많아야 6단어) | +| 03 | ② | 중첩 블록 주석 | (b) r10이 고침 | `6e992970`: `LockWaitMigrationInspector.endOfBlockComment`, 테스트 `aStatementInsideANestedBlockCommentIsNotRead` | +| 03 | ③ | `executeInTransaction=true` + `SET LOCAL` + `VACUUM FULL` 통과 | (a) → RR7-03-05 | Javadoc의 "늘 거부"와 동작이 다르다(A2) | +| 03 | ④ | `REINDEX (CONCURRENTLY 'false')`를 동시로 판정 | (b) | 거부 쪽 오판이라 거짓 통과가 없고, 쓸 이유가 없는 입력이다 | +| 03 | ⑤ | `.sql.conf`의 placeholder·환경 변수에서 검사기 실패 | (b) | 거부 쪽이다. Flyway 치환 결과를 모른 채 통과시키지 않는 것이 맞는 방향이다 | +| 03 | ⑥ | Sync 사본과 IDE | (b) | 생성 소스의 일반 성질이다. IntelliJ 기본(Gradle 위임)에서는 Sync가 먼저 돈다 | +| 03 | ⑦ | persistence-jpa 디렉터리가 없는 파생 서비스 | (b) | 문서화된 capability 제거는 `runtimeOnly` 한 줄 제거이지 디렉터리 삭제가 아니다 | +| 03 | ⑧ | ledger V002 주석 "Flyway runs each migration in a transaction" | (b) | 적용된 마이그레이션은 고치지 않는다는 규칙이 정한다(`docs/work/reference/review-criteria.md` 9절, checksum). 틀린 설명은 r10이 가이드·검사기 Javadoc에서 바로잡았다 | +| 03 | ⑨ | `MessagingMigrationNamespaceTest` 정규식 | (b) | 소수 버전을 실패시키는 거부 쪽이라 조용히 빠지지 않는다 | +| 03 | ⑩ | `mixed=true`·전역 `executeInTransaction=false`를 쓰는 서비스 | (b) | 검사기 Javadoc과 가이드가 가정으로 적는다(약속 범위 밖으로 명시) | +| 04 | ① | 경로·브랜치 필터 trigger | (c) → RR7-05-01 | r10이 "매 변경"을 약속하며 정책 질문이 결함이 됐다. 18.4절 | +| 04 | ② | 설계상 거짓 실패 모양(`timeout ./gradlew`, `|| exit 1` 등) | (b) | README 16절 결정(거짓 실패 쪽을 받아들임) | +| 04 | ③ | `${{ }}` 값이 `--dry-run`·`|| true`로 펼쳐짐 | (b) | 실행 전 값을 알 수 없고, workflow 작성자가 자기 식으로 넣는 의도된 변경이다. 식 인자를 모두 세지 않으면 matrix 플래그마다 거짓 실패가 난다 | +| 04 | ④ | `CDPATH`·심볼릭 링크 | (b) | GitHub runner 기본 환경에 `CDPATH`가 없다 | +| 04 | ⑤ | composite action 안의 `run:` | (b) | 판독기가 읽지 않아 세지 않는 쪽(거짓 실패)이다 | +| 04 | ⑥ | httpclient 문서의 lane 이름·장애 주입 주기 | (b) 다른 커밋 처리 | `e6b6e18e`. 기준 커밋에서 `docs/httpclient/support-matrix.md:61`(`spring62ApiSurfaceScan`)·`:65`(main push, nightly)·`release-checklist.md:12`가 맞다 | +| 04 | ⑦ | 실제 GitHub runner·pwsh 동작 | (b) | 결함 주장이 아니라 실행 환경의 한계다. RR6-04-04는 코드·테스트로 닫혔다 | + +#### round7 1차 「Declined to judge」 12건 판정 (2026-11-07) + +총괄 요청으로 이 리뷰 1차 문서의 「Declined to judge」를 같은 방식으로 판정했다. 기준은 리뷰 브랜치를 fast-forward한 `2c8a359d`다(t3·t5 수정과 결정 +색인의 2026-11-06 결정 포함). 번호는 각 영역 문서 「Declined to judge」의 순서다(각 영역의 마지막 줄 "round6 …의 Declined"는 위 표가 다뤄 세지 +않는다). 결과: (a) 3건(그중 1건은 RR7-01-01에 합침), (b) 8건, (c) 1건. + +(a)로 새로 올린 발견 둘은 판정 때 이 표에만 적었다(총괄 지시가 18절 판정 표와 18.4절만 고치라고 했다). 2026-11-07 수정 브랜치를 합칠 때 18.1절 색인 표에 더했다. + +| 발견 | 심각도 | 한 줄 내용 | 이번 수정 / 이전부터 | 증거 | +|---|---|---|---|---| +| RR7-02-02 | Minor | in-memory fake가 시작을 적용한 같은 핸들의 재시작(응답 유실)에 `NOT_OWNER` — 두 저장소·포트 Javadoc은 `ALREADY_STARTED_SAME_OPERATION` | 이전부터 | E1 | +| RR7-03-06 | Minor | "코드로 만드는 Flyway는 모두 `FlywaySchemaPolicy.configure()`에서" 규칙을 ArchUnit이 `Flyway.configure()` 호출로만 지켜 `new FluentConfiguration()`·`new ClassicConfiguration()`이 빠진다 | 이번 수정 | E1 | + +| 영역 | # | 항목 | 판정 | 근거 | +|---|---|---|---|---| +| 01 | ① | `ARE_REQUEST_HANDLER_TYPES`에 WebFlux `WebFilter`·`WebHandler` 등이 없음 | (a) → RR7-01-01에 합침 | r9는 설정에 중첩된 클래스를 `org.springframework.web..` 전체로 봤다. 목록이 좁아진 같은 원인이고 다른 리뷰도 RR7-01-01에 함께 적었다 | +| 01 | ② | gRPC: 취소된 호출이 carrier·IAE로 끝나면 로그가 남음 | (b) | 문서는 "인식 못 한 실패"에서만 취소를 뺀다(`src/adapter/inbound/grpc/README.md`). 약속 위반이 없다 | +| 01 | ③ | gRPC: raw status를 다른 예외로 감싸 던지면 원인 사슬의 status 설명이 스택에 남음 | (b) | 인식 못 한 실패를 원인 사슬째 남기는 것은 네 전송 공통 설계다(web `GlobalExceptionHandler.handleUnknown`도 같다). RR6-01-05가 약속한 것은 서비스가 끝낸 raw status 자체의 설명이고 그것은 지켜진다 | +| 02 | ① | in-memory fake가 같은 핸들의 재시작에 `NOT_OWNER` | (a) → RR7-02-02 | 포트 Javadoc과 두 저장소, 결정 「넘겨받기 전 핸들의 재전송」(2026-11-06, 전이를 적용한 핸들에게는 "이미 처리됨")과 다르다. fake가 계약 밖으로 갈라졌다(A6) | +| 02 | ② | 같은 owner token·다른 operation id의 claim이 넘겨받을 수 있는 기록에서 `OwnerOperationConflict` 대신 넘겨받음 | (b) | 아무것도 실행되지 않은 기록이라 넘겨받아도 안전하다. `OwnerOperationConflict`에는 Javadoc 약속이 없고, t5가 더한 계약 케이스 `aClaimWithTheOwnerTokenUnderAnotherOperationIsAnOwnerOperationConflict`(살아 있는 claim)는 세 저장소가 같게 답한다. 결정 「같은 token·다른 operation의 claim·inspect」(2026-11-06, `docs/work/reference/decisions.md` 2.4)가 claim의 `OwnerOperationConflict`를 진행 중인 기록으로 한정했다. 넘겨받을 수 있는 기록은 넘겨받기를 먼저 보는 RR6-02-01 순서를 따른다 | +| 03 | ① | `new FluentConfiguration()`·`new ClassicConfiguration()` 경로 | (a) → RR7-03-06 | 규칙 문장(`persistence-jpa/CLAUDE.md`, `FlywaySchemaPolicy` Javadoc)이 모든 생성을 말하는데 장치는 한 길만 막는다(A10) | +| 03 | ② | 세션 잠금: 연결이 살아 있는 채 unlock이 실패하면 잠금이 풀의 연결에 남을 수 있음 | (b) | 결정 「Flyway PostgreSQL 잠금」(세션 수준, `docs/work/reference/decisions.md` 2.5)의 범위 안의 성질이다. 남은 잠금은 다음 배포가 `lockRetryCount` 뒤 오류로 멈추는 닫힌 실패이고, 풀이 그 연결을 닫으면 풀린다. 재현하지 않았고 결정의 전제를 바꿀 증거가 아니다 | +| 04 | ① | `trap 'exit 0' EXIT` 뒤 `trap - EXIT`로 풀어도 계속 세지 않음 | (b) | 거짓 실패 쪽이다(README 16절 결정) | +| 04 | ② | `kill $$` 등 신호로 셸을 끝내는 명령을 모델링하지 않음 | (b) | 신호로 끝난 단계는 실패로 끝나 거짓 통과가 없다 | +| 05 | ① | `push: tags:`만 있거나 `release` trigger만 있는 workflow도 단계 실행으로 셈 | (c) → 18.4절 | 결정 「경로 필터 workflow와 단계 검사」(2026-11-06)는 `paths:`만 정했다. 태그·릴리스 trigger는 같은 원칙(매 변경에 도는가)의 다른 모양이지만 `releaseCheck`는 정의상 태그 전용이라 새 결정이 필요하다 | +| 05 | ② | `runs-on`을 `labels:` 없는 `group:` 매핑으로만 쓰면 세지 않음 | (b) | 거짓 실패 쪽이고 실패 메시지가 이유("may be a Windows runner")를 말한다 | +| 05 | ③ | 같은 repo의 재사용 workflow를 `owner/repo/.github/workflows/x.yml@ref`로 부르면 호출자로 못 알아봄 | (b) | 거짓 실패 쪽이다. 메시지가 "no workflow in this directory calls it"을 말한다 | + +### 18.6 멈춤 기준 상태 (`docs/work/improve.md` 4.5절, 2026-11-07) + +1. 마지막 확인 리뷰 발견 0: **아님.** round7 15건(18.1절). 15건 모두 고쳤다(18.7절). 고친 커밋을 보는 다음 확인 리뷰가 판정한다. +2. 열린 「Declined to judge」 0: **참.** + - round6 30건은 모두 판정했다(18.5절). (b) 중 다른 브랜치가 닫는 2건은 그 브랜치가 리뷰 브랜치에 합쳐져(`ddf174cd`, `0fa01019`) + 합친 트리 `2c8a359d`에서 확인해 닫았다. + - round7 1차 12건(01: 3, 02: 2, 03: 2, 04: 2, 05: 3)도 모두 판정했다(18.5절 「round7 1차」 표, `cb340001`): (a) 3건, (b) 8건, + (c) 1건. (c)는 18.4절 넷째 결정이 됐다. +3. 합친 트리의 라운드 끝 게이트: **참.** `claude/integration-r8-a4196a`(`48565718`)에서 PR 단계·main 단계·바뀐 영역 lane 전부 rc=0(18.8절). +4. README의 남은 항목 0: **아님.** 18.4절 결정 4건은 모두 답을 받았고 결정 색인에 위치를 적었다. 남은 것은 수정 세션이 「범위 밖」으로 + 적고 고치지 않은 아래 넷이다. 결함인지 판정하지 않았다. 다음 확인 리뷰가 판정한다. 수정마다 새로 기대는 것은 각 커밋 본문 「위험·한계」에 있다. + - 멱등(r8-f4): 적용한 핸들이 markFailed를 다른 retention으로 다시 보내면 Redis·fake는 `ALREADY_MARKED_SAME_OPERATION`, PostgreSQL은 + `OPERATION_CONFLICT`다. `IdempotencyFailOutcome.OPERATION_CONFLICT` Javadoc은 둘 다 `OPERATION_CONFLICT`라고 적는다. 또 Redis TRANSITION의 + start `ALREADY`는 전이 종류를 보지 않아, EXECUTING 핸들로 renew한 뒤 그 핸들로 start하면 Redis만 `ALREADY_STARTED_SAME_OPERATION`이다 + (executor는 renew를 부르지 않아 손으로 만든 호출로만 닿음). + - 아키텍처 규칙(r8-f2): STOMP channel interceptor 타입(`org.springframework.messaging.support.ChannelInterceptor`·`Message`·`MessageChannel`)이 + 사용자 전송 타입 목록에 없다. 설정 클래스 자신에 직접 쓴 WebFlux `WebFilter`·`WebHandler`는 요청 처리기 목록 밖이다(WebFlux는 classpath에 없음). + 둘 다 이전부터다. + - 전송 오류(r8-f1): web 필터가 던진 carrier는 `EnvelopeErrorController`가 status만 봐 500 `INTERNAL_ERROR`가 된다. 템플릿에 carrier를 던지는 + 필터는 없다(grep). + - 이력 ID(t4-2): `docs/manual`·`docs/work` 밖 문서(`AGENTS.md`, `docs/httpclient/*.md`, `src/adapter/inbound/web/README.md` 등)에 본문 이력 ID가 + 남아 있다. 이력 0 규칙을 그 문서까지 넓힐지는 소유자 결정이다. + +### 18.7 round7 처리 (2026-11-07) + +round7 결함 15건과 고치다 같이 고친 것을 수정 브랜치 다섯 개(`claude/r8-f1-transport-errors-b21ebf`, `claude/r8-f2-arch-rules-60140e`, +`claude/r8-f3-persistence-9e8157`, `claude/r8-f4-idempotency-3a6a0f`, `claude/r8-f5-small-fixes-f40412`)가 고쳤다. 기준은 `73d39212`(리뷰 브랜치 +`2c8a359d` + 매뉴얼 수정 1차)다. 2026-11-07 매뉴얼 브랜치 둘(`447a77a3`, `81ef58ab`)과 1차 Declined 판정(`cb340001`)과 함께 +`claude/integration-r8-a4196a`에 합쳤다. 검증 칸은 각 커밋 본문에서 옮겼다. 모두 desktop에서 공유 잠금 아래 돌렸고 로그 경로는 커밋 본문에 있다. + +| 결함 | 상태 | 고친 커밋 | 검증 | +|---|---|---|---| +| RR7-01-01·02 | 고침 | `a8166598` | RED: 기준 + 테스트·fixture만으로 `ArchitectureViolationFixtureTest` 87건 중 5건 실패(중첩 JAX-RS·설정 경유·`@ServerEndpoint`는 위반 0건, CORS 두 모양은 거짓 위반). GREEN: `:app-bootstrap:architectureTest --rerun` 237건 실패 0. 변이 둘(설정용 목록에 `servlet.function`, 요청 처리기 목록에 `io.vertx.ext.web`)을 `UserTransportTypeListsTest` 2건·fixture 테스트 3건이 잡음. `:ci :verifyDependencyLocks --warning-mode=fail`, `architectureCheck`, `testQualityCheck`, 두 빌드 단계 검사, sample, optional `ci`, compose 검사 rc=0 | +| RR7-01-03~06 | 고침 | `5f6a86d7` | RED: 기준 + 테스트만으로 7개 leaf에서 17건 실패(500 `INTERNAL_ERROR`, `INTERNAL`, ERROR + 입력이 든 메시지). GREEN: shared-contract 269, application-core 413, web 334, graphql 401, grpc 74, websocket 105, app-bootstrap 225 실패 0. `:ci :verifyDependencyLocks --warning-mode=fail`, web·graphql·websocket `systemTest`·`:conditionalTransportQualification`, `documentContractTest` 66, 7개 leaf `testQualityCheck` rc=0 | +| 같은 모양 추가 2건: `Retry-After` 누락 7개, GraphQL `@Argument` 변환 실패(r8-f1 보고 「범위 밖」 1·2, 소유자 답 2026-11-07 "권하는 안대로") | 고침 | `ef8ef170` | RED: `5f6a86d7` + 테스트만으로 11건 실패(advisor 7, 레지스트리 대조 1, GraphQL 3 — `INTERNAL_ERROR`, ERROR + `BindException` "rejected value [alice@example.com]"). GREEN: `:ci :verifyDependencyLocks --warning-mode=fail`(web test 341, graphql 404, app-bootstrap 225), `documentContractTest` 67, web·graphql `systemTest`·`:conditionalTransportQualification`, `testQualityCheck` rc=0 | +| RR7-02-01 | 고침 | `c746f980` | RED: 기준 + 테스트만으로 `closingFromAnInterruptedThreadStillWaitsForTheDrainThread` 실패("Expecting empty but was: [httpclient-runtime-drain]"). GREEN: `ClientRuntimeRegistryTest`, httpclient `check`·`testQualityCheck`, `httpClientStableContractTest`(apache, jdk), `spring70CompatibilityTest`, `:ci` rc=0. interrupt된 채 5초 마감을 넘기는 경로는 테스트하지 않음 | +| RR7-02-02 | 고침 | `14435106` | 아래 행과 같은 실행. RED: in-memory fake 계약 59건 중 4건 실패(적용한 핸들의 start·renew·markFailed 재전송, "expected: ALREADY_MARKED_SAME_OPERATION but was: NOT_OWNER" 등) | +| 멱등 남은 차이 3건: 넘겨받기 전 핸들의 complete·markFailed 재전송, release한 핸들의 start(결정 「넘겨받기 전 핸들의 재전송」「해제된 핸들로 start」, 2026-11-06) | 고침 | `14435106` | `IdempotencyStoreContract` 10케이스 추가. RED: Redis command fake 2, 실 Redis 2, 실 PostgreSQL 5 실패. GREEN: application-core 422, persistence-jpa 664, cache-redis 225, redis-runtime 65, `redisContainerContractTest` 100, `jpaPlatformContractTest` 429, `postgresqlIdempotencyIntegrationTest` 10, fake를 쓰는 leaf 넷(composition idempotency 32, redis-sdk 310, web 329, sample 339), `documentContractTest` 66 실패 0 | +| RR7-03-01~05 | 고침 | `6ec0c4f7` | RED: 기준 + 테스트(+ 기준 문서 주장을 단언하는 임시 메서드, 임시 ledger V004)로 `LockWaitMigrationInspectorTest` 80건 중 2, `postgresqlMigrationLockWaitIntegrationTest` 47건 중 4, `postgresqlConcurrentIndexMigrationIntegrationTest` 9건 중 3, ledger `integrationTest` 6건 중 4 실패. GREEN: persistence-jpa `check`(test 666)·`testQualityCheck`, 두 IT lane 42·7건, optional ledger `check integrationTest testQualityCheck`, `documentContractTest` 66, 두 빌드 단계 검사 rc=0 | +| RR7-03-06 | 고침 | `6764246a` | RED: `6ec0c4f7` + fixture·테스트로 `architectureTest` 234건 중 4건 실패(`FluentConfiguration`·`ClassicConfiguration`·하위 클래스·생성자 참조 fixture가 통과). GREEN: `architectureTest` 233건 실패 0, `architectureCheck`, persistence-jpa·app-bootstrap `check`, `documentContractTest` 66, `testQualityCheck` rc=0 | +| RR7-05-01 | 고침(18.4절 (a)) | `6cd5e925` | RED: 기준 + 테스트만으로 `WorkflowGradleInvocationsTest` 44건 중 1건 실패(필터 workflow 셋 모두 `uncountedReason=null`). GREEN: 같은 테스트, `-p build-logic check javadoc`, 두 빌드 `verifyStrictLaneStages --dry-run`, `:ci :verifyDependencyLocks` rc=0 | +| 태그·릴리스 trigger 판정(18.4절 넷째) | 고침(18.4절 (a)) | `a490c20f` | RED: `ac3c6a81` + 테스트만으로 68건 중 2건 실패(`WorkflowGradleInvocationsTest`, `StrictLaneStagesFunctionalTest` UnexpectedBuildSuccess). GREEN: 두 클래스 46·22건 실패 0, `-p build-logic check javadoc`(173건), 두 빌드 단계 검사, `check-work-docs.py`·상대 링크 검사 rc=0 | +| 깨진 상대 링크 3개(`src/README.md`, fileserver·objectstorage README, 기준 커밋부터) | 고침 | `eab82df1` | `check-work-docs.py --links`를 src·docs·`README.md`·.github에 돌려 깨진 링크 0. lychee는 돌리지 못함 | +| `AGENTS.md` 커밋 예외 문장(매뉴얼 수정 세션이 범위 밖에서 봄) | 고침 | `ac3c6a81` | 본문을 읽는 테스트가 없다(git grep) | + +### 18.8 합친 트리와 게이트 (2026-11-07, desktop) + +`2c8a359d`에서 딴 `claude/integration-r8-a4196a`에 아래 순서로 `git merge --no-ff`를 했다: `447a77a3`(매뉴얼 수정), `ef8ef170`(r8-f1), +`a8166598`(r8-f2), `6764246a`(r8-f3), `14435106`(r8-f4), `a490c20f`(r8-f5), `81ef58ab`(매뉴얼 이력 ID), `cb340001`(1차 Declined 판정). + +합칠 때 생긴 충돌과 처리: + +| 병합 | 파일 | 충돌 | 처리 | +|---|---|---|---| +| r8-f5 | `docs/upgrade/2026-11-maturity-review.md` 머리 「커밋」 줄 | r8-f1이 「r8-f1 전송 오류 처리(B-45~B-48)」, r8-f5가 「`paths` 필터 trigger(B-36)」·「태그 push·`release`(B-36)」를 같은 줄 끝에 더함 | 셋 다 남기고 날짜 순(11-06 `paths` → 11-07 r8-f1 → 11-07 태그)으로 이었다 | +| 매뉴얼 이력 ID | `scripts/check-work-docs.py` `HISTORY_PATTERNS` | 매뉴얼 수정이 회차 패턴 위에 주석 한 줄을 더하고 그 패턴을 고침, 이력 ID 브랜치가 같은 자리에 패턴 셋을 더함 | 패턴 셋을 두고, 주석은 그 주석이 설명하는 회차 패턴 바로 위에 뒀다. 회차 패턴은 매뉴얼 수정 판(자동 병합) | +| 매뉴얼 이력 ID | `docs/work/evidence.md` 8·9절 경계 | 이력 ID 브랜치가 8절 끝에 문단·표를 더함, 매뉴얼 수정이 9절 제목 날짜를 「2026-11-06~07」로 고침 | 8절 추가분을 두고 9절 제목은 매뉴얼 수정 판 | + +- 자동 병합: `docs/work/reference/decisions.md`(r8-f1·f4·f5·매뉴얼 수정이 서로 다른 행), `docs/manual/07-authorization.md`(r8-f2 문단과 이력 ID + 걷어내기가 다른 문단), `docs/manual/04-persistence.md`, `docs/upgrade/2026-11-maturity-review.md` 본문. 합친 결과를 읽어 두 브랜치의 문장이 모두 + 남은 것과 업그레이드 안내 B 행 번호가 겹치지 않는 것을 봤다. +- 합친 뒤 노트북 검사: `check-work-docs.py`(전체·`--history docs/manual`·lychee 범위 `--links`), `check-review-index.py` 모두 rc=0. + +게이트: 대상 `48565718`(18.7절까지 적은 커밋). desktop 새 detached worktree에서 공유 잠금 아래 차례로 돌렸다. 모든 Gradle 명령에 +`--no-build-cache`를 붙였다. 로그 desktop `~/integration-r8-logs/`(`pr-summary.txt`·`main-summary.txt`, 명령마다 `<단계>-<이름>.log`, 실행 +스크립트 `gates.sh`). 바뀐 영역 lane은 `git diff --name-only 2c8a359d 48565718`(120파일)을 `on.pull_request.paths`가 있는 workflow와 +`pr-adapters.yml` `changes` job의 정규식에 맞춰 골랐다. 첫 실행에서 모두 통과해 다시 돌린 것은 없다. + +| 단계 | 명령 | rc | 시간 | 직전 부하 | 실제 실행 | 테스트(실패·skip) | +|---|---|---|---|---|---|---| +| PR | `tasks --group verification` | 0 | 5초 | 0.39 | 5 executed | — | +| PR | `:ci :verifyDependencyLocks --warning-mode=fail --continue` | 0 | 6분 29초 | 0.76 | 752 executed, 4 up-to-date, FROM-CACHE 0 | 7373 (0·28) | +| PR | `:verifyStrictLaneStages --dry-run` | 0 | 11초 | 11.83 | 4 up-to-date | — | +| PR | `bash scripts/verify-compose-profile-contracts.sh` | 0 | 3초 | 10.62 | — | — | +| PR | `:sample-portfolio:check :sample-portfolio:qualityCheck` | 0 | 31초 | 10.62 | 14 executed, 42 up-to-date | 340 (0·0) | +| PR | `-p optional-platforms ci` | 0 | 1분 10초 | 8.78 | 113 executed, 4 up-to-date | 593 (0·0) | +| PR | `-p optional-platforms :verifyStrictLaneStages --dry-run` | 0 | 2초 | 14.87 | 4 up-to-date | — | +| PR(web) | `:adapter:inbound:web:systemTest :adapter:inbound:web:webJettyCompatTest` | 0 | 26초 | 14.08 | 4 executed | 34 (0·0) | +| PR(websocket) | `:adapter:inbound:websocket:websocketJettyTest` | 0 | 4초 | 9.56 | 2 executed | 8 (0·0) | +| PR(websocket) | `:adapter:inbound:websocket:websocketNginxTest` | 0 | 6초 | 9.12 | 3 executed | 4 (0·0) | +| PR(httpclient) | `httpClientStableContractTest -Phttpclient.contract.transports=apache` | 0 | 6초 | 8.71 | 1 executed | 17 (0·0) | +| PR(httpclient) | 같은 것 `=jdk` | 0 | 5초 | 8.25 | 1 executed | 17 (0·0) | +| PR(httpclient) | `spring70CompatibilityTest` | 0 | 5초 | 7.91 | 1 executed | 23 (0·0) | +| PR(jpa) | `jpaPlatformContractTest -Pjpa.matrix.versions=16` | 0 | 3분 36초 | 7.68 | 3 executed | 429 (0·0) | +| PR(jpa) | 같은 것 `=18` | 0 | 3분 36초 | 2.58 | 1 executed | 429 (0·0) | +| PR(jpa) | `jpaPlatformMigrationTest` | 0 | 1분 20초 | 1.82 | 1 executed | 45 (0·0) | +| PR(redis-sdk-topology) | standalone 7.4 compose + `redisTopologyTest` ×3(redis-runtime·redis-sdk·cache-redis) | 0 | 1분 26초 | 2.57 | 3 executed | 119 (0·0) | +| PR(build-logic) | `-p build-logic test` | 0 | 40초 | 1.25 | 3 executed, 3 up-to-date | 173 (0·0) | +| PR(fileserver-pr) 1/5 | `:application-fileserver:test :composition:fileserver-platform:test` | 0 | 2초 | 2.39 | 42 up-to-date — 같은 worktree `:ci`가 실행(361건·37건) | — | +| PR(fileserver-pr) 2/5 | `:adapter:outbound:fileserver:test` | 0 | 1초 | 2.27 | 26 up-to-date — `:ci`가 실행 | — | +| PR(fileserver-pr) 3/5 | `:adapter:inbound:web-fileserver:test` | 0 | 2초 | 2.27 | 29 up-to-date — `:ci`가 실행 | — | +| PR(fileserver-pr) 4/5 | `…web-fileserver:test --tests '*FileserverHardeningContractTest' …fileserver:test --tests '*PhysicalPathResolverTest'` | 0 | 4초 | 2.27 | 2 executed | 30 (0·0) | +| PR(fileserver-pr) 5/5 | `:adapter:outbound:fileserver:test --tests '*LargeFileBoundedMemoryTest'` | 0 | 3초 | 2.73 | 1 executed | 2 (0·0) | +| PR(object-storage) | `:adapter:outbound:objectstorage:objectStorageMinioContractTest` | 0 | 8초 | 2.67 | 2 executed | 19 (0·0) | +| PR(문서) | `check-work-docs.py`, `--history docs/manual`, lychee 범위 `--links`(`gates.md` 2절), `check-review-index.py` | 0 | 0초 | 2.62 | — | 이력 ID 0줄(13파일), 링크 520개 깨짐 0(572파일), 색인 172/172 | +| main | `:mainCheck --continue --warning-mode=fail` | 0 | 8분 16초 | 2.62 | 241 executed, 255 up-to-date, FROM-CACHE 0 (아래 주 1) | 440 (0·0) | +| main | configuration-cache 1/3: `ci`·`mainCheck`·`integrationCheck`·`releaseCheck` `--dry-run` 두 번씩 | 0 | 34초 | 8.43 | 재사용 4/4 | — | +| main | configuration-cache 2/3: `:domain-core:check :application-core:check --configuration-cache` | 0 | 4초 | 5.74 | 4 executed, 25 up-to-date | — | +| main | configuration-cache 3/3: 같은 것 다시 | 0 | 1초 미만 | 5.74 | 25 up-to-date, 재사용 1/1 | — | +| main | `:integrationCheck --continue` | 0 | 16분 55초 | 5.74 | 101 executed, 173 up-to-date | 1021 (0·0) | +| main | `:performanceCheck --continue` | 0 | 23초 | 0.73 | 60 executed | 26 (0·0) | +| main | `-p optional-platforms performanceCheck --continue` | 0 | 4초 | 1.78 | 10 executed | 1 (0·0) | +| main | `-p optional-platforms integrationCheck` | 0 | 20초 | 2.04 | 10 executed | 47 (0·0) | +| main | `:adapter:outbound:httpclient:test -Phttp3.tests.enabled=true`(실험 job) | 0 | 40초 | 2.18 | 1 executed | 360 (0·0) | +| main | notification-platform `pr` 1~4/7(compile, application-core·notification·persistence-jpa 등 test) | 0 | 각 1~2초 | 1.44~1.48 | 모두 up-to-date — 같은 worktree `:ci`가 실행 | — | +| main | notification-platform `pr` 5/7 `jpaPlatformContractTest` | 0 | 3분 32초 | 1.44 | 1 executed | 429 (0·0) | +| main | notification-platform `pr` 6/7 `jpaPlatformMigrationTest` | 0 | 1분 20초 | 1.75 | 1 executed | 45 (0·0) | +| main | notification-platform `pr` 7/7 `:adapter:outbound:notification:check -x test` | 0 | 2초 | 1.26 | 1 executed, 28 up-to-date | — | +| main | `bash scripts/run-compose-runtime-smoke.sh --matrix src/config/runtime/compose-profile-contracts.json` | 0 | 12분 6초 | 1.51 | — | 18 lane 모두 통과 | +| 태그 | `:releaseCheck -PgitRevision=48565718…` | 0 | 4초 | 1.26 | 20 executed | 1 (0·0) | +| 태그 | `-p optional-platforms releaseCheck -PgitRevision=48565718…` | 0 | 8초 | 1.24 | 16 executed | 27 (0·0) | + +1. `:mainCheck` 로그의 FROM-CACHE 2줄(`:domain-core:checkstyleMain`·`checkstyleTest`)은 `verifyFeatureScaffold`가 띄우는 중첩 Gradle 빌드(생성 + 명령 왕복용 임시 복사본) 안의 것이다. `--no-build-cache`가 중첩 빌드로 넘어가지 않는다. 바깥 빌드 집계는 FROM-CACHE 0이다. +2. `:ci`의 skip 28은 기준 `2c8a359d`의 통합 게이트(2026-11-07)와 같은 수다. in-memory fake 계약의 시간 케이스 19, app-bootstrap 조건부 adapter + 계약, notification provider sandbox 등 이전부터 있던 것이다. +3. 바뀐 영역 lane이 실제로 돈 것(로그 `> Task` 줄): `postgresqlIdempotencyIntegrationTest`, `postgresqlConcurrentIndexMigrationIntegrationTest`, + `postgresqlMigrationLockWaitIntegrationTest`, `redisContainerContractTest`, `httpClientFailureInjectionTest`, `app-bootstrap:integrationTest` + (`integrationCheck` 안), `:app-bootstrap:documentContractTest`·`verifyEnvKeys`·`verifyPublicPathSnapshot`·`verifyFeatureScaffold`(`mainCheck` 안). +4. `integrationCheck`가 뺀 lane: `redisTopologyTest` ×3(입력 필요 — PR 단계에서 standalone으로 따로 돌림), `objectStorageAwsQualificationTest` + (보호된 AWS sandbox 입력 필요, 못 돌림). +5. `--warning-mode=fail`로 돌린 `:ci`·`:mainCheck` 로그에 Deprecated 경고가 없다(`grep -i deprecat`는 `verifyEnvKeys` 통과 줄 하나만 걸림). + +못 돌린 것과 해당 없는 것: + +- lychee(`link-check.yml`): desktop·노트북에 없다. 같은 범위 상대 링크 검사로 대신했다. 외부 URL은 보지 못했다. +- `ci-quality-gates.yml` `grpc-proto-buf`: buf가 없다. 해당 없음 — diff에 `.proto`·`buf*.yaml`이 없다. +- `dependency-vulnerability.yml` `dependency-review`·`dependency-submission`: GitHub에서만 돈다. 해당 없음 — lockfile·`libs.versions.toml` 변경이 없다. + `trivy-fs`: trivy가 없어 못 돌렸다. +- 경로가 안 걸린 PR workflow: `messaging-certification.yml`, `notification-platform.yml`의 pull request trigger(main push의 `pr` job은 위에서 돌림). +- PR·main 단계가 아닌 것: nightly·수동 전용(`fileserver-nightly`, `jpa-nightly`, `jpa-next`, redis 전체 matrix, MinIO fault, AWS), `release.yml`의 + `releaseCheck` 두 명령 밖 job(이미지·서명 등, 태그 단계). + +## 19. round7 수정 확인 리뷰 round8 (2026-11-07) + +`2c8a359d..83a12f66`(round7 결함 수정 다섯 브랜치와 매뉴얼 수정을 합친 것)을 봤다. 기준 커밋 `83a12f66`. 범위는 리뷰 기록 밖 116개 파일 ++3,747줄이라 독립 리뷰어 둘(`docs/work/improve.md` 4.1절)이 따로 봤다. + +- 정본 리뷰어 A: 영역 문서 `round8/01~06`(브랜치 `claude/r8-review-a-3851a7`). 상한(추가 1,500줄)을 넘어 영역 여섯과 공통 문서로 나눴다. 영역 표는 + [round8/01](round8/01-transport-errors.md) 「범위」다. +- 리뷰어 B: 공유 노트 `r8-review-b.md`(브랜치 `claude/r8-review-b-9079ca`, 리뷰 폴더에 커밋하지 않음). 임시 번호 `B-NN-MM`. +- 두 리뷰가 끝난 뒤 총괄이 같은 결함을 짝지었다. B에만 있던 둘은 정본 리뷰어가 근거와 변이 탐침으로 다시 확인해 다음 번호로 넣었다(round8/03 + 「합칠 때 넣은 결함」). 이 절은 총괄 지시로 정본 리뷰어가 썼다. + +| 영역 | 대상 커밋 | `git diff --shortstat` | +|---|---|---| +| [01 전송 오류](round8/01-transport-errors.md) | `5f6a86d7`, `ef8ef170` | 30 파일, +1056 −125 | +| [02 아키텍처 규칙](round8/02-architecture-rules.md) | `a8166598` | 14 파일, +725 −94 | +| [03 마이그레이션·Flyway 규칙](round8/03-migration.md) | `6ec0c4f7`, `6764246a` | 28 파일, +747 −125 | +| [04 멱등 저장소](round8/04-idempotency.md) | `14435106` | 12 파일, +382 −61 | +| [05 build-logic·httpclient·작은 문서](round8/05-build-logic-httpclient.md) | `6cd5e925`, `a490c20f`, `c746f980`, `eab82df1`, `ac3c6a81` | 11 파일, +547 −100 | +| [06 매뉴얼·검사 스크립트](round8/06-manual-scripts.md) | `b872b0ea`, `73d39212`, `6dd9ef76`, `b619c442`, `447a77a3`, `b7d13104`, `81ef58ab` | 18 파일, +253 −67 | +| 공통 문서 | 업그레이드 안내, application-core·persistence-jpa README | 3 파일, +37 −15 | +| 보지 않음 | 리뷰 기록 `cb340001`·`48565718`·`83a12f66`(README 18절) | — | + +### 19.1 결과 + +Critical 0, Important 2, Minor 8, 회귀 1. 결함 10건: 이번 수정이 만든 것 6건, 섞임 3건(이전부터 있던 것을 이번 수정이 넓히거나 새로 약속함), +이전부터 1건. + +| ID | 심각도 | 내용 | 이번 수정 / 이전부터 | 출처 | 증거 | 결정이 필요한 질문 | +|---|---|---|---|---|---|---| +| RR8-01-01 | Important(회귀) | GraphQL이 원인 사슬의 carrier를 앱이 등록한 매핑보다 먼저 보아, 등록한 실패가 carrier를 원인으로 들면 앱 코드 대신 carrier 코드로 답한다(수정 전 `ORDER_UNAVAILABLE`, 수정 뒤 `DB_UNAVAILABLE`) | 이번 수정 | A·B | E2 | 19.4절 ① | +| RR8-01-02 | Minor | 락 timeout이 4xx가 되며 어느 락인지 서버에 남지 않는데, stub runbook은 이름·시간이 없는 metric과 없는 `integration_lock` 테이블을 보라고 한다 | 섞임 | A·B | E1 | — | +| RR8-02-01 | Minor | STOMP inbound `ChannelInterceptor`가 사용자 전송 타입이 아니어서, 프레임마다 도는 interceptor가 `@SystemCaller`를 불러도 안 잡힌다. 매뉴얼 07의 새 문장은 중첩 클래스가 이 사각지대에 들지 않는다고 적는다 | 섞임 | A·B | E2(B 탐침 P4), E1 | — | +| RR8-03-01 | Important | 실패한 `DROP INDEX CONCURRENTLY` 마이그레이션에 runbook 복구 SQL을 그대로 따르면 재배포가 `42704 index does not exist`로 다시 막힌다 | 이번 수정 | A | E3 | — | +| RR8-03-02 | Minor | 동시 인덱스 IT의 Javadoc이 runbook에 없는 절 이름을 가리킨다 | 이번 수정 | A | E1 | — | +| RR8-03-03 | Minor | runbook SQL 리더 `OutboxRunbookSql`이 마이그레이션 runbook도 읽는데 이름은 outbox 전용이다 | 이번 수정 | B | E1 | — | +| RR8-03-04 | Minor | ledger IT의 예외 목록 검사 테스트가 빈 목록 위에서 돌아, 검사 코드를 망가뜨려도 통과한다(변이 생존) | 이번 수정 | B | E2 | — | +| RR8-04-01 | Minor | 적용한 핸들이 markFailed를 다른 retention·disposition으로 다시 보내면 fake·Redis·PostgreSQL의 답이 서로, 그리고 포트 Javadoc과 다르다 | 섞임 | A·B | E3 | 19.4절 ② | +| RR8-04-02 | Minor | Redis는 renew를 적용한 핸들이 start를 보내도 "이미 시작됨"이라 답해 호출자가 작업을 다시 실행한다(fake·PostgreSQL은 `NOT_OWNER`) | 이전부터 | A·B | E3 | — | +| RR8-06-01 | Minor | 독립 리뷰어 둘이면 정본 리뷰어가 커밋한 문서가 색인 검사를 rc=1로 남기는데, 매뉴얼은 리뷰어에게 rc=0을 요구한다 | 이번 수정 | A | E2 | — | + +심각도 조정: RR8-01-02를 A는 Important, B는 Minor로 봤다. `docs/work/reference/review-criteria.md` 3절로 Minor로 정했다. +- 이 runbook은 `status: stub`이고 본문을 "after domain adoption"에 쓰라고 적는다. 절차로 내놓은 문서가 아니다. +- 템플릿 코드는 `DistributedLockPort.tryAcquire`를 부르지 않는다. +- 피해는 진단을 못 하는 것이고, 응답·데이터·보안은 맞다. +- 이유와 반론은 round8/01 RR8-01-02 「심각도 조정」에 있다. + +r8 수정이 고쳤다고 한 항목의 재확인(영역 문서 「항목 재확인」): +- 닫힘: RR7-01-03·04·06, RR7-01-01·02, RR7-02-01·02, RR7-03-02·04·05·06, RR7-05-01, 멱등 남은 차이 3건, 태그·릴리스 workflow 결정, + `Retry-After` 7개, GraphQL `BindException`, 깨진 링크 셋, `AGENTS.md` 커밋 문장. +- 부분: RR7-01-05(GraphQL에서 RR8-01-01), RR7-03-01(RR8-03-04), RR7-03-03(RR8-03-01). + +### 19.2 리뷰어 B와의 대응 + +| B ID | 정본 ID | 처리 | +|---|---|---| +| B-01-01 | RR8-01-01 | 같은 결함. B가 더 본 모양(`LockAcquisitionTimeoutException` 자체를 등록한 GraphQL 매핑이 무시됨)은 round8/01 RR8-01-01 「합칠 때 덧붙인 것」 | +| B-01-02 | RR8-01-02 | 같은 결함. 심각도를 Minor로 맞춤(19.1절) | +| B-02-01 | RR8-02-01 | 같은 결함. B 탐침 P4(E2)를 증거에 더함. B는 「이전부터」, 정본은 「섞임」(매뉴얼 07의 새 문장이 이 빈칸을 덮었다고 약속함) | +| B-03-01 | RR8-03-03 | B에만 있음. 근거를 다시 읽고 넣음(이름 문제라 E1) | +| B-03-02 | RR8-03-04 | B에만 있음. 변이 탐침으로 확인하고 넣음(round8/03 명령 A10~A12) | +| B-04-01 | RR8-04-01 | 같은 결함, 같은 값. B는 「이전부터」, 정본은 「섞임」(fake의 다른 retention 답이 이번 수정으로 바뀜). 고치는 법이 달라 19.4절 ②에 두 안을 둠 | +| B-04-02 | RR8-04-02 | 같은 결함, 같은 값, 같은 분류 | + +겹침 비율: 두 리뷰가 모두 찾은 결함 5건 / 합친 결함 10건 = **50%**. A에만 있던 것 3건(RR8-03-01·02, RR8-06-01), B에만 있던 것 +2건(RR8-03-03·04). 이 비율은 「확인 리뷰 독립 리뷰어 둘」 결정(2026-11-07)이 다시 볼 값이다. design-docs `delegation-loop/metrics.md` M11 칸은 총괄이 적는다. + +### 19.3 실행 + +| 리뷰어 | 명령 | 결과 | 로그 | +|---|---|---|---| +| A | 탐침 A1~A7(GraphQL 등록 매핑을 두 커밋에서, 멱등 저장소를 fake·Redis 명령 fake·실 Redis·실 PostgreSQL에서, 실패한 `DROP INDEX CONCURRENTLY`의 runbook 복구를 실 PostgreSQL에서) | 모두 rc=0, 값은 각 영역 문서 | desktop `~/r8-review-a-logs/` | +| A | A8 바뀐 leaf 10개 `test`·`architectureTest --rerun`, A9 `-p build-logic test --rerun` | rc=0, FROM-CACHE 0, 실패 0(합계는 round8/03 「A8 결과」) | 같음 | +| A | A10~A12 ledger 예외 목록 테스트 원래·변이·대조 | rc=0·0·1(변이 생존, 대조는 잡힘) | `~/r8-review-a-logs/pass2/` | +| B | 탐침 P1~P6(GraphQL 등록 매핑, 멱등 저장소 넷, STOMP interceptor) | B 노트 3절 | desktop `~/r8-review-b-logs/` | + +탐침 코드는 공유 노트 폴더 `r8-review-a-probes/`(A), `r8-review-b-probes/`(B)에 있어 고칠 때 RED 테스트로 옮겨 쓸 수 있다. 두 리뷰 모두 라운드 끝 +게이트는 다시 돌리지 않았다. 마지막 실행은 18.8절의 `48565718`이다(`83a12f66`과 코드가 같다). + +### 19.4 결정이 필요한 것 + +| # | 항목 | 선택지 | 권하는 안과 이유 | 정할 사람 | 소유자 답 | +|---|---|---|---|---|---| +| ① | RR8-01-01 GraphQL 판정 순서: 앱이 등록한 매핑과 원인 사슬의 carrier 중 무엇이 먼저인가(공개 응답 코드) | (a) 플랫폼 거부 → 실패 **자신**이 carrier → 등록된 application 매핑 → 원인 사슬의 첫 carrier → 거부된 인자 → 가림 (b) 지금 순서를 두고 업그레이드 안내 B-46·GraphQL README·매퍼 Javadoc에 "원인 사슬의 carrier가 등록 매핑보다 먼저"를 적는다 (c) 등록 매핑을 실패 자신이 carrier인 경우보다도 먼저 본다 | (a). A·B가 같은 안을 권한다. r8-f1 전에 등록 매핑이 답하던 응답을 그대로 두고, 앱 도메인 advice가 먼저 받는 web과 맞으며, 결정 「감싼 carrier를 전송이 읽는 법」의 전제("바뀌는 응답은 500이던 경우뿐")로 돌아간다. (b)는 앱에 원인 버리기를 강요하고 web과 계속 다르다. (c)는 r8-f1 전에도 없던 변화라 범위가 넓다. 어느 안이든 B-45에 "GraphQL에서 `LockAcquisitionTimeoutException`을 등록한 매핑은 쓰이지 않는다"를 더한다((a)에서도 그 예외는 실패 자신이 carrier다) | 소유자 | (a), 2026-11-07. 결정 색인 2.3절 「GraphQL 판정 순서」 | +| ② | RR8-04-01 적용한 핸들의 markFailed 재전송에 인자가 다를 때의 답 | (a) 다른 disposition은 `OPERATION_CONFLICT`(세 저장소를 바꿈), 다른 retention은 "이미 처리됨"(PostgreSQL fail digest에서 retention을 뺌) (b) 다른 disposition은 `NOT_OWNER` 그대로(지금 세 저장소가 같음, Javadoc만 고침), 다른 retention은 "이미 처리됨" (c) 다른 retention도 `OPERATION_CONFLICT`(renew의 lease처럼. Redis 기록에 retention을 더하고 Lua를 바꿈) | (a)(A 권장). 결정 「전이의 operation id」(2026-11-06)가 `OPERATION_CONFLICT`를 "claim과 다른 id"와 "같은 id·다른 인자"로 정했다. 다른 disposition은 "같은 id·다른 인자"다. `NOT_OWNER`는 적용한 핸들에게 "넘겨받혔다"는 틀린 신호를 준다. retention은 complete의 replay TTL처럼 기록된 결과를 바꾸지 않는 보관 기간이라 비교하지 않는다(r8-f4가 complete 재전송을 응답 digest로만 판정하고 replay TTL을 비교하지 않은 것과 같다). B는 비용이 가장 작은 (b)를 권했다 — 세 저장소 코드를 disposition 쪽으로 바꾸지 않는다. 어느 안이든 공유 계약에 케이스 둘을 더한다 | 소유자 | (a), 2026-11-07. 결정 색인 2.4절 「적용한 핸들의 markFailed 재전송 인자」 | +| ③ | 이력 ID 0 규칙을 `docs/manual`·`docs/work` 밖으로 넓힐지(18.6절 넷째) | (a) 넓히지 않는다 (b) 진입 문서만: `AGENTS.md`와 leaf `CLAUDE.md` (c) `docs/reviews/**` 밖 전부 | (b). 새 세션이 처음 읽는 규칙 문서에서만 ID가 이해를 막는다(매뉴얼 규칙을 만든 이유와 같다). 모듈 README·설계 문서의 ID는 같은 repo의 리뷰 문서로 따라갈 수 있다. (c)는 65줄을 걷어내고 이력 근거를 잃는다. B는 판정을 소유자에게 넘겼다 | 소유자 | (b), 2026-11-07. 결정 색인 2.1절 「이력 ID 0 규칙의 범위」 | +| ④ | 결정 「감싼 carrier를 전송이 읽는 법」이 인자 변환 단계까지 덮는지(round8/01 「Declined to judge」) | (a) 덮지 않는다. web의 인자 변환 실패(`MethodArgumentTypeMismatchException`·`HttpMessageNotReadableException`)는 원인에 carrier가 있어도 지금처럼 `BAD_PARAMETER`·`VALIDATION_FAILED`, STOMP도 `ConversionFailedException`·`MessageConversionException` 안의 carrier를 거부로 본다 (b) 덮는다. web 두 처리기와 STOMP 거부 판정이 원인 사슬의 carrier를 먼저 본다 | (a). 인자 변환 실패는 요청 형식 오류이고 그 코드는 전송이 정한다(매뉴얼 06 「요청 파라미터 형식 오류」). 템플릿에 carrier를 던지는 변환기가 없어 바뀌는 응답이 없다. 바뀌는 것은 STOMP 로그 줄 하나다 | 소유자 | (a), 2026-11-07. 결정 색인 2.3절 「인자 변환 단계의 감싼 carrier」 | + +개선 제안(결함 아님, 총괄이 받거나 닫는다): B가 18.6절 셋째(web 필터가 던진 carrier)를 결함 아님으로 판정하며, web README에 "필터에서 +던진 예외는 `GlobalExceptionHandler`를 거치지 않고 컨테이너가 예외째 로그를 남긴다(persistence 원인 포함)" 한 줄을 제안했다. web +README 「EnvelopeErrorController」 절(`src/adapter/inbound/web/README.md:302-308`)이 이미 "필터가 던진 예외는 `GlobalExceptionHandler`를 지나지 +않는다"를 적는다. 남는 것은 컨테이너 로그 이야기이고, 이 리뷰는 그것을 실행으로 확인하지 않았다. 받으면 그 줄을 확인하는 테스트와 함께 더한다. + +네 결정 모두 소유자가 권하는 안으로 정했다(2026-11-07). 개선 제안도 받았다. 수정 세션이 실제 Tomcat에서 컨테이너 로그 줄을 +확인한 뒤 web README에 넣었다(`11c76089`, 확인 테스트 `FilterFailureContainerLogIT`). 적용한 커밋은 19.7절이다. + +### 19.5 18.6절에서 넘어온 「남은 항목」 판정 + +| 항목 | 판정 | 어디 | +|---|---|---| +| 멱등: 다른 retention의 markFailed, Redis start `ALREADY` | 결함 | RR8-04-01, RR8-04-02 | +| 아키텍처: STOMP channel interceptor | 결함 | RR8-02-01 | +| 아키텍처: 설정 클래스 자신에 쓴 WebFlux `WebFilter`·`WebHandler` | 결함 아님 | 매뉴얼 07 「규칙이 못 보는 길」이 적은 사각지대, WebFlux는 classpath에 없음(round8/02) | +| 전송 오류: web 필터가 던진 carrier → 500 | 결함 아님 | `EnvelopeErrorController` Javadoc·web README가 적은 동작, 템플릿 필터는 carrier를 던지지 않음(round8/01). B의 개선 제안은 19.4절 끝 | +| 이력 ID 범위 | 결정 필요 | 19.4절 ③ | + +### 19.6 멈춤 기준 상태 (`docs/work/improve.md` 4.5절, 2026-11-07) + +1. 마지막 확인 리뷰 발견 0: **아님.** round8 10건(19.1절). 10건 모두 고쳤다(19.7절). 고친 커밋을 보는 round9 확인 리뷰가 판정한다. +2. 열린 「Declined to judge」 0: **참.** round8/01의 1건(인자 변환 단계의 감싼 carrier)은 19.4절 ④ (a)로 닫았다(결정 색인 2.3절 + 「인자 변환 단계의 감싼 carrier」, 적용 `ee5b4e1b`). B는 Declined가 없다. +3. 합친 트리의 라운드 끝 게이트: **아님.** `claude/integration-r9-f1bc5c`(`8a0b1216`)에서 명령 둘이 rc=1이다(19.8절). 둘 다 기준 + `3eb3b067`에서도 실패하거나 같은 원인이 보여 round8 수정이 만든 실패는 아니다. 그래도 고치기 전까지 이 기준은 참이 아니다. + - 메시징 인증 증거 대조(`verifyMessagingCertificationEvidence`): 커밋된 증거 파일이 broker 이미지를 태그(`apache/kafka:4.1.0`)로 + 적는데, 2026-11-03 `1400dc15`가 테스트 이미지를 digest로 고정한 뒤 다시 만들지 않았다. 기준에서도 같은 차이로 rc=1이다. + - compose runtime smoke의 all-adapters lane: app 컨테이너가 `mem_limit: 512m`(`docker-compose.yml`)을 넘어 커널 OOM으로 죽는다. + 기준에서도 4번 중 2번 죽었고, 죽는 때가 smoke 요청과 겹치지 않아 통과했다. smoke는 app의 재시작을 보지 않는다. +4. README의 남은 항목 0: **아님.** 19.4절 결정 넷과 개선 제안은 모두 답을 받았고 결정 색인에 위치를 적었다(19.4절 「소유자 답」). + 남은 것은 아래다. 결함인지 round9 확인 리뷰가 판정한다. 수정마다 새로 기대는 것은 각 커밋 본문 「위험·한계」에 있다. + - 수정 세션이 「범위 밖」으로 적고 고치지 않은 넷: + - 아키텍처 규칙(r9-g2): Spring Security의 요청 처리 확장점(JWT converter 등)을 사용자 전송 패키지 밖에 두면, STOMP interceptor와 + 같은 사각지대가 생긴다. 서블릿 타입을 쓰지 않는 한 규칙이 잡지 못한다. 템플릿은 모두 `..adapter.inbound.web..` 패키지에 둔다. + - 아키텍처 규칙(r9-g2): 설정이 `registration.interceptors(x)`로 interceptor를 넘기기만 할 때 설정 자신이 잡히는지는 확인하지 + 않았다. interceptor 자신은 잡힌다. + - 마이그레이션(r9-g3): `REINDEX CONCURRENTLY`가 swap 뒤에 실패해 `_ccold`가 남는 경우를 실행으로 재현하지 않았다. runbook은 + 문서로만 다룬다. + - 멱등(r9-g4): 실 Redis는 standalone만 돌렸다. sentinel·cluster 위상에서 새 Lua(`lastKind`)를 돌리지 않았다. + - 합칠 때 본 하나: `RunbookSql` 클래스 Javadoc은 이 리더를 쓰는 lane을 "outbox runbook과 마이그레이션 runbook"으로 적는다. + r9-g1의 락 timeout runbook lane도 이 리더를 쓰게 됐는데 목록에 없다(brief 범위 밖이라 고치지 않음). + - 3의 두 게이트 실패와, smoke가 app 재시작을 보지 않는 것. 고칠 묶음이 필요하다(19.8절 「실패한 게이트」). + +다음은 수정 묶음(3의 두 실패) → round9 확인 리뷰다. round8 수정이 Important 둘(RR8-01-01, RR8-03-01)을 고쳤으므로 round9는 독립 +리뷰어 둘이다(4.1절 셋째 경우). RR8-06-01을 고쳐(`51230caf`) 정본 리뷰어는 `check-review-index.py --extra-index`로 색인 검사를 보인다. + +### 19.7 round8 처리 (2026-11-07) + +round8 결함 10건과 19.4절 결정 넷, 개선 제안 하나를 수정 브랜치 다섯이 고쳤다. RR8-06-01과 결정 ③은 매뉴얼 수정 2차 +(`claude/manual-gap-fix-2-9b0fe2`, 끝 `3eb3b067`)가, 나머지는 그 끝에서 딴 네 브랜치(`claude/r9-g1-inbound-456713`, +`claude/r9-g2-stomp-interceptor-f5675d`, `claude/r9-g3-migration-7ce36d`, `claude/r9-g4-idempotency-c669be`)가 고쳤다. +2026-11-07 `claude/integration-r9-f1bc5c`에 합쳤다(19.8절). 검증 칸은 각 커밋 본문에서 옮겼다. 모두 desktop에서 공유 잠금 아래 +돌렸고 로그 경로는 커밋 본문에 있다. 「결정」 칸은 수정 세션이 정한 기본값이다. 다섯 모두 소유자가 확인했다(2026-11-07). + +| 결함 | 상태 | 고친 커밋 | 검증 | 결정 | +|---|---|---|---|---| +| RR8-01-01 | 고침(19.4절 ① (a)) | `e1fb049b` | RED: 기준 `3eb3b067` + 테스트만으로 `GraphQlWireErrorMapperTest`·`GraphQlArgumentBindingFailureTest` 22건 중 1건 실패(기대 `[ORDER_UNAVAILABLE, BUSINESS]`, 실제 `[DB_UNAVAILABLE, DEPENDENCY]`). 지킴 테스트 둘(실패 자신이 carrier인 등록 타입, 등록 매핑이 답해도 남는 carrier 줄)은 기준에서도 통과. GREEN: graphql·shared-contract `check` rc=0(407·269건 실패 0), `check-work-docs.py` rc=0 | 등록된 매핑이 답해도 원인 사슬의 서버 쪽 carrier 로그 줄은 남긴다. 소유자 확인(2026-11-07) | +| RR8-01-02 | 고침 | `ba189869` | RED(문서 주장을 단언한 임시 탐침, 커밋 안 함): `integration_lock` 조회가 `BadSqlGrammarException`(`postgresqlDistributedLockIntegrationTest` 7건 중 1건 실패), timeout 뒤 metric에 outcome 밖 tag 없음(`MeteredDistributedLockTest` 11건 중 1건 실패). GREEN: application-core·persistence-jpa `check` rc=0(1,089건 실패 0), `postgresqlDistributedLockIntegrationTest` 8건(runbook의 SQL 두 블록을 파일에서 읽어 도는 새 2건 포함), `documentContractTest` 67건 rc=0 | runbook에 key → UUID 계산 SQL을 하나 더 넣었다(코드에서 아는 key의 보유자 찾기). 소유자 확인(2026-11-07) | +| 결정 ④(round8/01 「Declined to judge」) | 고침(19.4절 ④ (a)) | `ee5b4e1b` | RED: 기준 + 테스트만으로 `StompHandlerFailureLogTest` 13건 중 2건 실패(기대 WARN 거부 줄, 실제 ERROR persistence 줄). web·GraphQL은 RED 없음(지금 동작이 결정과 같음): 지킴 테스트가 기준에서 통과하고, web 변이(`handleTypeMismatch`가 원인의 carrier를 먼저 봄)는 12건 중 1건 실패(400 대신 503). GREEN: websocket·web·graphql·shared-contract `check` rc=0(107·343·408·269건 실패 0) | 결정 ④를 GraphQL `@Argument` binder에도 적용한다(동작 변화 없음, 지킴 테스트 하나). 소유자 확인(2026-11-07) | +| web README 개선 제안(19.4절 끝) | 받음, 넣음 | `11c76089` | 쓰기 전 확인: 기준 + `FilterFailureContainerLogIT`로 `:adapter:inbound:web:systemTest` rc=0. WARN 이상 줄은 Tomcat `[dispatcherServlet]` ERROR와 SQL 원인 사슬 하나뿐이고 `GlobalExceptionHandler` 줄은 없다. 브랜치 마지막 트리 `64089130`에서 PR 단계 게이트(`:ci :verifyDependencyLocks --warning-mode=fail` 등)와 바뀐 경로의 pr-adapters lane(web·websocket·jpa) rc=0 | — | +| RR8-02-01 | 고침 | `06b94338` | RED: 기준 + 테스트·fixture·의존성 줄만으로 `ArchitectureViolationFixtureTest` 99건 중 5건 실패(다섯 모두 위반 0건), 허용 2건 통과. GREEN: `:app-bootstrap:architectureTest --rerun` 249건 실패 0. 변이 셋이 각자 맡은 fixture만 실패시킴. 트리 `742428a9`에서 `:app-bootstrap:check`(305건), `architectureCheck`, `testQualityCheck`, `:ci :verifyDependencyLocks --warning-mode=fail`(6,906건 실패 0), 두 빌드 단계 검사, sample, optional `ci`, compose 검사 rc=0 | interceptor 두 타입(`ChannelInterceptor`·`ExecutorChannelInterceptor`)을 요청 처리기 목록에도 넣었다. 소유자 확인(2026-11-07) | +| RR8-03-01 | 고침(같은 절의 단계 순서도) | `8ebe98e6` | RED: 기준 + 임시 테스트로 `postgresqlConcurrentIndexMigrationIntegrationTest` 9건 중 2건 실패(기준 runbook대로 하면 재배포가 `42704 index does not exist`, 기준 순서의 drop 단계가 열린 쓰기 트랜잭션을 기다림). GREEN: persistence-jpa `check`(666건)·`testQualityCheck`, 같은 lane 9건(새 2건 포함), `documentContractTest` 67건, optional ledger `integrationTest` 47건 rc=0, 바꾼 문서 5개 상대 링크 깨짐 0 | — | +| RR8-03-02 | 고침 | `dae6dcaf` | RED 없음(Javadoc 문구). persistence-jpa `spotlessCheck`·`compilePostgresqlIntegrationTestJava` rc=0 | — | +| RR8-03-03 | 고침 | `e3ebc25e` | RED 없음(이름 문제). persistence-jpa `check`(666건), 사용처 lane 셋(동시 인덱스 7건, order key runbook 10건, disposition runbook 8건) rc=0 | — | +| RR8-03-04 | 고침 | `4cd38cf4` | RED 없음(테스트 구조 개선). 대신 변이: 기준 + 리뷰 변이 A11은 목록 검사가 통과(변이 생존), 이 커밋 + 같은 변이는 `GrpcOperationLedgerMigrationLockWaitIT` 8건 중 위반 fixture 4건 실패. GREEN: optional ledger `check`(13건)·`integrationTest`(52건, 새 5건 포함)·`testQualityCheck` rc=0 | — | +| RR8-04-01·02 | 고침(19.4절 ② (a)) | `7535a4ca` | RED: 기준 + 계약 케이스만으로 in-memory fake 62건 중 1, Redis 명령 fake 62건 중 2, 실 Redis 103건 중 2, 실 PostgreSQL 62건 중 2 실패. GREEN: application-core 426·cache-redis 228·redis-runtime 65·persistence-jpa 666건 `check`와 `testQualityCheck`, `redisContainerContractTest` 103, `jpaPlatformContractTest` 432, fake를 쓰는 leaf 넷(composition idempotency 32, redis-sdk 310, web 341, sample 339), `documentContractTest` 67 rc=0. `postgresqlIdempotencyIntegrationTest`는 1차에서 옛 동작(다른 retention → conflict)을 고정한 케이스 1건이 실패해 결정대로 고친 뒤 10건 실패 0 | claim·takeover도 `lastKind`에 `CLAIM`을 쓴다. 소유자 확인(2026-11-07) | +| RR8-06-01 | 고침 | `51230caf` | RED: 정본 리뷰어 커밋 `27260ad0`의 리뷰 폴더에 옵션 없이 `check-review-index.py` rc=1(180 중 172). GREEN: 리뷰어 A의 색인 표를 `--extra-index`로 넘기면 rc=0(180/180), 그 커밋 트리의 폴더 rc=0(182/182), 없는 파일을 넘기면 rc=1. `check-work-docs.py` 기본·`--history docs/manual`·`--links` rc=0 | — | +| 결정 ③ | 고침(19.4절 ③ (b)) | `6b253c6c` | `AGENTS.md`·`src/**/CLAUDE.md` 87줄의 이력 ID를 내용과 날짜로 바꾸고 근거를 `docs/work/evidence.md` 10절로 옮김. `check-work-docs.py` 기본(두 문서 묶음까지 봄)·`--history docs/manual`·lychee 범위 `--links`(578파일 깨짐 0) rc=0, `documentContractTest --rerun` 67건, `MongoNamespaceContractTest --rerun` 3건 rc=0 | — | + +### 19.8 합친 트리와 게이트 (2026-11-07, desktop) + +리뷰 브랜치 끝 `83a12f66`에서 딴 `claude/integration-r9-f1bc5c`에 먼저 `claude/manual-gap-fix-2-9b0fe2`(`3eb3b067`)를 fast-forward로 +받았다. 이 커밋은 round8 리뷰 기록 `27260ad0`·`83948d58`을 품는다. 이어서 아래 순서로 `git merge --no-ff`를 했다: `4cd38cf4`(r9-g3 +마이그레이션) → `11c76089`(r9-g1 전송 오류·락) → `06b94338`(r9-g2 STOMP interceptor) → `7535a4ca`(r9-g4 멱등). + +합칠 때 생긴 충돌과 처리: + +| 병합 | 파일 | 충돌 | 처리 | +|---|---|---|---| +| r9-g1 | `docs/upgrade/2026-11-maturity-review.md` 머리 「커밋:」 줄 | r9-g3가 줄 끝에 「실패한 동시 인덱스 drop의 복구 절차」, r9-g1이 r8-f1 항목 뒤에 「r9-g1 GraphQL 판정 순서와 인자 변환 단계」를 더함 | 둘 다 남기고 각 브랜치가 둔 자리에 뒀다 | +| r9-g1 | `PostgreSqlDistributedLockIntegrationTest`(텍스트 충돌 없음) | r9-g3가 `OutboxRunbookSql`을 `RunbookSql`로 바꿨고, r9-g1의 새 테스트 두 곳이 옛 이름을 부른다. 그대로면 `postgresqlIntegrationTest` source set이 컴파일되지 않는다 | 병합 커밋 `f33903cc`에서 새 이름으로 바꿨다. 아래 `integrationCheck`에서 이 테스트를 포함한 락 lane 8건이 돌았다 | +| r9-g2 | 같은 머리 줄 | r9-g2가 끝에 「STOMP channel interceptor를 사용자 전송으로 셈」을 더함 | 앞 항목을 두고 끝에 더했다 | +| r9-g4 | 같은 머리 줄 | r9-g4가 끝에 「멱등 저장소의 markFailed 재전송 인자와 renew 뒤 start」를 더함 | 앞 항목을 두고 끝에 더했다 | + +- 자동 병합: `docs/work/reference/decisions.md`(r9-g1이 2.3절에 행 둘과 한 문장, r9-g4가 2.4절에 행 하나와 적용 조건), + `src/application-core/README.md`(r9-g1은 락 절, r9-g4는 멱등 절), 업그레이드 안내 본문(B-16·B-45·B-46 행과 5절 두 행이 서로 다른 행). + 두 브랜치가 더한 줄이 합친 결과에 모두 있는 것을 diff로 셌다. 머리 「커밋:」 줄에는 네 브랜치 항목이 하나씩 있다. +- 합친 뒤 결정 색인 기본값 행의 「누가」를 소유자로 바꿨다(`07f7c305`). brief가 든 여덟 행과, 같은 확인을 받은 「GraphQL 판정 순서」의 + 로그 줄 기본값이다. + +게이트: 대상 `8a0b1216`(19.7절까지 적은 커밋, 트리 `88743668`). desktop 새 detached worktree에서 공유 잠금 아래 차례로 돌렸다. 모든 +Gradle 명령에 `--no-build-cache`를 붙였다. 로그는 desktop `~/integration-r9-logs/`에 있다: `pr-summary.txt`·`main-summary.txt`· +`tag-summary.txt`, 명령마다 `<단계>-<이름>.log`와 그 명령이 새로 쓴 결과 XML 사본 `<단계>-<이름>-xml/`, 실행 스크립트 `gates.sh`. +바뀐 영역 lane은 `git diff --name-only 83a12f66 8a0b1216`(95파일)을 `on.pull_request.paths`가 있는 workflow와 `pr-adapters.yml` +`changes` job의 정규식에 맞춰 골랐다. + +| 단계 | 명령 | rc | 시간 | 직전 부하 | 실제 실행 | 테스트(실패·skip) | +|---|---|---|---|---|---|---| +| PR | `tasks --group verification`(workflow 그대로) | 0 | 2초 | 0.36 | 4 executed, FROM-CACHE 1 | — | +| PR | 같은 것 `--no-build-cache`(다시) | 0 | 2초 | 3.37 | 1 executed, 4 up-to-date, FROM-CACHE 0 | — | +| PR | `:ci :verifyDependencyLocks --warning-mode=fail --continue` | 0 | 6분 35초 | 0.36 | 752 executed, 4 up-to-date, FROM-CACHE 0 | 7394 (0·28) | +| PR | `:verifyStrictLaneStages --dry-run` | 0 | 12초 | 12.80 | 4 up-to-date | — | +| PR | `bash scripts/verify-compose-profile-contracts.sh` | 0 | 3초 | 11.94 | 18 lane 일치 | — | +| PR | `:sample-portfolio:check :sample-portfolio:qualityCheck` | 0 | 31초 | 11.94 | 14 executed, 42 up-to-date | 340 (0·0) | +| PR | `-p optional-platforms ci` | 0 | 1분 11초 | 9.14 | 113 executed, 4 up-to-date | 593 (0·0) | +| PR | `-p optional-platforms :verifyStrictLaneStages --dry-run` | 0 | 2초 | 14.61 | 4 up-to-date | — | +| PR(web) | `:adapter:inbound:web:systemTest :adapter:inbound:web:webJettyCompatTest` | 0 | 26초 | 14.61 | 4 executed | 35 (0·0) | +| PR(websocket) | `:adapter:inbound:websocket:websocketJettyTest` | 0 | 5초 | 10.53 | 2 executed | 8 (0·0) | +| PR(websocket) | `:adapter:inbound:websocket:websocketNginxTest` | 0 | 6초 | 9.93 | 3 executed | 4 (0·0) | +| PR(httpclient) | `httpClientStableContractTest -Phttpclient.contract.transports=apache` | 0 | 4초 | 9.37 | 1 executed | 17 (0·0) | +| PR(httpclient) | 같은 것 `=jdk` | 0 | 5초 | 8.94 | 1 executed | 17 (0·0) | +| PR(httpclient) | `spring70CompatibilityTest` | 0 | 5초 | 7.79 | 1 executed | 23 (0·0) | +| PR(jpa) | `jpaPlatformContractTest -Pjpa.matrix.versions=16` | 0 | 3분 38초 | 7.25 | 3 executed | 432 (0·0) | +| PR(jpa) | 같은 것 `=18` | 0 | 3분 36초 | 2.19 | 1 executed | 432 (0·0) | +| PR(jpa) | `jpaPlatformMigrationTest` | 0 | 1분 21초 | 1.87 | 1 executed | 45 (0·0) | +| PR(redis-sdk-topology) | standalone 7.4 compose + `redisTopologyTest` ×3(redis-runtime·redis-sdk·cache-redis) | 0 | 1분 27초 | 2.49 | 3 executed | 122 (0·0) | +| PR(fileserver-pr) 1/5 | `:application-fileserver:test :composition:fileserver-platform:test` | 0 | 2초 | 1.38 | 42 up-to-date — 같은 worktree `:ci`가 실행(361건·37건, `pr-ci-xml/`) | — | +| PR(fileserver-pr) 2/5 | `:adapter:outbound:fileserver:test` | 0 | 1초 | 1.38 | 26 up-to-date — `:ci`가 실행(238건, skip 3) | — | +| PR(fileserver-pr) 3/5 | `:adapter:inbound:web-fileserver:test` | 0 | 2초 | 1.59 | 29 up-to-date — `:ci`가 실행(144건) | — | +| PR(fileserver-pr) 4/5 | `…web-fileserver:test --tests '*FileserverHardeningContractTest' …fileserver:test --tests '*PhysicalPathResolverTest'` | 0 | 4초 | 1.59 | 2 executed | 30 (0·0) | +| PR(fileserver-pr) 5/5 | `:adapter:outbound:fileserver:test --tests '*LargeFileBoundedMemoryTest'` | 0 | 3초 | 1.87 | 1 executed | 2 (0·0) | +| PR(messaging-certification) | `:messaging:messaging-kafka:verifyMessagingCertificationEvidence` | **1** | 1분 9초 | 1.80 | 12 executed, 14 up-to-date | 37 (0·0) — 테스트는 통과, 증거 대조 실패(아래) | +| PR(문서) | `check-work-docs.py`, `--history docs/manual`, lychee 범위 `--links`(`gates.md` 2절), `check-review-index.py` | 0 | 1초 | 1.78 | — | 이력 ID 0줄(13파일), 링크 555개 깨짐 0(578파일), 색인 182/182 | +| main | `:mainCheck --continue --warning-mode=fail` | 0 | 7분 53초 | 1.78 | 250 executed, 246 up-to-date, 바깥 FROM-CACHE 0(아래 주 1) | 441 (0·0) | +| main | configuration-cache 1/3: `ci`·`mainCheck`·`integrationCheck`·`releaseCheck` `--dry-run` 두 번씩 | 0 | 36초 | 2.95 | 재사용 4/4 | — | +| main | configuration-cache 2/3: `:domain-core:check :application-core:check --configuration-cache` | 0 | 3초 | 3.03 | 4 executed, 25 up-to-date | — | +| main | configuration-cache 3/3: 같은 것 다시 | 0 | 1초 미만 | 3.11 | 25 up-to-date, 재사용 1/1 | — | +| main | `:integrationCheck --continue` | 0 | 16분 56초 | 3.11 | 101 executed, 173 up-to-date | 1031 (0·0) | +| main | `:performanceCheck --continue` | 0 | 23초 | 0.82 | 60 executed | 26 (0·0) | +| main | `-p optional-platforms performanceCheck --continue` | 0 | 4초 | 1.55 | 10 executed | 1 (0·0) | +| main | `-p optional-platforms integrationCheck` | 0 | 21초 | 1.55 | 10 executed | 52 (0·0) | +| main | `:adapter:outbound:httpclient:test -Phttp3.tests.enabled=true`(실험 job) | 0 | 40초 | 1.50 | 1 executed | 360 (0·0) | +| main | notification-platform `pr` 1~4/7(compile, application-core·notification·persistence-jpa·web-notification·notification-platform test) | 0 | 각 1~2초 | 1.11~1.27 | 모두 up-to-date — 같은 worktree `:ci`가 실행(426·skip 19, 375·skip 1, 666, 17, 16) | — | +| main | notification-platform `pr` 5/7 `jpaPlatformContractTest` | 0 | 3분 33초 | 1.27 | 1 executed | 432 (0·0) | +| main | notification-platform `pr` 6/7 `jpaPlatformMigrationTest` | 0 | 1분 21초 | 2.08 | 1 executed | 45 (0·0) | +| main | notification-platform `pr` 7/7 `:adapter:outbound:notification:check -x test` | 0 | 2초 | 2.38 | 1 executed, 28 up-to-date | — | +| main | `bash scripts/run-compose-runtime-smoke.sh --matrix src/config/runtime/compose-profile-contracts.json` | **1** | 11분 28초 | 2.38 | — | 17 lane 통과, all-adapters 실패(아래) | +| 태그 | `:releaseCheck -PgitRevision=8a0b1216…` | 0 | 4초 | 5.04 | 20 executed | 1 (0·0) | +| 태그 | `-p optional-platforms releaseCheck -PgitRevision=8a0b1216…` | 0 | 9초 | 4.79 | 16 executed | 27 (0·0) | + +1. `:mainCheck` 로그의 FROM-CACHE 51줄은 모두 `verifyFeatureScaffold`가 띄운 중첩 Gradle 빌드 안에 있다(로그 1030~1463줄, 중첩 빌드 + 집계 "49 from cache"와 "2 from cache"). 바깥 빌드 집계(496 actionable tasks)는 FROM-CACHE 0이다. +2. `:ci`의 skip 28은 r8 통합 게이트(18.8절)와 같은 수다. +3. 바뀐 영역 lane이 집계 안에서 실제로 돈 것(로그 `> Task` 줄과 XML 사본): `postgresqlDistributedLockIntegrationTest` 8건(runbook SQL을 + 읽는 새 2건 포함), `postgresqlIdempotencyIntegrationTest` 10건, `postgresqlConcurrentIndexMigrationIntegrationTest` 9건, + `postgresqlMigrationLockWaitIntegrationTest` 42건, outbox runbook lane 둘(8·10건), `redisContainerContractTest` 103건, + `messagingCertificationTest` 37건, `app-bootstrap:integrationTest`(`integrationCheck` 안), optional ledger `integrationTest` 52건, + `mainCheck` 안의 `documentContractTest` 67건·`verifyEnvKeys`·`verifyPublicPathSnapshot`·`verifyFeatureScaffold`와 `testQualityCheck` + 57개(모두 중첩 빌드 밖). +4. `--warning-mode=fail`로 돌린 `:ci`·`:mainCheck` 로그에 Deprecated 경고가 없다(`grep -i deprecat`는 `verifyEnvKeys` 통과 줄 하나만 걸림). + +**실패한 게이트** — 첫 실행 결과를 그대로 두고, 기준 `3eb3b067`에서 같은 명령을 돌려 원래 있던 실패인지 가렸다. brief대로 고치지 않았다. + +| 게이트 | 원인 | 기준 `3eb3b067` | 담당 | 권하는 고침 | +|---|---|---|---|---| +| messaging-certification `verifyMessagingCertificationEvidence` | 커밋된 `messaging-testkit/…/broker-certification-evidence.jsonl`(2026-08-24 `01372634`)은 `brokerImage`를 `apache/kafka:4.1.0`으로 적는다. 2026-11-03 `1400dc15`가 `src/config/testing/container-images.properties`의 kafka를 `apache/kafka@sha256:bff074a5…`로 고정한 뒤 실행은 digest를 적는다. 시나리오 넷(confirm-timeout, connection-cut-after-write, high-latency, settlement-lost)의 결과는 같고 이미지 표기만 다르다 | rc=1, 같은 차이, 1분 23초, 26 executed, 테스트 37건 실패 0(`base-msgcert.log`) | `1400dc15`(digest 고정 때 증거를 다시 만들지 않음). 이 workflow는 `src/messaging/**`가 바뀔 때만 PR에서 돈다. 이번에는 `6b253c6c`가 `src/messaging/CLAUDE.md`를 고쳐 처음 켜졌다 | 실행이 만든 증거로 커밋된 파일을 바꾼다(태스크 메시지가 말하는 절차) | +| compose runtime smoke, all-adapters lane | app 컨테이너가 `mem_limit: 512m`(`docker-compose.yml:83`, 처음 커밋부터)을 넘어 커널 cgroup OOM으로 죽는다(`anon-rss` 약 520MB). `restart: unless-stopped`로 다시 뜨는데, 죽는 때가 smoke 요청과 겹치면 그 단계(graphql-smoke 또는 notification-smoke)가 실패한다 | smoke 전체 1번 통과(OOM 없음), all-adapters lane만 3번 모두 통과. 그중 2번은 app이 OOM으로 죽었다 다시 떴다(커널 11:36:47, 11:41:36). smoke는 app 재시작을 보지 않아 통과로 남았다 | round8 브랜치가 아니다. 합친 트리는 5번 모두 OOM이었고 3번 실패했다(smoke 전체 2번, lane 3번 중 1번). 표본이 작아 합친 변경이 메모리를 조금 늘렸을 가능성은 배제하지 못했다. 바뀐 main 코드는 15개 파일 +201줄이고 runtime classpath는 같다 | 고칠 묶음이 정한다: all-adapters lane의 app 메모리 한도, 또는 smoke가 app의 재시작·OOM 종료(`RestartCount`, `OOMKilled`)를 실패로 보게 하기 | + +- 증거: desktop `~/integration-r9-logs/` — `base-msgcert.*`, `smoke-rerun-summary.txt`(전체 smoke 합친 트리 2번째·기준), + `lane-compare-summary.txt`와 `lane-*-cg.txt`(lane만 기준·합친 트리 번갈아 3번씩, app cgroup `memory.peak` 1초 표본), `oom-kills.txt`(커널의 + OOM 줄 7개, 10:00~11:45), `runtime-smoke-evidence/`(두 트리의 smoke 증거 폴더). +- app의 cgroup 최고치는 두 트리 모두 한도에 닿았다(기준 508.6~512.0MiB, 합친 트리 499.1~512.0MiB, 표본 사이 최고치는 놓칠 수 있다). + +못 돌린 것과 해당 없는 것: + +- lychee(`link-check.yml`, 경로 걸림): desktop·노트북에 없다. 같은 범위 상대 링크 검사로 대신했다. 외부 URL은 보지 못했다. +- `ci-quality-gates.yml` `grpc-proto-buf`: buf가 없다. 해당 없음 — diff에 `.proto`·`buf*.yaml`이 없다. `release-gate` job은 이 job과 + 위 PR job들의 결과를 모으기만 한다. +- `dependency-vulnerability.yml` `dependency-review`: GitHub에서만 돈다. diff에 `src/app-bootstrap/gradle.lockfile` 한 줄(r9-g2, + `spring-messaging` 7.0.9가 `architectureTestCompileClasspath`에 더해짐, 같은 버전이 이미 다른 classpath에 있음)이 있다. PR에서 결과를 + 봐야 한다. `trivy-fs`: trivy가 없어 못 돌렸다. +- 경로가 안 걸린 PR workflow: `build-logic.yml`, `object-storage-qualification.yml`. +- PR·main 단계가 아닌 것: nightly·수동 전용(`fileserver-nightly`, `jpa-nightly`, `jpa-next`, redis 전체 matrix, MinIO fault, AWS, + notification `nightly-chaos`), `release.yml`의 `releaseCheck` 두 명령 밖 job(이미지·서명 등, 태그 단계). +- desktop 정리: worktree `~/workspace/integration-r9`·`~/workspace/integration-r9-base`를 지웠다(compose가 root로 만든 `tmp/heap-dumps`를 + `redis:7.4`로 지운 뒤). 기존 checkout `refactor/maturity-review-2026-11`(`3d73b6f1`)과 `stash@{0}`는 그대로다. 남은 smoke 컨테이너는 없다. diff --git a/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md b/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md new file mode 100644 index 00000000..82e4f842 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round7/01-core-inbound.md @@ -0,0 +1,226 @@ +# 01 core·inbound r10 확인 리뷰 (2026-11-06) + +> 대상: `6e992970`(r10)의 r10-01 묶음. RR6-01-01~09 수정: 설정 안 요청 처리 코드 판정, record·enum·예외 +> 상위 타입, gRPC 취소·raw status 로그, 네 전송의 `IllegalArgumentException` WARN 한 줄, shared-contract 패키지 규칙. +> 기준 커밋 `06f520e6`(이 영역의 코드는 `6e992970` 뒤로 바뀌지 않았다). + +## 범위 + +### pathspec + +``` +src/shared-contract src/adapter/inbound/graphql src/adapter/inbound/grpc src/adapter/inbound/web src/adapter/inbound/websocket +src/app-bootstrap ':!src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java' +docs/manual/07-authorization.md docs/runbooks/idempotency-unavailable.md +``` + +`git diff --shortstat 6e992970^ 6e992970 -- `: 33개 파일, +1056 −137. 커밋 하나가 +5,143줄이라 +`docs/work/improve.md` 4.4절대로 영역 pathspec으로 나눴다(README 18절). `JpaProductionArchitectureTest`(Flyway 규칙)는 03, +`web/README.md`의 503 행은 02에서 함께 봤다. + +함께 읽은 주변 코드: `ApplicationBoundaryArchitectureTest`의 `ARE_USER_TRANSPORT_TYPES`(`:471-491`)와 `45d2a478`(r9)의 같은 판정식, +`GraphQlWireErrorMapper.sharedCodeOf`, `ServerFailureLog.of`, `GrpcExceptionHandlingInterceptor` 전체, shared-contract 패키지 디렉터리, +매뉴얼 07 「시스템이 부르는 쓰기」·「규칙이 못 보는 길」, round6 RR6-01-01·02의 고치는 법. + +### 수정 보고의 「새로 가정하는 것」 + +README 17절 처리 표에는 이 칸이 없고 묶음 보고는 repo에 남지 않았다. 커밋 본문 「위험·한계」와 17절 「결정」 칸에서 뽑았다. + +| 가정 | 확인 | +|---|---| +| 설정 안의 endpoint는 `ARE_REQUEST_HANDLER_TYPES` 목록 타입에 의존한다 | 거짓인 경우가 있다. 목록에 JAX-RS와 주석형 JSR-356 endpoint가 없다. 그런데 이 목록이 이제 설정에 **중첩된** 클래스에도 쓰인다(RR7-01-01) | +| 설정이 요청 처리기 타입에 의존하면 그 설정 안에 요청 처리 코드가 있다 | 거짓인 경우가 있다. 메서드 참조로 route만 등록한 설정도 의존한다(RR7-01-02) | +| 네 전송의 IAE는 carrier 검사 뒤에만 `refusedArgument`로 간다 | 참. web `GlobalExceptionHandler.java:93-97`, GraphQL `GraphQlWireErrorMapper.java:133-139`, gRPC `GrpcExceptionHandlingInterceptor.java:133-141`(carrier 분기 뒤 `status.getCause()`), STOMP `StompHandlerFailureLog.java:34-43` | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장(README 17절 r10-01)과 구현이 맞는가, 테스트가 이름대로를 보는가, 심각도 보정, Declined to judge, 읽기 전용. 하위 에이전트는 repo 설정이 막아 diff를 여러 번에 나눠 직접 봤다 | 항목마다 닫힘 여부, 새 fixture가 막으려는 모양 밖에서 무엇이 바뀌었나 | +| `docs/work/reference/review-criteria.md` 7절 | 규칙 테스트는 위반·허용 fixture를 둘 다 가지나, 변이·탐침으로 확인 | 새 판정식을 r9 판정식과 같은 fixture에 돌림 | +| `docs/work/reference/defect-patterns.md` A1·A10 | 갈라진 복사본(두 타입 목록), 글로만 있는 규칙 | `ARE_USER_TRANSPORT_TYPES`와 `ARE_REQUEST_HANDLER_TYPES`의 차이 | + +### 실행한 명령과 결과 + +desktop(`ssh desktop`) 임시 worktree 두 개(`~/workspace/t1-r10-review` = `06f520e6`, `~/workspace/t1-r10-review-r9` = `45d2a478`)에 +탐침을 얹고 `flock /tmp/claude-gates/heavy.lock` 아래에서 돌렸다. 로그 `~/t1-r10-review-logs/`(desktop), 탐침 코드와 결과는 공유 노트 폴더 +`rr7-probes/`. + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 1 | `./gradlew :app-bootstrap:architectureTest --tests dev.caskeleton.bootstrap.architecture.Rr7ProbeTest` (`06f520e6`) | rc=0, 21초. 결과는 아래 표 | 4.58 | +| 2 | 같은 명령 (`45d2a478`, 같은 탐침) | rc=0, 20초 | 4.89 | +| 3 | `./gradlew :shared-contract:test … :adapter:inbound:web:test :adapter:inbound:grpc:test :adapter:inbound:graphql:test :adapter:inbound:websocket:test :app-bootstrap:architectureTest --rerun --continue` (`06f520e6`, 탐침 포함 트리) | README 18.3절 | README 18.3절 | + +탐침 `Rr7ProbeTest`는 `USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS`를 다섯 모양에 돌려 위반 여부를 파일에 적는다. + +| 탐침 | 모양 | `06f520e6` | `45d2a478` | +|---|---|---|---| +| P1 | `@Configuration` 안의 중첩 JAX-RS 자원(`@Path`·`@POST`)이 `@SystemCaller`를 부름 | 위반 없음 | 위반(`NestedJaxRsConfiguration$RunNowResource`) | +| P1c | 같은 자원을 최상위 클래스로(대조군) | 위반 | 위반 | +| P2 | `@Configuration` 안의 중첩 `@ServerEndpoint`·`@OnMessage`가 `@SystemCaller`를 부름 | 위반 없음 | 위반(`…$RunNowEndpoint`) | +| P3 | 한 설정이 메서드 참조 route(`orders::list`, 처리 코드는 `OrderHandler`)와 `@SystemCaller` bean을 함께 등록 | 위반(`MethodRefRouteConfiguration`) | 위반 없음 | +| P3c | 같은 route만 있는 설정(대조군) | 위반 없음 | 위반 없음 | + +### 못 본 것 + +- 멱등성 저장소·계약 변경은 02, Flyway 규칙(`JpaProductionArchitectureTest`)은 03에서 봤다. +- 실제 JAX-RS·JSR-356 런타임 기동: 이 템플릿에는 그 런타임이 없다(app-bootstrap `testCompileOnly 'jakarta.ws.rs:jakarta.ws.rs-api'`만). 탐침은 규칙 판정만 본다. +- `ARE_REQUEST_HANDLER_TYPES`에 빠진 타입을 모두 찾지는 않았다. 목록 방식의 한계는 매뉴얼 07 「규칙이 못 보는 길」에 적혀 있다. 아래 RR7-01-01은 그중 **r9가 잡던 것을 r10이 놓치게 된** 모양만 적는다. + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR6-01-01 (설정 안 함수형 endpoint 회귀) | 닫힘 | 람다 route·data fetcher를 가진 설정을 다시 사용자 전송으로 센다(`ApplicationBoundaryArchitectureTest.java:534-581`). 위반 fixture `RunNowRouteConfigurationFixture`·`RunNowDataFetcherConfigurationFixture`와 테스트 `aConfigurationWhoseFunctionalRouteCallsASystemCallerIsCaught`·`…DataFetcher…`. 다만 고친 방법이 중첩 클래스 판정을 좁혀 새 구멍(RR7-01-01)과 새 거짓 실패(RR7-01-02)를 만들었다 | +| RR6-01-02 (익명 configurer 필드 거짓 양성) | 닫힘 | 허용 fixture `SystemCallerBesideFieldReadingWebMvcConfigurerFixture`, 테스트 `aWebMvcConfigurerNestedInAConfigurationMayReadTheConfigurationsField`. 이 수정의 부작용이 RR7-01-01이다 | +| RR6-01-03 (record·enum·예외 거짓 양성) | 닫힘 | `ApplicationBoundaryArchitectureTest.java:741-809`, fixture 3개와 테스트 3개(`Runnable` record는 여전히 잡힘) | +| RR6-01-04 (gRPC 취소 판정) | 닫힘 | `GrpcExceptionHandlingInterceptor.java`의 `delegate.isCancelled()` 분기(`:143`), 테스트 `aFailureOnACallTheClientCancelledIsNotLogged`·`aCancelledStatusTheServiceClosesALiveCallWithIsLoggedAsUnhandled` | +| RR6-01-05 (던진 raw status 설명 로그) | 닫힘 | `failureBehind`가 status 예외를 건너뛴다. 테스트 `aThrownRawStatusIsLoggedByItsCodeWithoutItsDescription`·`…WithACauseIsLoggedWithTheCauseAlone` | +| RR6-01-06 (STOMP IAE ERROR) | 닫힘 | `ServerFailureLog.refusedArgument`를 네 전송이 쓴다. 테스트 4개(web·GraphQL·gRPC·STOMP)와 `ServerFailureLogTest` | +| RR6-01-07 (runbook 문구, RR6-02-03과 같음) | 닫힘 | `docs/runbooks/idempotency-unavailable.md:22-25`·`:102-105` | +| RR6-01-08 (GraphQL 테스트가 carrier 대신 IAE) | 닫힘 | `aClientSideCarrierIsNotLogged`가 `IdempotencyInFlightException`을 넣는다 | +| RR6-01-09 (shared-contract 규칙이 아무것도 못 잡음) | 닫힘 | 대상 `dev.caskeleton.shared..`, 목록 12개가 `src/shared-contract/src/main/java/dev/caskeleton/shared/`의 디렉터리와 같다(ls). 다른 leaf에 `dev.caskeleton.shared` 패키지는 없다(grep). 위반·허용 fixture와 목록 대조 테스트 `SharedContractPackageRuleTest` | + +## 결함 + +### RR7-01-01 · Minor · 설정에 중첩된 클래스를 요청 처리기 목록으로만 보아, 설정 안의 JAX-RS 자원·`@ServerEndpoint`가 `@SystemCaller`를 불러도 잡히지 않는다 (회귀) + +- **위치**: + - 코드: `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java:574-577`(중첩 클래스도 `ARE_REQUEST_HANDLER_TYPES`), `:498-548`(목록에 `jakarta.ws.rs..`, `jakarta.websocket.server..`·`jakarta.websocket.OnMessage` 없음), `:471-491`(`ARE_USER_TRANSPORT_TYPES`에는 `jakarta.ws.rs..`·`jakarta.websocket..` 있음). + - 문서: `docs/manual/07-authorization.md:104`(표시 검사는 JAX-RS를 사용자 전송 타입으로 센다), `:105` ②. +- **무엇이 틀렸나**: + - r9는 설정 클래스 자신만 판정에서 뺐다. 설정에 중첩된 다른 클래스는 `ARE_USER_TRANSPORT_TYPES`로 봤다(`45d2a478`의 같은 파일 `:516-522`). + - r10은 설정에 중첩된 클래스도 설정처럼 `ARE_REQUEST_HANDLER_TYPES`로만 본다(RR6-01-02 고치는 법을 따랐다). + - 두 목록은 다르다. 요청 처리기 목록에는 JAX-RS(`jakarta.ws.rs..`)와 주석형 JSR-356 endpoint(`@ServerEndpoint`, `@OnMessage`)가 없다. 사용자 전송 타입 목록에는 둘 다 있다. + - 그래서 설정에 중첩된 JAX-RS 자원이나 `@ServerEndpoint`는 r9에서는 잡혔고 r10에서는 잡히지 않는다. 탐침 P1·P2가 두 커밋에서 반대로 나왔다. 최상위 클래스로 두면 r10도 잡는다(P1c). + - 두 목록이 왜 다른지 적힌 곳이 없다. Javadoc(`:520-532`)은 요청 처리기 목록을 "controller, route, servlet, filter, interceptor, WebSocket handler, GraphQL, gRPC"로 적고 JAX-RS를 말하지 않는다. +- **발생 조건·영향**: + - 조건: 파생 서비스가 JAX-RS나 주석형 JSR-356 endpoint를 쓰고, 그 endpoint 클래스를 작업 bean을 등록하는 설정 안에 중첩해 둔다. 이 템플릿에는 두 런타임이 없어서 드물다. + - 영향: 인증만 된 사용자 요청이 권한 검사 없는 `@SystemInvoked` 쓰기를 부른다. 빌드는 신호를 내지 않는다. RR3-01-01·RR6-01-01과 같은 피해다. + - Minor로 둔 이유: 두 전송 모두 템플릿에 없는 런타임이고, 중첩 위치까지 겹쳐야 한다. 다만 이 커밋이 만든 회귀라 따로 센다. +- **테스트가 못 본 이유**: 새 fixture는 `HandlerFunction`(목록에 있음)을 중첩한 모양 하나뿐이다. r9가 잡던 중첩 모양 가운데 목록 밖 타입을 쓴 것은 없다. +- **고치는 법**: + - 권장: 설정 클래스 **자신**만 `ARE_REQUEST_HANDLER_TYPES`로 보고, 중첩 클래스는 r9처럼 `ARE_USER_TRANSPORT_TYPES`로 본다. 대신 RR6-01-02 모양(익명 `WebMvcConfigurer`가 바깥 필드를 읽음)은 "바깥 설정 인스턴스(`this$0`)로 가는 의존만 있는 경로"를 빼는 식으로 따로 허용한다. 그러면 두 목록의 차이가 중첩 클래스에 새지 않는다. + - 대안 1: `ARE_REQUEST_HANDLER_TYPES`에 `jakarta.ws.rs..`, `jakarta.websocket.server..`, `jakarta.websocket.OnMessage`·`OnOpen`을 더한다. 간단하지만 두 목록이 계속 갈라질 수 있어(A1), 두 목록의 차이를 단언하는 테스트를 같이 둬야 한다. + - 대안 2: 요청 처리기 목록을 `ARE_USER_TRANSPORT_TYPES`에서 "설정용 타입"(`WebMvcConfigurer`, `CorsRegistry`, `…config.annotation..`)을 뺀 것으로 정의해 목록을 하나로 만든다. + - RED 테스트 모양: 탐침 P1·P2를 위반 fixture로 옮긴다(`rr7-probes/…/probe/rr7/NestedJaxRsConfiguration.java`, `NestedServerEndpointConfiguration.java`). `06f520e6`에서 위반 0으로 실패해야 한다. +- **이번 수정 / 이전부터**: 이번 수정(회귀). +- **증거**: E2 — 명령 1·2(탐침 P1·P1c·P2를 두 커밋에서 실행). 코드 경로는 E1. +- **다른 리뷰와 합침**: 같은 커밋을 따로 본 리뷰(`claude/t1-baseline-7d623a` `3add4917`, `round7/review.md`의 RR7-01-01)가 같은 결함을 같은 모양(중첩 `@Path`·`@ServerEndpoint`, r9 위반 1건 → r10 0건)으로 찾았다. 그 리뷰는 WebFlux `WebFilter`·`WebHandler`도 같은 방식으로 빠진다고 적었다(E1). 결함 하나로 센다. +- **3차 합침(2026-11-07)**: 1차 「Declined to judge」 첫째 항목(WebFlux `WebFilter`·`WebHandler`가 요청 처리기 목록에 없음)도 같은 원인이다. r9는 설정에 중첩된 클래스를 `org.springframework.web..` 전체로 봤다. README 18.5절에서 (a)로 판정해 이 결함에 합쳤다. + +### RR7-01-02 · Minor · 메서드 참조로 함수형 route만 등록한 설정도 사용자 전송으로 세어, 같은 설정이 handler bean을 등록하면 거짓 실패한다 — Javadoc·매뉴얼은 "요청 처리 코드가 있을 때만"이라고 적는다 + +- **위치**: + - 코드: `ApplicationBoundaryArchitectureTest.java:525-527`(Javadoc "A configuration names one only when request-handling code is in it"), `:574-579`(설정이 `RouterFunctions` 같은 목록 타입에 의존하기만 하면 전송). + - 문서: `docs/manual/07-authorization.md:105`("요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다"), `docs/upgrade/2026-11-maturity-review.md` B-16("요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다"). +- **무엇이 틀렸나**: + - 설정이 `RouterFunctions.route().GET("/orders", orders::list)`처럼 메서드 참조로 route를 등록하면, 요청 처리 코드는 `OrderHandler`에 있고 설정에는 없다. + - 그래도 설정은 `org.springframework.web.servlet.function..` 타입에 의존하므로 사용자 전송이 된다. 같은 설정이 `@SystemCaller` bean을 `new`로 만들면 위반이다(탐침 P3). route만 있는 설정은 통과한다(P3c). + - Javadoc은 "요청 처리 코드가 있을 때만" 설정이 요청 처리기 타입을 부른다고 적는다. 매뉴얼과 업그레이드 안내는 "요청 처리 코드를 다른 클래스에 두라"고만 한다. 그대로 따라 처리 코드를 `OrderHandler`로 옮겨도 빌드는 실패하고, 메시지는 요청이 지나가지 않는 경로를 말한다. +- **발생 조건·영향**: 함수형 endpoint를 쓰는 서비스가 한 기능의 설정에 route 등록과 예약 작업 bean을 함께 둔다. Spring 문서가 보여 주는 route 등록 모양 그대로다. 빌드가 실패하는 쪽(거짓 실패)이라 데이터·권한 피해는 없다. 고치는 사람은 안내와 다른 이유로 막힌다. +- **테스트가 못 본 이유**: 허용 fixture는 `WebMvcConfigurer`와 controller bean 두 모양뿐이다. route를 등록하지만 처리 코드는 없는 설정의 fixture가 없다. +- **고치는 법**: + - 권장: 문서를 동작에 맞춘다. 매뉴얼 07 ②·B-16·Javadoc에 "함수형 route·data fetcher·interceptor를 **등록하는** 설정은 처리 코드가 다른 클래스에 있어도 사용자 전송이다. route 등록은 handler bean을 만드는 설정과 다른 설정에 둔다"를 적는다. 탐침 P3을 "걸리는" fixture로 남긴다. + - 대안: 판정을 좁힌다. 설정이 요청 처리기 타입에 의존해도, 설정 자신의 메서드(람다 본문 포함)가 `@SystemCaller` 쪽으로 가는 호출을 갖지 않으면 빼는 식이다. 정확하지만 ArchUnit 규칙이 복잡해지고, `@Bean` 메서드가 작업을 `new`하는 호출과 람다 안 호출을 구별해야 한다. + - RED 테스트 모양: 권장안이면 문서 변경이라 RED가 없다. 대안이면 P3을 허용 fixture로 두고 `06f520e6`에서 위반 1로 실패하는 것을 본다. +- **이번 수정 / 이전부터**: 이번 수정(r9에서는 설정을 통째로 뺐으므로 P3이 통과했다). +- **증거**: E2 — 명령 1·2(탐침 P3·P3c). 문서 대조는 E1. +- **같은 모양(2차)**: 다른 리뷰(`3add4917`)가 Declined로 적은 경우도 같은 원인이다. `ARE_REQUEST_HANDLER_TYPES`가 `org.springframework.web.bind.annotation..`·`jakarta.servlet.http..`를 패키지째 담아, `@CrossOrigin`·`RequestMethod`(CORS 설정에서 흔함)나 `HttpServletRequest`를 쓰는 설정이 handler bean을 함께 등록해도 거짓 실패한다(E1). 고칠 때 이 모양도 허용 fixture로 둔다. + +## Declined to judge + +- `ARE_REQUEST_HANDLER_TYPES`에 빠진 다른 타입(예: 리액티브 `org.springframework.web.server.WebFilter`·`WebHandler`): 이 템플릿은 서블릿 스택이고 WebFlux가 classpath에 없다. 목록 방식의 한계로 매뉴얼 07 `:128-129`가 적는다. RR7-01-01은 r9가 잡던 모양만 다룬다. +- gRPC: 취소된 호출에서 carrier나 IAE로 끝나면 여전히 로그가 남는다. 문서(`src/adapter/inbound/grpc/README.md`)는 "인식 못 한 실패"에 대해서만 취소를 빼므로 어긋나지 않는다. +- gRPC: 서비스가 raw status를 다른 예외로 감싸 던지면(`new IllegalStateException("…", statusException)`) 원인 사슬의 status 설명이 스택에 남는다. RR6-01-05가 약속한 것은 "서비스가 끝낸 raw status"라 범위 밖으로 봤다. 입력값 유출 정책을 넓힐지는 결정할 일이다. +- round6 01의 「Declined to judge」 7건은 2차에서 판정했다(README 18.5절). 그중 둘이 아래 RR7-01-05·06이 됐다. + +## 결론 + +Critical 0, Important 0, 회귀 1(RR7-01-01). 결함 2건, 모두 Minor, 모두 이번 수정이 만들었다. + +- RR6-01-01~09는 모두 닫혔다. 주장한 fixture·테스트가 있고 이름대로 본다. +- 새 결함 둘은 RR6-01-01·02를 고친 방법에서 나왔다. 하나는 r9가 잡던 중첩 endpoint를 놓치는 회귀, 하나는 안내대로 해도 실패하는 거짓 실패다. + +## 2차 추가 결함 (2026-11-06, 총괄 요청) + +총괄이 세 가지를 더 맡겼다. 같은 커밋을 따로 본 리뷰(`claude/t1-baseline-7d623a` `3add4917`)의 발견 중 이 리뷰와 겹치지 않는 것, 다른 세션이 +코드 읽기로만 찾은 결함 후보 하나, round6 01의 「Declined to judge」 판정. 넘겨받은 발견은 그쪽 근거를 읽은 뒤 이 리뷰의 기준 커밋 +`06f520e6`에서 탐침을 다시 돌려 확인했다. + +### 2차 실행 + +desktop 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`, 다시 만들고 끝나고 지움), 공유 잠금 아래. 로그 `~/t1-r10-review-logs/`, +탐침 코드와 결과는 공유 노트 `rr7-probes/pass2/`·`rr7-probes/results/pass2-06f520e6.txt`. + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 4 | `./gradlew :adapter:inbound:web:test --tests …Rr7LockTimeoutWebProbeTest` | rc=0. `GlobalExceptionHandler.handleUnknown`이 `LockAcquisitionTimeoutException`에 500 `INTERNAL_ERROR` `retryable=false` | 1.32 | +| 5 | `./gradlew :adapter:inbound:graphql:test --tests …Rr7LockTimeoutGraphQlProbeTest` | rc=0. `GraphQlWireErrorMapper.masking()`이 같은 예외를 `INTERNAL_ERROR`·`INTERNAL`·`retryable=false`로 | 1.73 | +| 6 | `./gradlew :adapter:inbound:grpc:test --tests "…GrpcExceptionHandlingInterceptorTest.rr7probe*"` (다른 리뷰의 탐침을 결과를 파일로 쓰게 바꿔 기존 테스트 클래스에 끼움) | rc=0. 던짐: `INTERNAL`, ERROR 한 줄에 `IllegalArgumentException: unknown recipient alice@example.com` 첨부. 넘김: `INVALID_ARGUMENT`, WARN 한 줄(메시지 없음) | 2.01 | + +### RR7-01-03 · Minor · gRPC 서비스가 `IllegalArgumentException`을 원인으로 든 raw status를 던지면 `INTERNAL_ERROR`로 답하고 그 메시지를 ERROR로 남긴다 — 같은 status를 `onError`로 넘기면 `BAD_PARAMETER`·WARN이다 + +- **출처**: 다른 리뷰 `3add4917` `round7/review.md` RR7-01-02. 그쪽 근거(코드 경로·탐침)를 확인하고 명령 6으로 다시 재현했다. +- **위치**: + - 코드: `src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptor.java:137`(`status.getCause() instanceof IllegalArgumentException` — 던진 경우 원인 자리에는 status 예외가 있다), `:153`(`closeWithError`가 던진 예외 자체를 status의 원인으로 둔다), `:156-178`(`logUnrecognised`가 `failureBehind`로 status 예외를 벗겨 그 뒤의 IAE를 붙인다). + - 문서: `src/adapter/inbound/grpc/README.md:157-158`("`IllegalArgumentException`은 … WARN 한 줄 … 메시지 없음"), `:160`("raw status는 `onError`로 넘겼든 던졌든"), `src/shared-contract/README.md:94-98`("네 전송 모두 … 메시지는 … 남기지 않고 예외도 붙이지 않는다"). +- **무엇이 틀렸나**: + - `onError(Status.INVALID_ARGUMENT.withCause(iae).asRuntimeException())`는 `close(Status.fromThrowable(t))`가 되어 status의 원인이 IAE다. `BAD_PARAMETER`·WARN. + - 같은 예외를 던지면 원인 자리에 status 예외가 온다. `:137` 판정이 IAE를 보지 못해 `INTERNAL_ERROR`로 답한다. + - 이어서 r10의 `failureBehind`가 status 예외를 벗기고 IAE를 ERROR 줄에 붙인다. 입력값이 든 메시지가 로그에 남는다. +- **발생 조건·영향**: 입력 검증 실패를 `Status.INVALID_ARGUMENT.withCause(e).asRuntimeException()`로 던지는 서비스(grpc-java의 흔한 모양). 클라이언트는 재시도할 수 없는 `INTERNAL`을 받고, 서버 로그에 입력값이 ERROR와 스택으로 남는다. grpc 어댑터는 기본 조립에 없어 Minor. +- **테스트가 못 본 이유**: r10의 테스트는 원인이 `IllegalStateException`인 raw status와 원인 없는 raw status만 던진다. +- **고치는 법**: `close`에서 판정용 원인을 `failureBehind(status.getCause())`로 한 번 구해 carrier·IAE 판정과 로그에 같은 값을 쓴다. 대안: `closeWithError`가 던진 예외가 `StatusRuntimeException`·`StatusException`이면 그 status를 그대로 쓰고 원인은 status의 원인으로 둔다. RED: 명령 6의 탐침을 "던짐과 넘김의 status·로그 줄이 같다"는 단언으로 옮긴다. 지금 `INTERNAL ≠ INVALID_ARGUMENT`로 실패한다. +- **이번 수정 / 이전부터**: 이전부터. r9도 같은 답을 했다. r10이 RR6-01-05를 고치며 이 경로를 다시 썼는데 이 경우를 놓쳤다. +- **증거**: E2 — 명령 6. r9 동작은 다른 리뷰의 E1. + +### RR7-01-04 · Important · `LockAcquisitionTimeoutException`은 오류 코드를 운반하는 타입이 아니고 받는 처리기도 없어, 409 `LOCK_ACQUISITION_TIMEOUT`(재시도 가능) 대신 500 `INTERNAL_ERROR`(재시도 불가)로 답한다 + +- **출처**: 다른 세션이 코드 읽기로 찾은 후보(총괄 전달). 명령 4·5로 확인했다. +- **위치**: + - 코드: `src/application-core/src/main/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutException.java:13`(`extends RuntimeException`만, `ApiErrorCarrier` 아님), `:6-11`(Javadoc "The web adapter maps it to 409"), `src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java:195-202`(carrier가 아니면 `INTERNAL_ERROR`), GraphQL `GraphQlWireErrorMapper.java:199-206`(`sharedCodeOf`도 carrier만). + - 계약·문서: `docs/registries/error-codes.yaml:777-785`(409, `retryable: true`, `retry_after_seconds: 1`), `docs/runbooks/lock-acquisition-timeout.md:15`(증상 "HTTP 409 with `error.code=LOCK_ACQUISITION_TIMEOUT`"), `src/application-core/README.md:574-580`("web adapter 가 `errorCode()` + 고정 client-safe 메시지로 409 를 만든다"). + - 테스트: `src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockAcquisitionTimeoutClassificationContractTest.java:20-27`(Javadoc "D7 forbids collapsing a lock-acquisition timeout to a generic 500"), `:84-90`(예외의 `errorCode()`만 본다). +- **무엇이 틀렸나**: + - 예외는 `errorCode()` 메서드를 갖지만 `ApiErrorCarrier`를 구현하지 않는다. 전송들은 `ApiErrorCarrier`인지로만 코드를 읽는다. + - 이 예외를 받는 `@ExceptionHandler`도, GraphQL·gRPC 매핑도 없다(grep: main 코드에서 이 타입을 아는 곳은 던지는 persistence-jpa lock 둘과 지표 decorator뿐). + - 그래서 web은 500 `INTERNAL_ERROR` `retryable=false`(명령 4), GraphQL은 `INTERNAL_ERROR`(명령 5)로 답하고 "unhandled exception"으로 ERROR를 남긴다. gRPC도 carrier가 아니라 `INTERNAL`이다(E1). + - 레지스트리·runbook·Javadoc·README는 409 재시도 가능을 약속한다. 분류 계약 테스트는 "일반 500으로 뭉개지 않는다"(D7)를 이름에 걸지만 enum과 레지스트리 행만 본다. +- **발생 조건·영향**: + - 조건: 파생 서비스가 분산 lock capability(`DistributedLockPort.tryAcquire`)를 요청 처리 경로에서 쓰고 경합이 생긴다. 템플릿 자체의 운영 코드에는 호출자가 없다. + - 영향: 클라이언트는 재시도하면 될 경합을 재시도 불가 500으로 받는다. 운영자는 runbook대로 409를 찾지만 500 `INTERNAL_ERROR`와 "unhandled exception" ERROR만 보인다. 공개 계약(오류 코드 레지스트리)과 다른 응답이라 Important다. +- **테스트가 못 본 이유**: 분류 계약 테스트가 enum·레지스트리만 보고, 실제 전송 응답을 보는 테스트가 없다(A6 — 이름이 말한 성질을 단언하지 않음). +- **고치는 법**: + - 권장: `LockAcquisitionTimeoutException`이 `ApiErrorCarrier`를 구현한다(`errorCode()`의 반환 타입을 `ApiErrorCode`로). 그러면 네 전송이 따로 고치지 않아도 409·`Retry-After: 1`·4xx라 로그 없음으로 답한다. + - 대안: web에 전용 `@ExceptionHandler`를 둔다. web만 고쳐지고 GraphQL·gRPC는 그대로라 권하지 않는다. + - RED: 명령 4의 탐침을 `GlobalExceptionHandlerTest`에 "409·`LOCK_ACQUISITION_TIMEOUT`·`retryable=true`·`Retry-After`" 단언으로 옮긴다. 지금 500으로 실패한다. 분류 계약 테스트에 "예외가 `ApiErrorCarrier`다"를 더한다. +- **이번 수정 / 이전부터**: 이전부터(r10이 바꾼 파일이 아니다). +- **증거**: E2 — 명령 4·5. gRPC는 E1. + +### RR7-01-05 · Minor · 다른 예외에 감싼 carrier를 web·GraphQL·STOMP는 못 보고 gRPC만 원인 사슬에서 찾아, 같은 실패의 응답 코드와 로그가 전송마다 다르다 + +- **출처**: round6 01 「Declined to judge」 첫째 항목(README 18.5절 판정 (c)). 응답 코드가 바뀌는 수정이라 방향은 소유자 결정이다(README 18.4절). +- **위치**: web `GlobalExceptionHandler.java:195-198`(`ex instanceof ApiErrorCarrier`), GraphQL `GraphQlWireErrorMapper.java:200`, STOMP `StompHandlerFailureLog.java:34`, gRPC `GrpcExceptionHandlingInterceptor.java:180-192`(`carrierOf`가 원인 사슬을 따라감). 약속: `src/shared-contract/README.md` 「ServerFailureLog」("전송은 같은 줄을 쓴다", persistence 실패는 분류만). +- **무엇이 틀렸나**: 서비스가 `PersistenceFailureException`을 다른 예외로 감싸 던지면 web·GraphQL·STOMP는 500 `INTERNAL_ERROR`로 답하고 "unhandled"로 원인 사슬째(SQL 원인 포함) ERROR를 남긴다. gRPC는 감싼 carrier의 코드로 답하고 분류만 남긴다. 같은 규칙(실패 → 코드·로그)이 전송마다 다시 구현돼 갈라졌다(A1). web 쪽은 A8(SQL 원인을 로그에 싣지 않는다)도 어긴다. +- **발생 조건·영향**: use case나 adapter가 carrier를 감싸 던질 때. 템플릿 코드에는 그런 곳이 없다(round6 01 확인). 같은 실패에 클라이언트가 받는 코드가 전송마다 다르고, web 로그에 SQL 값·제약 이름이 남는다. +- **테스트가 못 본 이유**: 전송 테스트가 모두 맨 위 carrier만 넣는다. +- **고치는 법**: shared-contract에 "원인 사슬의 첫 carrier"를 찾는 함수 하나를 두고 네 전송이 쓴다(gRPC의 `carrierOf`를 옮김). 방향 선택지는 README 18.4절. RED: 네 전송 테스트에 감싼 `PersistenceFailureException`을 넣어 코드와 로그 줄이 같음을 단언한다. +- **이번 수정 / 이전부터**: 이전부터. +- **증거**: E1(네 전송의 판정 코드). 실행 탐침 없음 — 판정이 `instanceof` 한 줄이라 코드로 결정적이다. + +### RR7-01-06 · Minor · STOMP `@MessageMapping`의 payload 변환·검증 실패(`MessageConversionException`, `MethodArgumentNotValidException`)를 ERROR로, 예외 메시지(입력 조각)까지 남긴다 + +- **출처**: round6 01 「Declined to judge」 다섯째 항목(README 18.5절 판정 (a)). +- **위치**: `src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLog.java:32-45`(carrier·IAE가 아니면 `log.error("unhandled failure in a STOMP message handler", failure)`). 기준: `docs/work/reference/defect-patterns.md` A8("클라이언트 탓 실패(입력 오류)는 WARN 한 줄로 남기고 입력값을 싣지 않는다"). +- **무엇이 틀렸나**: payload를 읽지 못하거나 검증에 실패한 메시지는 클라이언트 탓 실패다. r10은 IAE만 WARN 한 줄로 바꿨고, 변환·검증 실패는 여전히 ERROR와 예외 전체로 남는다. Jackson 변환 실패 메시지는 받은 JSON 조각을 담는다. +- **발생 조건·영향**: 잘못된 JSON이나 검증에 걸리는 payload를 보내는 클라이언트마다 ERROR 한 줄과 스택이 남고, 입력 조각이 로그에 실린다. 경보가 ERROR에 걸리면 클라이언트 실수가 사고로 보인다. +- **테스트가 못 본 이유**: `StompHandlerFailureLogTest`에 변환·검증 실패 케이스가 없다. +- **고치는 법**: `MessageConversionException`·`MethodArgumentNotValidException`(Spring messaging)을 IAE와 같이 `BAD_PARAMETER`/`VALIDATION_FAILED`의 WARN 한 줄(타입만)로 남긴다. 프레임 응답은 그대로(보내지 않음). RED: 실제 `WebSocketAnnotationMethodMessageHandler`로 깨진 JSON payload를 보내 ERROR가 남는 것을 본다(round6 01 탐침 `Rr6StompProbeTest`의 모양). +- **이번 수정 / 이전부터**: 이전부터(r10이 같은 클래스에 IAE만 더함). +- **증거**: E1. 실행 탐침은 돌리지 않았다(Spring이 변환 실패를 `@MessageExceptionHandler`로 넘기는 경로는 round6 01이 같은 handler로 확인한 경로와 같다). + +### 2차 반영 뒤 결론 + +Critical 0, Important 1(RR7-01-04), 회귀 1(RR7-01-01). 결함 6건: 이번 수정 2(RR7-01-01·02), 이전부터 4(RR7-01-03~06). diff --git a/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md b/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md new file mode 100644 index 00000000..9112b1c8 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round7/02-idempotency-outbound.md @@ -0,0 +1,136 @@ +# 02 멱등성·outbound r10 확인 리뷰 (2026-11-06) + +> 대상: `6e992970`(r10)의 r10-02 묶음. RR6-02-01~05 수정: 같은 attempt의 재claim이 lease 지난 claim과 재시도 가능 실패를 +> 넘겨받음, 시작 확인을 그 시작을 적용한 핸들로만, command fake의 시계·key TTL, 503 뜻과 매뉴얼 05 문구. +> 기준 커밋 `06f520e6`(이 영역의 코드는 `6e992970` 뒤로 바뀌지 않았다). + +## 범위 + +### pathspec + +``` +src/application-core src/adapter/outbound/cache-redis src/adapter/outbound/redis-runtime +src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency +docs/manual/05-idempotency.md +``` + +`git diff --shortstat 6e992970^ 6e992970 -- `: 15개 파일, +407 −458. 함께 본 것: `src/adapter/inbound/web/README.md`의 503 행, +`docs/upgrade/2026-11-maturity-review.md` 「멱등성(같은 attempt의 재시도, r10)」 행, `src/adapter/outbound/persistence-jpa/README.md`의 +멱등성 문단, `docs/study/postgresql-jpa-walkthrough.ko.md` 1720줄 근처의 판정 순서표. + +함께 읽은 주변 코드: `IdempotencyExecutor`의 claim·시작·재조정 분기 전체(`:126-232`), Redis `CLAIM`·`TRANSITION` 프로그램 전체 +(`IdempotencyScripts.java`), `PostgreSqlIdempotencyStore.claim`·`markExecutionStarted`, `InMemoryIdempotencyStore` 전체, +`InMemorySemanticRedisCommands`의 CLAIM·TRANSITION·RENEW·INSPECT 사본, 샘플 `PublishPosterImageUseCase:106`(요청마다 새 attempt). + +### 수정 보고의 「새로 가정하는 것」 + +| 가정 | 확인 | +|---|---| +| 같은 attempt를 두 호출이 **동시에** 쓰지 않는다(호출자 계약) | 문서화는 됐다: `IdempotencyClaimAttempt` Javadoc, 매뉴얼 05 `:77-79`, application-core README. 템플릿의 HTTP 경로는 요청마다 새 attempt를 만든다(샘플 `PublishPosterImageUseCase.java:106`). 계약을 어기면 두 번째 호출은 `NOT_CLAIMED` → 500 `IDEMPOTENCY_RECOVERY_REQUIRED`를 받고 작업은 두 번 돌지 않는다(E1, 아래 시나리오 3) | +| 시작이 적용된 기록의 revision은 그 시작을 낸 핸들 revision + 1뿐이다 | 참. 넘겨받기는 늘 revision을 올리고(`CLAIM`의 `rev + 1`, PG `resetClaim`), 시작 전에 revision을 바꾸는 다른 전이가 없다. renew는 실행 중에만 된다 | +| 넘겨받기 판정을 같은 attempt 재생보다 먼저 해도 지문 불일치·완료 재생 판정은 그대로다 | 참. 세 저장소 모두 지문 → 완료 → 포기 → 넘겨받기 → 같은 attempt 순서다(Redis `CLAIM`, PG `PostgreSqlIdempotencyStore.java:117-171`, fake `InMemoryIdempotencyStore.java:52-86`) | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 테스트가 이름대로 보는가, 읽기 전용 | RR6-02-01~05 닫힘, 바뀐 판정 순서가 다른 경로에 미치는 영향 | +| `docs/work/reference/defect-patterns.md` A4·A5·A6 | 결과 불명을 확실함으로, 경쟁을 코드 순서로, 주장하는 것을 보지 않는 테스트 | 같은 attempt의 늦은 시작·재생 핸들 시작이 작업을 두 번 돌리는 길이 남았나, 계약 케이스가 그 길을 보나 | + +### 실행한 명령과 결과 + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 1 | `./gradlew … :application-core:test :adapter:outbound:redis-runtime:test :adapter:outbound:cache-redis:test :adapter:outbound:persistence-jpa:test … --continue` (`06f520e6`, desktop) | README 18.3절 | README 18.3절 | + +실 Redis·실 PostgreSQL 계약 lane(`redisContainerContractTest`, `jpaPlatformContractTest`의 멱등성 계약, `postgresqlIdempotencyIntegrationTest`)은 +다시 돌리지 않았다. 17.2절의 `2c692554` 실행이 마지막이다(E0). 이 영역에서 결함을 찾지 못해 실 vendor로 확인할 의심이 없었다. + +### 따라간 시나리오 (E1) + +1. **시작을 거절당한 attempt의 재시도**: claim(rev r) → lease 지남 → 시작 `LEASE_EXPIRED`(503) → 같은 attempt 재claim → 세 저장소 모두 + `TakenOverClaimed`(attempt 2, rev r+1) → 시작 → 실행. 계약 `anAttemptWhoseStartWasRefusedTakesItsClaimOverWhenItClaimsAgain`. +2. **멈췄던 첫 호출의 늦은 시작**: 위 1의 넘겨받기 뒤 첫 호출이 rev r 핸들로 시작 → Redis `TRANSITION`은 상태가 목표와 같아도 rev가 + r+1이 아니면(넘겨받은 쪽이 시작했으면 r+2) `ALREADY`를 주지 않고 rev 검사로 `NOT_OWNER`. PG는 기록된 시작 digest가 다른 핸들의 것이라 + `classifyStartMismatch` → `NOT_OWNER`. 계약 `aLateStartThroughTheHandleBeforeTheTakeoverIsRefusedAsAStaleOwner`. +3. **같은 attempt의 두 번째 호출이 실행 중에 옴**: 재claim은 `ReplayedAcquire`(현재 핸들) → 시작 → `NOT_CLAIMED` → executor `default` + → 500. 전에는 Redis가 `ALREADY`로 작업을 한 번 더 돌렸다. 계약 `theSameAttemptStartingAnExecutionItAlreadyStartedIsToldItIsNotClaimed`. +4. **시작 응답을 잃은 호출의 같은 호출 안 회복**: `INDETERMINATE` → `inspect` → `EXECUTING_SAME_OPERATION` → `runStarted`. 바뀐 `ALREADY` + 조건은 같은 핸들(rev r → 기록 r+1)이라 그대로 확인된다. + +## 못 본 것 + +- 실 Redis·실 PostgreSQL에서의 재실행(위 설명). +- 배포 중 섞인 버전(옛 인스턴스의 `TRANSITION`은 재생 핸들 시작에 `ALREADY`): round6 02의 Declined to judge에 이미 있다. 2차에서 + 결함 아님으로 닫았다(README 18.5절). + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR6-02-01 (시작 거절 뒤 같은 attempt가 영원히 503) | 닫힘 | Redis `IdempotencyScripts.java` CLAIM의 넘겨받기 분기가 같은 owner 재생보다 앞, PG `PostgreSqlIdempotencyStore.java:141-160`, fake `InMemoryIdempotencyStore.java:71-84`, command fake 같은 순서. 계약 케이스 6개 추가(위 시나리오 1~3과 재시도 가능 실패·포기·지문) | +| RR6-02-02 (command fake 위 시간 케이스 skip) | 닫힘 | `RedisIdempotencyStoreContractTest`가 `elapse`를 `commands.advance`로 재정의, command fake의 hash TTL(`InMemorySemanticRedisCommands`의 `expireHashAfter`·`hash`). adapter 손 사본 20개 삭제는 "계약과 겹친 것"이라는 README 17절 설명을 따랐다(E0). 하나씩 계약 케이스와 대조하지는 않았다 | +| RR6-02-03 (runbook "message") | 닫힘 | 01의 RR6-01-07과 같은 문장. `docs/runbooks/idempotency-unavailable.md:22-25` | +| RR6-02-04 (503 뜻이 웹 매핑 표·인계 표에 없음) | 닫힘 | `src/adapter/inbound/web/README.md` 503 행, `docs/upgrade/2026-11-maturity-review.md` 프론트 인계 표 503 행 | +| RR6-02-05 (매뉴얼 05 첫 문장과 PG 항목 어긋남) | 닫힘 | `docs/manual/05-idempotency.md:57-61`이 저장소별로 나눠 적는다 | + +## 결함 + +없음. + +## Declined to judge + +- `InMemoryIdempotencyStore`는 시작 응답을 잃은 같은 핸들의 재시작(기록 rev r+1, 핸들 rev r)에 `NOT_OWNER`를 준다. 두 저장소는 + `ALREADY_STARTED_SAME_OPERATION`이다. fake는 응답 유실을 만들지 못하고 계약에 그 케이스가 없어 드러나지 않는다. 이 커밋 전부터이고, + fake와 저장소의 차이를 계약 밖에서 고칠지는 범위 밖이다. +- 같은 owner token에 다른 operation id로 온 claim이 재시도 가능 실패·lease 지난 claim을 만나면, 전에는 `OwnerOperationConflict`(500)였고 + 이제 넘겨받는다(넘겨받기가 같은 owner 판정보다 앞이 되어서). 아무것도 실행되지 않은 기록이라 안전하고, 계약에 이 경우 케이스가 없다. + 동작 변경으로 적어 둔다. 업그레이드 안내에는 없다. +- round6 02의 「Declined to judge」 6건은 2차에서 판정했다(README 18.5절). 그중 하나가 아래 RR7-02-01이 됐다. + +## 결론 + +Critical 0, Important 0, 회귀 0. 결함 0건. RR6-02-01~05는 모두 닫혔다. 바뀐 판정 순서와 시작 확인 조건은 세 저장소·두 fake에서 +같고, 같은 attempt의 늦은 시작·재생 핸들 시작으로 작업이 두 번 도는 길은 남지 않았다(E1). 실 vendor 재실행은 하지 않았다. + +## 2차 추가 결함 (2026-11-06, 총괄 요청) + +round6 02의 「Declined to judge」를 판정하며(README 18.5절) 하나를 결함으로 올렸다. 다른 리뷰(`3add4917`)는 이 영역에서 새 결함을 적지 않았다. + +### RR7-02-01 · Minor · `ClientRuntimeRegistry.close()`는 닫는 스레드가 interrupt 상태면 drain 스레드가 끝났는지 보지 않고 정상으로 돌아온다 — "돌아오면 스레드가 남지 않는다"는 약속과 다르다 + +- **출처**: round6 02 「Declined to judge」 둘째 항목(README 18.5절 판정 (a)). +- **위치**: `src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistry.java:164-171`(Javadoc "Joining the thread is what makes 'no thread left' true when this returns"), `:181`·`:186`(`awaitTermination`·`join`은 interrupt 상태면 바로 `InterruptedException`), `:192-194`(잡아서 flag만 되살리고 반환), `:148-161`(`close()`는 그대로 정상 종료). +- **무엇이 틀렸나**: 16.1절 수정이 "close가 돌아오면 drain 스레드가 없다"를 join으로 보장했다. 그런데 닫는 스레드가 이미 interrupt 상태면 기다리는 첫 호출이 곧바로 예외를 내고, 그 catch는 flag를 되살린 뒤 아무 확인 없이 돌아온다. `close()`는 예외 없이 끝나지만 drain 스레드는 살아 있을 수 있다. 다른 실패 경로(`awaitTermination` 시간 초과, join 뒤 생존)는 `IllegalStateException`을 던지는데 interrupt 경로만 조용하다(A14). +- **발생 조건·영향**: interrupt된 스레드에서 registry를 닫는 경우(종료 훅을 interrupt로 끊는 런처, 테스트 프레임워크의 시간 제한 interrupt 뒤 정리). Spring 기본 종료 스레드는 보통 interrupt되지 않아 드물다. 그때 스레드가 남아도 호출자는 모른다. +- **테스트가 못 본 이유**: `ClientRuntimeRegistryTest`의 두 스레드 테스트가 interrupt되지 않은 스레드에서만 닫는다. +- **고치는 법**: interrupt를 받으면 남은 마감까지 interrupt를 무시하고 기다린 뒤(끝에 flag 복원) 스레드 생존을 확인하고, 살아 있으면 다른 경로처럼 `IllegalStateException`을 던진다. 대안: interrupt 경로에서도 바로 `IllegalStateException("interrupted before the drain thread exited")`를 던진다(더 단순하지만 정상 종료가 실패로 보일 수 있다). RED: 테스트 스레드에 `Thread.currentThread().interrupt()` 뒤 `close()`를 부르고, 돌아온 직후 drain 스레드가 살아 있으면 예외가 있었어야 함을 단언한다. +- **이번 수정 / 이전부터**: 이전부터(r9 16.1절 수정). r10이 바꾼 파일이 아니다. +- **증거**: E1(코드 경로). 실행 탐침은 돌리지 않았다 — interrupt 상태에서 `awaitTermination`이 바로 던지는 것은 `ThreadPoolExecutor` 계약이고, 그 뒤 경로는 catch 블록 하나라 코드로 결정적이다. + +### 2차 반영 뒤 결론 + +Critical 0, Important 0, 회귀 0. 결함 1건(RR7-02-01, Minor, 이전부터). 멱등성 쪽 r10 변경에서 찾은 새 결함은 여전히 0이다. + +## 3차 추가 결함 (2026-11-07, 총괄 요청) + +이 문서 1차 「Declined to judge」 둘을 판정했다(README 18.5절). 첫째를 결함으로 올리고, 둘째는 닫았다. 기준은 리뷰 브랜치를 fast-forward한 +`2c8a359d`다(t5 멱등 수정 `200019aa` 포함). + +### RR7-02-02 · Minor · in-memory fake는 시작을 적용한 그 핸들이 시작을 다시 보내면(응답 유실) `NOT_OWNER`로 답한다 — 두 저장소와 포트 Javadoc은 `ALREADY_STARTED_SAME_OPERATION`이다 + +- **출처**: 이 문서 1차 「Declined to judge」 첫째 항목(README 18.5절 판정 (a)). +- **위치**: + - fake: `src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java`의 `markExecutionStarted` — 시작하면 `row.advance(EXECUTING)`가 기록의 핸들(revision)을 바꾸고, 다시 온 같은 핸들은 `!row.owner.equals(owner)`로 `NOT_OWNER`가 된다. + - 약속: `IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION` Javadoc("This exact start — from the handle presented — was already applied (a lost reply)"). 저장소: Redis `TRANSITION`은 기록 revision이 핸들 + 1이면 `ALREADY`, PostgreSQL은 기록된 시작 digest가 같으면(`replayVerdict` `SAME_ARGUMENTS`) `ALREADY_STARTED_SAME_OPERATION`. + - 결정: 「넘겨받기 전 핸들의 재전송」(2026-11-06, `docs/work/reference/decisions.md` 2.4) — 이미 일어난 전이를 다시 보내면 그 전이를 실제로 적용한 핸들에게만 "이미 처리됨"으로 확인한다. fake는 그 핸들에게도 거절한다. +- **무엇이 틀렸나**: 포트 계약은 "시작 응답을 잃은 호출자가 같은 핸들로 다시 시작하면 이미 시작됐다고 확인한다"이다. 두 저장소는 그렇게 답하고 fake는 `NOT_OWNER`로 답한다. 공유 계약(`IdempotencyStoreContract`)에 그 케이스가 없어 fake가 계약 밖으로 갈라진 채 통과한다(A6). +- **발생 조건·영향**: fake 위에서 executor나 use case를 시험하는 테스트가 같은 핸들로 시작을 두 번 보내면, 운영 저장소에서는 계속 실행될 흐름이 fake에서는 "회복 필요"(500)로 끝난다. 테스트가 운영과 다른 답을 근거로 통과하거나 실패한다. +- **테스트가 못 본 이유**: 계약에 "같은 핸들로 시작 두 번" 케이스가 없다. fake는 응답 유실을 만들 수 없어도 같은 호출을 두 번 하는 것은 할 수 있다. +- **고치는 법**: 계약에 케이스를 더한다 — claim → 시작 → 같은 핸들로 다시 시작 → `ALREADY_STARTED_SAME_OPERATION`과 현재 핸들. fake는 시작을 적용한 핸들(revision)을 기억해 그 핸들이면 `ALREADY_STARTED_SAME_OPERATION`으로 답한다(complete의 `completedBy`와 같은 방식). RED: 그 계약 케이스가 fake 계약 테스트에서 `NOT_OWNER`로 실패한다. 두 저장소 계약 테스트는 통과해야 한다. +- **이번 수정 / 이전부터**: 이전부터. +- **증거**: E1(fake·두 저장소의 판정 코드). 실행 탐침은 돌리지 않았다 — fake 판정은 `equals` 한 줄이라 코드로 결정적이다. + +### 3차 반영 뒤 결론 + +Critical 0, Important 0, 회귀 0. 결함 2건(RR7-02-01·02, 모두 Minor, 이전부터). diff --git a/docs/reviews/2026-11-03-rereview/round7/03-persistence.md b/docs/reviews/2026-11-03-rereview/round7/03-persistence.md new file mode 100644 index 00000000..f425b1ff --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round7/03-persistence.md @@ -0,0 +1,219 @@ +# 03 persistence r10 확인 리뷰 (2026-11-06) + +> 대상: `6e992970`(r10)의 r10-03 묶음. RR6-03-01~05 수정: Flyway PostgreSQL 잠금을 세션 수준으로(module-defaults와 +> `FlywaySchemaPolicy.configure()`), 직접 `Flyway.configure()` 금지 규칙, 동시 인덱스 IT, 검사기의 `E'…'`·중첩 주석, +> Flyway 목록 고정 테스트, ledger Spotless, "Flyway는 늘 트랜잭션으로 감싼다" 설명 정정. +> 기준 커밋 `06f520e6`(이 영역의 코드는 `6e992970` 뒤로 바뀌지 않았다). + +## 범위 + +### pathspec + +``` +src/adapter/outbound/persistence-jpa ':!src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency' +':!src/adapter/outbound/persistence-jpa/gradle.lockfile' src/adapter/outbound/persistence-notification +src/adapter/inbound/messaging ':!src/adapter/inbound/messaging/gradle.lockfile' src/grpc src/sample-portfolio +src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java +docs/jpa docs/manual/04-persistence.md docs/study +``` + +`git diff --shortstat 6e992970^ 6e992970 -- `: 28개 파일, +877 −113(lockfile 두 줄 제외). 함께 본 것: +`docs/upgrade/2026-11-maturity-review.md` 2절 15번과 「Flyway 잠금」 행. + +함께 읽은 주변 코드: 운영 코드에서 Flyway를 만드는 모든 곳(`grep org.flywaydb`의 main 6개 파일), `MigrationStartupRunner`, +`src/grpc/CLAUDE.md` 「Durable operation ledger adoption」(ledger는 서비스 Flyway에 위치를 더한다), Flyway 11.14.1 +`PostgreSQLAdvisoryLockTemplate`(`javap`), `LockWaitMigrationInspector` 전체, round6 03. + +### 수정 보고의 「새로 가정하는 것」 + +| 가정 | 확인 | +|---|---| +| Flyway가 잡은 연결은 실행 내내 그것의 것이다(Hikari 직접 연결) | 참. Spring Boot의 Flyway와 템플릿 스트림 모두 애플리케이션 `DataSource`(Hikari)를 받는다. Flyway는 한 연결로 잠그고 푼다. PgBouncer transaction 모드에서 깨진다는 한계는 `docs/jpa/migration-guide.md:27-31`에 적혔다 | +| 세션 잠금으로 바꿔도 잠금 대기 동작은 같다 | 참. Flyway 11.14.1은 두 방식 모두 `pg_try_advisory_[xact_]lock`을 `lockRetryCount`만큼 다시 시도한다(`PostgreSQLAdvisoryLockTemplate.lock`, `javap`). 무한 대기로 바뀌지 않는다 | +| 배포 마이그레이션 도구도 같은 값을 쓴다 | 이 repo 밖이라 확인할 수 없다. 업그레이드 안내 2절 15번과 가이드 `:24-25`가 시킨다 | +| 템플릿이 직접 만드는 Flyway는 모두 `FlywaySchemaPolicy.configure()`를 거친다 | 운영 코드는 참(멱등성·알림·sample 스트림, schema-per-tenant, inbox는 같은 값 사본). 규칙은 `Flyway.configure()`·`configure(ClassLoader)` 호출만 본다(아래 Declined) | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 문서가 동작과 맞는가 | RR6-03-01~05 닫힘, 새로 쓴 설명이 Flyway 실제 동작과 맞나 | +| `supabase-postgres-best-practices` 관점(잠금·마이그레이션) | 강한 잠금은 시간 제한, 동시 빌드는 트랜잭션 밖, 오래된 트랜잭션 확인 | 세션 잠금의 전제, CIC 대기 대상 | +| `docs/work/reference/defect-patterns.md` A2 | 문서와 코드 불일치 | 고친 설명 문장마다 Flyway 실제 동작과 대조 | + +### 실행한 명령과 결과 + +desktop 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`), 공유 잠금 아래. 로그 `~/t1-r10-review-logs/`(desktop). + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 1 | `./gradlew :adapter:outbound:persistence-jpa:rr7ReindexProbe` — 탐침 `Rr7ReindexProbeIntegrationTest`를 임시 lane으로 등록(worktree의 `build.gradle`만 고침), 실 PostgreSQL(Testcontainers, `PostgreSqlReadinessSupport`) | rc=0, 19초. 결과는 아래 표 | 4.28 | +| 2 | `./gradlew … :adapter:outbound:persistence-jpa:test :adapter:outbound:persistence-notification:test :adapter:inbound:messaging:test … :app-bootstrap:architectureTest --rerun --continue` | rc=0. persistence-jpa `test` 664건 실패 0(실행, 임시 lane 때문에 캐시 아님), persistence-notification·messaging `test`는 FROM-CACHE, `architectureTest` 229건 실패 0(`--rerun`, 탐침 1건 포함) | 4.46 | +| 3 | `javap -c -p org.flywaydb.database.postgresql.PostgreSQLAdvisoryLockTemplate`(flyway-database-postgresql 11.14.1, 노트북 Gradle 캐시의 jar) | 세션 모드 `pg_try_advisory_lock` + `RetryStrategy` | — | + +탐침 1은 각 문장 하나만 든 `V1__reindex.sql`을 `.sql.conf` 없이 `FlywaySchemaPolicy.configure()`로 적용한다. Flyway가 트랜잭션 안에서 +돌리면 PostgreSQL이 `25001`로 거부하고, 트랜잭션 밖에서 돌리면 적용된다. + +| 문장 | 결과 | +|---|---| +| `REINDEX TABLE CONCURRENTLY probe` | 실패 `25001` (REINDEX CONCURRENTLY cannot run inside a transaction block) | +| `REINDEX INDEX CONCURRENTLY ix_probe_note` | 실패 `25001` | +| `REINDEX (CONCURRENTLY) TABLE probe` | 실패 `25001` | +| `REINDEX SCHEMA CONCURRENTLY public` | **적용됨**(Flyway가 트랜잭션 밖에서 돌림) | +| `REINDEX DATABASE CONCURRENTLY ` | **적용됨** | + +### 못 본 것 + +- `postgresqlConcurrentIndexMigrationIntegrationTest`·`postgresqlMigrationLockWaitIntegrationTest`·ledger `integrationTest`는 다시 돌리지 않았다. + 17.2절의 `2c692554` 실행이 마지막이다(E0). +- transaction 모드 PgBouncer 뒤의 실제 동작: 환경이 없다. 가이드의 설명은 Flyway 코드(한 연결로 잠그고 풂)와 맞는다(E1). + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR6-03-01 (CIC·REINDEX CONCURRENTLY가 Flyway 기본값에서 끝나지 않음) | 닫힘 | `persistence-jpa.yml:140-149`, `FlywaySchemaPolicy.java:115-127`, 스트림 5곳과 testkit `MigrationContractRunner`가 그것을 쓴다. inbox 사본은 `MessagingInboxSchemaStreamTest`가 값 대조. `JpaProductionArchitectureTest.everyProductionFlywayIsConfiguredThroughTheSchemaPolicy`. 실 PG IT 4건(17.2절, E0). 다만 고치며 쓴 설명 하나가 Flyway 동작과 다르다(RR7-03-02) | +| RR6-03-02 (`E'…\'…'` 문자열 판정) | 닫힘 | `LockWaitMigrationInspector.java`의 `opensEscapeString`·`endOfLiteral`, 테스트 `aLockAfterAnEscapeStringIsStillFound`(4 형태)·`aStatementFlywayRunsOutsideATransactionAfterAnEscapeStringIsNamed`. 중첩 주석(round6 Declined)도 `endOfBlockComment`로 함께 고쳤다 | +| RR6-03-03 (Flyway 목록에 문장이 더해지는 경우) | 닫힘 | `LockWaitMigrationInspectorTest.flywaysPostgreSqlParserStillHasTheStatementListTheInspectorCopied`가 `PostgreSQLParser`의 정적 패턴 전부를 고정한다(PR `ci`) | +| RR6-03-04 (ledger Spotless가 Sync 사본 검사) | 닫힘 | `src/grpc/grpc-operation-ledger-jpa/build.gradle:37-41` `targetExclude` | +| RR6-03-05 ("Flyway는 늘 트랜잭션으로 감싼다" 설명) | 부분 | 세 곳 모두 고쳤다(가이드 `:121-135`, 검사기 Javadoc, study 문서 `:1337-1367`). 새 문장이 "Flyway는 `REINDEX … CONCURRENTLY`를 트랜잭션 안에서 돌린다"로 넓게 적어 `SCHEMA`·`DATABASE` 형태에서 틀린다(RR7-03-02). ledger IT에 더한 안내는 없는 장치를 가리킨다(RR7-03-01) | + +## 결함 + +### RR7-03-01 · Minor · ledger 잠금 대기 IT가 동시 인덱스 파일을 "이 테스트에 예외로 적으라"고 안내하지만 예외를 적을 곳이 없다 + +- **위치**: + - 코드: `src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java:38-43`(Javadoc "Name such a file as an exception in this test"), `:98-104`(실패 메시지 "name it as an exception here"), `:69-72`(`migrationsAfterTheFirst()`는 V001 뒤 모든 파일, 거르는 목록 없음). +- **무엇이 틀렸나**: + - r10은 ledger 트리에 동시 인덱스 파일(트랜잭션 밖에서 도는 파일)이 생기면 이 IT가 `25001`로 실패할 때 안내를 붙였다(RR6-03-05). + - 안내는 "그 파일을 이 테스트에 예외로 적으라"다. 그러나 IT에는 예외 목록도, 파일을 거르는 장치도 없다. 매개변수는 트리의 V001 뒤 파일 전부다. +- **발생 조건·영향**: ledger에 `CREATE INDEX CONCURRENTLY` V004를 더하는 사람. IT가 실패하고, 메시지대로 하려면 테스트 구조를 새로 만들어야 한다. 무엇을 어떻게 빼야 하는지(빼도 되는 조건, 빼면 대신 무엇이 그 파일을 보나)는 안내에 없다. 거짓 실패 쪽이라 데이터 피해는 없다. +- **테스트가 못 본 이유**: ledger 트리에 지금 그런 파일이 없다. 안내는 오지 않을 실패에만 붙는다. +- **고치는 법**: + - 권장: IT에 "트랜잭션 밖에서 도는 파일" 목록(파일 이름과 이유)을 두고 `migrationsAfterTheFirst()`에서 뺀다. 그 목록의 파일은 `ConcurrentIndexMigrationInspector`의 두 검사(`.sql.conf`, 혼자인 문장)로 대신 본다. 메시지는 그 목록 이름을 가리킨다. + - 대안: 안내를 "이 IT는 그런 파일을 다룰 수 없다. 테스트에 거르는 장치를 더하는 변경이 필요하다"로 바꾼다. 장치를 만들지 않는 대신 기대를 바로잡는다. + - RED 테스트 모양: 임시 ledger 트리에 `V004__cic.sql`(+`.sql.conf`)을 두고 IT를 돌려 `25001` 실패를 본다. 권장안 뒤에는 목록에 이름을 넣으면 통과하고 inspector가 그 파일을 검사한다. +- **이번 수정 / 이전부터**: 이번 수정. +- **증거**: E1 — 코드 위치(grep으로 IT에 예외·제외 장치가 없음을 확인). 실행 탐침은 하지 않았다(ledger 트리를 바꿔야 해서 optional 빌드 integrationTest가 필요, 결함이 메시지의 사실 문제라 코드로 충분). + +### RR7-03-02 · Minor · "Flyway는 `REINDEX … CONCURRENTLY`를 트랜잭션 안에서 돌린다"고 적었지만 `REINDEX SCHEMA|DATABASE CONCURRENTLY`는 트랜잭션 밖에서 돌린다 + +- **위치**: + - 문서: `docs/jpa/migration-guide.md:122-125`("but not `REINDEX … CONCURRENTLY`, which it runs in the transaction for PostgreSQL to refuse"), `docs/study/postgresql-jpa-walkthrough.ko.md:1340-1342`("`REINDEX … CONCURRENTLY`는 모른다. 그 파일은 트랜잭션 안에서 돌고"). + - 코드: `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java:13-16`(Javadoc), `:54-57`(실패 메시지 "Flyway runs REINDEX ... CONCURRENTLY in one unless the migration says otherwise"). +- **무엇이 틀렸나**: + - Flyway 11의 트랜잭션 밖 목록에는 `^REINDEX( VERBOSE)? (SCHEMA|DATABASE|SYSTEM)`이 있다(`LockWaitMigrationInspectorTest.java:295`가 고정한 Flyway 패턴). 그래서 `REINDEX SCHEMA CONCURRENTLY`·`REINDEX DATABASE CONCURRENTLY`는 Flyway가 스스로 트랜잭션 밖에서 돌린다. + - 탐침 1: 그 두 문장은 `.sql.conf` 없이 적용됐다. `REINDEX TABLE|INDEX CONCURRENTLY`와 `REINDEX (CONCURRENTLY) TABLE`만 `25001`로 거부됐다. + - 문서·Javadoc·실패 메시지는 `REINDEX … CONCURRENTLY` 전체를 "Flyway가 모르는, 트랜잭션 안에서 도는" 문장으로 적는다. RR6-03-05가 고치려던 것과 같은 종류(Flyway가 언제 트랜잭션을 쓰는지에 대한 틀린 설명)다. 가이드의 "but not `REINDEX … CONCURRENTLY`"는 이전부터 있었고, r10이 "which it runs in the transaction"을 붙이고 같은 말을 검사기 Javadoc·메시지·study 문서로 넓혔다. +- **발생 조건·영향**: 행동 지시("동시 문장마다 `executeInTransaction=false`를 적는다")는 맞으므로 잘못된 배포로 이어지지 않는다. 틀린 것은 이유다. 검사기 메시지를 받은 사람이 `REINDEX SCHEMA CONCURRENTLY` 파일에서 "Flyway가 트랜잭션 안에서 돌린다"고 믿고 원인을 잘못 짚을 수 있다. `LockWaitMigrationInspector` Javadoc(`:150-151`, "`REINDEX TABLE CONCURRENTLY`는 목록에 없다")은 정확하다 — 같은 주제에 정확한 문장과 넓은 문장이 함께 있다. +- **테스트가 못 본 이유**: IT `flywayRunsReindexConcurrentlyInATransactionWherePostgresqlRefusesIt`는 `REINDEX TABLE CONCURRENTLY`만 본다. 문장은 문서·메시지라 대조하는 테스트가 없다. +- **고치는 법**: + - 권장: 네 곳을 "Flyway는 `REINDEX INDEX|TABLE … CONCURRENTLY`(괄호 옵션 형태 포함)를 트랜잭션 안에서 돌린다. `REINDEX SCHEMA|DATABASE|SYSTEM`은 `CONCURRENTLY`와 상관없이 트랜잭션 밖에서 돌린다"로 고친다. 행동 지시는 그대로 둔다. + - 대안: IT의 REINDEX 케이스를 탐침 1처럼 다섯 형태로 넓혀 Flyway 동작을 고정하고, 문서는 그 IT를 가리킨다. + - RED 테스트 모양: 대안을 쓰면 `REINDEX SCHEMA CONCURRENTLY public`이 "트랜잭션 안에서 거부된다"고 단언하는 케이스가 지금 실패한다(탐침 1 결과). +- **이번 수정 / 이전부터**: 섞임. 가이드의 "but not `REINDEX … CONCURRENTLY`"는 이전부터, "which it runs in the transaction"과 검사기 Javadoc·메시지·study 문서의 같은 문장은 이번 수정. +- **증거**: E3 — 명령 1(실 PostgreSQL, Flyway 11.14.1). 패턴은 E1. + +## Declined to judge + +- `JpaProductionArchitectureTest`의 Flyway 규칙은 `Flyway.configure()`·`Flyway.configure(ClassLoader)` 호출만 본다. `new FluentConfiguration()`·`new ClassicConfiguration()`으로 만든 Flyway는 지나간다. 문서(`persistence-jpa/CLAUDE.md:100-104`, 매뉴얼 04 `:122-124`)는 "`Flyway.configure()`를 부르면 실패한다"로 정확히 적는다. 생성자 경로를 막을지는 규칙 범위 결정이라 판단하지 않았다. +- 세션 잠금에서 연결이 끊기지 않은 채 unlock이 실패하면(Flyway가 "Unable to release PostgreSQL advisory lock"을 로그로만 남기는 경우) 잠금이 Hikari 풀의 연결에 남을 수 있다. Flyway 코드 경로로만 본 것이고 재현하지 않았다. 트랜잭션 잠금에는 없던 위험이다. 결정(Flyway 공식 옵션 채택)의 전제를 바꿀 만한 증거는 아니다. +- round6 03의 「Declined to judge」 10건은 2차에서 판정했다(README 18.5절). 그중 하나가 아래 RR7-03-05가 됐다. + +## 결론 + +Critical 0, Important 0, 회귀 0. 결함 2건, 모두 Minor. + +- 이번 수정: RR7-03-01(ledger IT의 없는 예외 장치 안내). +- 섞임: RR7-03-02(REINDEX 설명 — 이전부터 있던 넓은 문장을 이번 수정이 이유를 붙여 네 곳으로 넓힘). +- RR6-03-01~04는 닫혔고, RR6-03-05는 부분이다(위 두 결함). 세션 잠금 전제(한 연결, 재시도 대기)는 Flyway 코드와 맞는다. + +## 2차 추가 결함 (2026-11-06, 총괄 요청) + +같은 커밋을 따로 본 리뷰(`claude/t1-baseline-7d623a` `3add4917`, `round7/review.md`)의 03 영역 발견 둘을 넘겨받았다. 그쪽의 RR7-03-01·02는 이 +리뷰의 RR7-03-01·02와 번호만 같고 다른 결함이라 새 번호를 붙였다(README 18.2절 대응표). 그쪽 탐침(공유 노트 `r7-probes/probe/pg/`)과 같은 +모양을 이 리뷰의 기준 커밋 `06f520e6`에서 다시 돌렸고, 고치는 법을 확인하려고 "실패 이력 행 삭제" 경우를 하나 더했다. round6 03의 +「Declined to judge」 판정에서 하나를 더 올렸다. + +### 2차 실행 + +desktop 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`), 공유 잠금 아래. 탐침 `Rr7CicRecoveryProbeIntegrationTest`를 임시 lane +`rr7CicProbe`로 등록해 실 PostgreSQL(Testcontainers)에서 돌렸다. 모두 `FlywaySchemaPolicy.configure()`(세션 잠금)로 적용했다. 탐침 코드는 +공유 노트 `rr7-probes/pass2/`, 결과는 `rr7-probes/results/pass2-06f520e6.txt`. + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 4 | `./gradlew :adapter:outbound:persistence-jpa:rr7CicProbe` 첫 실행 | rc=1, 3초 — 내 탐침의 컴파일 오류(타입). 고쳐 다시 돌림 | 2.01 | +| 5 | 같은 명령 | rc=0, 15초. 아래 표 | 2.66 | + +V1은 `probe` 테이블, 일반 인덱스, `note`가 겹치는 행 하나(2001, `'note 1'`)를 만든다. + +| 경우 | V2 | 결과 | +|---|---|---| +| 섞임, `.sql.conf` 없음 | `INSERT (3001)` + `CREATE UNIQUE INDEX CONCURRENTLY` | Flyway가 실행 전에 거부("Detected both transactional and non-transactional statements"). 행 3001 없음, 이력 V1만 | +| 섞임, `executeInTransaction=false` | 같음 | `FlywayMigrateException`. **행 3001이 남음**(부분 적용), `ix_probe_note_u valid=false`, 이력 `2 success=false` | +| 복구: 가이드대로 | 유일 인덱스 하나 + `.sql.conf` → 실패 → 겹친 행 삭제, `DROP INDEX` → 재배포 | `FlywayValidateException: … Detected failed migration to version 2`. 이력 `2 success=false`가 그대로 | +| 복구: 실패 행도 삭제 | 위 + `DELETE FROM flyway_schema_history WHERE version = '2' AND NOT success` → 재배포 | 성공. `ix_probe_note_u valid=true`, 이력 `2 success=true` | + +### RR7-03-03 · Important · 실패한 동시 인덱스 마이그레이션의 복구를 "`DROP INDEX` 하나"라고 안내하지만, 남은 실패 이력이 다음 배포를 막고 runbook은 그 행을 지우는 것을 금지한다 + +- **출처**: 다른 리뷰 `3add4917` RR7-03-02. 그쪽 근거(가이드·runbook 문장, 탐침)를 확인하고 명령 5로 다시 재현했다. +- **위치**: + - 안내(같은 문장 세 벌): `docs/jpa/migration-guide.md:147-149`, `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java:18-19`·`:71-73`(`requireIsolatedStatement` Javadoc), `:92`(실패 메시지), `docs/study/postgresql-jpa-walkthrough.ko.md:1369-1371`. + - 막는 규칙: `docs/runbooks/migration-failed.md:42-66`(실패 분류에 이 경우가 없다), `:95`("delete or rewrite Flyway history to make validation green" 금지), `:107`(history repair 전 DB 소유자에게). +- **무엇이 틀렸나**: + - 트랜잭션 밖에서 돈 마이그레이션이 실패하면 Flyway는 이력에 `success=false` 행을 남긴다. + - 다음 배포의 validate는 그 행 때문에 실패한다. 무효 인덱스를 지우고 원인 데이터를 고쳐도 같다(명령 5 셋째 경우). + - 실패 행까지 지우면 재배포가 성공한다(넷째 경우). 그런데 문서 어디에도 그 단계가 없고, runbook은 이력 수정을 금지한다. +- **발생 조건·영향**: 가이드대로 쓴 동시 인덱스 마이그레이션이 실패한다(유일 인덱스의 중복 값, deadlock, `statement_timeout`, 운영자 취소). 운영자가 안내대로 `DROP INDEX` 뒤 다시 배포해도 기동이 또 멈추고, runbook에서 이 실패를 찾을 수 없다. r10 전에는 Flyway 기본 잠금 때문에 빌드가 실패까지 가지 못하고 멈췄다. r10이 빌드를 실제로 돌게 해 이 경로가 흔해졌다. 운영자에게 효과 없는 조치를 시키는 문서라 Important다. +- **테스트가 못 본 이유**: 동시 인덱스 IT는 성공하는 빌드와 상한에 걸려 취소되는 경우만 본다. 실패 뒤 재배포를 돌린 테스트가 없다. +- **고치는 법**: 정책 예외라 소유자 결정이 먼저다(README 18.4절). 권장안은 세 문장을 "무효 인덱스를 `DROP INDEX`하고, 그 버전의 실패 이력 행만 지운 뒤(`DELETE FROM WHERE version = '' AND NOT success`), 원인을 고쳐 다시 배포한다"로 고치고, runbook 「Classify the failure」에 이 경우와 SQL을, 「Do not」에 이 한 가지 예외를 적는 것이다. 성공한 행과 checksum은 건드리지 않는다. RED: 명령 5의 셋째 경우를 IT로 옮기고 문서 절차(넷째 경우)를 그대로 실행하게 한다. +- **이번 수정 / 이전부터**: 이전부터(가이드 문장은 `6d27356e`부터). r10이 바로 옆 문단을 고쳐 쓰고 빌드를 실제로 돌게 했다. +- **증거**: E3 — 명령 5(실 PostgreSQL, Flyway 11.14.1). 고치는 법의 SQL도 E3(넷째 경우). + +### RR7-03-04 · Minor · 학습 문서와 검사기 Javadoc이 "섞인 파일은 부분 적용되지 않는다"고 적지만, 가이드가 요구하는 `.sql.conf`를 붙이면 부분 적용된다 + +- **출처**: 다른 리뷰 `3add4917` RR7-03-01. 명령 5로 다시 재현했다. +- **위치**: `docs/study/postgresql-jpa-walkthrough.ko.md:1346-1348`(r10이 쓴 문장), `ConcurrentIndexMigrationInspector.java:16-19`(Javadoc: "Next to any other statement, one Flyway runs outside a transaction makes Flyway refuse the whole script before it runs any of it"). +- **무엇이 틀렸나**: Flyway의 `mixed=false` 거부는 `.sql.conf`가 트랜잭션 여부를 정하지 않은 파일에만 걸린다. 가이드·검사기 `validate`는 동시 인덱스 문장마다 `executeInTransaction=false`를 적으라고 한다. 그 설정이 붙은 섞인 파일은 Flyway가 문장마다 따로 커밋해 앞 문장이 남는다(명령 5 둘째 경우: 행 3001이 남고 무효 인덱스와 실패 이력이 생김). +- **발생 조건·영향**: 학습 문서를 믿고 `.sql.conf`를 붙인 채 다른 문장과 동시 인덱스를 섞는다. `requireIsolatedStatement`가 그 파일을 거부하지만 서비스가 마이그레이션 테스트를 둘 때만 돈다(가이드 `:146-147` "nothing checks it at startup"). 그 밖에서는 부분 적용과 실패 이력(RR7-03-03의 복구 문제)이 남는다. 문서 오류라 Minor. +- **테스트가 못 본 이유**: `.sql.conf`가 있는 섞인 파일을 Flyway로 끝까지 돌린 테스트가 없다. +- **고치는 법**: 두 곳을 "`.sql.conf` 없이 섞으면 Flyway가 실행 전에 거부한다. `executeInTransaction=false`를 붙이고 섞으면 문장마다 따로 커밋해 부분 적용된다. 그래서 동시 인덱스 문장은 혼자 둔다"로 고친다. 회귀 방지로 명령 5의 첫째·둘째 경우를 IT에 사실로 고정한다. +- **이번 수정 / 이전부터**: 이번 수정(RR6-03-05를 고치며 쓴 문장). +- **증거**: E3 — 명령 5. + +### RR7-03-05 · Minor · 잠금 대기 검사기 Javadoc은 `VACUUM FULL`을 늘 거부한다고 적지만, `.sql.conf`가 `executeInTransaction=true`를 정하면 `SET LOCAL` 뒤의 `VACUUM FULL`을 통과시킨다 + +- **출처**: round6 03 「Declined to judge」 셋째 항목(README 18.5절 판정 (a)). +- **위치**: `src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java:62-64`(Javadoc: "A locking statement that cannot run in a transaction itself ({@code VACUUM FULL}, …) can never be bounded and is refused"), `:248-252`(설정이 `IN_A_TRANSACTION`이면 `SET LOCAL` 범위를 적용해 상한 있는 것으로 판정). +- **무엇이 틀렸나**: `.sql.conf`에 `executeInTransaction=true`를 쓰면 검사기는 그 파일을 트랜잭션 안이라 보고 `SET LOCAL` 뒤의 `VACUUM FULL`을 상한 있는 문장으로 통과시킨다. Javadoc의 "늘 거부"와 다르다. +- **발생 조건·영향**: 그 조합의 마이그레이션은 PostgreSQL이 배포 때 `25001`로 거부해 잠금 대기는 생기지 않는다. 검사기의 목적(상한 없는 잠금 대기를 막음)은 지켜지고, 검사기가 먼저 알려 주지 못할 뿐이다. 문서와 동작의 차이라 Minor. +- **테스트가 못 본 이유**: `LockWaitMigrationInspectorTest`에 `executeInTransaction=true` + `VACUUM FULL` 케이스가 없다. +- **고치는 법**: 권장: 트랜잭션 안에서 돌 수 없는 문장(`VACUUM`, 비동시 `REINDEX SCHEMA|DATABASE|SYSTEM` 등)이 `executeInTransaction=true` 파일에 있으면 검사기가 "PostgreSQL이 배포 때 거부한다"는 이유로 거부한다. 대안: Javadoc을 "설정이 트랜잭션을 정하지 않은 파일에서"로 좁힌다. RED: 그 조합 파일을 `unboundedLockingStatements(Path)`에 넣어 빈 결과가 나오는 것을 본다. +- **이번 수정 / 이전부터**: 이전부터. +- **증거**: E1(판정 코드). round6 03도 같은 판정을 코드 위치로 적었다(E0). 실행 탐침은 돌리지 않았다. + +### 2차 반영 뒤 결론 + +Critical 0, Important 1(RR7-03-03), 회귀 0. 결함 5건: 이번 수정 2(RR7-03-01·04), 섞임 1(RR7-03-02), 이전부터 2(RR7-03-03·05). + +## 3차 추가 결함 (2026-11-07, 총괄 요청) + +이 문서 1차 「Declined to judge」 둘을 판정했다(README 18.5절). 첫째를 결함으로 올리고, 둘째는 결정 「Flyway PostgreSQL 잠금」으로 닫았다. + +### RR7-03-06 · Minor · "코드로 만드는 Flyway는 모두 `FlywaySchemaPolicy.configure()`에서 시작한다"는 규칙을 ArchUnit은 `Flyway.configure()` 호출로만 지킨다 — `new FluentConfiguration()`·`new ClassicConfiguration()`은 Flyway 기본(트랜잭션) 잠금으로 돌아간다 + +- **출처**: 이 문서 1차 「Declined to judge」 첫째 항목(README 18.5절 판정 (a)). 다른 리뷰(`3add4917`)도 같은 항목을 Declined로 적었다. +- **위치**: + - 규칙: `src/adapter/outbound/persistence-jpa/CLAUDE.md:100-104`("every Flyway built in code starts from `FlywaySchemaPolicy.configure()`"), `FlywaySchemaPolicy.java` Javadoc("Every Flyway the template builds itself starts from {@link #configure()}"). + - 지키는 장치: `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java:167-190`(`callMethod(Flyway, "configure")`·`configure(ClassLoader)`만 거부). +- **무엇이 틀렸나**: Flyway 설정을 만드는 공개 길은 셋이다: `Flyway.configure()`, `new FluentConfiguration()`(+`.load()`), `new ClassicConfiguration()` + `new Flyway(configuration)`. 규칙 문장은 셋 모두를 말하고, ArchUnit은 첫째만 막는다(A10 — 둘째·셋째는 글로만 있음). +- **발생 조건·영향**: 파생 서비스가 자기 스트림을 `new FluentConfiguration()`으로 만든다. 빌드는 통과하고, 그 스트림의 `CREATE INDEX CONCURRENTLY` 마이그레이션은 RR6-03-01처럼 Flyway 자신의 열린 트랜잭션을 기다려 끝나지 않는다. 이 repo 코드에는 그런 생성이 없다(grep). +- **테스트가 못 본 이유**: 규칙에 둘째·셋째 길의 위반 fixture가 없다. +- **고치는 법**: 같은 규칙에 `callConstructor(FluentConfiguration.class, …)`(인자 없는 것과 `ClassLoader` 하나)와 `callConstructor(ClassicConfiguration.class, …)`를 `FlywaySchemaPolicy` 밖에서 거부하는 조건을 더한다. 대안: 문서를 "`Flyway.configure()`를 부르지 않는다"로 좁힌다(지키는 범위에 말을 맞춤, 권하지 않음 — 막으려는 피해가 그대로 남는다). RED: 둘째·셋째 길로 Flyway를 만드는 위반 fixture가 지금 규칙을 통과한다. +- **이번 수정 / 이전부터**: 이번 수정(규칙과 문장 모두 r10이 만들었다). +- **증거**: E1(규칙 코드와 Flyway 11.14.1의 공개 생성자). + +### 3차 반영 뒤 결론 + +Critical 0, Important 1(RR7-03-03), 회귀 0. 결함 6건: 이번 수정 3(RR7-03-01·04·06), 섞임 1(RR7-03-02), 이전부터 2(RR7-03-03·05). diff --git a/docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md b/docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md new file mode 100644 index 00000000..016437a6 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round7/04-build-logic-shell.md @@ -0,0 +1,81 @@ +# 04 build-logic 셸 판독 r10 확인 리뷰 (2026-11-06) + +> 대상: `6e992970`(r10)의 r10-04 묶음 중 셸 스크립트 판독(`ShellScript`)과 단계 검사 플러그인 쪽. RR6-04-03(조건부 `exit`·`exec`· +> `set -n`·`trap`), RR6-04-05(세지 않는 이유 셋과 실패 메시지). workflow 판독·Gradle 명령줄 쪽은 05다. +> 기준 커밋 `06f520e6`. 그 뒤 커밋 `e6b6e18e`가 같은 패키지의 `StrictTestLanePlugin`을 바꿨지만 이 pathspec의 파일은 바꾸지 않았다. + +## 범위 + +### pathspec + +``` +src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/ShellScript.java +src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java +src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java +src/build-logic/build.gradle src/build-logic/README.md +``` + +`git diff --shortstat 6e992970^ 6e992970 -- `: 5개 파일, +659 −100. build-logic 묶음 전체는 +1,916줄이라 상한(1,500줄)을 넘어 +셸 판독(04)과 workflow 판독(05)으로 나눴다. 셸 모양의 테스트는 대부분 `WorkflowGradleInvocationsTest`에 있어(05 pathspec) 그 파일의 +셸 케이스도 함께 읽었다. + +함께 읽은 주변 코드: `ShellScript.java` 전체(1,659줄 중 `Evaluator`·`Parser`의 바뀐 곳과 그 호출자), `OPAQUE_COMMANDS`(`eval`·`source`·`.` +뒤의 디렉터리를 읽지 않음), round6 04의 RR6-04-03·05와 그 Declined. + +### 수정 보고의 「새로 가정하는 것」 + +| 가정 | 확인 | +|---|---| +| 스크립트가 0으로 끝날 수 있는 길은 `exit`·`exec`·`set -n`·`EXIT`/`ERR` trap과 그것을 부르는 함수다 | 남은 길(`eval "exit 0"`, `source`한 파일 안의 `exit`)은 `OPAQUE_COMMANDS`가 그 뒤 디렉터리를 "읽지 않음"으로 만들어 뒤 명령이 세어지지 않는다(거짓 실패 쪽). 거짓 통과로 새지 않는다(E1) | +| 리터럴이 아닌 `exit` 값은 0일 수 있다 | 판독기가 그렇게 본다(`exitsWithSuccess`). 거짓 실패 쪽 | +| 파이프 안·`( )`·`$( )` 안의 `exit`은 그 하위 셸만 끝낸다 | 참(bash에 `lastpipe`가 기본으로 꺼져 있음). 판독기는 그 경우를 건너뛴다(`walk`) | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 테스트가 이름대로 보는가 | RR6-04-03·05 닫힘 | +| `docs/work/reference/defect-patterns.md` A7 | 거짓 통과 게이트 | 새 분기마다 "세지 말아야 할 명령을 세는가"(거짓 통과)와 "셀 명령을 안 세는가"(설계상 허용된 거짓 실패)를 나눠 봄 | + +### 실행한 명령과 결과 + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 1 | `./gradlew -p build-logic test --rerun` (desktop `~/workspace/t1-r10-review`, `06f520e6` + 05의 탐침 1건) | rc=0, 40초, 169건 실패 0 skip 0 | 3.69 | + +### 따라간 모양 (E1) + +- 최상위 `exit 0` 뒤, `[ -z "$X" ] && exit 0` 뒤, `if …; then exit 0; fi` 뒤: 앞은 `terminated`, 뒤 둘은 `mayHaveEnded`로 뒤 명령을 세지 않는다. +- `./gradlew ci || exit`·`|| exit 1`: 인자 없는 `exit`은 실패 상태를 지키고, 그 명령은 "읽지 않음"(3번 이유)으로 남는다. +- `trap 'exit 0' EXIT`, `trap cleanup EXIT`(함수 안 인자 없는 `exit`), `trap 'exit' ERR`: 첫째와 셋째만 뒤 명령을 세지 않는다. EXIT trap의 인자 없는 `exit`은 상태를 지킨다는 판단은 bash 동작과 맞다. +- `exec > log 2>&1`(재지정만): 셸을 바꾸지 않으므로 끝내지 않는다고 본다. `exec ./gradlew ci`: 바꾼다. +- `set +o errexit`, `set -n`, `set -o noexec`, `set "$OPTS"`: 앞 둘은 읽고, 값이 펼쳐지는 `set`은 "알 수 없음"으로 errexit·noexec 둘 다 꺼졌을 수 있다고 본다. +- `echo | exit 0`: 파이프 안이라 하위 셸만 끝난다. 세는 데 영향 없음. +- 사용자 정의 `shell:` 템플릿(`bash {0}`처럼 `-e` 없는 것): `SHELLS` 표에 없는 이름이라 "읽지 않음"으로 남는다(05 `WorkflowGradleInvocations.java:155-159`, `:412-420`). + +## 못 본 것 + +- 실제 GitHub runner의 bash 동작: 실행할 수 없다. 판단은 bash 매뉴얼의 `exit`·`trap`·`set -e` 설명과 판독기 코드 대조다(E1). +- 이 repo의 실제 workflow 판정이 수정 전후 같다는 README 17절 주장("세는 명령 48개")은 다시 세지 않았다. 두 빌드의 `verifyStrictLaneStages --dry-run`은 17.2절 `2c692554`에서 통과했다(E0). + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR6-04-03 (맨 위 `exit`만 봄) | 닫힘 | `ShellScript.java`의 `effects`·`mayEnd`·`trap`·`endingIn`·`called`, 테스트(`WorkflowGradleInvocationsTest`의 조건부 `exit`·`exec`·`set -n`·함수 안 `exit`·EXIT/ERR trap 케이스) | +| RR6-04-05 (세지 않는 이유를 반대로 적음) | 닫힘 | 이유를 셋(실패를 막지 못함 / 돌지 않을 수 있음 / 판독기가 읽지 않음)으로 나눴다. `ShellScript` Javadoc `:25-56`, 각 이유 문구, `StrictLaneStagesPlugin.NOT_COUNTED`(`:61-75`), AGENTS.md·CLAUDE.md·`src/README.md`·`build-logic/README.md`·업그레이드 B-36이 같은 셋을 적는다. 단 `NOT_COUNTED`의 끝 문장은 05의 RR7-05-01 | + +## 결함 + +없음. + +## Declined to judge + +- 한 번 걸린 `trap 'exit 0' EXIT`를 `trap - EXIT`로 풀어도 판독기는 뒤 명령을 계속 세지 않는다. 거짓 실패 쪽이고 이 모양을 쓰는 workflow는 드물다. +- `kill $$`, `kill -TERM 0`처럼 셸을 신호로 끝내는 명령: 판독기가 보지 않는다. 신호로 끝난 단계는 실패로 끝나므로 거짓 통과가 아니다. +- round6 04의 「Declined to judge」 7건은 2차에서 판정했다(README 18.5절). 그중 경로·브랜치 필터 항목은 05의 RR7-05-01로 합쳤다. + +## 결론 + +Critical 0, Important 0, 회귀 0. 결함 0건. RR6-04-03·05는 닫혔다. 새 분기가 만드는 오판은 모두 "세지 않음"(거짓 실패) 쪽이고, 따라간 모양에서 +세지 말아야 할 명령을 세는 길은 찾지 못했다(E1). diff --git a/docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md b/docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md new file mode 100644 index 00000000..d5d954d3 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round7/05-build-logic-workflow.md @@ -0,0 +1,97 @@ +# 05 build-logic workflow 판독 r10 확인 리뷰 (2026-11-06) + +> 대상: `6e992970`(r10)의 r10-04 묶음 중 workflow 판독(`WorkflowGradleInvocations`)과 Gradle 명령줄 쪽. RR6-04-01(작업 없이 끝나는 +> 옵션), RR6-04-02(옵션 표를 Gradle과 대조), RR6-04-04(Windows runner 기본 셸), RR6-04-06(요청형 trigger·`workflow_call`·`needs`). +> 셸 판독 쪽은 04다. 기준 커밋 `06f520e6`(이 pathspec의 파일은 `6e992970` 뒤로 바뀌지 않았다). + +## 범위 + +### pathspec + +``` +src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java +src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java +src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/GradleCommandLineTest.java +AGENTS.md CLAUDE.md src/README.md +``` + +`git diff --shortstat 6e992970^ 6e992970 -- `: 6개 파일, +1288 −101. 함께 본 것: `docs/upgrade/2026-11-maturity-review.md` B-36, +`StrictLaneStagesPlugin.NOT_COUNTED`(04 pathspec), 이 repo의 `.github/workflows/*.yml` 15개의 trigger. + +### 수정 보고의 「새로 가정하는 것」 + +| 가정 | 확인 | +|---|---| +| change·release trigger(`push`, `pull_request`(+types), `pull_request_target`, `merge_group`, `schedule`, `release`)가 하나라도 있으면 그 workflow는 "매 변경에 돈다" | 거짓인 경우가 있다. `paths:` 필터가 붙은 trigger는 그 경로가 바뀔 때만 돈다. 그런데 실패 메시지·문서는 "매 push·pull request·schedule에 도는 workflow"에서 단계를 돌리라고 한다(RR7-05-01) | +| `workflow_call` workflow는 `uses: ./.github/workflows/`로 부르는 job을 통해서만 돈다 | 참. 다른 repo 표기(`owner/repo/.github/workflows/x.yml@ref`)로 같은 repo를 부르면 못 알아보지만 세지 않는 쪽(거짓 실패)이다 | +| 판독기의 Gradle 옵션 표는 실행 중인 Gradle의 `--help`와 같다 | 참. `GradleCommandLineTest`가 대조한다(이 실행에서 통과, 아래 명령 1) | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 문서·메시지가 동작과 같은가 | RR6-04-01·02·04·06 닫힘, 새 메시지가 시키는 것과 판독기가 세는 것 | +| `ci-cd-and-automation` | 게이트가 매 변경에 도는가 | trigger·필터·job 조건 | +| `docs/work/reference/defect-patterns.md` A2·A7 | 문서와 코드 불일치, 거짓 통과 게이트 | 판독기가 "돈다"고 보는 workflow의 범위 | + +### 실행한 명령과 결과 + +desktop 임시 worktree `~/workspace/t1-r10-review`(`06f520e6`), 공유 잠금 아래. 로그 `~/t1-r10-review-logs/`(desktop), 탐침 코드는 공유 노트 폴더 `rr7-probes/`. + +| # | 명령 | 결과 | 직전 부하(1분) | +|---|---|---|---| +| 1 | `./gradlew -p build-logic test --tests dev.caskeleton.buildlogic.strictlane.Rr7WorkflowProbeTest` | rc=0. 결과는 아래 | 4.66 | +| 2 | `./gradlew -p build-logic test --rerun` | rc=0, 40초, 169건 실패 0 skip 0(탐침 1건 포함) | 3.69 | + +탐침 `Rr7WorkflowProbeTest`는 `WorkflowGradleInvocations.read`에 두 workflow를 준다. + +| workflow | 읽은 결과 | +|---|---| +| `on: pull_request: paths: ["docs/**"]` + `push: branches: [main], paths: ["docs/**"]`, `run: ./gradlew ci` | `uncountedReason=null` — 실행으로 센다 | +| `on: workflow_dispatch`, 같은 step(대조군) | "its workflow starts only on workflow_dispatch … so it may not run" — 세지 않는다 | + +## 못 본 것 + +- 실제 GitHub의 trigger 해석(`paths` 필터, `types`, `needs`의 건너뜀): 실행할 수 없다. GitHub 문서 기준(E1). +- `--stop`·`--foreground`는 `GradleCommandLineTest`도 실행하지 않는다(데몬을 멈추거나 붙잡음). 표에 둔 근거는 Javadoc의 Gradle 소스 설명뿐이다(E0). + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR6-04-01 (작업 없이 끝나는 Gradle 옵션) | 닫힘 | `GRADLE_OPTIONS_THAT_RUN_NO_TASK`(`WorkflowGradleInvocations.java:134-143`), 묶음(`-qv`) 처리, 테스트 | +| RR6-04-02 (옵션 표를 지키는 테스트 없음) | 닫힘 | `GradleCommandLineTest`가 옵션 표 전체를 실행 중인 Gradle `--help`와 대조하고, 작업 없이 끝나는 옵션을 실제로 실행한다(`--stop`·`--foreground` 제외) | +| RR6-04-04 (Windows runner 기본 셸) | 닫힘 | `defaultShellReason`: `container:`가 있거나 `ubuntu-*`·`macos-*`·`linux`·`macos` 라벨일 때만 기본 셸을 bash로 읽는다. 식(`${{ matrix.os }}`)·Windows 라벨·라벨 없는 self-hosted는 세지 않는다 | +| RR6-04-06 (요청형 trigger·`workflow_call`·`needs`) | 닫힘 | `startReason`·`runsOnChanges`·`needsReason`, 테스트. 다만 고치며 쓴 메시지·문서가 새 약속을 했다(RR7-05-01) | + +## 결함 + +### RR7-05-01 · Minor · 실패 메시지와 문서는 "매 push·pull request·schedule에 도는 workflow"에서 단계를 돌리라고 하지만, 판독기는 `paths:` 필터로 일부 변경에만 도는 workflow도 센다 + +- **위치**: + - 코드: `src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java:61-75`(`NOT_COUNTED` 끝: "in a step and job that run on every push, pull request or schedule"), `WorkflowGradleInvocations.java:44-55`(Javadoc "A workflow counts when one of its triggers is part of the change or release flow"), `:96-101`(`CHANGE_TRIGGERS`), `:620-627`(`runsOnChanges`는 trigger 이름과 `types`만 본다). + - 문서: `docs/upgrade/2026-11-maturity-review.md` B-36 할 일 칸("단계는 매 push·pull request·schedule에 도는 workflow와 job에서"). +- **무엇이 틀렸나**: + - r10은 "요청이 있어야 도는 workflow"를 세지 않게 하면서, 무엇이 "매 변경에 도는" workflow인지를 메시지와 문서에 처음 적었다: 매 push·pull request·schedule. + - 판독기는 trigger 이름과 `types`만 본다. `paths:`·`paths-ignore:` 필터는 읽지 않는다. + - 탐침: `pull_request`와 `push` 모두 `paths: ["docs/**"]`인 workflow의 `./gradlew ci`를 실행으로 센다. 이 workflow는 docs만 바뀐 변경에서만 돌고, 코드가 바뀐 PR에서는 돌지 않는다. + - 이 repo에도 `paths:` 필터가 있는 workflow가 7개 있다(`build-logic.yml`, `fileserver-pr.yml`, `link-check.yml`, `messaging-certification.yml`, `notification-platform.yml`, `object-storage-qualification.yml`, `redis-sdk-topology.yml`). 지금은 단계 명령을 거기서만 돌리지 않아 판정은 맞다. +- **발생 조건·영향**: 파생 서비스가 무거운 단계(`integrationCheck` 등)를 비용 때문에 `paths:` 필터 workflow로 옮긴다. 검사는 통과하고, 필터 밖 변경에서는 그 단계가 돌지 않는다. 메시지와 업그레이드 안내가 약속한 "매 변경"과 다르다. +- **테스트가 못 본 이유**: `WorkflowGradleInvocationsTest`의 trigger 케이스는 이벤트 이름·`types`·`workflow_call`·`needs`만 다룬다. 필터 케이스가 없다. +- **이번 수정 / 이전부터**: 섞임. 필터를 읽지 않는 동작은 이전부터다(round6 04 「Declined to judge」 첫 줄: "어떤 필터가 충분한지는 저장소 정책이라 판단하지 않았다"). "매 push·pull request·schedule"이라는 약속은 이번 수정이 메시지·문서에 썼다. +- **고치는 법** — 정책 선택이 먼저다(README 18.4절 「결정이 필요한 것」): + - 권장(a): `paths:`·`paths-ignore:`가 붙은 trigger는 "매 변경"이 아니므로 그 trigger만으로는 세지 않는다. 이유는 2번(돌지 않을 수 있음). `branches:` 필터는 기본 브랜치를 포함하면 센다. 이 repo의 단계 명령은 필터 없는 workflow에 있어 판정이 바뀌지 않는다. + - 대안(b): 동작은 두고 메시지·B-36을 "change trigger 중 하나로 시작하는 workflow(경로 필터는 보지 않는다)"로 고친다. 필터의 충분성은 저장소 책임으로 문서에 적는다. + - RED 테스트 모양: (a)면 탐침 workflow를 `WorkflowGradleInvocationsTest`에 넣고 `uncountedReason`이 null이 아님을 단언한다. `06f520e6`에서 실패한다(탐침 결과). +- **증거**: E2 — 명령 1(탐침). 이 repo workflow의 필터 목록은 E1(`grep -n "paths:" .github/workflows/*.yml`). + +## Declined to judge + +- `push: tags: ['v*']`만 있는 workflow(태그 push에만 돈다)도 change trigger로 센다. 릴리스 단계(`releaseCheck`)는 그런 workflow에서 도는 것이 맞아서 결함으로 보지 않았다. 다른 단계를 거기에만 두는 경우는 RR7-05-01과 같은 정책 질문이다. +- `runs-on`을 `group:` 매핑으로만 쓰고 `labels:`가 없는 job은 Windows일 수 있다고 보아 세지 않는다(거짓 실패 쪽, 메시지가 이유를 말함). +- 다른 repo 표기로 같은 repo의 재사용 workflow를 부르는 job: 위 「새로 가정하는 것」 둘째 줄. 거짓 실패 쪽. + +## 결론 + +Critical 0, Important 0, 회귀 0. 결함 1건(Minor, 섞임 — 동작은 이전부터, 약속은 이번 수정). RR6-04-01·02·04·06은 닫혔다. RR7-05-01은 +고치기 전에 소유자가 경로 필터 정책을 정해야 한다. diff --git a/docs/reviews/2026-11-03-rereview/round8/01-transport-errors.md b/docs/reviews/2026-11-03-rereview/round8/01-transport-errors.md new file mode 100644 index 00000000..e001e292 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round8/01-transport-errors.md @@ -0,0 +1,169 @@ +# 01 전송 오류 처리 round7 수정 확인 리뷰 (2026-11-07) + +> 대상: `5f6a86d7`(RR7-01-03~06: 네 전송이 원인 사슬의 첫 carrier를 보고, 락 timeout을 carrier로, STOMP 거부를 WARN 한 줄로)와 +> `ef8ef170`(`Retry-After`를 레지스트리대로, GraphQL `@Argument` 변환 실패를 `BAD_PARAMETER`로). +> 범위 `2c8a359d..83a12f66`, 기준 커밋 `83a12f66`(브랜치 `claude/integration-r8-a4196a`, 리뷰 브랜치 `refactor/maturity-review-2026-11`에서 딴 통합 결과). +> 독립 리뷰어 둘 중 정본 리뷰어(세션 r8-review-a)가 썼다. 이 라운드의 영역 표와 나눈 이유는 아래 「범위」에 있고, 다른 영역 문서는 이 표를 가리킨다. +> 이 라운드의 색인 절은 두 리뷰를 합친 뒤 총괄이 README에 쓴다(`docs/work/improve.md` 4.1절 7단계). 그 전까지 색인 검사는 rc=1이다(RR8-06-01). + +## 범위 + +### pathspec + +``` +src/shared-contract src/adapter/inbound/web src/adapter/inbound/graphql src/adapter/inbound/grpc src/adapter/inbound/websocket +src/application-core/src/main/java/dev/caskeleton/application/lock src/application-core/src/test/java/dev/caskeleton/application/lock +src/app-bootstrap/src/test docs/runbooks/lock-acquisition-timeout.md +``` + +`git diff --stat 2c8a359d..83a12f66 -- `: 30개 파일, +1056 −125. + +범위 전체(`docs/reviews/**` 제외)는 116개 파일 +3,747줄이다. 확인 리뷰 상한(추가 1,500줄, `docs/work/improve.md` 4.4절)을 넘어 영역 여섯으로 +나눴다. 한 세션이 여섯 영역을 차례로 봤다. + +| 영역 | 대상 커밋 | `git diff --shortstat` | +|---|---|---| +| 01 전송 오류(이 문서) | `5f6a86d7`, `ef8ef170` | 30 파일, +1056 −125 | +| [02 아키텍처 규칙](02-architecture-rules.md) | `a8166598` | 14 파일, +725 −94 | +| [03 마이그레이션·Flyway 규칙](03-migration.md) | `6ec0c4f7`, `6764246a` | 28 파일, +747 −125 | +| [04 멱등 저장소](04-idempotency.md) | `14435106` | 12 파일, +382 −61 | +| [05 build-logic·httpclient·작은 문서](05-build-logic-httpclient.md) | `6cd5e925`, `a490c20f`, `c746f980`, `eab82df1`, `ac3c6a81` | 11 파일, +547 −100 | +| [06 매뉴얼·검사 스크립트](06-manual-scripts.md) | `b872b0ea`, `73d39212`, `6dd9ef76`, `b619c442`, `447a77a3`, `b7d13104`, `81ef58ab` | 18 파일, +253 −67 | +| 공통 문서(영역마다 자기 행을 읽음) | `docs/upgrade/2026-11-maturity-review.md`, `src/application-core/README.md`, `src/adapter/outbound/persistence-jpa/README.md` | 3 파일, +37 −15 | + +여섯 영역과 공통 문서의 합이 범위 전체와 같다(116 파일, +3,747 −587, 빠진 파일 0). + +함께 읽은 주변 코드: `GraphQlExceptionResolver` 전체(등록된 매핑이 어떻게 고르는지), web `GlobalExceptionHandler` 전체와 sample +`DomainExceptionHandler`(도메인 advice 순서), `ServerFailureLog.of`, `MeteredDistributedLock`·`LockRegistryDistributedLock`(락 timeout이 어디서 +로그를 남기는지), `docs/registries/metrics.yaml`의 `lock.acquisition`, `EnvelopeErrorController` Javadoc(필터가 던진 실패), `RetryAfterAdvisor`와 +`docs/registries/error-codes.yaml`의 `retry_after_seconds` 행 전체. + +### 수정 보고의 「새로 가정하는 것」 + +수정 보고는 repo에 없다(공유 노트 `r8-f1-transport-errors.md`). 그 노트 「정한 기본값」, 두 커밋 본문 「위험·한계」, README 18.4·18.7절에서 뽑았다. + +| 가정 | 확인 | +|---|---| +| 원인 사슬의 첫 carrier를 보면 바뀌는 응답은 "지금 500 `INTERNAL_ERROR`로 뭉개지는 경우뿐"이다(소유자 결정의 전제, README 18.4절 RR7-01-05 행) | **거짓.** GraphQL은 원인 사슬의 carrier를 등록된 application 매핑보다 먼저 본다. 앱이 등록한 실패가 carrier를 원인으로 들면 그 매핑의 코드 대신 carrier 코드로 답한다. 수정 전에는 매핑 코드였다(RR8-01-01) | +| 4xx carrier는 서버 로그를 남기지 않아도 된다("4xx라 'unhandled exception' ERROR 줄이 사라진다", B-45) | 락 timeout에는 문제가 된다. 이제 어느 락에서 났는지 서버에 아무 흔적이 없는데, runbook은 그 정보가 없는 metric과 없는 테이블을 보라고 한다(RR8-01-02) | +| Spring 7.0.9 변환기는 받은 메시지를 읽기 실패에만 싣는다(STOMP 쓰기/읽기 실패 구분) | 참. 노트의 바이트코드 확인과 테스트 `aReplyTheConverterCannotWriteIsLoggedAtErrorWithTheFailure`가 지킨다 | +| `RetryAfterAdvisor` 표와 레지스트리를 `OperationalError` 코드만 대조해도 된다 | 참. 레지스트리에 `retry_after_seconds`가 있는 행 17개가 모두 `OperationalError` 코드이고 표의 17개와 같다(`error-codes.yaml`을 grep으로 셈). 다른 leaf 코드는 `RetryAfterHint`로 말한다 | +| GraphQL `BindException`은 인자 binder만 던진다 | 참으로 봤다. 템플릿 GraphQL 코드에 `BindException`을 만드는 곳이 없다(grep) | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현이 맞나, 테스트가 이름대로 보나, 심각도 보정, 읽기 전용. 하위 에이전트는 repo 설정이 막아 직접 봤다 | 고친 항목마다 닫힘, 바뀐 판정 순서가 다른 경로의 답을 바꾸는지 | +| `docs/work/reference/review-criteria.md` 1·3·4·6절 | 약속과 실제가 다른 곳, Critical/Important/Minor, E 수준, 관점 6·8·17 | 소유자 결정의 전제, runbook 조치, 공개 응답 코드 | +| `docs/work/reference/defect-patterns.md` | 같은 규칙을 경계마다 다시 구현(A1), 글로만 있는 약속 | 네 전송의 판정 순서, web 도메인 advice와 GraphQL 등록 매핑 | + +### 실행한 명령과 결과 + +desktop 임시 worktree `~/workspace/r8-review-a`(`83a12f66`)와 `~/workspace/r8-review-a-base`(`2c8a359d`)에 탐침을 얹고 +`flock /tmp/claude-gates/heavy.lock` 아래에서 차례로 `--no-build-cache`로 돌렸다. 로그 desktop `~/r8-review-a-logs/`(`summary.txt`), +탐침 코드와 돌리는 법은 공유 노트 폴더 `r8-review-a-probes/`에 있다. 명령 번호는 여섯 영역 문서가 같이 쓴다. + +| # | 명령 | 대상 | 결과 | 시간 | 직전 부하(1분) | +|---|---|---|---|---|---| +| A1 | `:adapter:inbound:graphql:test --tests '*Rr8RegisteredMappingProbeTest'` | `83a12f66` + 탐침 | rc=0. 등록 매핑의 실패가 carrier를 원인으로 들면 `code=DB_UNAVAILABLE category=DEPENDENCY`, 원인이 없으면 `ORDER_UNAVAILABLE` | 19초 | 1.29 | +| A2 | 같은 명령 | `2c8a359d` + 같은 탐침 | rc=0. 두 경우 모두 `code=ORDER_UNAVAILABLE category=BUSINESS` | 18초 | 2.19 | +| A8 | 바뀐 leaf 테스트 `--rerun`(shared-contract, application-core, web, graphql, grpc, websocket, httpclient, cache-redis, persistence-jpa `test`, app-bootstrap `architectureTest`) | `83a12f66` + 탐침 | 03 영역 문서 「실행한 명령과 결과」 | — | — | + +탐침 `Rr8RegisteredMappingProbeTest`는 `GraphQlExceptionResolver`에 앱 실패 `OrderUnavailableException`을 `ORDER_UNAVAILABLE`(`BUSINESS`)로 +등록하고, 그 실패가 `PersistenceFailureException(DB_UNAVAILABLE)`을 원인으로 든 경우와 원인 없는 경우를 `GraphQlWireErrorMapper.map`에 넣는다. + +### 못 본 것 + +- 실제 GraphQL·gRPC 서버 기동: 판정은 매퍼·인터셉터 단위로 봤다. 묶음 보고의 systemTest·qualification lane 통과는 E0다. +- STOMP 필수 header 누락(`MessageHandlingException`) ERROR 유지는 결정 색인 2.3절의 기본값이라 다시 판정하지 않았다. + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR7-01-03 (gRPC가 던진 raw status와 넘긴 raw status의 판정이 다름) | 닫힘 | `GrpcExceptionHandlingInterceptor.java:135-150`이 status 예외를 벗긴 실패 하나(`failureBehind`)로 carrier·IAE 판정과 로그를 한다. 테스트 `GrpcExceptionHandlingInterceptorTest`의 던짐/넘김 두 경우 | +| RR7-01-04 (락 timeout이 500) | 닫힘 | `LockAcquisitionTimeoutException implements ApiErrorCarrier`(`LockAcquisitionTimeoutException.java:16-17`), `RetryAfterAdvisor.java:35`. web 409·`Retry-After: 1`, GraphQL 같은 코드 테스트. 다만 4xx가 되며 진단 흔적이 사라진 것은 RR8-01-02 | +| RR7-01-05 (감싼 carrier를 gRPC만 봄) | 부분 | 네 전송 일곱 자리가 `ApiErrorCarrier.firstIn` 하나를 쓴다(grep). 그런데 GraphQL에서는 이 판정이 등록된 application 매핑보다 앞서, 결정이 전제한 범위 밖의 응답까지 바꿨다(RR8-01-01) | +| RR7-01-06 (STOMP 거부 ERROR + 입력) | 닫힘 | `StompHandlerFailureLog.java:64-92`, 실제 handler 경로 테스트 `aClientArgumentRefusalIsLoggedAtWarnByItsTypeWithoutItsMessage` 4건과 쓰기 실패 ERROR 테스트 | +| r8-f1 범위 밖 1(`Retry-After` 7개 누락) | 닫힘 | `RetryAfterAdvisor.java:19-43`이 레지스트리 17행과 같다. 대조 테스트 `OperationalErrorRegistryContractTest.everyRegisteredRetryAfterIsTheHeaderTheWebAdapterSends` | +| r8-f1 범위 밖 2(GraphQL `BindException`) | 닫힘 | `GraphQlWireErrorMapper.java:221-224`, 실제 binder 경로 테스트 `GraphQlArgumentBindingFailureTest` | + +## 결함 + +### RR8-01-01 · Important · GraphQL이 원인 사슬의 carrier를 앱이 등록한 매핑보다 먼저 보아, 등록한 실패가 carrier를 원인으로 들면 앱이 정한 코드 대신 carrier 코드로 답한다 (회귀) + +- **위치**: + - 코드: `src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapper.java:121-131`(`map`: 공유 코드가 있으면 등록 매핑을 보지 않음), `:210-219`(`sharedCodeOf`가 원인 사슬 전체에서 carrier를 찾음). + - 코드(약속): `GraphQlExceptionResolver.java:10-14`("Registered ones — the failures the application deliberately models — map to their own code"). + - 결정·문서: `docs/work/reference/decisions.md:88`(「감싼 carrier를 전송이 읽는 법」: "감싼 carrier의 응답이 500 `INTERNAL_ERROR` 대신 그 carrier의 코드가 된다"), `docs/reviews/2026-11-03-rereview/README.md:506`(결정 근거 "바뀌는 응답은 지금 500 `INTERNAL_ERROR`로 뭉개지는 경우뿐이다"), `docs/upgrade/2026-11-maturity-review.md:104`(B-46 "전에는 500 `INTERNAL_ERROR`"), `src/adapter/inbound/graphql/README.md:66-80`, `src/adapter/inbound/graphql/CLAUDE.md:122-126`. + - 비교(web): `GlobalExceptionHandler.java:56-60`("domain exceptions are handled by a separate `@RestControllerAdvice`"), sample `DomainExceptionHandler.java:26`(`@Order(Ordered.HIGHEST_PRECEDENCE)`). +- **무엇이 틀렸나**: + - GraphQL 판정 순서는 플랫폼 거부 → carrier → 등록된 application 매핑 → 거부된 인자다. + - 수정 전에는 carrier 단계가 실패 **자신**만 봤다. 그래서 앱이 등록한 실패(carrier 아님)는 원인에 무엇이 있든 등록 매핑으로 갔다. + - 수정 뒤에는 carrier 단계가 원인 사슬 전체를 본다. 앱이 등록한 실패가 carrier를 원인으로 들면 carrier 단계에서 끝나고, 등록 매핑은 보지 않는다. + - 탐침: 같은 실패(`OrderUnavailableException`, 원인 `PersistenceFailureException(DB_UNAVAILABLE)`)가 `2c8a359d`에서는 `ORDER_UNAVAILABLE`, `83a12f66`에서는 `DB_UNAVAILABLE`(`DEPENDENCY`)로 나갔다. + - 소유자 결정은 "바뀌는 응답은 500 `INTERNAL_ERROR`로 뭉개지던 경우뿐"이라는 전제로 내려졌다. 이 경우는 500이 아니라 앱이 정한 코드였다. 결정 범위 밖의 공개 응답이 바뀌었다. + - web은 다르게 답한다. 앱의 도메인 advice(sample처럼 `HIGHEST_PRECEDENCE`)가 그 실패 타입을 받아 앱 코드로 답한다. 같은 유스케이스 실패에 web은 `ORDER_UNAVAILABLE`, GraphQL은 `DB_UNAVAILABLE`이다. 커밋 제목("네 전송이 같은 실패에 같은 코드로")과도 반대다. +- **발생 조건·영향**: + - 조건: 앱이 `GraphQlExceptionResolver`에 자기 실패를 등록하고, 그 실패를 만들 때 하위 실패를 원인으로 넘긴다(`new X(..., cause)`). 원인을 넘기는 것은 로그를 위한 Java의 보통 관례다. 예: 결제 의존 실패(`DependencyFailureException`)를 `PaymentUnavailableException`으로 바꿔 던짐. + - 영향: 클라이언트가 분기하는 `extensions.code`·`classification`·`retryable`이 앱이 정한 값에서 인프라 코드로 바뀐다. 예에서 `PAYMENT_UNAVAILABLE`을 기다리는 클라이언트가 `DEPENDENCY_5XX_SERVER`를 받는다. 업그레이드 안내 B-46은 이 변화를 적지 않아 서비스가 미리 알 수 없다. + - Important로 둔 이유: 공개 응답 코드가 앱이 일부러 정한 값과 다르게 나가고, 이번 수정이 만든 회귀다. 템플릿 자체에는 원인을 든 등록 매핑이 없어 템플릿 테스트에서는 드러나지 않는다. +- **테스트가 못 본 이유**: 새 테스트 `aCarrierWrappedInAnotherExceptionKeepsItsOwnCode`는 등록 매핑이 없는 `masking()` 매퍼로 감싼 carrier만 본다. 등록 매핑과 감싼 carrier가 함께 있는 경우가 없다. +- **고치는 법**: + - 권장: 판정 순서를 플랫폼 거부 → 실패 **자신**이 carrier → 등록된 application 매핑 → 원인 사슬의 첫 carrier → 거부된 인자로 바꾼다. 등록 매핑은 앱이 그 타입에 내린 결정이라 원인보다 앞선다. web의 도메인 advice 순서와 같아진다. 로그 줄은 지금처럼 찾은 carrier로 정한다. + - 대안: 지금 순서를 두고 "등록한 실패는 carrier를 원인으로 넘기지 않는다"를 매퍼 Javadoc·GraphQL README·B-46에 적는다. 앱 코드에 원인 버리기를 강요하고 web과 계속 다르다. + - RED 테스트 모양: 탐침 `Rr8RegisteredMappingProbeTest`를 `GraphQlWireErrorMapperTest`의 테스트로 옮긴다. 등록 매핑 + carrier 원인 → `ORDER_UNAVAILABLE`을 단언하면 `83a12f66`에서 `DB_UNAVAILABLE`로 실패한다. + - 고치는 법이 공개 응답을 되돌리므로 `docs/work/improve.md` 7절대로 소유자 확인이 필요하다. 다만 결정 전제 밖에서 바뀐 것을 결정 범위로 되돌리는 것이다. +- **이번 수정 / 이전부터**: 이번 수정(회귀). +- **증거**: E2 — 명령 A1·A2(같은 탐침을 두 커밋에서). 순서·문서 대조는 E1. +- **합칠 때 덧붙인 것(2026-11-07, `B-01-01`)**: 리뷰어 B가 같은 결함을 같은 모양으로 찾았다(B 탐침 P1, `~/r8-review-b-logs/`). B가 더 본 모양 하나: 서비스가 `LockAcquisitionTimeoutException` 자체를 `GraphQlExceptionResolver`에 등록해 두었으면(수정 전에는 500이라 둘 이유가 있었다) 그 매핑이 쓰이지 않고 `LOCK_ACQUISITION_TIMEOUT`이 나간다. 이 모양은 실패 **자신**이 carrier라, 권장안으로 순서를 고쳐도 그대로다. 그래서 어느 안을 고르든 업그레이드 안내 B-45의 "이 예외에 자기 `@ExceptionHandler`를 둔 서비스는 그쪽 응답이 그대로 나간다"(web 이야기)에 GraphQL 등록 매핑은 무시된다는 줄을 더한다. + +### RR8-01-02 · Minor · 락 timeout이 4xx가 되며 어느 락인지 서버 어디에도 남지 않는데, runbook은 그 정보가 없는 metric과 없는 테이블을 보라고 한다 + +- **위치**: + - 문서: `docs/runbooks/lock-acquisition-timeout.md:17`("A 4xx answer, so no server ERROR line — look at the metric"), `:25`("Check `lock.acquisition` metric for lock name and duration"), `:26`("check DB `integration_lock` table"). + - 레지스트리·코드: `docs/registries/metrics.yaml:301-318`(`lock.acquisition`은 `outcome` tag 하나뿐인 counter, "key 는 tag 로 넣지 않는다"), `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/lock/MeteredDistributedLock.java:48-50`(timeout은 세기만 하고 로그 없음), `src/adapter/outbound/persistence-jpa/src/main/resources/db/migration/postgresql/V4__int_lock.sql`(테이블 이름 `INT_LOCK`, `LOCK_KEY`는 key의 UUID). + - 코드(약속): `LockAcquisitionTimeoutException.java:14`("`getMessage()` is server-log-only"), `src/application-core/README.md:585`("진단용 `getMessage()`(key·waitTime 포함)는 서버 로그 전용"), `ServerFailureLog.java:76-83`(5xx가 아닌 carrier는 로그 없음). +- **무엇이 틀렸나**: + - 수정 전에는 락 timeout이 500 "unhandled exception" ERROR로 남았고, 그 예외 메시지에 락 key와 대기 시간이 있었다(r8-f1 RED 로그의 `unhandled exception on uri=…` + 예외). + - 수정 뒤에는 4xx carrier라 `ServerFailureLog.of`가 아무것도 남기지 않는다. 락 adapter(`MeteredDistributedLock`, `LockRegistryDistributedLock`)도 timeout에 로그를 남기지 않는다. 이제 "어느 락이 막혔나"는 서버 어디에도 없다. + - runbook은 "metric을 보라", "metric에서 lock name과 duration을 확인하라"고 한다. `lock.acquisition`은 `outcome` 하나만 tag로 가진 counter다. 이름도 시간도 없다. 레지스트리는 key를 tag로 넣지 말라고 적는다. + - runbook은 holder를 `integration_lock` 테이블에서 찾으라고 한다. 테이블은 `INT_LOCK`이고, `LOCK_KEY`는 key 자체가 아니라 key의 UUID다. `APP_MULTI_INSTANCE_ENABLED=false`(기본, in-process 락)이면 테이블이 쓰이지 않는다. + - 예외 Javadoc과 application-core README는 메시지가 "서버 로그 전용"이라고 적는다. 그 메시지를 남기는 서버 로그는 이제 없다. +- **발생 조건·영향**: + - 조건: 락 경합이 늘어 409 `LOCK_ACQUISITION_TIMEOUT`이 쌓이고, 운영자가 이 runbook을 연다. + - 영향: 운영자는 runbook대로 metric에서 락 이름을 찾지 못하고, 없는 테이블을 조회한다. 어느 임계 구역이 경합하는지 알아낼 길이 runbook에 없다. 수정 전에는 적어도 ERROR 로그에 key가 있었다. + - 처음에는 Important로 적었다(운영자에게 틀린 조치를 시키는 runbook). 두 리뷰를 합칠 때(2026-11-07) Minor로 정했다. 아래 「심각도 조정」. +- **테스트가 못 본 이유**: runbook을 읽는 테스트(`RunbookCoverageContractTest`)는 front matter의 `error_codes`와 stub 여부만 본다. 이 runbook은 그 테스트의 stub 허용 목록(`RunbookCoverageContractTest.java:101`)에 있다. 본문 절차를 실행하는 lane이 없다. 4xx carrier가 로그를 남기지 않는 것은 의도된 동작이고, 락에 대해 그 결과를 따로 보는 테스트가 없다. +- **고치는 법**: + - 권장: runbook Diagnosis를 있는 정보로 다시 쓴다. ① 경합 비율은 `lock.acquisition{outcome=timeout}`(이름·시간 없음을 명시). ② multi-instance면 holder는 `INT_LOCK`의 `REGION`·`CLIENT_ID`·`CREATED_DATE`로 보고, `LOCK_KEY`가 key의 UUID라 key 이름을 직접 볼 수 없다고 적는다. ③ 그 SQL에 `runbook-sql` 표시를 달아 다른 runbook처럼 실 PostgreSQL lane이 읽어 돌린다. 예외 Javadoc·application-core README의 "서버 로그 전용"은 "로그에 남지 않는다. 클라이언트에 보내지 않는다"로 고친다. + - 대안: 락 timeout에 WARN 한 줄(key의 digest, 대기 시간)을 남기는 곳을 정한다(`MeteredDistributedLock`). key에 엔티티 id가 들 수 있어 원문은 남기지 않는다(persistence-jpa `CLAUDE.md` 「Non-negotiables」). 그러면 runbook이 그 줄을 가리킬 수 있다. 로그 정책을 바꾸므로 소유자 결정이다. + - RED 테스트 모양: 권장안은 문서 수정이라 코드 RED가 없다. runbook SQL을 실 PostgreSQL에서 돌리는 테스트를 더하면, 지금 runbook의 `integration_lock`로는 "relation does not exist"로 실패한다. +- **심각도 조정(2026-11-07, 두 리뷰를 합칠 때)**: 리뷰어 A는 Important, B는 Minor(`B-01-02`)로 봤다. `review-criteria.md` 3절로 Minor로 정한다. + - Important의 "운영자에게 틀린 조치를 시키는 문서"는 절차로 내놓은 문서를 말한다. 이 runbook은 front matter `status: stub`이고 본문 끝이 "author body after domain adoption"이라 적어, 절차가 아니라 채울 자리로 내놓았다. `RunbookCoverageContractTest.java:101`의 stub 허용 목록에도 있다. + - "현실적 조건"을 보면, 템플릿 코드는 `DistributedLockPort.tryAcquire`를 부르지 않는다(main 코드 grep: 포트를 쓰는 곳은 락 adapter와, bean 타입만 확인하는 `StartupSafetyValidator`뿐). 이 코드는 포트를 쓰기로 한 서비스에서만 나고, 그 서비스가 runbook 본문을 쓸 차례다. + - 피해는 진단을 못 하는 것이다. 응답·데이터·보안·공개 계약은 맞다. + - 반론: 이번 수정이 이 runbook을 고쳐(`last_updated`, Symptoms) 관리되는 문서처럼 보이게 했다. 그래서 등급은 낮추되, runbook을 `active`로 올리기 전에 Diagnosis 두 줄을 먼저 고쳐야 한다는 점은 그대로 둔다. +- **이번 수정 / 이전부터**: 섞임. Diagnosis 두 줄의 잘못은 이전부터다. 이번 수정이 key가 남던 유일한 로그를 없애고 runbook에 "metric을 보라"를 더해, 틀린 안내가 유일한 진단 경로가 됐다. +- **증거**: E1 — 위 `file:line`(레지스트리 정의, adapter 코드, `ServerFailureLog.of`의 분기). + +## 18.6절에서 넘어온 항목 판정 + +README 18.6절 4번이 "다음 확인 리뷰가 판정한다"고 넘긴 전송 오류 항목이다. + +| 항목 | 판정 | 근거 | +|---|---|---| +| web 필터가 던진 carrier는 `EnvelopeErrorController`가 status만 봐 500 `INTERNAL_ERROR` | 결함 아님 | `EnvelopeErrorController.java:6-21` Javadoc이 필터가 던진 실패를 status로 분류한다고 적고, 다른 status가 필요한 필터는 `EnvelopeResponseWriter`로 그 코드를 쓰라고 안내한다. 템플릿 필터(web·web-advanced·graphql) 가운데 carrier를 던지는 것은 없다(grep: `JsonBodyLimitFilter`는 `MaxUploadSizeExceededException`, web-advanced carrier는 handler·resolver에서 던짐). carrier 계약(`ApiErrorCarrier`·shared-contract README)은 전송 처리기를 말하고 필터는 말하지 않는다 | + +## Declined to judge + +- `MethodArgumentTypeMismatchException`·`HttpMessageNotReadableException`처럼 Spring MVC가 감싸 web 전용 처리기로 가는 실패에 carrier가 원인으로 있는 경우(사용자 `Converter`나 Jackson creator가 carrier를 던짐): web은 원인을 보지 않고 `BAD_PARAMETER`·`VALIDATION_FAILED`로 답하고, STOMP는 `ConversionFailedException`의 원인 carrier로 로그를 정한다. 결정 「감싼 carrier를 전송이 읽는 법」이 전송 처리기 앞단(인자 변환)까지 덮는지 정해진 것이 없다. 템플릿에 carrier를 던지는 변환기가 없어(grep) 결함으로 세지 않았다. 맡긴 쪽이 결정 범위를 정할 일이다. 두 리뷰를 합칠 때(2026-11-07) README 19.4절 ④의 결정 행으로 올렸다. + +## 결론 + +Critical 0, Important 1, Minor 1, 회귀 1(RR8-01-01). 결함 2건: 이번 수정 1건, 섞임 1건. (처음 적을 때는 Important 2였다. RR8-01-02를 두 리뷰를 합칠 때 Minor로 정했다.) + +- RR7-01-03·04·06과 r8-f1 범위 밖 두 건은 닫혔다. RR7-01-05는 네 전송이 같은 함수를 쓰게 됐지만, GraphQL에서 그 함수의 자리가 등록 매핑보다 앞이라 + 결정 범위 밖의 응답을 바꿨다. +- 락 timeout은 이제 맞는 코드로 답하지만, 진단 흔적이 사라진 자리를 runbook이 틀린 안내로 채우고 있다. diff --git a/docs/reviews/2026-11-03-rereview/round8/02-architecture-rules.md b/docs/reviews/2026-11-03-rereview/round8/02-architecture-rules.md new file mode 100644 index 00000000..5ba7b377 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round8/02-architecture-rules.md @@ -0,0 +1,105 @@ +# 02 아키텍처 규칙 round7 수정 확인 리뷰 (2026-11-07) + +> 대상: `a8166598`(RR7-01-01·02: 설정 클래스 자신만 요청 처리기 목록으로, 중첩 클래스는 사용자 전송 목록에서 설정용 타입을 뺀 것으로 판정. +> route 등록 판정은 문서를 동작에 맞춤). 범위 `2c8a359d..83a12f66`, 기준 커밋 `83a12f66`. 영역 표와 명령 번호는 +> [01 문서](01-transport-errors.md) 「범위」·「실행한 명령과 결과」에 있다. + +## 범위 + +### pathspec + +``` +src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java +src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java +src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration +src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration +docs/manual/07-authorization.md +``` + +`git diff --stat 2c8a359d..83a12f66 -- `: 14개 파일, +725 −94. `ArchitectureViolationFixtureTest`의 Flyway 부분(`6764246a`)은 +03에서 봤다. 매뉴얼 07의 이력 ID 걷어내기(`81ef58ab`)는 06에서 봤다. + +함께 읽은 주변 코드: `ApplicationBoundaryArchitectureTest`의 `SYSTEM_DRIVEN_INBOUND_PACKAGES`·`ARE_USER_TRANSPORT_TYPES`·`ARE_USER_TRANSPORTS`(`:450-680`), +websocket adapter의 STOMP 설정(`WebSocketConfig.configureClientInboundChannel`)과 그 interceptor 둘, 매뉴얼 07 「시스템이 부르는 쓰기」·「규칙이 못 보는 길」, +업그레이드 안내 B-16. + +### 수정 보고의 「새로 가정하는 것」 + +공유 노트 `r8-f2-arch-rules.md`의 칸을 옮겼다. + +| 가정 | 확인 | +|---|---| +| 1. 설정용 타입(`servlet.config.annotation`, `reactive.config`, `socket.config.annotation`, `messaging.simp.config`, `web.cors`, `RequestMethod`)의 코드는 기동 때만 돈다. 이것을 구현해 요청마다 도는 클래스(CORS source·processor)는 요청 타입을 파라미터로 받아 따로 잡힌다 | 참. CORS source·processor는 `HttpServletRequest`(`jakarta.servlet.http`)나 `ServerWebExchange`(`org.springframework.web.server`)를 받아 사용자 전송 타입으로 잡힌다. `WebMvcConfigurer`의 `addInterceptors`·`addArgumentResolvers`는 `HandlerInterceptor`·`HandlerMethodArgumentResolver`(사용자 전송 타입, 설정용 아님)를 이름에 남겨 잡힌다 | +| 2. 설정용 타입에만 의존하는 중첩 클래스는 요청 경로가 아니다 | 대체로 참. 다만 설정용 타입 `ChannelRegistration`(`messaging.simp.config`)이 받는 STOMP inbound channel interceptor는 요청(클라이언트 프레임)마다 돈다. 그 interceptor 타입은 사용자 전송 목록에 없어 이 가정과 상관없이 보이지 않는다(RR8-02-01) | +| 3. `@CrossOrigin`은 handler annotation, `HttpServletRequest`를 받는 설정 람다는 요청 처리 코드다 | 참. 거짓 실패 쪽이다 | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 테스트가 이름대로, 읽기 전용 | RR7-01-01·02 닫힘, 새 목록 셋의 경계 | +| `docs/work/reference/review-criteria.md` 7절 | 규칙 테스트가 위반·허용 fixture를 둘 다 가지나 | 새 fixture 9개(위반 5, 허용 4)와 목록 대조 테스트 | +| `docs/work/reference/defect-patterns.md` A1·A10 | 갈라진 목록, 글로만 있는 약속 | 사용자 전송 목록이 템플릿 자신의 STOMP 진입 타입을 덮는지 | + +### 실행한 명령과 결과 + +명령 A8(`:app-bootstrap:architectureTest --rerun` 포함)의 결과는 [03 문서](03-migration.md) 「실행한 명령과 결과」에 있다. 이 영역의 발견은 +탐침 없이 코드로 확인했다. STOMP channel interceptor 탐침을 쓰려 했으나 `spring-messaging`이 `architectureTestCompileClasspath`에 없다 +(`src/app-bootstrap/gradle.lockfile:364`, runtime에만 있음). lockfile을 바꾸는 탐침은 리뷰 범위를 넘어 쓰지 않았다. + +### 못 본 것 + +- JAX-RS·JSR-356 런타임 기동: 템플릿에 런타임이 없다. 규칙 판정만 봤다(묶음 보고의 fixture 테스트, E0). + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR7-01-01 (설정에 중첩된 JAX-RS 자원·`@ServerEndpoint` 회귀) | 닫힘 | `ApplicationBoundaryArchitectureTest.java:653-667`(`waysInFor`: 중첩 클래스는 `MAKE_A_NESTED_CLASS_A_WAY_IN` = 사용자 전송 목록 − 설정용), 위반 fixture `jaxrs/RunNowResourceConfigurationFixture`·`RunNowThroughTheConfigurationFixture`·`jsr356/RunNowEndpointConfigurationFixture`와 테스트 셋. 목록 대조 `UserTransportTypeListsTest` 두 테스트 | +| RR7-01-02 (메서드 참조 route 등록의 거짓 실패와 문서) | 닫힘 | 판정은 그대로, Javadoc(`:549-563`)·실패 메시지(`:801-812`)·매뉴얼 07 `:106`·B-16이 "등록도 사용자 전송"으로 맞음. 위반 fixture `RoutesBesideASystemCallerConfigurationFixture`, 허용 fixture `OrderRoutesConfigurationFixture`, CORS 두 모양 허용 fixture | +| round7 1차 Declined ①(WebFlux `WebFilter`·`WebHandler`가 중첩 클래스에서 빠짐) | 닫힘 | 중첩 클래스가 `org.springframework.web..` 전체를 보는 사용자 전송 목록으로 판정된다(`:471-481`) | + +## 결함 + +### RR8-02-01 · Minor · STOMP inbound channel interceptor(`ChannelInterceptor`)가 사용자 전송 타입이 아니어서, 클라이언트 프레임마다 도는 interceptor가 `@SystemCaller`를 불러도 잡히지 않는다 — 매뉴얼 07은 설정에 중첩된 클래스는 이 사각지대에 들지 않는다고 적는다 + +- **위치**: + - 코드: `src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java:471-481`(`org.springframework.messaging`은 `simp`만), `:483-487`(이름 둘: `Controller`, `MessageMapping`), `:614-615`(중첩 클래스 판정), `:580-586`(`messaging.simp.config`가 설정용 타입). + - 템플릿의 같은 진입점: `src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/WebSocketConfig.java:92-94`(`configureClientInboundChannel`이 interceptor를 등록), `WebSocketCorrelationInterceptor`·`WebSocketInboundAuthorizationInterceptor`(`ChannelInterceptor` 구현). + - 문서: `docs/manual/07-authorization.md:133-135`("설정 안에 중첩한 클래스는 더 넓은 사용자 전송 타입 목록으로 보므로 여기에 들지 않는다"), `:84`("사용자 전송: 사용자가 보낸 요청이 들어오는 inbound adapter다(web·GraphQL·gRPC·WebSocket)"). +- **무엇이 틀렸나**: + - STOMP 클라이언트가 보낸 프레임은 모두 inbound channel interceptor를 지난다. 템플릿도 이 자리에서 인증·상관 id를 처리한다. + - interceptor 타입 `org.springframework.messaging.support.ChannelInterceptor`와 그 인자 `Message`·`MessageChannel`은 사용자 전송 목록 밖이다. 목록은 `org.springframework.messaging` 가운데 `simp`와 `@MessageMapping`만 담는다. + - 그래서 `WebSocketMessageBrokerConfigurer`를 구현한 설정이 `configureClientInboundChannel`에서 익명 `ChannelInterceptor`를 등록하고, 그 `preSend`가 `@SystemCaller`를 불러도 잡히지 않는다. 설정 자신은 설정용 타입(`ChannelRegistration`)만 쓰고, 중첩된 익명 interceptor는 목록 밖 타입만 쓴다. `simp` 타입(`StompHeaderAccessor`)을 쓰지 않는 최상위 interceptor 클래스도 같다. + - 이번 수정은 매뉴얼 07 「규칙이 못 보는 길」에 "설정 안에 중첩한 클래스는 … 여기에 들지 않는다"를 더했다. STOMP interceptor는 그 문장이 덮는다고 말하는 경우인데 잡히지 않는다. +- **발생 조건·영향**: + - 조건: 서비스가 STOMP inbound interceptor에서 작업을 부르고(예: 특정 destination의 프레임이 오면 정산 작업을 돌림), `simp` 타입을 쓰지 않는다. + - 영향: 인증만 된 WebSocket 클라이언트가 권한 검사 없는 `@SystemInvoked` 쓰기를 부른다. 빌드는 신호를 내지 않는다. + - Minor로 둔 이유: interceptor에서 작업을 부르는 모양이 드물고, 대부분의 interceptor는 `StompHeaderAccessor`를 써서 잡힌다. +- **테스트가 못 본 이유**: STOMP 쪽 fixture는 `@MessageMapping`·`WebSocketHandler`·`@ServerEndpoint` 모양만 있다. `UserTransportTypeListsTest`는 목록끼리의 관계만 본다. 목록이 각 전송의 진입 타입을 덮는지는 보지 않는다. +- **고치는 법**: + - 권장: `USER_TRANSPORT_TYPE_NAMES`에 `org.springframework.messaging.support.ChannelInterceptor`와 `org.springframework.messaging.support.ExecutorChannelInterceptor`를 더한다. 두 타입은 템플릿에서 websocket adapter만 쓴다(grep). broker listener의 `@Payload`·`@Header`를 피하려던 이유(`:463-465`)와 부딪히지 않는다. 함수형 인터페이스가 아니라 설정 자신이 람다로 쓸 수 없으므로 요청 처리기 목록에는 넣지 않아도 된다. + - 대안: 매뉴얼 07 「규칙이 못 보는 길」에 STOMP channel interceptor를 사각지대로 적고, `:135` 문장을 "목록에 든 타입에 한해"로 좁힌다. 막지 않고 리뷰에 맡긴다. + - RED 테스트 모양: 위반 fixture 둘(설정에 중첩된 익명 interceptor, `simp` 타입을 쓰지 않는 최상위 interceptor)이 `@SystemCaller`를 부르고, `83a12f66`에서 위반 0으로 실패하는 것을 본다. 허용 fixture: 같은 설정이 interceptor 없이 broker만 설정. fixture는 `spring-messaging`이 필요해 `architectureTestCompileOnly`와 lockfile을 함께 바꾼다. +- **이번 수정 / 이전부터**: 섞임. 목록의 빈칸은 이전부터다(r8-f2 보고 「범위 밖」이 같은 것을 적었다). 이번 수정이 매뉴얼에 "중첩 클래스는 사각지대에 들지 않는다"를 더했다. +- **증거**: E1 — 위 `file:line`. 탐침은 컴파일 classpath 때문에 쓰지 않았다(「실행한 명령과 결과」). +- **합칠 때 덧붙인 것(2026-11-07, `B-02-01`)**: 리뷰어 B가 같은 결함을 탐침으로 확인했다(B 탐침 P4, 버릴 worktree에서 `architectureTestCompileOnly 'org.springframework:spring-messaging'`과 lockfile 한 줄을 더하고 `--write-locks`로 실행, `~/r8-review-b-logs/`). 결과: `StompHeaderAccessor`를 읽는 interceptor는 잡히고 일반 `ChannelInterceptor`는 잡히지 않는다. 증거는 E2(B의 실행)로 올린다. B는 이 결함을 「이전부터」로 적었다. 이 리뷰는 매뉴얼 07 `:135`의 새 문장이 이 빈칸을 덮었다고 약속해 「섞임」으로 둔다. + +## 18.6절에서 넘어온 항목 판정 + +| 항목 | 판정 | 근거 | +|---|---|---| +| STOMP channel interceptor 타입이 사용자 전송 목록에 없음 | 결함 → RR8-02-01 | 위 | +| 설정 클래스 자신에 직접 쓴 WebFlux `WebFilter`·`WebHandler`가 요청 처리기 목록 밖 | 결함 아님 | 매뉴얼 07 `:133-135` 「규칙이 못 보는 길」이 "설정 클래스 자신에 쓴 요청 처리 코드가 요청 처리기 타입 목록에 없는 타입으로 쓰인 경우"를 사각지대로 적고, 막는 것을 리뷰로 둔다(`:145-147`). 템플릿은 서블릿 스택이고 WebFlux가 classpath에 없다. 중첩 클래스로 둔 WebFlux 타입은 이번 수정으로 잡힌다 | + +## Declined to judge + +없다. + +## 결론 + +Critical 0, Important 0, Minor 1, 회귀 0. 결함 1건(섞임). + +- RR7-01-01·02는 닫혔다. 목록을 셋으로 나누고 대조 테스트를 둔 방법은 round7 권장안보다 r9 동작에 가깝고, 고른 이유가 커밋 본문에 있다. +- 남은 것은 사용자 전송 목록이 템플릿 자신의 STOMP 진입 타입 하나를 덮지 않는 것이다. 이번 수정의 매뉴얼 문장이 그 빈칸을 덮었다고 말한다. diff --git a/docs/reviews/2026-11-03-rereview/round8/03-migration.md b/docs/reviews/2026-11-03-rereview/round8/03-migration.md new file mode 100644 index 00000000..a5670314 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round8/03-migration.md @@ -0,0 +1,194 @@ +# 03 마이그레이션·Flyway 규칙 round7 수정 확인 리뷰 (2026-11-07) + +> 대상: `6ec0c4f7`(RR7-03-01~05: 실패한 동시 인덱스 마이그레이션 복구 절차, 검사기 설명, ledger IT)과 `6764246a`(RR7-03-06: Flyway 규칙이 설정 +> 객체를 직접 만드는 길도 막음). 범위 `2c8a359d..83a12f66`, 기준 커밋 `83a12f66`. 영역 표는 [01 문서](01-transport-errors.md) 「범위」에 있다. + +## 범위 + +### pathspec + +``` +docs/jpa docs/runbooks/migration-failed.md docs/study docs/manual/04-persistence.md +src/adapter/outbound/persistence-jpa/build.gradle src/adapter/outbound/persistence-jpa/CLAUDE.md +src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration +src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest src/adapter/outbound/persistence-jpa/src/test +src/adapter/outbound/persistence-jpa/src/testFixtures src/grpc +src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java +src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/persistence +src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence +``` + +`git diff --stat 2c8a359d..83a12f66 -- `: 28개 파일, +747 −125. `ArchitectureViolationFixtureTest`의 Flyway 테스트 두 개는 02의 +pathspec에 들지만 여기서 봤다. 매뉴얼 04의 이력 ID 걷어내기(`81ef58ab`)는 06에서 봤다. + +함께 읽은 주변 코드: `PostgreSqlConcurrentIndexMigrationIntegrationTest` 전체(도우미 `within`·`cancelLockWaits`·`aftermath`), +`LockWaitMigrationInspector`의 `LOCKING` 패턴과 `outsideATransaction`, migration-guide 「Bound the lock wait」·「Concurrent index builds」, +`docs/jpa/runbooks.md` 「An invalid index exists」, PostgreSQL `DROP INDEX CONCURRENTLY`의 단계(아래 탐침으로 확인). + +### 수정 보고의 「새로 가정하는 것」 + +수정 보고는 repo에 없다(공유 노트 `r8-f3-persistence.md`에 이 칸이 없다). 두 커밋 본문 「위험·한계」와 README 18.4절 결정 칸에서 뽑았다. + +| 가정 | 확인 | +|---|---| +| 동시 인덱스 문장 하나만 든 마이그레이션이 실패하면, 무효 인덱스를 지우고 그 버전의 실패 행만 지운 뒤 다시 배포하면 된다(runbook 절차, 소유자 결정 (a)) | **`CREATE`·`REINDEX`에는 참, `DROP INDEX CONCURRENTLY`에는 거짓.** 실패한 drop이 남긴 무효 인덱스는 그 마이그레이션이 지우려던 인덱스다. 절차대로 지우면 재배포의 `DROP INDEX CONCURRENTLY`가 "does not exist"로 다시 실패한다(RR8-03-01, 명령 A7) | +| runbook의 `DELETE`는 한 행만 지운다 | 참. 탐침에서 1행(명령 A7). 0행이면 다시 분류하라는 안내가 있다 | +| 검사기 변경으로 새로 걸리는 파일은 PostgreSQL이 배포 때 거부하는 파일뿐이다 | 참. 바뀐 분기는 Flyway가 트랜잭션 밖에서만 돌리는 잠금 문장(`VACUUM FULL`, `REINDEX SCHEMA|DATABASE|SYSTEM`)이 `.sql.conf`의 `executeInTransaction=true`로 트랜잭션 안에 들어간 경우뿐이다(`LockWaitMigrationInspector.java:256-273`) | +| ledger 복사 파일 두 개(`ConcurrentIndexMigrationInspector`, `MigrationResource`)는 JDK만 쓴다 | 참. 두 파일의 import가 `java.*`뿐이다 | +| Flyway `Configuration`에 대입 가능한 타입의 생성자 접근을 막으면 직접 만든 설정이 모두 걸린다 | 참으로 봤다. 하위 클래스의 생성자도 상위 생성자를 부른다. 리플렉션·`configuration(Map)`으로 잠금 값을 덮는 길은 커밋 본문이 한계로 적었다 | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 읽기 전용 | RR7-03-01~06 닫힘, runbook 절차가 범위로 적은 세 문장 모두에서 맞는지 | +| `docs/work/reference/review-criteria.md` 1절 「운영자에게 틀린 조치를 시키는 문서」 | 문서대로 실행한 결과 | runbook SQL을 runbook에서 읽어 실 PostgreSQL에서 그대로 돌림 | +| `docs/work/improve.md` 4.1절 5단계(탐침) | 코드 읽기로 정해지지 않는 동작은 별도 worktree 탐침으로 | `DROP INDEX CONCURRENTLY`가 기다리다 취소되면 무엇을 남기는지(무효 표시가 먼저 커밋되는지) | + +### 실행한 명령과 결과 + +명령 번호는 여섯 영역 문서가 같이 쓴다(A1·A2는 01, A3~A6은 04). desktop `~/workspace/r8-review-a`(`83a12f66` + 탐침), 공유 잠금, +`--no-build-cache`, 로그 `~/r8-review-a-logs/`. + +| # | 명령 | 결과 | 시간 | 직전 부하(1분) | +|---|---|---|---|---| +| A7 | `:adapter:outbound:persistence-jpa:postgresqlConcurrentIndexMigrationIntegrationTest --tests '*PostgreSqlConcurrentIndexMigrationIntegrationTest.rr8probe*'` | rc=0. 결과는 아래 표 | 36초 | 2.27 | +| A8 | `:shared-contract:test --rerun :application-core:test --rerun :adapter:inbound:web:test --rerun :adapter:inbound:graphql:test --rerun :adapter:inbound:grpc:test --rerun :adapter:inbound:websocket:test --rerun :adapter:outbound:httpclient:test --rerun :adapter:outbound:cache-redis:test --rerun :adapter:outbound:persistence-jpa:test --rerun :app-bootstrap:architectureTest --rerun --continue` | 아래 「A8 결과」 | — | — | + +탐침 `rr8probeAFailedConcurrentDropRecoveredByTheRunbook`(기존 lane 클래스에 넣은 메서드, 공유 노트 `r8-review-a-probes/drop-index-probe.java.txt`): +V1이 표를 만들고 `ix_probe_id`를 만든다. 다른 연결이 그 표를 읽은 채 트랜잭션을 열어 둔다. V2 `DROP INDEX CONCURRENTLY ix_probe_id`(`.sql.conf` +`executeInTransaction=false`)를 템플릿 Flyway로 배포하고, 기존 도우미 `within`이 30초 뒤 잠금 대기를 취소한다. 그다음 runbook의 SQL 세 블록을 +runbook 파일에서 읽어(`OutboxRunbookSql`) 차례로 돌리고 다시 배포한다. + +| 단계 | 결과 | +|---|---| +| 배포 | 30초 안에 끝나지 않아 취소. `57014 canceling statement due to user request` | +| 실패 뒤 | `indexes [ix_probe_id false, probe_pkey true], history [1 true, 2 false]` — 무효 인덱스 + 실패 행 | +| runbook 1단계(빌드 확인) | 0행 | +| runbook 2단계(무효 인덱스 drop) 뒤 | `indexes [probe_pkey true]` | +| runbook 4단계(실패 행 delete) | 1행 | +| runbook 5단계(다시 배포) | 실패. `42704 ERROR: index "ix_probe_id" does not exist` | +| 다시 배포 뒤 | `history [1 true, 2 false]` — 처음과 같은 막힌 상태 | + +#### A8 결과 + +rc=0, 1분 52초, 직전 부하 1.57. `175 actionable tasks: 122 executed, 53 up-to-date`, FROM-CACHE 0. 테스트 태스크 10개가 모두 실행됐다(로그 `> Task` 줄). +결과 XML 합계(탐침 포함, 실패·오류 0): + +| leaf | 테스트 | skip | +|---|---|---| +| shared-contract `test` | 269 | 0 | +| application-core `test` | 426(탐침 3) | 19(in-memory fake 시간 케이스, 이전부터) | +| web `test` | 341 | 0 | +| graphql `test` | 405(탐침 1) | 0 | +| grpc `test` | 74 | 0 | +| websocket `test` | 105 | 0 | +| httpclient `test` | 360 | 0 | +| cache-redis `test` | 228(탐침 3) | 0 | +| persistence-jpa `test` | 666 | 0 | +| app-bootstrap `architectureTest` | 242 | 0 | + +A9 `-p build-logic test --rerun`: rc=0, 41초, 직전 부하 5.13, 173건 실패·skip 0(05 영역). + +### 못 본 것 + +- ledger optional 빌드의 lane(`-p optional-platforms … integrationTest`): 묶음 보고의 실행(E0)만 있다. 바뀐 코드는 IT 도우미라 다시 돌리지 않았다. +- `REINDEX … CONCURRENTLY` 실패의 복구: `_ccnew` 인덱스가 남고 원래 인덱스는 살아 있어 2단계가 맞는 조치다. 코드로만 봤다. + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR7-03-01 (ledger IT의 없는 예외 목록) | 부분(합칠 때 고침) | `GrpcOperationLedgerMigrationLockWaitIT.java`의 `RUN_OUTSIDE_A_TRANSACTION`과 그 목록을 가이드에 묶는 테스트, 파일마다 따로 실행하는 `GrpcOperationLedgerMigrations.before`. 처음에는 닫힘으로 적었다. 목록을 지키는 테스트가 빈 목록 위에서 아무것도 단언하지 않는 것은 아래 RR8-03-04 | +| RR7-03-02 (REINDEX 다섯 형태 설명) | 닫힘 | 가이드 `:80-91`·`:136-141`, 검사기 Javadoc, 학습 문서 8.2절이 "SCHEMA·DATABASE는 Flyway가 트랜잭션 밖, INDEX·TABLE CONCURRENTLY는 안"으로 같다 | +| RR7-03-03 (실패 행 때문에 다음 배포가 막힘) | 부분 | `CREATE [UNIQUE] INDEX CONCURRENTLY`는 runbook 절차로 복구된다(기존 IT). `DROP INDEX CONCURRENTLY`는 같은 절차로 다시 막힌다(RR8-03-01) | +| RR7-03-04 ("섞인 파일은 부분 적용되지 않는다") | 닫힘 | 설정 없음/`executeInTransaction=false` 두 경우를 IT가 고정, 문서가 두 경우를 나눠 적음 | +| RR7-03-05 (`executeInTransaction=true` + `VACUUM FULL` 통과) | 닫힘 | `LockWaitMigrationInspector.java:256-273`(트랜잭션 안에서 돌 수 없는 문장은 `.sql.conf`와 상관없이 거부), 테스트 2건 | +| RR7-03-06 (Flyway 설정 객체 직접 생성) | 닫힘 | `JpaProductionArchitectureTest`의 `EVERY_FLYWAY_STARTS_FROM_THE_SCHEMA_POLICY`(생성자 접근 규칙), 위반 fixture 4개·허용 fixture 1개 | + +## 결함 + +### RR8-03-01 · Important · 실패한 `DROP INDEX CONCURRENTLY` 마이그레이션에 runbook 복구 절차를 그대로 따르면 재배포가 "index does not exist"로 다시 실패해 같은 막힌 상태로 돌아간다 + +- **위치**: + - 문서: `docs/runbooks/migration-failed.md:115-120`(이 절의 대상에 `DROP INDEX CONCURRENTLY`를 넣음), `:132-133`(2단계 "Drop the invalid index the build left"), `:154`(5단계 "Flyway runs the same migration from the start and builds the index"). + - 같은 절차를 가리키는 곳: `docs/jpa/migration-guide.md:168-173`, `docs/jpa/runbooks.md:76-80`, `docs/study/postgresql-jpa-walkthrough.ko.md:1381-1383`, `ConcurrentIndexMigrationInspector.java:23-30`·`:107-115`(Javadoc과 실패 메시지). + - 테스트: `PostgreSqlConcurrentIndexMigrationIntegrationTest.aFailedConcurrentIndexMigrationIsRecoveredByTheRunbookProcedure`는 `CREATE UNIQUE INDEX CONCURRENTLY` 한 경우만 돌린다. +- **무엇이 틀렸나**: + - `DROP INDEX CONCURRENTLY`는 인덱스를 먼저 무효로 표시해 커밋하고, 그 표를 쓰는 트랜잭션이 끝나기를 기다린 뒤 지운다. 기다리는 중에 취소·`statement_timeout`·`lock_timeout`으로 실패하면 그 인덱스는 무효로 남고 Flyway는 실패 행을 남긴다(탐침 「실패 뒤」). + - runbook 2단계는 그 무효 인덱스를 지우라고 한다. 그 인덱스가 바로 마이그레이션이 지우려던 인덱스다. 4단계로 실패 행을 지우고 5단계로 다시 배포하면, 같은 `DROP INDEX CONCURRENTLY ix_probe_id`가 "does not exist"(`42704`)로 실패하고 실패 행이 다시 생긴다(탐침 「다시 배포 뒤」). + - 5단계 문장 "builds the index"는 drop 마이그레이션에 맞지 않는다. 절의 범위 문장(`:117-118`)은 drop을 대상에 넣는다. +- **발생 조건·영향**: + - 조건: 서비스가 쓰지 않는 인덱스를 `DROP INDEX CONCURRENTLY `(`IF EXISTS` 없이) 마이그레이션으로 지운다. 배포가 오래 열린 트랜잭션(보고서 쿼리, 운영자가 열어 둔 `BEGIN`) 뒤에서 기다리다 취소된다. 가이드도 "오래 열린 트랜잭션이 빌드를 잡는다"고 적을 만큼 흔한 상황이다. + - 영향: P1 runbook을 따른 운영자가 같은 실패를 되풀이한다. 새 릴리스는 계속 기동하지 못한다. runbook은 0행이면 다시 분류하라고만 하고, 이 경우를 다루지 않는다. 운영자가 결국 "이력을 고치지 않는다"의 예외를 넓히거나 마이그레이션 파일을 고치는 쪽(둘 다 금지)으로 밀린다. + - Important로 둔 이유: 운영자에게 틀린 조치를 시키는 runbook이고, 문서대로 실 PostgreSQL에서 실행해 재현했다. +- **테스트가 못 본 이유**: runbook을 실행하는 IT가 unique `CREATE` 실패 한 경우만 본다. 절의 범위는 `CREATE`·`DROP`·`REINDEX` 셋이다. +- **고치는 법**: + - 권장: runbook 2단계를 문장 종류로 나눈다. 실패한 마이그레이션이 `CREATE`·`REINDEX`면 남은 무효 인덱스(`REINDEX`면 `_ccnew`)를 지운다. `DROP INDEX CONCURRENTLY`면 지우지 않는다 — 다시 배포한 같은 문장이 무효 인덱스를 지운다. 5단계 문장도 "runs the same statement again"으로 고친다. 가이드·학습 문서·검사기 메시지의 한 줄 요약도 같이 고친다. IT에 탐침 모양(drop을 기다리게 한 뒤 취소)을 더해 고친 절차로 재배포가 성공하는지 본다. + - 대안: 가이드와 `ConcurrentIndexMigrationInspector`가 `DROP INDEX CONCURRENTLY`에 `IF EXISTS`를 요구한다. 그러면 지금 절차도 통한다. 이미 배포된 파일은 고칠 수 없어, 새 파일부터만 지켜진다. + - RED 테스트 모양: 탐침 `rr8probeAFailedConcurrentDropRecoveredByTheRunbook`을 단언으로 바꾼다(재배포 뒤 `history [1 true, 2 true]`). `83a12f66`의 runbook으로는 `42704`로 실패한다. +- **이번 수정 / 이전부터**: 이번 수정. 이 runbook 절은 `6ec0c4f7`이 새로 만들었다. +- **증거**: E3 — 명령 A7(runbook SQL을 runbook 파일에서 읽어 실 PostgreSQL에서 그대로 실행). + +### RR8-03-02 · Minor · 동시 인덱스 IT의 Javadoc이 runbook에 없는 절 이름("A concurrent index migration failed")을 가리킨다 + +- **위치**: `src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlConcurrentIndexMigrationIntegrationTest.java:65-66`. 실제 절 제목은 `docs/runbooks/migration-failed.md:113` "Recover a failed concurrent index migration"이다. +- **무엇이 틀렸나**: 클래스 Javadoc이 runbook의 `("A concurrent index migration failed")` 절을 읽는다고 적는다. 그런 제목은 없다. 비슷한 말은 Diagnosis 목록의 한 줄(`:66`, 소문자)뿐이다. 다른 문서(가이드, 검사기, `docs/jpa/runbooks.md`)는 모두 올바른 제목을 쓴다. +- **발생 조건·영향**: 테스트를 읽고 runbook 절을 찾는 사람이 틀린 이름으로 찾는다. 동작 영향은 없다. +- **테스트가 못 본 이유**: Javadoc의 인용은 검사 대상이 아니다. +- **고치는 법**: Javadoc을 `"Recover a failed concurrent index migration"`으로 고친다. RED 없음(문구). +- **이번 수정 / 이전부터**: 이번 수정. +- **증거**: E1 — 위 `file:line`. + +## 합칠 때 넣은 결함 (2026-11-07, 총괄 요청) + +독립 리뷰어 B에게만 있던 두 결함(`B-03-01`, `B-03-02`, 노트 `r8-review-b.md` 6절)을 총괄이 보냈다. 근거를 다시 읽고 하나는 변이 탐침으로 확인해 +이 영역의 다음 번호로 넣었다. + +| # | 명령 | 대상 | 결과 | 시간 | 직전 부하(1분) | +|---|---|---|---|---|---| +| A10 | `-p optional-platforms :grpc:grpc-operation-ledger-jpa:integrationTest --tests '*GrpcOperationLedgerMigrationLockWaitIT.everyMigrationListedAsRunningOutsideATransactionIsOneConcurrentIndexBuildThatSaysSo'` | `83a12f66` 그대로 | rc=0, 1건 통과 | 13초 | 0.13 | +| A11 | 같은 명령 | 변이: 루프 안 거부 조건 셋(트리에 없음, 동시 인덱스 문장 없음, 검사기 예외)에 모두 `&& migration.isEmpty()`를 붙여 아무것도 거부하지 못하게 함 | rc=0, 1건 통과 — 변이가 살아남음 | 6초 | 0.80 | +| A12 | 같은 명령 | 원래 코드 + 목록에 트리에 없는 파일 하나(`V999__not_in_the_tree.sql`) | rc=1, 1건 실패 `… is not a migration in the ledger tree` | 5초 | 1.13 | + +desktop 임시 worktree `~/workspace/r8-review-a-pass2`(`83a12f66`), 공유 잠금, `--no-build-cache`, FROM-CACHE 0, 로그 `~/r8-review-a-logs/pass2/`. +변이 스크립트는 공유 노트 `r8-review-a-probes/pass2/ledger_mutation.py`, 결과 `pass2/results.txt`. worktree는 지웠다. + +### RR8-03-03 · Minor · runbook SQL 리더 `OutboxRunbookSql`이 이제 마이그레이션 runbook도 읽는데 이름은 outbox 전용이다 + +- **위치**: `src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java:9-18`(Javadoc "the outbox runbooks, and the migration runbook's recovery"), 사용처 `PostgreSqlConcurrentIndexMigrationIntegrationTest.java:209`(마이그레이션 runbook), `PostgreSqlOutboxDispositionRunbookIntegrationTest.java:44-50`, `PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java:50-56`. +- **무엇이 틀렸나**: 클래스는 runbook 하나에서 `runbook-sql` 블록을 읽는 공용 리더가 됐다. 이름 `OutboxRunbookSql`은 outbox runbook 전용이라고 말한다(관점 24 「이름과 내용이 다름」). 이번 수정이 Javadoc만 넓히고 이름은 두었다(공유 노트 `r8-f3-persistence.md` 「합칠 때 볼 것」 "이름은 그대로"). +- **발생 조건·영향**: 다음에 다른 runbook(예: RR8-01-02를 고칠 때의 `INT_LOCK` 조회)의 SQL을 lane으로 돌리려는 사람이 이름으로 공용 리더를 찾지 못하고 사본을 만든다. 사본은 runbook과 갈라질 수 있다(A1). 동작 영향은 없다. +- **테스트가 못 본 이유**: 이름은 검사 대상이 아니다. +- **고치는 법**: `RunbookSql`로 이름을 바꾼다. 사용처 세 클래스는 같은 source set이다. 동작 변경 없음이라 RED가 없고, 같은 source set의 IT lane 셋이 그대로 통과하는지 본다. +- **이번 수정 / 이전부터**: 이번 수정(`6ec0c4f7`). +- **증거**: E1 — 위 `file:line`과 사용처 grep. 이름 문제라 탐침으로 더 알 것이 없다. +- **출처**: 리뷰어 B `B-03-01`. + +### RR8-03-04 · Minor · ledger IT의 예외 목록 검사 테스트가 빈 목록 위에서 돌아, 검사 코드를 망가뜨려도 통과한다 + +- **위치**: `src/grpc/grpc-operation-ledger-jpa/src/integrationTest/java/dev/caskeleton/grpc/ledger/GrpcOperationLedgerMigrationLockWaitIT.java:88`(`RUN_OUTSIDE_A_TRANSACTION = Map.of()`), `:141-177`(`everyMigrationListedAsRunningOutsideATransactionIsOneConcurrentIndexBuildThatSaysSo`, 루프 `:149`, 단언 `:176`). 이 테스트를 지키는 장치로 가리키는 곳: `docs/jpa/migration-guide.md:126-128`, 같은 IT의 실패 메시지(`:125-133`). +- **무엇이 틀렸나**: + - 테스트 이름이 말하는 성질은 "목록의 파일은 트리에 있고, 동시 인덱스 문장 하나이고, `executeInTransaction=false`를 적었다"다. + - 목록이 비어 있어 루프 본문이 한 번도 돌지 않는다. 단언 `refused.isEmpty()`는 늘 참이다. + - 변이 A11: 거부 조건 셋을 모두 무력하게 바꿔도 통과한다. 대조 A12: 원래 코드는 목록에 잘못된 파일이 들어가면 잡는다. 검사 코드는 지금 맞지만, 그것을 지키는 테스트가 없다. +- **발생 조건·영향**: 누가 이 검사 코드를 고치다 망가뜨려도 빌드는 모른다. 첫 동시 인덱스 파일이 목록에 들어갈 때 처음으로 검사가 돌고, 그때 망가진 검사가 가이드를 어긴 파일(섞인 문장, `.conf` 없음)을 통과시킨다. 가이드는 이 테스트가 목록을 지킨다고 적는다. +- **테스트가 못 본 이유**: 규칙 테스트에 위반·허용 fixture가 없다(`review-criteria.md` 7절). r8-f3는 임시 V004 탐침으로 확인했고 탐침은 repo에 남지 않았다. +- **고치는 법**: + - 권장: 판정을 static 메서드로 뺀다. 입력은 목록, 트리, 파일 이름 → SQL, 파일 이름 → `executeInTransaction`이고 출력은 거부 이유 목록이다. 같은 IT에 문자열 fixture로 위반 넷(트리에 없음, 동시 인덱스 문장 없음, `.conf` 없음, 다른 문장과 섞임)과 허용 하나(동시 인덱스 문장 하나 + `executeInTransaction=false`)를 두고 그 메서드를 부른다. 실제 목록 검사도 그 메서드를 부른다. + - 대안: 판정을 testkit의 `ConcurrentIndexMigrationInspector` 쪽으로 옮겨 persistence-jpa 단위 테스트가 fixture를 갖게 한다. ledger는 이미 그 파일을 복사해 쓰므로 같은 검사가 두 빌드에서 돈다. 다만 복사 파일이 늘면 "JDK만" 규칙을 지킬 파일이 늘어난다. + - RED 테스트 모양: 위반 fixture 넷이 각각 거부되는지 단언한다. A11의 변이를 얹으면 그 테스트들이 실패해야 한다. +- **이번 수정 / 이전부터**: 이번 수정(`6ec0c4f7`). +- **증거**: E2 — 명령 A10~A12(이름 붙은 테스트를 원래·변이·대조로 실행). +- **출처**: 리뷰어 B `B-03-02`. 이 리뷰는 처음에 RR7-03-01을 닫힘으로 적었다. + +## Declined to judge + +없다. + +## 결론 + +Critical 0, Important 1, Minor 3, 회귀 0. 결함 4건, 모두 이번 수정이 만들었다. 그중 RR8-03-03·04는 두 리뷰를 합칠 때 넣었다. + +- RR7-03-02·04·05·06은 닫혔다. RR7-03-01은 목록과 안내는 생겼지만 목록 검사를 지키는 테스트가 없다(RR8-03-04). 검사기 변경과 Flyway 규칙은 주장대로 동작하고 위반·허용 fixture를 둘 다 가진다. +- RR7-03-03은 부분이다. 새 runbook 절차는 `CREATE` 실패에는 맞지만, 절이 대상으로 넣은 `DROP INDEX CONCURRENTLY` 실패에는 같은 막힌 상태로 돌아간다. diff --git a/docs/reviews/2026-11-03-rereview/round8/04-idempotency.md b/docs/reviews/2026-11-03-rereview/round8/04-idempotency.md new file mode 100644 index 00000000..8e536446 --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round8/04-idempotency.md @@ -0,0 +1,140 @@ +# 04 멱등 저장소 round7 수정 확인 리뷰 (2026-11-07) + +> 대상: `14435106`(RR7-02-02와 멱등 남은 차이 3건: 이미 적용된 전이는 그 전이를 적용한 핸들에게만 "이미 처리됨"으로 확인). +> 범위 `2c8a359d..83a12f66`, 기준 커밋 `83a12f66`. 영역 표는 [01 문서](01-transport-errors.md) 「범위」에 있다. + +## 범위 + +### pathspec + +``` +src/application-core/src/main/java/dev/caskeleton/application/idempotency src/application-core/src/testFixtures +src/application-core/CLAUDE.md src/adapter/outbound/cache-redis src/adapter/outbound/redis-runtime +src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency docs/testing +``` + +`git diff --stat 2c8a359d..83a12f66 -- `: 12개 파일, +382 −61. 공통 문서(application-core·persistence-jpa README, 업그레이드 +안내 5절, 결정 색인 2.4절)의 이 커밋 행도 읽었다. + +함께 읽은 주변 코드: Redis `TRANSITION` 스크립트 전체(`IdempotencyScripts.java:130-200`)와 `RedisIdempotencyStoreAdapter`의 결과 변환, +`PostgreSqlIdempotencyStore`의 `markFailed`·`replayVerdict`·`appliedFrom`, `InMemoryIdempotencyStore` 전체, `IdempotencyExecutor`가 시작 결과를 쓰는 곳 +(`:192-196`), 결과 enum 넷의 Javadoc. + +### 수정 보고의 「새로 가정하는 것」 + +공유 노트 `r8-f4-idempotency.md`에 이 칸이 없다. 노트 「정한 규칙」·「범위 밖」과 커밋 본문 「위험·한계」, README 18.6절에서 뽑았다. + +| 가정 | 확인 | +|---|---| +| "적용한 핸들" = owner identity가 같고 기록보다 revision이 하나 낮은 핸들. 이것으로 다섯 전이의 재전송을 가른다 | 전이 **종류**를 함께 보지 않는 곳이 있다. Redis는 start 재전송에 기록 상태(`EXECUTING`)와 revision만 본다. renew를 적용한 핸들이 start를 보내면 "이미 시작됨"이다(RR8-04-02) | +| 템플릿 호출자(`IdempotencyExecutor`)는 넘겨받기 전 핸들로 다시 보내지 않고 renew·release를 부르지 않아 HTTP 동작은 같다 | 참. `IdempotencyExecutor`에 `renew`·`releaseBeforeExecution` 호출이 없다(grep). 아래 두 결함은 포트를 직접 부르는 코드에서만 드러난다 | +| 적용한 핸들의 markFailed 재전송이 다른 retention·disposition이면 저장소마다 답이 다르고 Javadoc과도 다르다(커밋 본문 「위험·한계」, 범위 밖으로 남김) | 참. 명령 A3~A6이 세 저장소(실 Redis·실 PostgreSQL 포함)에서 확인했다(RR8-04-01) | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 읽기 전용 | 결정 「넘겨받기 전 핸들의 재전송」이 세 저장소에 같게 들어갔는지 | +| `docs/work/reference/review-criteria.md` 7절 「fake와 공유 계약」 | fake와 실제 adapter가 같은 계약을 상속, 계약 밖 동작은 결함 | 계약에 없는 재전송 모양에서 세 저장소의 답 | +| `docs/work/reference/defect-patterns.md` A6(계약 밖 fake) | fake가 실제와 갈라짐 | fake가 Redis 쪽으로 맞춰지며 PostgreSQL과 갈라진 곳 | + +### 실행한 명령과 결과 + +탐침 세 메서드를 공유 계약 `IdempotencyStoreContract`(testFixtures)에 넣어 네 하위 클래스가 모두 돌게 했다(공유 노트 +`r8-review-a-probes/idempotency-probe.java.txt`). 각 메서드는 결과를 단언하지 않고 파일 `rr8-idempotency.txt`에 적는다. desktop +`~/workspace/r8-review-a`(`83a12f66` + 탐침), 공유 잠금, `--no-build-cache`, 로그 `~/r8-review-a-logs/`. + +| # | 명령 | 저장소 | rc | 시간 | 직전 부하(1분) | +|---|---|---|---|---|---| +| A3 | `:application-core:test --tests '*InMemoryIdempotencyStoreContractTest'` | in-memory fake | 0 | 9초 | 2.68 | +| A4 | `:adapter:outbound:cache-redis:test --tests '*.RedisIdempotencyStoreContractTest'` | Redis 명령 fake(Lua의 Java 사본) | 0 | 9초 | 2.89 | +| A5 | `:adapter:outbound:cache-redis:redisContainerContractTest` | 실 Redis(Testcontainers, `LiveRedisIdempotencyStoreContractTest`) | 0 | 78초 | 3.30 | +| A6 | `:adapter:outbound:persistence-jpa:jpaPlatformContractTest --tests '*PostgreSqlIdempotencyStoreContractTest'` | 실 PostgreSQL | 0 | 68초 | 1.47 | + +| 탐침 | fake | Redis 명령 fake | 실 Redis | 실 PostgreSQL | Javadoc이 말하는 답 | +|---|---|---|---|---|---| +| 적용한 핸들이 markFailed를 같은 disposition·**다른 retention**(1시간 → 2시간)으로 다시 보냄 | `ALREADY_MARKED_SAME_OPERATION` | `ALREADY_MARKED_SAME_OPERATION` | `ALREADY_MARKED_SAME_OPERATION` | `OPERATION_CONFLICT` | `OPERATION_CONFLICT` | +| 적용한 핸들이 markFailed를 **다른 disposition**(`NO_EFFECT_RETRYABLE` → `EFFECT_UNKNOWN_ABANDONED`)으로 다시 보냄 | `NOT_OWNER` | `NOT_OWNER` | `NOT_OWNER` | `NOT_OWNER` | `OPERATION_CONFLICT` | +| 시작한 핸들로 renew(`RENEWED`)한 뒤 **같은 핸들로 start** | `NOT_OWNER` | `ALREADY_STARTED_SAME_OPERATION` | `ALREADY_STARTED_SAME_OPERATION` | `NOT_OWNER` | `NOT_OWNER`(이 핸들이 적용한 start가 아니다) | + +A8(application-core·cache-redis·persistence-jpa `test` 포함)은 [03 문서](03-migration.md) 「A8 결과」에 있다. + +### 못 본 것 + +- Redis 클러스터·sentinel 위상: 탐침은 standalone 실 Redis만 봤다. 판정은 스크립트 하나 안에서 끝나 위상과 상관없다고 봤다(E1). + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR7-02-02 (fake가 적용한 핸들의 재전송에 `NOT_OWNER`) | 닫힘 | `InMemoryIdempotencyStore`가 마지막 전이와 그 핸들·인자를 기억한다(`Applied`, `repeats`). 계약 케이스 `aStartResentThroughTheHandleItWasAppliedFrom…`·`aRenewalResent…`·`aFailureResentThroughTheHandleItWasAppliedFromIsConfirmed`가 네 저장소에서 통과(A3~A6, 계약 전체 실행) | +| 넘겨받기 전 핸들의 complete·markFailed 재전송 → `NOT_OWNER` | 닫힘 | Redis `TRANSITION`의 ALREADY 조건이 `rev == handle rev + 1`만(`IdempotencyScripts.java:164`), PostgreSQL `replayVerdict`·complete가 `appliedFrom`을 봄. 계약 케이스 둘 | +| release한 핸들의 start(`ABSENT`·`NOT_OWNER` 둘 다) | 닫힘 | `IdempotencyStartOutcome` Javadoc, 계약 케이스가 다음 claim의 시작까지 본다 | + +## 결함 + +### RR8-04-01 · Minor · 적용한 핸들이 markFailed를 다른 retention이나 disposition으로 다시 보내면 세 저장소의 답이 서로, 그리고 포트 Javadoc과 다르다 — 이번 수정이 fake를 Redis 쪽으로 옮겨 PostgreSQL과 갈라졌다 + +- **위치**: + - 포트 Javadoc: `src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java:18-23`(`OPERATION_CONFLICT`: "this failure was already recorded with another disposition or retention"). + - fake: `src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java:190-194`(disposition만 비교, 다른 disposition은 "as in the stores" `NOT_OWNER`). + - Redis: `src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java:148-166`(기록 상태와 revision만 비교, retention은 기록에 없음), `RedisIdempotencyStoreAdapter.java:294`. + - PostgreSQL: `src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java:336-355`(전이 종류가 disposition마다 다르고, digest에 retention이 든다). + - 계약: `IdempotencyStoreContract`에 이 두 모양의 케이스가 없다. +- **무엇이 틀렸나**: + - 다른 retention: fake와 Redis는 retention을 기억하지 않아 "이미 처리됨"(`ALREADY_MARKED_SAME_OPERATION`), PostgreSQL은 digest가 달라 `OPERATION_CONFLICT`다. Javadoc은 `OPERATION_CONFLICT`라고 적는다. + - 다른 disposition: 세 저장소 모두 `NOT_OWNER`다(기록 상태나 전이 종류가 달라 재전송으로 보지 않고 revision 검사로 내려간다). Javadoc은 `OPERATION_CONFLICT`라고 적는다. + - 이번 수정 전 fake는 적용한 핸들의 재전송을 모두 `NOT_OWNER`로 답했다. 이번 수정이 disposition만 기억하게 해 다른 retention에 Redis와 같은 "이미 처리됨"을 준다. fake 주석은 다른 disposition을 "as in the stores"라고 적지만, 그 답은 포트 Javadoc과 다르다. 이 결정은 결정 색인에 없다. +- **발생 조건·영향**: + - 조건: 포트를 직접 부르는 코드가 응답을 잃은 markFailed를 다른 retention이나 disposition으로 다시 보낸다(예: 재시도 사이에 설정을 다시 읽음, 실패를 다시 분류함). 템플릿 executor는 같은 값으로만 보낸다. + - 영향: 같은 호출에 저장소를 바꾸면 답이 바뀐다. "이미 처리됨"을 받은 호출자는 자기가 정한 retention이 기록된 줄 안다. fake로 테스트한 서비스는 PostgreSQL에서 다른 답을 받는다(fake가 계약 밖으로 갈라진 A6 모양). + - Minor로 둔 이유: 템플릿 호출 경로에는 없고, 데이터 손상 없이 답의 이름만 다르다. +- **테스트가 못 본 이유**: 공유 계약은 같은 인자의 재전송과 다른 lease의 renew 재전송만 본다. markFailed의 인자 차이 케이스가 없다. +- **고치는 법**: + - 권장: 계약을 하나로 정하고 공유 계약 케이스 둘을 더한다. 안: 다른 disposition은 `OPERATION_CONFLICT`(Javadoc대로, 세 저장소 모두 바꿈), 다른 retention은 "이미 처리됨"(retention은 이미 기록된 실패의 보관 기간이라 결과를 바꾸지 않는다 — Javadoc과 PostgreSQL digest에서 retention을 뺌). 이렇게 하면 Redis 기록 모양(Lua)을 바꾸지 않는다. 계약을 적은 곳끼리 다르고 결정이 없으므로 `docs/work/improve.md` 7절대로 고치기 전에 소유자에게 묻는다. + - 대안: Javadoc을 지금 동작에 맞춘다(다른 disposition은 `NOT_OWNER`, 다른 retention은 저장소마다 다름을 명시). 계약 케이스는 `isIn(...)`으로 둔다. 갈라짐을 그대로 문서화하는 것이라 A6 모양이 남는다. + - RED 테스트 모양: 공유 계약에 두 케이스를 정한 답으로 더한다. `83a12f66`에서 탐침 표의 칸대로 저장소 일부가 실패한다. +- **이번 수정 / 이전부터**: 섞임. Redis·PostgreSQL의 답과 Javadoc의 불일치는 이전부터다. fake가 다른 retention에 "이미 처리됨"을 주게 된 것은 이번 수정이다. r8-f4 보고 「범위 밖」 1과 README 18.6절이 같은 것을 적었다. +- **증거**: E3 — 명령 A3~A6(실 Redis·실 PostgreSQL 포함). 코드 경로는 E1. +- **합칠 때 덧붙인 것(2026-11-07, `B-04-01`)**: 리뷰어 B가 같은 값을 얻었다(B 탐침 P2·P3·P5·P6). B는 「이전부터」로 적었다. 이 리뷰는 fake의 다른 retention 답이 이번 수정으로 `NOT_OWNER`에서 `ALREADY_MARKED_SAME_OPERATION`으로 바뀌어 「섞임」으로 둔다. 고치는 법은 두 리뷰의 권하는 안이 disposition 차이에서 다르다(B: `NOT_OWNER` 유지, 이 리뷰: `OPERATION_CONFLICT`). 소유자 결정 표는 README 19.4절이다. + +### RR8-04-02 · Minor · Redis는 renew를 적용한 핸들이 start를 보내도 "이미 시작됨"으로 답해, 그 답을 받은 호출자가 작업을 다시 실행한다 — fake와 PostgreSQL은 `NOT_OWNER`다 + +- **위치**: + - Redis: `IdempotencyScripts.java:148-166`(`state == toState`이고 `rev == handle rev + 1`이면 ALREADY. 마지막 전이가 무엇이었는지 보지 않음), `RedisIdempotencyStoreAdapter.java:175`(ALREADY → `ALREADY_STARTED_SAME_OPERATION`). 명령 fake `InMemorySemanticRedisCommands.java:287`도 같다. + - 포트 Javadoc: `IdempotencyStartOutcome.java:7-14`("This exact start — from the handle presented — was already applied"). + - 호출자: `src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyExecutor.java:194-195`(`STARTED`와 `ALREADY_STARTED_SAME_OPERATION`이 같은 분기로 action을 실행). +- **무엇이 틀렸나**: + - 호출자가 시작한 핸들 h(revision r)로 renew하면 기록은 `EXECUTING`·revision r+1이 된다. 그 뒤 같은 h로 start를 보내면 Redis는 기록 상태가 start의 목표 상태(`EXECUTING`)와 같고 revision이 h보다 하나 높다는 것만 보고 "이미 시작됨"이라 답한다. 그 revision을 만든 것은 start가 아니라 renew다. + - fake와 PostgreSQL은 마지막 전이 종류(RENEW)를 보고 재전송이 아니라고 판정해 `NOT_OWNER`로 답한다(탐침 셋째 행). + - 이번 수정의 규칙("이미 적용된 전이는 그 전이를 적용한 핸들에게만")은 Redis에서 전이 종류 없이 revision 차이로만 구현돼, 같은 상태에 머무는 전이(renew) 뒤의 start를 구별하지 못한다. +- **발생 조건·영향**: + - 조건: 포트를 직접 쓰는 호출자가 긴 작업에 renew를 쓰고, start 응답을 잃었다고 보고 같은 핸들로 start를 다시 보낸다. 템플릿 executor는 renew를 부르지 않는다. + - 영향: 호출자는 "이미 시작됨"을 자기 start의 확인으로 받고 action을 실행한다. 이미 실행 중인 작업이 한 번 더 돈다. round6 RR6-02-01이 막으려던 중복 실행과 같은 모양이다. + - Minor로 둔 이유: 템플릿 호출 경로에는 없고, 호출자가 시작 응답을 받은 핸들로 renew까지 한 뒤 start를 다시 보내는 드문 순서가 필요하다. +- **테스트가 못 본 이유**: 공유 계약의 start 재전송 케이스는 start 바로 뒤의 재전송만 본다. renew가 끼어든 순서가 없다. +- **고치는 법**: + - 권장: Redis 기록에 마지막 전이 종류를 남기고(`HSET … 'lastKind'`), ALREADY 조건에 "마지막 전이가 이 전이"를 더한다. renew는 이미 `renewedFromRev`를 따로 남기므로(`:245`), 같은 방식으로 start·complete·fail도 적는다. 명령 fake를 같이 고친다. + - 대안: `TRANSITION`의 start 분기만 "기록에 `renewedFromRev`가 있으면 ALREADY가 아니다"로 막는다. 지금 유일한 같은 상태 전이가 renew라서 충분하지만, 같은 상태 전이가 늘면 다시 갈라진다. + - RED 테스트 모양: 탐침 셋째를 공유 계약 케이스로 옮긴다(renew 뒤 같은 핸들의 start → `NOT_OWNER`). `83a12f66`에서 Redis 명령 fake와 실 Redis가 `ALREADY_STARTED_SAME_OPERATION`으로 실패한다. +- **이번 수정 / 이전부터**: 이전부터. start의 ALREADY 조건은 round6부터 `rev == handle rev + 1`이었다. r8-f4 보고 「범위 밖」 2와 README 18.6절이 같은 것을 적었다. +- **증거**: E3 — 명령 A4·A5(Redis 명령 fake와 실 Redis), A3·A6(fake·실 PostgreSQL 비교). +- **합칠 때 덧붙인 것(2026-11-07, `B-04-02`)**: 리뷰어 B가 같은 값을 얻었다(B 탐침 P3·P6, 대조 P2·P5). 분류(이전부터)와 고치는 법(Redis 기록에 마지막 전이 종류를 남김)이 같다. + +## 18.6절에서 넘어온 항목 판정 + +| 항목 | 판정 | 근거 | +|---|---|---| +| 적용한 핸들의 markFailed를 다른 retention으로 다시 보낼 때 저장소·Javadoc 불일치 | 결함 → RR8-04-01 | 명령 A3~A6 | +| Redis TRANSITION의 start ALREADY가 전이 종류를 보지 않음 | 결함 → RR8-04-02 | 명령 A3~A6 | + +## Declined to judge + +없다. + +## 결론 + +Critical 0, Important 0, Minor 2, 회귀 0. 결함 2건: 섞임 1건, 이전부터 1건. + +- RR7-02-02와 멱등 남은 차이 3건은 닫혔다. 새 계약 케이스 10개가 네 저장소에서 같다. +- 남은 둘은 같은 원인의 다른 모양이다. "적용한 핸들"을 revision 하나로만 가려, 인자가 다른 재전송(RR8-04-01)과 같은 상태에 머무는 전이 뒤의 재전송(RR8-04-02)에서 저장소가 갈라진다. diff --git a/docs/reviews/2026-11-03-rereview/round8/05-build-logic-httpclient.md b/docs/reviews/2026-11-03-rereview/round8/05-build-logic-httpclient.md new file mode 100644 index 00000000..021a668f --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round8/05-build-logic-httpclient.md @@ -0,0 +1,79 @@ +# 05 build-logic·httpclient·작은 문서 round7 수정 확인 리뷰 (2026-11-07) + +> 대상: `6cd5e925`(RR7-05-01: `paths` 필터 trigger로만 도는 workflow를 단계 실행으로 세지 않음), `a490c20f`(태그 push·`release`로만 도는 +> workflow는 `releaseCheck`에만 셈), `c746f980`(RR7-02-01: interrupt된 스레드의 `close()`도 drain 스레드 종료를 기다림), `eab82df1`(깨진 상대 +> 링크 셋), `ac3c6a81`(`AGENTS.md` 커밋 예외 문장). 범위 `2c8a359d..83a12f66`, 기준 커밋 `83a12f66`. 영역 표는 [01 문서](01-transport-errors.md) +> 「범위」에 있다. + +## 범위 + +### pathspec + +``` +src/build-logic src/adapter/outbound/httpclient AGENTS.md src/README.md +src/adapter/outbound/fileserver/README.md src/adapter/outbound/objectstorage/README.md +``` + +`git diff --stat 2c8a359d..83a12f66 -- `: 11개 파일, +547 −100. 업그레이드 안내 B-36 행과 결정 색인 2.7절의 두 행도 읽었다. + +함께 읽은 주변 코드: `WorkflowGradleInvocations`의 trigger 판독 전체(`triggers`·`blockTriggers`·`flowTrigger`·`start`·`flow`)와 `StrictLaneStagesPlugin.problems` +(`Invocation.executes`를 부르는 유일한 곳), `ClientRuntimeRegistry`의 `close`·`stopDrainThread`·drain 스케줄러 생성. + +### 수정 보고의 「새로 가정하는 것」 + +공유 노트 `r8-f5-small-fixes.md` 「정한 기본값」과 두 커밋 본문 「위험·한계」에서 뽑았다. + +| 가정 | 확인 | +|---|---| +| `branches`·`branches-ignore` 없이 `tags`·`tags-ignore`만 단 `push`는 branch push로 시작하지 않는다 | 참. GitHub Actions는 ref 종류 하나에만 필터를 달면 다른 종류의 이벤트로는 workflow를 시작하지 않는다. 판독기는 그 조합만 `RELEASE`로 본다(`WorkflowGradleInvocations.java` `Trigger.of`) | +| `tags`와 `paths`를 함께 단 push는 어느 단계에도 세지 않는다(거짓 실패 쪽) | 참. `flow`가 `paths` 필터를 태그보다 먼저 보아 `PATH_FILTERED`가 된다. 거짓 통과는 없다 | +| 이 repo의 `release.yml`이 부르는 `-p optional-platforms integrationCheck`는 이제 세지 않아도 `integration-main.yml`이 같은 단계를 돈다 | 참. `integration-main.yml`의 그 명령은 필터 없는 `push`(main)·`schedule` workflow에 있다(grep) | +| `Invocation.executes`·`whyNotExecuting`의 두 인자 판정을 모든 호출자가 쓴다 | 참. `StrictLaneStagesPlugin.java:165`·`:236` 두 곳뿐이고 둘 다 단계 이름을 넘긴다 | +| interrupt된 `close()`는 최대 5초까지 막힐 수 있다 | 참. 마감은 처음 한 번 잡고(`ClientRuntimeRegistry.java:184`), 다시 기다릴 때도 같은 마감을 쓴다. 마감이 지나면 `IllegalStateException`이다. `awaitTermination`이 interrupt를 던지면 flag가 지워져 다음 대기는 바로 끝나지 않는다 | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 읽기 전용 | 세 항목 닫힘, trigger 조합별 판정 | +| `docs/work/reference/gates.md` 6절 「거짓 통과」 | 게이트가 막겠다는 것을 막는가 | 새 `RELEASE`·`PATH_FILTERED` 분기가 다른 trigger를 세는 쪽으로 잘못 넓히는 경우 | + +### 실행한 명령과 결과 + +| # | 명령 | 대상 | 결과 | 시간 | 직전 부하(1분) | +|---|---|---|---|---|---| +| A9 | `-p build-logic test --rerun` | `83a12f66` + 탐침(build-logic에는 탐침 없음) | rc=0, 173건 실패·skip 0, FROM-CACHE 0 | 41초 | 5.13 | +| A8 | httpclient `test --rerun` 포함 | 같음 | rc=0, httpclient 360건 실패 0([03 문서](03-migration.md) 「A8 결과」) | — | — | + +trigger 조합은 코드로 따라갔다. 따라간 조합: `pull_request` + `paths`(PATH_FILTERED), `push: tags`(RELEASE), `push: tags` + `paths`(PATH_FILTERED), +`release` + `workflow_dispatch`(RELEASE), `push: tags` + 필터 없는 `pull_request`(CHANGE), `schedule` + `push: paths`(CHANGE), +`workflow_call`만 있고 RELEASE caller만 부름(RELEASE), `push: branches: [main]`(CHANGE). + +### 못 본 것 + +- 실제 GitHub runner의 trigger 동작: 판독기는 workflow 파일만 읽는다. GitHub 문서의 필터 규칙과 대조했다(E1). +- interrupt된 채 5초 마감을 넘기는 `close()` 경로: 테스트가 없다(커밋 본문이 적음). 코드로만 봤다. + +## 항목 재확인 + +| ID | 판정 | 근거 | +|---|---|---| +| RR7-05-01 (`paths` 필터 workflow를 단계 실행으로 셈) | 닫힘 | `flow`가 `paths`·`paths-ignore`가 붙은 change trigger를 `PATH_FILTERED`로 보고, change trigger가 그것뿐이면 이유와 함께 세지 않는다. `WorkflowGradleInvocationsTest`의 필터 workflow 셋 | +| 태그·릴리스 workflow(18.4절 넷째 결정) | 닫힘 | `Invocation.whyNotExecuting(taskPath, buildDirectory)`가 `RELEASE` workflow의 명령을 `:releaseCheck`에만 센다. `StrictLaneStagesFunctionalTest`(TestKit)가 다른 단계에서 실패, `releaseCheck`에서 통과를 본다 | +| RR7-02-01 (interrupt된 `close()`) | 닫힘 | `ClientRuntimeRegistry.java:178-215`, 테스트 `closingFromAnInterruptedThreadStillWaitsForTheDrainThread` | +| 깨진 상대 링크 셋 | 닫힘 | `python3 scripts/check-work-docs.py --links`를 lychee 범위(`gates.md` 2절 명령)에 돌려 572개 파일, 링크 520개, 깨짐 0(노트북, 이 리뷰에서 다시 돌림) | +| `AGENTS.md` 커밋 예외 문장 | 닫힘 | `AGENTS.md:118-119`와 `docs/work/README.md` 4절, 결정 색인 「커밋 예외」가 "brief가 허용한 것만, commit과 push는 따로"로 같다 | + +## 결함 + +없다. + +## Declined to judge + +없다. + +## 결론 + +Critical 0, Important 0, Minor 0. 결함 0건. + +- 세 수정과 문서 둘이 주장대로다. 판독기의 새 분기는 세지 않는 쪽(거짓 실패)으로만 넓어졌고, 세는 쪽으로 넓어진 trigger 조합을 찾지 못했다. diff --git a/docs/reviews/2026-11-03-rereview/round8/06-manual-scripts.md b/docs/reviews/2026-11-03-rereview/round8/06-manual-scripts.md new file mode 100644 index 00000000..41d4794b --- /dev/null +++ b/docs/reviews/2026-11-03-rereview/round8/06-manual-scripts.md @@ -0,0 +1,112 @@ +# 06 매뉴얼·검사 스크립트 round7 범위 확인 리뷰 (2026-11-07) + +> 대상: `b872b0ea`·`6dd9ef76`·`b7d13104`(이력 검사 패턴), `73d39212`(cold-read 시험 1회차 빈틈), `b619c442`(독립 리뷰어 둘), `447a77a3`(운영 +> playbook 빈틈 여섯), `81ef58ab`(매뉴얼 본문 이력 ID 19줄). 범위 `2c8a359d..83a12f66`, 기준 커밋 `83a12f66`. 영역 표는 +> [01 문서](01-transport-errors.md) 「범위」에 있다. 이 커밋들은 round7 결함 수정이 아니라 같은 통합 브랜치에 합쳐진 매뉴얼 수정이다. brief의 +> 범위가 `2c8a359d..83a12f66` 전체라 함께 봤다. + +## 범위 + +### pathspec + +``` +docs/work scripts CLAUDE.md +docs/manual/03-placement.md docs/manual/05-idempotency.md docs/manual/06-errors.md docs/manual/08-testing.md +docs/manual/09-outbox-events.md docs/manual/README.md +``` + +`git diff --stat 2c8a359d..83a12f66 -- `: 18개 파일, +253 −67. 매뉴얼 04·07의 이력 ID 걷어내기 hunk도 여기서 봤다(그 파일은 03·02의 +pathspec). `docs/work/evidence.md`는 기록이라 결론에 쓰인 사실만 대조했다. + +함께 읽은 주변 코드: `scripts/check-review-index.py` 전체, `scripts/check-work-docs.py`의 `HISTORY_PATTERNS`, `.github/workflows/link-check.yml` +범위, `docs/reviews/2026-11-01-maturity-review/README.md` 13·14절(매뉴얼이 새로 적은 날짜의 출처). + +### 수정 보고의 「새로 가정하는 것」 + +수정 보고는 공유 노트 `manual-gap-fix-1.md`·`t4-2-manual-history-ids.md`다. 이 칸이 없어 「정한 기본값」과 커밋 본문에서 뽑았다. + +| 가정 | 확인 | +|---|---| +| 독립 리뷰어 둘일 때 정본 리뷰어만 리뷰 폴더에 문서를 커밋하고, 그 라운드 색인 절은 총괄이 쓴다 | 두 규칙이 함께 있으면, 정본 리뷰어의 커밋은 색인 검사를 rc=1로 남긴다. 같은 매뉴얼이 리뷰어에게 rc=0을 요구한다(RR8-06-01) | +| "상한에 가까움" = 추가 1,000줄 이상(기본값) | 판정 대상이 아니다(기본값). 이 라운드는 +3,747줄이라 해당한다 | +| 매뉴얼 본문의 「1라운드」는 2026-11-01에 한 첫 수정이다 | 참. `2026-11-01-maturity-review/README.md:368`(합친 트리 게이트 2026-11-01 23:32~23:45), `:399`(2라운드 지시 2026-11-01 23:20). 커밋 `34565130`의 날짜(2026-11-03)는 그 작업을 나중에 커밋한 날이다(13절 "커밋하지 않았다") | +| lychee 범위 상대 링크 검사 명령(`gates.md` 2절)이 workflow 범위와 같다 | 참. `link-check.yml`의 범위와 같고, 노트북에서 돌려 572개 파일·링크 520개·깨짐 0 | + +### 불러온 스킬과 적용한 기준 + +| 스킬 | 기준 | 본 것 | +|---|---|---| +| `superpowers:requesting-code-review` | 주장과 구현, 읽기 전용 | 매뉴얼 문장끼리 모순, 검사 스크립트와 문장의 약속 | +| `docs/work/reference/review-criteria.md` 1절 | 문서끼리 다르게 말하거나 문서대로 하면 실패하는 곳 | 이 리뷰 자신이 정본 리뷰어로 그 절차를 따라 함 | + +### 실행한 명령과 결과(노트북, Python 검사만) + +| # | 명령 | 결과 | +|---|---|---| +| N1 | `python3 scripts/check-work-docs.py` | rc=0. 분량 상한 안(improve.md 141/150, README 76/80 등), 이력 ID 0줄, 상대 링크 115개 | +| N2 | `python3 scripts/check-work-docs.py --history docs/manual` | rc=0. 13개 파일, 이력 ID 0줄 | +| N3 | `python3 scripts/check-work-docs.py --links $(git ls-files … lychee 범위 …)`(`gates.md` 2절 명령 그대로) | rc=0. 572개 파일, 링크 520개, 깨짐 0 | +| N4 | `python3 scripts/check-review-index.py docs/reviews/2026-11-03-rereview`(이 라운드 문서 여섯을 둔 작업 트리) | rc=1. 발견 제목 180개 중 색인에 없음 8개 — 이 라운드 발견 전부(RR8-01-01·02, RR8-02-01, RR8-03-01·02, RR8-04-01·02, RR8-06-01) | +| N5 | N4와 같은 검사를 임시 복사본에 돌림: README 끝에 이 리뷰 보고의 색인 표를 붙인 사본 | rc=0. 180/180 | + +N4·N5는 RR8-06-01의 증거다. N1~N3은 desktop에서 다시 돌리지 않았다(`docs/work/operate.md` 4.1절은 보고 증거로 쓸 때 desktop에서 한 번 더 돌리라고 +한다. 이 검사들은 결론에 쓰지 않은 확인이라 노트북 결과만 적는다). + +### 못 본 것 + +- design-docs 쪽 변경(`c47451a`, `7703b85` 등): 이 repo 밖이라 범위 밖이다. +- 매뉴얼이 바뀐 절차(독립 리뷰어 둘, push 전 검증)를 실제로 따라 해 보는 cold-read 시험: 이 리뷰가 독립 리뷰어 절차를 따랐을 뿐, 다른 절차는 시험하지 않았다. + +## 항목 재확인 + +이 커밋들은 round7 발견을 고친 것이 아니라 고친 항목이 없다. 처리 표 `docs/work/evidence.md` 8·9절의 행이 그 커밋의 주장이다. 결론에 쓰인 +날짜·문장 다섯을 대조했고 맞았다(위 표 셋째 줄, 매뉴얼 03·05·06·08·09의 바뀐 문장). + +## 결함 + +### RR8-06-01 · Minor · 독립 리뷰어 둘이면 정본 리뷰어가 리뷰 폴더에 커밋한 문서가 색인 검사를 rc=1로 남기는데, 같은 매뉴얼이 리뷰어에게 rc=0을 요구한다 + +- **위치**: + - `docs/work/improve.md:45`(7단계: "한 라운드를 여러 리뷰 세션이 나눠 보면 색인 절도 맡긴 쪽이 쓰고, 리뷰어는 보고에 같은 표를 둔다"), `:46`(8단계: 색인 검사 "rc=0이어야 한다"), `:54`("리뷰 폴더에 문서를 커밋하는 것은 brief가 정한 정본 리뷰어뿐이다"), `:97`(완료 기준 "색인 검사가 rc=0이다"). + - `docs/work/delegate.md:38`("그 라운드 색인 절은 총괄이 쓰고"), `docs/work/reference/decisions.md:35`(「리뷰 README 분담」). + - 검사: `scripts/check-review-index.py`는 영역 문서의 모든 발견 제목이 README에 있어야 rc=0이다. +- **무엇이 틀렸나**: + - 독립 리뷰어 둘이면 정본 리뷰어가 영역 문서를 리뷰 폴더에 커밋한다. 그 문서의 발견 제목(`### RR-NN-MM`)은 아직 README에 없다. 색인 절은 총괄이 두 리뷰를 합친 뒤 쓴다. + - 그래서 정본 리뷰어의 커밋 직후 색인 검사는 반드시 rc=1이다(명령 N4). + - 같은 매뉴얼의 8단계와 5절 완료 기준은 리뷰어에게 rc=0을 요구한다. 정본 리뷰어는 README를 쓰지 말라는 규칙과 rc=0을 보이라는 규칙을 함께 지킬 수 없다. + - 두 규칙은 이 범위의 서로 다른 커밋이 만들었다: 7·8단계는 `73d39212`, 정본 리뷰어 커밋은 `b619c442`. +- **발생 조건·영향**: + - 조건: `improve.md` 4.1절의 세 경우(멈추는 확인 리뷰, 추가 1,000줄 이상, Important 이상을 고친 수정)마다다. 이 라운드가 그 경우다. + - 영향: 정본 리뷰어는 rc=1을 보고하거나, 금지된 README 색인 절을 쓰게 된다. 총괄이 합치기 전까지 리뷰 브랜치의 색인 검사가 빨갛다. 그 사이 브랜치를 합치면 색인 검사로 막으려던 "색인에서 빠진 발견"과 구별되지 않는다. + - Minor로 둔 이유: 거짓 실패 쪽이고, 총괄이 색인 절을 쓰면 닫힌다. +- **테스트가 못 본 이유**: 매뉴얼 문장끼리의 모순은 `check-work-docs.py`가 보지 않는다. 독립 리뷰어 절차를 처음 따른 것이 이 라운드다. +- **고치는 법**: + - 권장: 8단계와 5절에 독립 리뷰어 둘의 경우를 적는다. "정본 리뷰어는 리뷰 폴더 README를 고치지 않고, 보고의 색인 표를 붙인 임시 사본으로 색인 검사를 돌려 rc=0을 보인다. 커밋한 트리의 rc=1은 총괄이 색인 절을 쓰면 닫힌다." 이 리뷰가 그렇게 했다(명령 N5). + - 대안 1: `check-review-index.py`에 색인 표 파일을 따로 받는 옵션(`--extra-index <파일>`)을 더해, 정본 리뷰어가 보고 표를 넘겨 돌린다. + - 대안 2: 정본 리뷰어가 README에 그 라운드 색인 절을 먼저 쓰고, 총괄은 합칠 때 다른 쪽 발견의 새 ID와 대응표만 더한다. 결정 「리뷰 README 분담」을 바꾸므로 결정 기록이 필요하다. + - RED 테스트 모양: 매뉴얼 문장이라 없다. 확인은 다음 독립 리뷰 라운드의 정본 리뷰어가 매뉴얼대로 해서 rc=0을 보이는지다. +- **이번 수정 / 이전부터**: 이번 수정. +- **증거**: E2 — 명령 N4(커밋 전 작업 트리에서 rc=1), N5(보고 표를 붙인 사본에서 rc=0). 문장 대조는 E1. + +## 18.6절에서 넘어온 항목 판정 + +| 항목 | 판정 | 근거 | +|---|---|---| +| `docs/manual`·`docs/work` 밖 문서(`AGENTS.md`, `docs/httpclient/*.md`, `src/adapter/inbound/web/README.md` 등)의 본문 이력 ID | 소유자 결정 필요 | 매뉴얼 규칙(`docs/work/README.md` 8절, `docs-writing.md` 6단계)은 `docs/work/`와 매뉴얼 본문을 대상으로 적는다. 그 밖 문서에 넓힐지는 정해진 것이 없다(README 18.6절). 아래 「결정이 필요한 것」 | + +### 결정이 필요한 것 + +| 항목 | 선택지 | 권하는 안과 이유 | 정할 사람 | +|---|---|---|---| +| 이력 ID 0 규칙을 `docs/manual`·`docs/work` 밖으로 넓힐지 | (a) 넓히지 않는다. 그 밖 문서는 모듈·설계 기록이라 리뷰 ID가 추적용이다 (b) 진입 문서만 넓힌다: `AGENTS.md`와 leaf `CLAUDE.md`(새 세션이 처음 읽는 규칙) (c) `docs/reviews/**` 밖 전부 | (b). 새 세션이 처음 읽는 규칙 문서에서만 ID가 이해를 막는다(매뉴얼 규칙을 만든 이유와 같다). 모듈 README·설계 문서의 ID는 같은 repo의 리뷰 문서로 따라갈 수 있다. (c)는 65줄을 걷어내야 하고(t4-2 노트) 이력 근거를 잃는다 | 소유자 | + +## Declined to judge + +없다. + +## 결론 + +Critical 0, Important 0, Minor 1, 회귀 0. 결함 1건(이번 수정). 결정 필요 1건(18.6절에서 넘어온 이력 ID 범위). + +- 이력 검사 패턴과 매뉴얼 날짜 치환은 주장대로다. 링크 검사 명령은 workflow 범위와 같다. +- 독립 리뷰어 절차는 이 라운드에서 처음 쓰였고, 정본 리뷰어의 색인 검사 단계 하나가 다른 규칙과 부딪힌다. diff --git a/docs/roadmap/messaging-r2.md b/docs/roadmap/messaging-r2.md index 40d88248..c463d1b7 100644 --- a/docs/roadmap/messaging-r2.md +++ b/docs/roadmap/messaging-r2.md @@ -10,7 +10,7 @@ - 대응하는 Test 태스크 없음 - 공통 스키마 validator 없음 -따라서 `config/messaging/readiness-cards.yaml`의 카드는 모두 `maturity: not-implemented`다. +따라서 `src/adapter/outbound/messaging/release/readiness-cards.yaml`의 카드는 모두 `maturity: not-implemented`다. 유일하게 `implemented-candidate`였던 `json-schema-envelope.v1`은 그 구현(adapter messaging의 `JsonSchemaIntegrationEventEncoder`와 `verifyMessagingJsonSchemaV1`)을 2026-09-25에 삭제하면서 `not-implemented`로 내렸다. 남은 evidence producer는 `verifyMessagingContracts` 하나다. @@ -41,7 +41,7 @@ verifyMessagingTargetBindingPreflight 1. 각 시나리오를 실제로 실행하는 Test 태스크. 2. 그 실행 결과(JUnit XML)에서 payload-free manifest를 만드는 producer. -3. `config/messaging/evidence/build-evidence-manifest-v1.schema.json`으로 그 manifest 바이트를 +3. `src/adapter/outbound/messaging/release/evidence/build-evidence-manifest-v1.schema.json`으로 그 manifest 바이트를 검증하는 단계(build-tools `VerifyMessagingEvidenceTask`가 쓰고 바로 검증한다). 4. 위 셋이 모두 생긴 다음에 `verifyMessagingR2` 태스크 등록. diff --git a/docs/runbooks/auth-jwks-unavailable.md b/docs/runbooks/auth-jwks-unavailable.md index 42bcc829..b7c529e4 100644 --- a/docs/runbooks/auth-jwks-unavailable.md +++ b/docs/runbooks/auth-jwks-unavailable.md @@ -4,7 +4,7 @@ category: TRANSIENT_DEPENDENCY error_codes: [AUTH_JWKS_UNAVAILABLE] severity: P1 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-06 status: stub --- @@ -13,6 +13,8 @@ status: stub ## Symptoms - HTTP 503 with `error.code=AUTH_JWKS_UNAVAILABLE` +- ERROR log line `security failure: code=AUTH_JWKS_UNAVAILABLE category=TRANSIENT_DEPENDENCY method=… path=…` + (logger `AuthErrorResponseWriter`) - All authentication failing; JWKS refresh attempts failing ## Diagnosis diff --git a/docs/runbooks/auth-public-path-misconfiguration.md b/docs/runbooks/auth-public-path-misconfiguration.md index df069a67..019a1976 100644 --- a/docs/runbooks/auth-public-path-misconfiguration.md +++ b/docs/runbooks/auth-public-path-misconfiguration.md @@ -4,7 +4,7 @@ category: INTERNAL error_codes: [INTERNAL_AUTH_MISCONFIGURATION] severity: P1 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-06 status: stub --- @@ -13,6 +13,8 @@ status: stub ## Symptoms - HTTP 500 with `error.code=INTERNAL_AUTH_MISCONFIGURATION` +- ERROR log line `security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL method=… path=…` + (logger `AuthErrorResponseWriter`) - Security filter misconfiguration detected at runtime ## Diagnosis diff --git a/docs/runbooks/auth-token-invalid-signature.md b/docs/runbooks/auth-token-invalid-signature.md index ce057a1f..02051f53 100644 --- a/docs/runbooks/auth-token-invalid-signature.md +++ b/docs/runbooks/auth-token-invalid-signature.md @@ -4,7 +4,7 @@ category: AUTH error_codes: [AUTH_TOKEN_INVALID_SIGNATURE] severity: P1 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-06 status: stub --- @@ -13,7 +13,9 @@ status: stub ## Symptoms - HTTP 401 with `error.code=AUTH_TOKEN_INVALID_SIGNATURE` -- `log_level=ERROR` — may indicate forged tokens or wrong signing key +- WARN log line `security failure: code=AUTH_TOKEN_INVALID_SIGNATURE category=AUTH method=… path=…` + (logger `AuthErrorResponseWriter`). It is a WARN because the caller sent the token; search by + `code=`, not by level. A burst of these may indicate forged tokens or a wrong signing key ## Diagnosis diff --git a/docs/runbooks/authz-tenant-mismatch.md b/docs/runbooks/authz-tenant-mismatch.md index 1bd30beb..47747cd9 100644 --- a/docs/runbooks/authz-tenant-mismatch.md +++ b/docs/runbooks/authz-tenant-mismatch.md @@ -4,7 +4,7 @@ category: AUTHZ error_codes: [AUTHZ_TENANT_MISMATCH] severity: P1 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-06 status: stub --- @@ -13,7 +13,9 @@ status: stub ## Symptoms - HTTP 403 with `error.code=AUTHZ_TENANT_MISMATCH` -- `log_level=ERROR` — cross-tenant access attempt detected +- The template does not emit this code; the service that decides cross-tenant access does. A 403 + carrier is answered without a log line (`ServerFailureLog`), so that service logs + `code=AUTHZ_TENANT_MISMATCH` where it decides, if this runbook is to find the attempt ## Diagnosis diff --git a/docs/runbooks/idempotency-unavailable.md b/docs/runbooks/idempotency-unavailable.md index 4a8446ec..8afacfac 100644 --- a/docs/runbooks/idempotency-unavailable.md +++ b/docs/runbooks/idempotency-unavailable.md @@ -131,7 +131,7 @@ status: active between them and is claimed again by a new request is deleted while that request runs, and the next request with the key runs the work a second time (re-review 2026-11-04 RR4-03-02). The program below deletes the key only while its `state` is `ABANDONED`. The application - accounts are denied `EVAL` (`infra/redis-sdk/acl/README.md`), so load it and run it by the + accounts are denied `EVAL` (`compose/redis/acl/README.md`), so load it and run it by the digest `SCRIPT LOAD` prints, as the service runs its own scripts: diff --git a/docs/runbooks/job-timeout.md b/docs/runbooks/job-timeout.md index 4c239492..30947cd7 100644 --- a/docs/runbooks/job-timeout.md +++ b/docs/runbooks/job-timeout.md @@ -50,7 +50,7 @@ status: stub - 의존성 지연이 근본 원인이면 해당 의존성 오너에게 escalate - 종료 예산은 차례로 더한 값이다: 웹 drain(`APP_SERVER_SHUTDOWN_TIMEOUT`, 기본 30s)이 끝난 뒤 async 대기 19s, 합계 49s에 preStop(5s)과 여유를 더한다. k8s `terminationGracePeriodSeconds`가 이보다 작으면(예: 기본 30s) - async 대기 중 SIGKILL이다. compose는 60s(`docker-compose.yml` `stop_grace_period`, 합계는 + async 대기 중 SIGKILL이다. compose는 60s(`compose.yaml` `stop_grace_period`, 합계는 `DeveloperExperienceContractTest`가 검사). 정합 이슈면 플랫폼/런타임 오너에게 escalate ## 6. Recovery / Verification diff --git a/docs/runbooks/lock-acquisition-timeout.md b/docs/runbooks/lock-acquisition-timeout.md index ea42c774..2f3f8bf4 100644 --- a/docs/runbooks/lock-acquisition-timeout.md +++ b/docs/runbooks/lock-acquisition-timeout.md @@ -4,7 +4,7 @@ category: CONFLICT error_codes: [LOCK_ACQUISITION_TIMEOUT] severity: P2 owner: oncall -last_updated: 2026-06-15 +last_updated: 2026-11-07 status: stub --- @@ -12,13 +12,52 @@ status: stub ## Symptoms -- HTTP 409 with `error.code=LOCK_ACQUISITION_TIMEOUT` +- HTTP 409 with `error.code=LOCK_ACQUISITION_TIMEOUT` and `Retry-After: 1`; GraphQL extension + `code=LOCK_ACQUISITION_TIMEOUT`, gRPC trailer `error-code: LOCK_ACQUISITION_TIMEOUT` (`ABORTED`), all + `retryable=true`. +- No server log line. A 4xx answer is not an incident, so no transport logs it, and the lock adapters + do not log a timeout either. The exception's message (lock key, wait time) reaches no log and no + client, so which lock timed out is recorded nowhere. Read the metric and the lock table below. +- Before 2026-11-07 the template answered this as 500 `INTERNAL_ERROR` with an "unhandled exception" + ERROR line (the exception was not an `ApiErrorCarrier`). A service on an older template sees that + instead. - Distributed lock wait exceeded configured timeout; high contention on a resource ## Diagnosis -- Check `lock.acquisition` metric for lock name and duration -- Identify lock holders (check DB `integration_lock` table) +1. Contention rate. With `APP_MULTI_INSTANCE_ENABLED=true` the JDBC lock is metered: compare + `lock.acquisition{outcome="timeout"}` with `lock.acquisition{outcome="acquired"}`. The counter has + no lock name and no wait time — a key is never a metric tag (`docs/registries/metrics.yaml`). The + in-process lock (`APP_MULTI_INSTANCE_ENABLED=false`, the default) has no metric and keeps nothing in + the database; the steps below apply only to the JDBC lock. +2. Who holds locks now. `INT_LOCK` has one row per held lock. `CLIENT_ID` is the holding instance's + lock repository id, and the times are UTC. A row whose `EXPIRED_AFTER` has passed is a dead lease: + the next acquisition of that key takes it over. The oldest live rows are the long holders. + + +```sql +SELECT lock_key, region, client_id, created_date, expired_after +FROM int_lock +ORDER BY created_date; +``` + +3. The holder of one lock whose key you know from the code (for example `orders/42`). `LOCK_KEY` is + not the key: Spring Integration stores the key's name-based UUID (`UUID.nameUUIDFromBytes` of the + key's UTF-8 bytes), so a key cannot be read back from the table. This computes the UUID from the + key and finds its row: + + +```sql +SELECT region, client_id, created_date, expired_after +FROM int_lock +WHERE lock_key = ( + SELECT overlay(overlay(h placing '3' from 13) + placing to_hex(8 | (('x' || substr(h, 17, 1))::bit(4)::int & 3)) from 17)::uuid::text + FROM md5('') AS h); +``` + +`:adapter:outbound:persistence-jpa:postgresqlDistributedLockIntegrationTest` runs both blocks, read +from this file, against real PostgreSQL while locks are held. ## Action diff --git a/docs/runbooks/migration-failed.md b/docs/runbooks/migration-failed.md index a2988d75..601f96a6 100644 --- a/docs/runbooks/migration-failed.md +++ b/docs/runbooks/migration-failed.md @@ -4,7 +4,7 @@ category: INTERNAL error_codes: [MIGRATION_FAILED] severity: P1 owner: oncall -last_updated: 2026-11-04 +last_updated: 2026-11-07 status: active --- @@ -22,7 +22,7 @@ status: active 1. Stop rollout and keep the failed revision out of readiness. Do not route traffic to a partially migrated instance. -2. Identify the exact stream from `src/config/jpa/readiness-cards.yaml`. Each stream has an +2. Identify the exact stream from `src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml`. Each stream has an independent `location` and `history-table`; do not infer ownership from a broad `classpath:db/migration` scan. 3. From a privileged migration session, capture the stream state before changing anything: @@ -63,6 +63,14 @@ status: active case — clean it up with `outbox-dead-letter.md` §8 and rerun, the migration stays as it is; - checksum mismatch: compare the deployed artifact with the already applied script before considering repair; + - a concurrent index migration failed (`CREATE [UNIQUE] INDEX CONCURRENTLY`, `DROP INDEX + CONCURRENTLY` or `REINDEX … CONCURRENTLY` that Flyway ran outside a transaction): a duplicate + value for a unique index, a deadlock, `statement_timeout` or a statement cancelled while it + waited for an open transaction. Outside a transaction nothing rolled back: the migration left + an invalid index and a history row with `success = false` for that version, and every later + deploy fails validation ("Detected failed migration to version …") until the row is gone. + Dropping the index alone does not clear it. Follow "Recover a failed concurrent index + migration" below; - connection/TLS failure: fix transport or credentials without changing Flyway history. ## Action @@ -92,7 +100,9 @@ status: active Do not: - edit an already applied migration; -- delete or rewrite Flyway history to make validation green; +- delete or rewrite Flyway history to make validation green. The one exception is the failed row + of a failed concurrent index migration, deleted as "Recover a failed concurrent index migration" + below says — that row and nothing else; - run `flyway repair` before checksum provenance is proven and reviewed; - use `clean`, destructive rollback, or schema-wide restore as the first response; - mark a capability `ACTIVE` before its migration and adapter readiness succeed. @@ -101,6 +111,68 @@ If commit outcome was indeterminate during the failure, reconcile by the applica `OperationId`/idempotency reference before retrying business work. Never blind-retry a commit whose result is unknown. +## Recover a failed concurrent index migration + +The one case where this runbook changes Flyway history (owner decision, 2026-11-06). It applies to a +migration that holds a single concurrent index statement which Flyway ran outside a transaction — +with the `executeInTransaction=false` the guide asks for, or on its own for `CREATE`/`DROP INDEX +CONCURRENTLY` (`docs/jpa/migration-guide.md` "Concurrent index builds") — and whose row for this +version in the stream's history table says `success = false`. A migration that mixed other +statements in has already committed them: reconstruct that state with the database owner instead. + +1. Confirm no build is still running. An index that is still being built looks invalid in the + catalog too, and dropping it races the build. This query returns no rows when none is: + + +```sql +SELECT pid, relid::regclass AS table_name, index_relid::regclass AS index_name, phase +FROM pg_stat_progress_create_index +WHERE datname = current_database(); +``` + +2. Remove the cause. For a unique index, clean up the duplicate rows with the data owner (a forward + fix, never by editing the migration). For a deadlock, a timeout or a cancelled statement, end or + wait out the transaction that held it: a build or a rebuild waits for every transaction older + than itself, a drop for every transaction that holds a lock on its table. Do this before step 3, + whose `DROP INDEX CONCURRENTLY` waits for the same transactions. +3. Drop the invalid index a failed build or rebuild left: the index a `CREATE [UNIQUE] INDEX + CONCURRENTLY` names, or the copy a `REINDEX … CONCURRENTLY` made, named after the index with + `_ccnew` (or `_ccold`) on the end (`docs/jpa/runbooks.md` "An invalid index exists" lists them). + Run it on its own, not inside `BEGIN`: `CONCURRENTLY` refuses a transaction block. + **Skip this step when the failed statement is `DROP INDEX CONCURRENTLY`.** The invalid index it + left is the index the migration drops, and the deploy in step 5 runs the same statement, which + drops it. Dropped by hand first, that statement fails with `42704` ("index … does not exist") + and leaves a new failed row. + + +```sql +DROP INDEX CONCURRENTLY IF EXISTS ; +``` + +4. Delete that version's failed row from the stream's history table, and nothing else. `` + is the `version` column of the failed row as the Diagnosis query shows it (`22.1` for + `V22_1__…`). It must delete exactly one row; if it deletes none, this is not the failure this + section is for, so classify it again. + + +```sql +DELETE FROM +WHERE version = '' AND NOT success; +``` + +5. Deploy again. Flyway runs the same migration from the start: it builds the index, rebuilds it, + or drops the index the failed drop left. + +The failed row is the record of a version that never applied, so deleting it leaves the order and +the checksum of every applied version as they were. Do not use `flyway repair` for this: it also +rewrites the checksums and descriptions of the remaining rows to match the scripts on disk, which +removes the evidence a checksum mismatch carries. `:adapter:outbound:persistence-jpa:postgresqlConcurrentIndexMigrationIntegrationTest` +runs the three SQL blocks above, read from this file, against real PostgreSQL for each statement +this section covers: a unique build that fails on a duplicate, and a rebuild and a drop cancelled +while they wait for an open transaction. Steps 1–4 run in order, step 3 for the build and the +rebuild only, and the next deploy applies the version with no invalid index left and the earlier +version's checksum unchanged. + ## Escalation - P1 immediate: the required application revision cannot become ready. diff --git a/docs/runbooks/outbox-dead-letter.md b/docs/runbooks/outbox-dead-letter.md index 0e6b4375..4799c29c 100644 --- a/docs/runbooks/outbox-dead-letter.md +++ b/docs/runbooks/outbox-dead-letter.md @@ -152,7 +152,7 @@ rolling 중 옛 버전이 방금 쓴 번호(floor보다 초당 10⁶씩 큰 벽 소비자는 그 사이 새 이벤트를 버린다. 그래서 **tenant scope를 바꾸는 배포는 rolling으로 하지 않는다**: 옛 버전 인스턴스를 모두 멈춘 뒤(옛·새 버전이 함께 쓰는 구간 없이) 새 버전을 띄운다. -tenant scope를 바꾼 서비스(샘플은 `portfolio` → 단일 scope)는 배포 전에 옛 scope의 미발행 행이 +tenant scope를 바꾼 서비스(예: 기능별 scope → 단일 scope)는 배포 전에 옛 scope의 미발행 행이 없는지 확인한다. 옛 scope 행과 새 scope 행은 서로 다른 aggregate로 보여 claim gate가 서로를 막지 않고, partition key도 달라 다른 partition으로 간다. @@ -252,7 +252,7 @@ COMMIT; ``` Step 1을 다시 돌려 0행이면 배포한다. 정리와 배포 사이에 옛 버전이 새 중복을 만들 수 있다(벽시계로 -순서 번호를 만든 샘플 코드가 그 원인이었다). 그래도 V21은 실패하고 롤백될 뿐이니 Step 1부터 다시 한다. +순서 번호를 만든 옛 코드가 그 원인이었다). 그래도 V21은 실패하고 롤백될 뿐이니 Step 1부터 다시 한다. `outbox_event_v21_duplicates`는 확인이 끝나면 지운다. 확인 쿼리, 정리 SQL, Step 0의 인덱스 SQL은 이 문서에서 그대로 읽어 실제 PostgreSQL에서 실행하는 diff --git a/docs/superpowers/plans/2026-09-19-startup-order-contract.md b/docs/superpowers/plans/2026-09-19-startup-order-contract.md deleted file mode 100644 index 686de418..00000000 --- a/docs/superpowers/plans/2026-09-19-startup-order-contract.md +++ /dev/null @@ -1,9 +0,0 @@ -# Startup Order Contract — Plan - -- [x] Add spring.factories-driven EnvironmentPostProcessor ordering test -- [x] Prove every registered processor implements Ordered -- [x] Pin each shipped processor to its StartupOrder constant -- [x] Prove readiness and validator/defaulting bands are strictly ordered -- [x] Run focused ordering test -- [x] Run app-bootstrap full TEST/ARCHITECTURE regressions -- [x] git diff --check diff --git a/docs/superpowers/plans/2026-09-19-test-support-ownership-closure.md b/docs/superpowers/plans/2026-09-19-test-support-ownership-closure.md deleted file mode 100644 index 564cb162..00000000 --- a/docs/superpowers/plans/2026-09-19-test-support-ownership-closure.md +++ /dev/null @@ -1,9 +0,0 @@ -# Test Support Ownership Closure — Plan - -- [x] Move AdapterActivationInventory from test to systemTest -- [x] Prove no TEST source consumes AdapterActivationInventory -- [x] Prove custom testkit publisher/source-set declarations are absent -- [x] Preserve taxonomy positive-control fixture placement -- [x] Run systemTest compile/focused consumers -- [x] Run app-bootstrap TEST and ARCHITECTURE regressions -- [x] git diff --check diff --git a/docs/superpowers/plans/2026-09-25-review-followup-tools/__pycache__/by_area.cpython-312.pyc b/docs/superpowers/plans/2026-09-25-review-followup-tools/__pycache__/by_area.cpython-312.pyc deleted file mode 100644 index a3bd502f..00000000 Binary files a/docs/superpowers/plans/2026-09-25-review-followup-tools/__pycache__/by_area.cpython-312.pyc and /dev/null differ diff --git a/docs/testing/TESTING_STRATEGY.md b/docs/testing/TESTING_STRATEGY.md index 19e705ea..6858520b 100644 --- a/docs/testing/TESTING_STRATEGY.md +++ b/docs/testing/TESTING_STRATEGY.md @@ -4,7 +4,7 @@ - 상태: **활성 SSOT** - 기계 기준: `build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/TestLaneCategory.java` - 관련 리뷰: `docs/reviews/2026-09-07-app-bootstrap-module-code-review.md` BOOT-014~016 -- 후속 결정: `docs/superpowers/specs/2026-09-16-verification-surface-reduction-design.md` +- 후속 결정: `docs/design/2026-09-16-verification-surface-reduction-design.md` ## 1. 공식 테스트 분류는 다섯 개뿐이다 @@ -154,6 +154,22 @@ fixture는 **지원 코드**다. TEST/INTEGRATION/SYSTEM/ARCHITECTURE/PERFORMANC PERFORMANCE는 기본 로컬 `check`에 붙이지 않는다. 명시적 benchmark/performance task나 scheduled workflow가 실행한다. +PERFORMANCE lane은 상한을 매번 단언한다. 측정만 하고 통과하는 모드는 없다. + +- convention(`ca.strict-test-lane`)이 테스트 JVM에 `performance.assertions.enabled=true`를 넣는다. + leaf나 lane이 이 값을 따로 선언하지 않는다. +- 빌드가 `-Pperformance.assertions.enabled`(또는 `GRADLE_OPTS`의 + `-Dorg.gradle.project.performance.assertions.enabled`)에 `true` 아닌 값을 주거나, lane이 테스트 + JVM 값을 덮어쓰면 테스트 전에 실패한다. 메시지가 지우거나 `true`로 바꿀 곳을 알려 준다. +- skip된 테스트가 하나라도 있으면 실패한다. skip은 아무도 재지 않은 상한이다. +- 그래서 사람이 desktop에서 돌리는 `./gradlew performanceCheck`와 workflow가 같은 상한을 단언한다. +- 판정 없이 숫자만 보려면 JMH가 있는 leaf의 `./gradlew ::jmh`를 쓴다. 게이트가 아니다. + 실패한 상한은 잰 값을 단언 메시지에 남긴다. + +2026-11-05 desktop 게이트에서 httpclient lane이 이 속성 기본값 `false`로 돌아, 힙 상한을 재지 않고 +통과했다. 그 전에는 JPA pool lane이 같은 속성 뒤에 숨어 아무 상한도 비교하지 않았다 +(`PoolLaneClaimTest`). 이 규칙은 그 두 번을 되풀이하지 않기 위한 것이다. + ## 7. 새 테스트를 추가할 때 판단 순서 1. 실제 외부 인프라가 필요한가? @@ -236,11 +252,26 @@ source set에서 태그 `jpa-contract`로 `jpaPlatformContractTest` lane이 돌 갖게 고쳤다. `committed()`는 이제 실제로 커밋된 경계만 담는다(바깥이 롤백되면 안쪽도 빠진다). - PostgreSQL 멱등성 store는 (1) 이전 revision의 핸들을 `OPERATION_CONFLICT`로, Redis·fake는 `NOT_OWNER`로 답했다. 핸들의 owner 튜플에는 revision이 들어가므로 `NOT_OWNER`로 맞췄다. - `OPERATION_CONFLICT`는 "같은 operation id가 다른 인자로 이미 적용됨" 한 뜻만 남는다. (2) 실행 + 그때 `OPERATION_CONFLICT`는 "같은 operation id가 다른 인자로 이미 적용됨" 한 뜻만 남겼다. 2026-11-06 소유자 + 결정으로 뜻이 하나 늘었다: owner token이 같아도 호출이 claim과 다른 operation id를 대면 다섯 전이 모두 + `OPERATION_CONFLICT`다(Redis만 거절하고 PostgreSQL·fake는 적용했다). (2) 실행 전(CLAIMED) claim의 renew를 받아 줬고 Redis·fake는 거부했다. renew는 실행 중인 작업의 lease만 늘리도록 PostgreSQL을 맞췄다(호출자 없음 — 템플릿 안 동작 변화 없음). (3) release 뒤의 다음 claim을 `TakenOverClaimed`(attempt 2)로, Redis는 `Acquired`로 답한다. executor는 둘을 같게 - 처리하므로 계약은 "다음 claim이 scope를 가진다"만 요구한다. + 처리하므로 계약은 "다음 claim이 scope를 가진다"만 요구한다. 같은 이유로 release 재시도는 PostgreSQL이 + `ALREADY_RELEASED_SAME_OPERATION`, Redis·fake가 `ABSENT`다. 기록이 없으면 셋 다 `ABSENT`다(Redis는 전에 + `ALREADY_RELEASED_SAME_OPERATION`으로 답해 확인할 수 없는 해제를 확인했다, 2026-11-06). 같은 까닭으로 + release한 핸들로 시작하면 PostgreSQL은 `NOT_OWNER`, Redis·fake는 `ABSENT`이고 계약은 둘 다 받는다. (4) 이미 + 적용된 전이를 "이미 처리됨"으로 확인받는 핸들이 셋 다 달랐다. Redis는 complete·markFailed를 그 operation의 + 어느 핸들에게나, PostgreSQL은 complete를 같은 owner token의 어느 핸들에게나 확인했고 다른 핸들의 + markFailed·renew·release는 `OPERATION_CONFLICT`로 답했다 — 주인이 renew가 돌려준 핸들로 다시 renew해도 + 그랬다. fake는 complete 말고는 적용한 핸들의 재전송도 `NOT_OWNER`였다. 셋 다 적용한 핸들(기록보다 + revision이 하나 낮은 핸들)에게만 확인하고 다른 핸들은 `NOT_OWNER`로 맞췄다(2026-11-06 소유자 결정). + (5) 그 "적용한 핸들"을 Redis는 revision 하나로만 가렸다. 그래서 renew를 적용한 핸들이 start를 보내면 Redis만 + "이미 시작됨"(호출자가 작업을 다시 돌린다), fake·PostgreSQL은 `NOT_OWNER`였다. Redis 기록에 마지막 전이 + 종류(`lastKind`)를 남겨 그 전이일 때만 확인한다. 적용한 핸들이 markFailed를 다른 disposition으로 다시 보내면 + 셋 다 `NOT_OWNER`였고, 다른 retention이면 PostgreSQL만 `OPERATION_CONFLICT`, Redis·fake는 "이미 처리됨"이었다. + 다른 disposition은 `OPERATION_CONFLICT`, 다른 retention은 "이미 처리됨"으로 맞췄다(2026-11-07 소유자 결정). - `OutboxAppendContract`는 static helper 두 개였고 JPA readiness 테스트만 불렀다. 추상 계약으로 바꿔 readiness 테스트가 상속한다(같은 두 케이스 + 트랜잭션 밖·읽기 전용·중복 eventId). 실 PostgreSQL에서 `inRead` 안의 append가 예외 없이 사라지는 것을 찾았다(실측: 예외 없음, 행 없음) — JPA 트랜잭션 diff --git a/docs/upgrade/2026-11-docs-records.md b/docs/upgrade/2026-11-docs-records.md new file mode 100644 index 00000000..0357e710 --- /dev/null +++ b/docs/upgrade/2026-11-docs-records.md @@ -0,0 +1,32 @@ +# 업그레이드 안내 — 2026-11 기록 문서 위치 + +- 범위: 템플릿 `docs/`의 설계서·계획서·납품 패키지·증거·학습 문서를 옮긴 변경 하나 +- 근거: `docs/README.md` 「설계와 기록」, design-docs `conventions/docs-system.md` + +## 1. 누가 읽나 + +이 템플릿을 `upstream` remote로 두고 merge해 받는 파생 서비스가 읽는다. 코드·설정·빌드는 바뀌지 않았다. +문서 경로만 바뀌었다. + +## 2. 옮긴 경로 + +| 전 | 지금 | +| --- | --- | +| `docs/superpowers/specs/` | `docs/design/` | +| `docs/superpowers/plans/` | `docs/history/plans/` | +| `docs/superpowers/packages/<어댑터>/` | `docs/history/packages/<어댑터>/` | +| `docs/graphql-superpowers-package/` | `docs/history/packages/graphql-superpowers-package/` | +| `docs/web-superpowers-package/` | `docs/history/packages/web-superpowers-package/` | +| `docs/websocket-superpowers-package/` | `docs/history/packages/websocket-superpowers-package/` | +| `docs/evidence/` | `docs/history/evidence/` | +| `docs/study/` | `docs/history/study/` | + +`docs/superpowers/plans/2026-09-25-review-followup-tools/__pycache__/`의 `.pyc`는 실행 산출물이라 지웠다. + +## 3. 할 일 + +1. 서비스 문서·코드 주석이 위 「전」 경로를 가리키면 「지금」 경로로 바꾼다. + `git grep -n -e docs/superpowers -e superpowers-package -e docs/evidence -e docs/study`로 찾는다. +2. 서비스가 이 기록을 지웠다면 merge에서 「삭제 대 이름 바꿈」 충돌이 난다. 지운 쪽을 고르면 된다. +3. 옮긴 기록 파일과 ADR 맨 위에 한국어 머리 블록(상태·작성일·요약·현재 정본)을 달았다. 본문은 원문 그대로다. + 서비스가 그 파일을 고쳤다면 맨 위 몇 줄에서 충돌이 날 수 있다. 형식은 `docs/README.md` 「기록 문서의 머리 블록」이다. diff --git a/docs/upgrade/2026-11-maturity-review.md b/docs/upgrade/2026-11-maturity-review.md index aaa5e736..1464f703 100644 --- a/docs/upgrade/2026-11-maturity-review.md +++ b/docs/upgrade/2026-11-maturity-review.md @@ -4,7 +4,7 @@ - 커밋: `34565130` High·P1 19건 · `1400dc15` 남은 발견·매뉴얼·생성 명령 · `5786126c` 남은 항목과 합친 뒤 결함 · `7ef8d0b4` 재리뷰 기록 · `bbe944bd` 재리뷰 결함 · `ecc74b7d` 2차 재리뷰 기록·이 안내 · `1885bf8d` 2차 재리뷰 결함 · `339cf8fd` 3차 확인 리뷰 기록 · `f40c03c6` 3차 확인 리뷰 Minor · `c2e55510` 마지막 확인 리뷰 기록 · - `2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) — `docs(...)` 커밋은 문서만 바꾼다 + `2678955c` 테스트 코드 정적 분석(B-40) · `70fb80bf` 소유자가 다시 정한 기본값 3가지(늦은 멱등 완료 기록, `failure-retention` 기동 검사, workflow `cd`) · B4 성능 lane 단언 상시화(2026-11-06, B-43) · `paths` 필터 trigger를 단계 실행으로 세지 않음(2026-11-06 소유자 결정, B-36) · r8-f1 전송 오류 처리(2026-11-07, B-45~B-48) · r9-g1 GraphQL 판정 순서와 인자 변환 단계(2026-11-07 소유자 결정, B-45·B-46) · 태그 push·`release` workflow는 `releaseCheck`에만 셈(2026-11-07 소유자 결정, B-36) · 실패한 동시 인덱스 drop의 복구 절차(2026-11-07, 재리뷰 RR8-03-01, 5절) · STOMP channel interceptor를 사용자 전송으로 셈(2026-11-07, B-16) · 멱등 저장소의 markFailed 재전송 인자와 renew 뒤 start(2026-11-07 소유자 결정, 5절) · 저장소 구조 정리(2026-11-07 소유자 결정, 3.6절 B-49~) — `docs(...)` 커밋은 문서만 바꾼다 - 근거 문서: `docs/reviews/2026-11-01-maturity-review/README.md` 13~16절, `docs/reviews/2026-11-03-rereview/README.md` 4·6·8~13절, 각 커밋의 `BREAKING CHANGE:` 꼬리말 - 아래 표의 각 줄은 위 범위의 diff와 코드로 확인했다. 확인하지 못한 것은 그 자리에 "확인 못 함"으로 적었고 9절에 @@ -35,7 +35,9 @@ | 12 | 자기 Flyway 마이그레이션 번호가 템플릿의 새 번호와 겹치지 않는지 본다(4절) | 같은 버전 두 개로 Flyway 실패 | 같은 stream에 자기 마이그레이션을 둔 서비스 | | 13 | `.env`에 옛 `.env.example` 값을 복사해 두었다면 5.6절 키를 다시 맞춘다 | 새 기본값이 안 먹거나(JDBC batch), 기동 실패(알림 콜백 상한) | `.env`를 복사해 쓰는 서비스 | | 14 | 자기 테스트 코드에 `./gradlew testQualityCheck`를 돌려 보고, 발견을 고치거나 이유를 단 Match로 뺀다(B-40) | `mainCheck`가 실패 | 테스트 코드가 있는 모든 서비스 | -| 15 | staging·prod 배포 마이그레이션 도구에 `flyway.postgresql.transactional.lock=false`(환경 변수 `FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false`)를 넣는다. 자기 Flyway stream은 `Flyway.configure()` 대신 `FlywaySchemaPolicy.configure()`로 만든다(5절 「Flyway 잠금」) | `CREATE INDEX CONCURRENTLY`·`REINDEX … CONCURRENTLY` 마이그레이션에서 배포가 오류 없이 멈춘다. 자기 stream이 `Flyway.configure()`를 부르면 `:app-bootstrap:architectureTest` 실패 | persistence-jpa 선택 + 배포 도구로 마이그레이션하거나 자기 stream을 둔 서비스 | +| 15 | staging·prod 배포 마이그레이션 도구에 `flyway.postgresql.transactional.lock=false`(환경 변수 `FLYWAY_POSTGRESQL_TRANSACTIONAL_LOCK=false`)를 넣는다. 자기 Flyway stream은 `Flyway.configure()` 대신 `FlywaySchemaPolicy.configure()`로 만든다(5절 「Flyway 잠금」) | `CREATE INDEX CONCURRENTLY`·`REINDEX … CONCURRENTLY` 마이그레이션에서 배포가 오류 없이 멈춘다. 자기 stream이 `Flyway.configure()`를 부르거나 설정 객체를 직접 만들면(`new FluentConfiguration()`·`new ClassicConfiguration()`, 재리뷰 round7 RR7-03-06부터) `:app-bootstrap:architectureTest` 실패 | persistence-jpa 선택 + 배포 도구로 마이그레이션하거나 자기 stream을 둔 서비스 | +| 16 | 자기 성능 lane(`performance()`)에서 `performance.assertions.enabled`를 `false`로 두는 `systemProperty` 줄을 지우고, 그 속성을 읽어 상한 단언을 건너뛰던 테스트는 항상 단언하게 고친다. 성능 lane의 `@Disabled`·assumption skip을 없앤다(B-43) | `performanceCheck`가 테스트 전에 실패(`its test JVM would get performance.assertions.enabled=false`)하거나 skip 때문에 실패(`forbids skipped tests`) | 자기 성능 lane이 있는 서비스 | +| 17 | 자기 `docs/registries/error-codes.yaml` 행에서 `log_level:` 줄을 지운다(B-44) | `mainCheck`의 `:app-bootstrap:documentContractTest`가 실패(`docs/registries/error-codes.yaml rows with a log_level; the code decides the level, not the registry`) | `error-codes.yaml`에 자기 행을 더한 서비스 | ### 되돌릴 수 없는 것 @@ -58,11 +60,11 @@ | B-05 | 알림: `ReconciliationJobStorePort.claimDue(int, Instant)` → `claimDue(int limit, Instant now, Duration lease)`. `ReconciliationJob`에 `long claimFence` 필드 추가. `reschedule`·`complete`는 fence가 다르면 아무것도 안 바꾼다 | 직접 구현한 store·job 생성 코드 컴파일 오류 | lease 인자를 받고, claim마다 fence를 올리고, 쓰기에 fence 조건을 건다. 계약은 `application-notification` testFixtures의 공유 계약 테스트로 확인 | `34565130`, `bbe944bd` · `src/application-notification/.../dispatch/ReconciliationJobStorePort.java` | | B-06 | 파일 서버: `CleanupQueuePort.claimDue(Instant, int)` → `claimDue(Instant, int, Duration lease)`, `markAbandoned(CleanupItem, String reasonCode)` 추가. `CleanupItem`에 `UUID claimToken` 필드 추가. `FileQuotaPort.usedBytes(QuotaScope)` 추가. `UploadContentPort.releaseLease(UploadSession, RequestContext)` 삭제 | 직접 구현한 포트·`CleanupItem` 생성 코드 컴파일 오류 | 새 메서드 구현, `releaseLease` 호출 제거 | `1400dc15`(cleanup), `5786126c`(quota·upload) · `src/application-fileserver/.../cleanup/CleanupQueuePort.java`, `.../api/metadata/FileQuotaPort.java`, `.../upload/UploadContentPort.java` | | B-07 | 패키지 이동: `dev.caskeleton.application.outbound.SecretSourcePort`·`SecretReference` → `dev.caskeleton.application.secret.*`. `dev.caskeleton.application.outbound.CallBudget` → `dev.caskeleton.application.objectstorage.content.CallBudget`(leaf `application-objectstorage`). `application.outbound` 패키지 삭제 | `package dev.caskeleton.application.outbound does not exist` | import를 바꾼다. `CallBudget`을 쓰는 leaf가 `application-objectstorage`에 의존해도 되는지 `modules.json` 간선을 확인 | `5786126c` · `src/application-core/.../secret/`, `src/application-objectstorage/.../content/CallBudget.java` | -| B-08 | `shared-contract`에서 `dev.caskeleton.shared.operation.Operation`·`OperationStatus` 삭제. sample-portfolio(`...sample.portfolio.adapter.inbound.web.operation`)로 옮겨졌다 | import 실패 | 쓰고 있었다면 자기 inbound adapter로 복사한다 | `1400dc15` · `src/shared-contract/src/main/java/dev/caskeleton/shared/operation/`(삭제) | +| B-08 | `shared-contract`에서 `dev.caskeleton.shared.operation.Operation`·`OperationStatus` 삭제. 샘플 모듈로 옮겼다가 샘플과 함께 지웠다(B-49) | import 실패 | 쓰고 있었다면 자기 inbound adapter로 복사한다 | `1400dc15` · `src/shared-contract/src/main/java/dev/caskeleton/shared/operation/`(삭제) | | B-09 | `SecuritySettings`(adapter:inbound:web): `audience`가 `String` → `List`. `@ConfigurationProperties` 제거, `SecuritySettings.bind(Environment)`로 strict 바인딩. 생성자 `(String, String, List)` → `(String, List, List)`. `bootstrap.security.AuthenticationModeSettings` 삭제 | `audience()`를 문자열로 쓰는 코드, 직접 생성하는 테스트 컴파일 오류 | `List`으로 바꾼다. 인증 모드는 `SecuritySettings.authMode()`에서 읽는다 | `34565130`(List), `5786126c`(strict·삭제) · `src/adapter/inbound/web/.../settings/SecuritySettings.java` | | B-10 | adapter 공개 타입 삭제·이동: graphql `execution.GraphQlTimeoutPolicy`·`dataloader.GraphQlDataLoaderRequestRegistry` 삭제(`runtime.GraphQlDeadlineInstrumentation`·`GraphQlPerParentFetchInstrumentation` 추가). jpa `experimental.tenant.TenantId` 삭제 → `dev.caskeleton.application.tenant.TenantId`. persistence-notification의 엔티티는 `...platform.entity`, 저장소는 `...platform.repository`로 이동, `inbox` 하위 클래스는 `platform`으로 올라옴, `PreferenceJpaRepository`·`SuppressionJpaRepository` 삭제, `JpaNotificationSideEffect` → application-notification `dispatch.SuppressionSideEffect`. graphql `GraphQlClientPolicy.effectivePageSize(Integer, Integer)` 삭제 → `pagination.GraphQlConnectionPolicy.effectivePageSize`(상한 검사 포함, 재리뷰 RR-01-14). grpc(optional-platforms) `GrpcOperationLedger.release(identity)` → `boolean release(identity, GrpcClaimToken)`: 진행 중이고 그 token이 가진 claim만 지운다(RR-01-15) | import 실패, 호출부·직접 구현한 ledger 컴파일 오류. leaf `check`의 API surface 비교가 스냅샷과 달라 실패(자기 공개 타입을 더했다면 merge 충돌) | import를 바꾼다. 스냅샷 파일은 upstream 것을 받고 자기 추가분을 다시 승인한다 | `1400dc15`·`5786126c` · `docs/architecture/graphql-api-surface.txt`, `docs/architecture/jpa-api-surface.txt`(166→165), `docs/notification/api-surface-snapshot.txt`(362→364) | | B-11 | 조립·지원 타입: `bootstrap.autoconfigure.operation.DurableOperationConfig` → `composition:durable-operation`의 `composition.operation.DurableOperationAutoConfiguration`. `bootstrap.settings.LoggingSettings` 삭제. `composition.outbox.OutboxLeaderElectionToken` 삭제. `TracingSamplingEnvironmentPostProcessor` → `TracingEnvironmentPostProcessor`, `StartupOrder.TRACING_SAMPLING` → `TRACING_PROPERTIES`. `StartupRuleRunner(Environment, List)` → `StartupRuleRunner(Environment)`. `SecretSourceValidator(ConfigurableEnvironment, SecretSourcePort, List)` → `SecretSourceValidator(Supplier>)` | 이 타입을 참조하는 코드·테스트 컴파일 오류 | 새 이름으로 바꾼다 | `1400dc15`, `34565130`, `bbe944bd` · `src/composition/durable-operation/`, `src/adapter/outbound/support/.../startup/` | -| B-39 | vendored messaging SPI `KafkaQuarantinePublisher`(`messaging-kafka`): `quarantine(ConsumerRecord, Throwable)` → `quarantine(ConsumerRecord, FailureCategory category, Throwable reason)`. 호출자가 격리 이유(읽을 수 없는 레코드 `DESERIALIZATION`, 시도 예산 소진은 실패의 category 또는 `POISON_MESSAGE`)를 넘기고, 구현은 그것을 `msg.failure-category` header로 쓴다 | 이 SPI를 직접 구현한 서비스는 `does not override abstract method` 컴파일 오류. 람다로 만든 것도 인자 수 오류 | 세 인자 메서드로 고친다. category를 header나 저장소에 그대로 남겨야 redrive가 두 경우를 가른다(템플릿 `KafkaDeadLetterQuarantine`, 테스트 `KafkaDeadLetterQuarantineTest`) | `bbe944bd`(리뷰 06-14), 3차 수정에서 목록에 추가(재리뷰 2차 RR-02-16) · `src/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaQuarantinePublisher.java` | +| B-39 | vendored messaging SPI `KafkaQuarantinePublisher`(`messaging-kafka`): `quarantine(ConsumerRecord, Throwable)` → `quarantine(ConsumerRecord, FailureCategory category, Throwable reason)`. 호출자가 격리 이유(읽을 수 없는 레코드 `DESERIALIZATION`, 시도 예산 소진은 실패의 category 또는 `POISON_MESSAGE`)를 넘기고, 구현은 그것을 `msg.failure-category` header로 쓴다 | 이 SPI를 직접 구현한 서비스는 `does not override abstract method` 컴파일 오류. 람다로 만든 것도 인자 수 오류 | 세 인자 메서드로 고친다. category를 header나 저장소에 그대로 남겨야 redrive가 두 경우를 가른다(템플릿 `KafkaDeadLetterQuarantine`, 테스트 `KafkaDeadLetterQuarantineTest`) | `bbe944bd`(리뷰 06-14), 3차 수정에서 목록에 추가(재리뷰 2차 RR-02-16) · `src/platforms/messaging/messaging-kafka/src/main/java/dev/caskeleton/messaging/kafka/KafkaQuarantinePublisher.java` | | B-41 | enum 값 추가: `IdempotencyStartOutcome.LEASE_EXPIRED`, `IdempotencyRenewOutcome.LEASE_EXPIRED`(둘 다 `carriesOwner()`=false). 주인이 아직 기록을 가졌지만 processing lease가 끝나 시작·renew를 거절한다는 뜻이다. 전에는 PostgreSQL이 둘 다 `NOT_OWNER`, Redis가 renew는 `NOT_OWNER`·시작은 `STARTED`였다 | `default` 없는 switch 식이 "does not cover all possible input values" 컴파일 오류. 직접 구현한 store는 `IdempotencyStoreContract`의 새 시간 케이스(lease 지난 시작·renew)에서 실패 | 새 값 분기를 더한다. `LEASE_EXPIRED`를 `NOT_OWNER`처럼 "기록을 잃었다"로 읽지 않는다 — 실행 중이면 주인은 여전히 `complete`·`markFailed` 한다. store는 lease가 끝난 시작·renew에 이 값을 돌려준다 | r9(재리뷰 README 15 남음, RR5-01-02) · `src/application-core/.../idempotency/IdempotencyStartOutcome.java`, `IdempotencyRenewOutcome.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java` | ### 3.2 설정·기동 — 기동이 실패하거나 런타임 예외가 난다 @@ -71,11 +73,11 @@ |---|---|---|---|---| | B-12 | JWT 모드에서 `APP_SECURITY_JWT_AUDIENCE` 필수(빈 값 거부, `${...}`가 안 풀린 값도 없는 값으로 봄). 토큰 `aud`가 목록 중 하나를 담아야 통과. `resource_access` role은 audience에 적은 client 것만 읽는다(realm role은 그대로) | 기동 실패 `APP_SECURITY_JWT_AUDIENCE (app.security.audience) is required`(exit 코드 확인 못 함). `.env.example`이 `APP_SECURITY_JWT_AUDIENCE=`(빈 값)를 싣고 있다. 다른 client의 role에 기대던 권한이 사라짐 | client id를 쉼표로 넣는다. 다른 client role로 권한을 받던 사용자가 있는지 IdP에서 확인 | `34565130`(필수·role), `1400dc15`(안 풀린 `${...}`) · `src/adapter/inbound/web/.../auth/JwtDecoderConfig.java`, `.../JwtToAuthenticatedPrincipalConverter.java`, `.../settings/SecuritySettings.java` | | B-13 | `app.security.*` strict 바인딩: 접두어 아래 오타 키, 또는 설정·placeholder 어디에도 쓰이지 않는 `APP_SECURITY_*` 환경 변수가 기동을 막는다 | 기동 실패(메시지는 `StrictSettingsBinder`가 키 이름을 담아 냄, 정확한 문구 확인 못 함) | 쓰지 않는 `APP_SECURITY_*` 변수를 지운다 | `5786126c` · `SecuritySettings.bind`, `src/adapter/outbound/support/.../StrictSettingsBinder.java` | -| B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl` | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로. Redis SDK admin 계정(`RedisAccountContribution`)을 조립했다면 그 변수를 `static` `RequiredProductionSecrets` bean으로도 낸다(코드에 든 참조는 검사가 보지 않는다, RR3-04-03, `src/adapter/outbound/redis-sdk/README.md`) | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | +| B-14 | prod 프로필에서 `fixture-`로 시작하는 비밀값을 거부(레지스트리 `secret` 행, 모듈이 기여한 비밀, `secret://…/` 참조 대상. `HOSTNAME`·앱 이름 같은 비밀 아닌 값은 보지 않는다 — RR2-04-01). Redis ACL fixture 파일 이름 변경: `infra/redis-sdk/acl/all-accounts.acl` → `lane-fixture-accounts.acl`(폴더는 지금 `compose/redis/acl/`, B-51) | prod 기동 실패, 요약 `prod secret/config-source contract is invalid`(exit 78). 옛 ACL 경로를 mount하던 compose는 파일 없음 | prod 값을 진짜 비밀로 바꾼다. compose의 ACL 경로를 새 이름으로. Redis SDK admin 계정(`RedisAccountContribution`)을 조립했다면 그 변수를 `static` `RequiredProductionSecrets` bean으로도 낸다(코드에 든 참조는 검사가 보지 않는다, RR3-04-03, `src/adapter/outbound/redis-sdk/README.md`) | `bbe944bd` · `src/app-bootstrap/.../runtime/SecretSourceValidator.java`, `docs/registries/secrets-classification.yaml` | | B-15 | 기동 rule이 모든 singleton보다 먼저 돈다(`StartupRuleRunner`가 `BeanFactoryPostProcessor`). `StartupRule`과 `RequiredProductionSecrets` bean은 `static @Bean`이고 `Environment`, bean factory, static 무인자 `RequiredProductionSecrets`의 `ObjectProvider`만 받아야 한다. 두 타입의 클래스는 `@Value`·`@Autowired`·`@Inject`·`@Resource` 멤버, `@PostConstruct`·`@PreDestroy`, `@ConfigurationProperties`를 가질 수 없다(post-processor보다 먼저 만들어져 비어 있게 된다, RR2-04-03) | non-static `@Bean`이거나 다른 bean을 받으면 기동 실패 `startup rule or secret list '<이름>' created [] while creating it ... Declare the rule with a static @Bean method ...`, 위 멤버가 있으면 `'<이름>' (...) is a StartupRule or RequiredProductionSecrets ... but it needs one: [...]`(둘 다 exit 78, 둘 다 모든 프로필. runner가 rule과 비밀 목록을 프로필과 무관하게 먼저 만들어, 인터페이스 타입 `@Bean`이 돌려준 실제 클래스까지 본다, RR3-04-01) | rule 선언을 `static`으로, 인자를 위 셋으로 줄인다. 값은 `violations(Environment)`가 받는 `Environment`에서 읽는다. 다른 bean이 필요한 검사는 rule이 아니라 일반 bean으로 둔다 | `34565130`, `bbe944bd` · `src/adapter/outbound/support/.../startup/StartupRule.java`, `StartupRuleRunner.java` | -| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `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` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르거나, 사용자 전송(controller 등)이 `@SystemCaller` bean을 직접·중간 클래스를 거쳐·그 작업이 구현하는 프로젝트 인터페이스로 부르면 architectureTest 실패. `@SystemCaller` 클래스가 `Runnable`·`ApplicationRunner` 같은 프로젝트 밖 타입을 구현·상속해도 실패. 설정(`@Configuration`)은 웹 bean과 handler bean을 함께 등록해도 사용자 전송으로 세지 않지만, 요청 처리 코드(함수형 route·data fetcher·interceptor 같은 요청 처리기 타입)를 그 설정이나 그 안에 중첩된 클래스에 직접 쓰면 사용자 전송으로 센다. record·enum이 언어로 받는 상위 타입(`Record`·`Enum` 등)과 예외 클래스는 프로젝트 밖 상위 타입으로 세지 않는다 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 스케줄러에 넘기거나, 메시지 handler·예약 작업이면 그 클래스에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다. 예약 작업은 서비스 leaf의 `..adapter.inbound.scheduler..` 패키지에 둔다. 세 경로와 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」(handler 작업 순서는 09장 「소비」 4단계). "지금 실행" endpoint가 필요하면 `@RequiresPermission` 유스케이스를 따로 만든다. 작업을 task scheduler에 직접 등록하던 코드는 작업이 `Runnable`을 구현하는 대신 등록하는 곳에서 `job::run`을 넘긴다. 요청 처리 코드는 handler를 등록하는 설정과 다른 클래스에 둔다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd`, r9 · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | +| B-16 | 권한 가드(새 `PermissionEnforcementGuard`): `@SystemInvoked` 유스케이스가 bean이면 기동 실패. `@RequiresPermission`을 단 bean에 적용되는 advisor가 없어도 기동 실패. ArchUnit `SYSTEM_INVOKED_USE_CASES_DECLARE_NO_PERMISSION`, `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` 추가, 새 표시 `@SystemCaller` | 기동 실패 `@SystemInvoked use cases are registered as beans ...` 또는 `beans declare @RequiresPermission but no advisor enforces it ...`(exit 72). `@SystemCaller`가 아닌 inbound adapter가 그 유스케이스를 부르거나, 사용자 전송(controller 등)이 `@SystemCaller` bean을 직접·중간 클래스를 거쳐·그 작업이 구현하는 프로젝트 인터페이스로 부르면 architectureTest 실패. `@SystemCaller` 클래스가 `Runnable`·`ApplicationRunner` 같은 프로젝트 밖 타입을 구현·상속해도 실패. 설정(`@Configuration`)은 웹 bean(`WebMvcConfigurer`·CORS 설정·controller bean)과 handler bean을 함께 등록해도 사용자 전송으로 세지 않지만, 요청 처리기 타입(함수형 route·data fetcher·interceptor)에 의존하면 사용자 전송으로 센다. 처리 코드를 설정에 직접 쓰든, 다른 클래스의 메서드를 참조해 등록만 하든 같다. 설정 안에 중첩된 클래스는 설정용 타입(configurer·registry·CORS 설정·`RequestMethod`)에만 의존할 때를 빼고 다른 클래스처럼 사용자 전송 타입으로 판정한다(중첩된 JAX-RS 자원·`@ServerEndpoint`도 잡힌다). STOMP inbound channel interceptor(`ChannelInterceptor`·`ExecutorChannelInterceptor`)도 사용자 전송 타입이자 요청 처리기 타입이다. 사용자 전송 패키지 밖에 둔 interceptor, 설정에 중첩한 interceptor(익명 클래스 포함), interceptor를 구현한 설정이 `@SystemCaller`에 닿거나, interceptor를 `@Bean`으로 내놓는 설정이 `@SystemCaller` bean도 만들면 실패한다(2026-11-07 전에는 STOMP 헤더 타입을 읽는 interceptor만 잡혔다). record·enum이 언어로 받는 상위 타입(`Record`·`Enum` 등)과 예외 클래스는 프로젝트 밖 상위 타입으로 세지 않는다 | 시스템만 부르는 쓰기 유스케이스는 composition에서 `new`로 만들어 스케줄러에 넘기거나, 메시지 handler·예약 작업이면 그 클래스에 `@SystemCaller`를 달고 생성자에서 `new`로 만든다. 예약 작업은 서비스 leaf의 `..adapter.inbound.scheduler..` 패키지에 둔다. 세 경로와 두는 곳은 매뉴얼 07장 「시스템이 부르는 쓰기」(handler 작업 순서는 09장 「소비」 4단계). "지금 실행" endpoint가 필요하면 `@RequiresPermission` 유스케이스를 따로 만든다. 작업을 task scheduler에 직접 등록하던 코드는 작업이 `Runnable`을 구현하는 대신 등록하는 곳에서 `job::run`을 넘긴다. route·data fetcher·interceptor 등록은 handler bean을 만드는 설정과 다른 설정에 둔다. STOMP channel interceptor 등록도 같다. `@RequiresPermission`을 쓰면 web adapter(`MethodSecurityConfig`)가 조립돼 있어야 한다 | `1400dc15`, `bbe944bd`, r9 · `src/composition/service-runtime/.../authorization/PermissionEnforcementGuard.java`, `src/application-core/.../security/SystemInvoked.java`, `SystemCaller.java` | | B-17 | `IntegrationEventDraft`: `eventId`·`causationId`는 소문자 UUIDv7만. ArchUnit `INTEGRATION_EVENT_DRAFTS_ARE_BUILT_BY_THE_SHARED_HELPER`: `new IntegrationEventDraft<>(...)` 금지, `IntegrationEventDrafts.draft(...)`만 | 이벤트를 만드는 쓰기 요청이 `IllegalArgumentException: eventId must be a canonical lower-case UUIDv7...`로 실패. architectureTest 실패 | event id를 UUIDv7로 만든다(예: sample `UuidOutboxEventIdFactory`가 `UuidCreator.getTimeOrderedEpochPlus1()`). draft는 헬퍼로 만든다. tenant가 없는 이벤트는 `IntegrationEventDrafts.SINGLE_TENANT_SCOPE`(`global`) | `1400dc15`, `bbe944bd` · `src/application-core/.../messaging/event/IntegrationEventDraft.java`, `IntegrationEventDrafts.java` | -| B-18 | `MessageHandler.schemaVersions()`(vendored `messaging-core-api`, default `{v1}`): 소비자 decode 목록을 handler 선언으로 만든다. 같은 (메시지 타입, 버전)에 다른 payload class를 선언하면 실패 | 컴파일은 된다. v1이 아닌 메시지는 `SCHEMA_VERSION_NOT_REGISTERED`로 거부. 발행 등록(`MessageContracts`)과 class가 다르면 기동 실패 `MESSAGING_CONTRACT_CONFLICT` | v2 이상을 읽는 handler는 `schemaVersions()`를 override한다. 소비 타입을 `MessageContracts`에 따로 등록하던 코드는 지운다 | `5786126c` · `src/messaging/messaging-core-api/.../delivery/MessageHandler.java`, `messaging-spring-boot-starter/.../MessageContracts.java` | +| B-18 | `MessageHandler.schemaVersions()`(vendored `messaging-core-api`, default `{v1}`): 소비자 decode 목록을 handler 선언으로 만든다. 같은 (메시지 타입, 버전)에 다른 payload class를 선언하면 실패 | 컴파일은 된다. v1이 아닌 메시지는 `SCHEMA_VERSION_NOT_REGISTERED`로 거부. 발행 등록(`MessageContracts`)과 class가 다르면 기동 실패 `MESSAGING_CONTRACT_CONFLICT` | v2 이상을 읽는 handler는 `schemaVersions()`를 override한다. 소비 타입을 `MessageContracts`에 따로 등록하던 코드는 지운다 | `5786126c` · `src/platforms/messaging/messaging-core-api/.../delivery/MessageHandler.java`, `messaging-spring-boot-starter/.../MessageContracts.java` | | B-19 | `APP_FLYWAY_ENABLED`가 모든 프로필에서 읽힌다. dev·prod 프로필 파일의 `spring.flyway.enabled: true`·`app.persistence.vendor` 고정값을 지우고 persistence-jpa `config/module-defaults`가 `${APP_FLYWAY_ENABLED:true}`를 싣는다 | dev·prod 환경에 `APP_FLYWAY_ENABLED=false`가 있으면 전에는 무시됐지만 이제 기동 때 마이그레이션이 안 돈다 | dev·prod 환경 값을 확인한다. 자기 `application-dev.yml`·`application-prod.yml`에 같은 고정값을 다시 넣지 않는다 | `5786126c` · `src/app-bootstrap/src/main/resources/application-{dev,prod}.yml`, `src/adapter/outbound/persistence-jpa/.../module-defaults/persistence-jpa.yml` | | B-20 | JDBC batch 기본 켜짐: `APP_JPA_HIBERNATE_BATCH_SIZE` 0→50, `APP_JPA_HIBERNATE_ORDER_INSERTS`·`ORDER_UPDATES` false→true(registry `compatibility_impact: behavior-change`) | 컴파일·기동은 그대로. SQL이 묶여 나가고 insert·update 순서가 바뀐다. IDENTITY 키 엔티티는 batch가 조용히 꺼진다. `.env`에 옛 값(0·false)이 있으면 새 기본값이 안 먹는다 | 문장 순서에 기대는 코드가 있는지 본다. 끄려면 0·false를 명시 | `1400dc15` · `persistence-jpa.yml`, `docs/registries/env-keys.yaml` | | B-21 | 트랜잭션 제한: `TransactionPort` 쓰기·읽기 트랜잭션 30초(`app.persistence-jpa.transaction.write-timeout`·`read-timeout`, env 키 아님) | 30초를 넘는 트랜잭션은 문장이 취소되고 `DB_QUERY_CANCELED`로 실패 | 긴 일괄 작업은 쪼갠다. 꼭 필요하면 프로필 yml에서 값을 올린다 | `1400dc15` · `persistence-jpa.yml` | @@ -84,7 +86,7 @@ | B-24 | `APP_IDEMPOTENCY_PROCESSING_LEASE`는 2초(`IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER`)보다 길어야 한다. `APP_IDEMPOTENCY_TTL`(replay TTL)은 그 lease보다 짧으면 안 된다(재리뷰 RR-03-11). `APP_IDEMPOTENCY_FAILURE_RETENTION`은 replay TTL보다 짧으면 안 된다(RR3-03-02) | 2초 이하면, replay TTL < lease면, 또는 failure retention < replay TTL이면 기동 실패(exit 78). 마지막은 메시지에 `failure-retention`·`replay-ttl` 두 키와 값이 나온다 | lease를 2초보다 길게(기본 30s), replay TTL을 lease 이상으로(기본 24h), failure retention을 replay TTL 이상으로(기본 24h — 기본값끼리는 그대로 뜬다) | `5786126c`, `bbe944bd`, 3차 수정, `70fb80bf`(2026-11-04 소유자 결정) · `src/composition/idempotency/.../IdempotencySettings.java` | | B-25 | 알림 콜백 본문 상한 65508 → 65251(바인딩에서 상한 검사) | `.env`에 옛 예제 값 `APP_NOTIFICATION_PLATFORM_CALLBACK_MAX_BODY_BYTES=65508`이 있으면 기동 실패 `max-body-bytes must be 1..65251` | 값을 지우거나 65251 이하로 | `5786126c` · `src/adapter/outbound/notification/.../autoconfigure/NotificationPlatformSettings.java` | | B-26 | `config/module-defaults/`에 같은 이름 파일이 둘이거나, 두 파일이 같은 키를 실으면 기동 실패 | 기동 실패 `two capability modules ship config/module-defaults/` 또는 `... both ship `(exit 78) | 자기 leaf의 module-defaults 파일 이름·키가 템플릿 모듈과 겹치지 않게 한다 | `1400dc15` · `src/adapter/outbound/support/.../startup/ModuleDefaultsEnvironmentPostProcessor.java` | -| B-27 | (sample-portfolio를 남겨 둔 경우) 데모 계정은 활성 프로필이 모두 `local`·`test`·`demo` 중 하나일 때만. 프로필이 없어도 거부 | 기동 실패 `the sample's demo accounts authenticate only under the local, test or demo profile` | `SPRING_PROFILES_ACTIVE=demo`(이미지·jar), `local`(bootRun)로 띄우거나 sample 보안 설정을 지운다. 세 프로필 모두 sample `application.yml`이 object storage를 끈다(RR2-04-02) | `5786126c`, `bbe944bd` · `src/sample-portfolio/.../security/SampleDemoAccountsProductionGuard.java` | +| B-27 | **샘플 삭제(B-49)로 템플릿에서 사라졌다. 받을 변경이 없다.** (sample-portfolio를 남겨 둔 경우) 데모 계정은 활성 프로필이 모두 `local`·`test`·`demo` 중 하나일 때만. 프로필이 없어도 거부 | 기동 실패 `the sample's demo accounts authenticate only under the local, test or demo profile` | `SPRING_PROFILES_ACTIVE=demo`(이미지·jar), `local`(bootRun)로 띄우거나 sample 보안 설정을 지운다. 세 프로필 모두 sample `application.yml`이 object storage를 끈다(RR2-04-02) | `5786126c`, `bbe944bd` · `src/sample-portfolio/.../security/SampleDemoAccountsProductionGuard.java` | ### 3.3 HTTP wire — 응답이 달라진다 @@ -98,6 +100,10 @@ | B-31 | 핸들러 밖 오류(`/error` 디스패치)를 `EnvelopeErrorController`가 실패 Envelope로 답한다. 전에는 Boot `/error` 맵이 `success:true`로 감싸져 요청 경로까지 실려 나갔다. 기본 JWT 체인에서 익명 400이 401로 바뀌지 않는다. 4xx·5xx 본문은 `success:true`로 감싸지 않는다. 보안 체인이 `DispatcherType.ERROR`를 허용한다 | 오류 본문 모양이 바뀐다. 자기 SecurityFilterChain이 ERROR 디스패치를 막으면 400이 401로 나간다 | 자기 체인에 `auth.dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()`을 넣는다(템플릿 `SecurityConfig`와 같게) | `bbe944bd` · `src/adapter/inbound/web/.../error/EnvelopeErrorController.java`, `.../auth/SecurityConfig.java` | | B-32 | 새·바뀐 오류 코드: 비동기 요청 timeout 500 `INTERNAL_ERROR` → 503 `REQUEST_TIMEOUT`(retryable). `IDEMPOTENCY_KEY_INVALID` 400(`details.reason`=`MISSING`·`MALFORMED`, `IdempotencyKeyHeader.parse`를 쓰는 엔드포인트, sample은 `BAD_PARAMETER`에서 바뀜). web-advanced 예외 10종이 모두 500 `INTERNAL_ERROR`였다가 각자 코드(`ADMISSION_REFUSED` 503 등) | 코드로 분기하던 클라이언트가 새 코드를 모른다 | 클라이언트 분기표에 더한다. web-advanced 표는 `src/adapter/inbound/web-advanced/README.md` 「오류 응답」 | `1400dc15` · `src/adapter/inbound/web/.../error/WebTransportError.java`, `HttpStatusErrorCodes.java`, `src/adapter/inbound/web-advanced/.../error/WebAdvancedError.java` | | B-33 | DB 실패 분류: 낙관적 잠금 충돌 500 → 409 `DB_OPTIMISTIC_CONFLICT`. 커밋 단계 연결 끊김(08xxx, 40003 등)을 재시도 가능으로 답하던 것 → 500 `DB_COMPLETION_UNKNOWN`(retryable=false) | 응답 status·code가 바뀐다 | 409는 다시 읽고 재시도, `DB_COMPLETION_UNKNOWN`은 업무 데이터로 결과를 확인 | `34565130`, `1400dc15` · `src/adapter/outbound/persistence-jpa/.../failure/PersistenceExceptionTranslator.java` | +| B-45 | 분산 락 timeout(`LockAcquisitionTimeoutException`): 500 `INTERNAL_ERROR`(retryable=false) → 409 `LOCK_ACQUISITION_TIMEOUT`(retryable=true, `Retry-After: 1`). GraphQL extension `code`·`retryable`, gRPC `ABORTED` + trailer `error-code`도 같은 코드. 예외가 `ApiErrorCarrier`가 되어 레지스트리가 약속한 값으로 답한다. 4xx라 "unhandled exception" ERROR 줄이 사라진다 | 500을 "재시도 금지"로 읽던 클라이언트가 이제 409를 받는다. 이 예외에 자기 `@ExceptionHandler`를 둔 서비스는 web에서 그쪽 응답이 그대로 나간다. GraphQL에서 이 예외를 `GraphQlExceptionResolver`에 등록한 매핑은 쓰이지 않는다: 실패 자신이 carrier라 그 코드가 등록 매핑보다 먼저다 | `Retry-After` 뒤 같은 요청을 다시 보내게 한다. 자기 처리기와 GraphQL 등록 매핑을 두었다면 지워도 된다 | r8-f1(2026-11-07, 재리뷰 RR7-01-04), r9-g1(2026-11-07, 재리뷰 RR8-01-01) · `src/application-core/.../lock/LockAcquisitionTimeoutException.java`, `src/adapter/inbound/web/.../observability/RetryAfterAdvisor.java` | +| B-46 | 다른 예외로 감싼 carrier: web·GraphQL도 gRPC처럼 원인 사슬의 첫 carrier 코드로 답한다(전에는 500 `INTERNAL_ERROR`). `IllegalArgumentException`이 carrier를 감쌌으면 `BAD_PARAMETER` 대신 그 carrier 코드다. STOMP ERROR 프레임의 `error-code`도 `IllegalArgumentException` 뒤의 carrier를 그 코드로 낸다. gRPC는 `Status.INVALID_ARGUMENT.withCause(iae)`처럼 `IllegalArgumentException`을 원인으로 든 raw status를 던져도 `onError`로 넘긴 것과 같이 `INVALID_ARGUMENT`·`BAD_PARAMETER`다(전에는 던지면 `INTERNAL`). 바뀌지 않는 것 둘(소유자 결정 2026-11-07): GraphQL에서 앱이 `GraphQlExceptionResolver`에 등록한 실패는 carrier를 원인으로 들어도 등록한 코드로 답한다(등록 매핑이 원인 사슬의 carrier보다 먼저, 실패 자신이 carrier면 그 코드가 먼저). 인자 변환 단계 — web `MethodArgumentTypeMismatchException`·`HttpMessageNotReadableException`, GraphQL `@Argument` binder — 는 원인에 carrier가 있어도 `BAD_PARAMETER`·`VALIDATION_FAILED`다. STOMP는 `@DestinationVariable`·`@Header`의 `ConversionFailedException`과 받은 메시지가 실린 `MessageConversionException`을 원인의 carrier와 상관없이 거부 WARN 한 줄로 남긴다 | 감싼 실패에 500·`INTERNAL`을 받던 클라이언트가 이제 그 carrier 코드(예: 503 `DB_UNAVAILABLE`)를 받는다. GraphQL 등록 매핑과 인자 변환 실패의 답은 그대로다 | 클라이언트 분기는 `error.code`로 한다(바꿀 것 없음). 감싼 실패를 일부러 500으로 보내려면 감싸지 말고 `IllegalStateException`을 던진다 | r8-f1(2026-11-07, 소유자 결정 2026-11-06, 재리뷰 RR7-01-05·RR7-01-03), r9-g1(2026-11-07, 재리뷰 RR8-01-01, README 19.4절 ①·④) · `src/shared-contract/.../error/ApiErrorCarrier.java` `firstIn`, 네 전송의 오류 처리기 | +| B-47 | `Retry-After`를 레지스트리 `retry_after_seconds`대로 붙인다. 새로 붙는 응답: 503 `DB_UNAVAILABLE` 5초, 409 `DB_SERIALIZATION_FAILURE`·`DB_DEADLOCK` 1초, 503 `DB_IDLE_IN_TX_TIMEOUT` 2초(나머지 `OUTBOX_PUBLISH_FAILED`·`JOB_*`는 HTTP로 나가지 않는 코드다). 전에는 web 표에서 빠져 헤더가 없었다. 표와 레지스트리를 `OperationalErrorRegistryContractTest`(document-contract, `mainCheck`)가 대조한다 | 이 응답에 `Retry-After`가 생긴다. 템플릿 `OperationalError` 행의 `retry_after_seconds`를 바꾼 서비스는 `RetryAfterAdvisor` 표도 같이 바꾸지 않으면 `mainCheck`가 실패한다(대조 대상은 `OperationalError` 코드뿐이다) | 헤더를 따르는 클라이언트는 그만큼 기다렸다 재시도한다. 자기 코드의 값은 그 코드가 `RetryAfterHint`로 말한다 | r8-f1(2026-11-07, 소유자 결정) · `src/adapter/inbound/web/.../observability/RetryAfterAdvisor.java`, `src/app-bootstrap/src/test/.../contract/OperationalErrorRegistryContractTest.java` | +| B-48 | GraphQL `@Argument` 값이 컨트롤러 파라미터 타입으로 바뀌지 않으면(Spring 인자 binder의 `BindException`) `INTERNAL_ERROR`(`INTERNAL`) 대신 `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`)로 답한다. 로그는 ERROR + 예외(`rejected value [...]`가 실림) 대신 WARN 한 줄 `request refused as BAD_PARAMETER by org.springframework.validation.BindException (executionId=…)`이다 | 그 실패에 `INTERNAL_ERROR`를 받던 클라이언트가 `BAD_PARAMETER`를 받는다. ERROR 경보가 잘못된 인자에 울리지 않는다 | 클라이언트는 `extensions.code`로 가른다. `BindException`에 자기 `GraphQlExceptionResolver` 매핑을 둔 서비스는 그 매핑이 그대로 먼저다 | r8-f1(2026-11-07, 소유자 결정) · `src/adapter/inbound/graphql/.../error/GraphQlWireErrorMapper.java` | ### 3.4 빌드 게이트·아키텍처 규칙 — `ci`가 빨개진다 @@ -105,10 +111,12 @@ |---|---|---|---|---| | B-34 | 템플릿 패키지 규칙(ArchUnit): `FEATURE_PACKAGES_DO_NOT_REUSE_TEMPLATE_PACKAGE_NAMES`, `TEMPLATE_PACKAGES_DO_NOT_DEPEND_ON_FEATURE_PACKAGES`. 템플릿 이름: application `usecase command query capability transaction security tenant observability secret messaging outbox idempotency operation lease lock cache realtime notification fileserver objectstorage`, domain `identifier stereotype` | 기능 패키지 이름이 이 목록과 겹치거나(예: `domain.lock`), 업무 코드를 템플릿 패키지(예: `application.usecase.*`)에 두고 기능 패키지를 import하면 `:app-bootstrap:architectureTest` 실패 | 기능 패키지 이름을 바꾸고, 업무 코드를 `dev.caskeleton.application.`로 옮긴다. 규칙 정본은 `src/application-core/CLAUDE.md` "Package ownership" | `5786126c`, r9 · `src/app-bootstrap/src/test/.../TemplatePackageOwnership.java`(표와 대조: `TemplatePackageOwnershipDocumentTest`) | | B-35 | JPA 규칙: 양방향 연관은 한쪽에서만 매핑(`mappedBy`), notification·fileserver 저장소 엔티티는 그 leaf 안에서만, `@Version` 엔티티의 bulk update는 version을 올려야 함 | 위반 엔티티·쿼리가 있으면 architectureTest 실패 | 매핑·쿼리를 고친다 | `34565130`, `1400dc15`, `bbe944bd` · `src/app-bootstrap/src/architectureTest/.../JpaProductionArchitectureTest.java` | -| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:sample-portfolio:check` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)에서 시작해 같은 `run:` 셸이 그 앞에서 실행한 `cd <상대 경로>`(`cd src && ./gradlew …`, `cd src; ./gradlew …`, 앞 줄의 `cd src`)를 따라간 뒤 `-p`를 붙인 디렉터리로 정하고(`70fb80bf`(2026-11-04 소유자 결정)), `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). 붙여 쓴 `-x`·`-p`도 Gradle처럼 읽는다(RR3-04-02). `run:` 스크립트를 bash 문법으로 읽고(heredoc·여러 줄 문자열·함수 본문 안의 `cd`는 따라가지 않음), 세지 않는 명령은 이유를 셋으로 나눠 적는다(r10). (1) 실패해도 단계가 실패하지 않을 수 있음: `\|\| exit <0 아닌 값>` 밖의 `\|\|`(`\|\| true` 등), pipefail 없는 파이프 왼쪽, `!`, `&`, `if`·`while` 조건, 스크립트 마지막이 아닌 `&&` 목록의 앞쪽, `set +e` 뒤, `exit 0` 하는 `EXIT`·`ERR` trap 뒤. (2) 돌지 않을 수 있음: `\|\|` 뒤, 마지막이 아닌 `&&` 목록의 뒤쪽, `if`·`while`·`for`·`case`·함수 본문 안, 최상위 `exit`·`exec <명령>`·`set -n` 뒤, 조건부이거나 부른 함수 안의 `exit 0`·인자 없는 `exit`·값을 모르는 `exit`·`exec`·`set -n` 뒤, 요청으로만 시작하는 workflow(`workflow_dispatch`·`repository_dispatch`·`issue_comment`·`types: [labeled]`인 `pull_request`·`workflow_run` 등; `push`·`pull_request`·`pull_request_target`·`merge_group`·`schedule`·`release`는 센다), 세는 job이 `uses: ./.github/workflows/<파일>`로 부르지 않는 `workflow_call` 재사용 workflow, 조건부이거나 `continue-on-error`인 job을 `needs`로 기다리는 job(자기 `if:`가 `always()`·`!cancelled()`면 센다). (3) 실패하면 단계도 실패하지만 검사가 읽지 않음: `\|\| exit 1`·`\|\| { …; exit 1; }`, `{ }`·`( )`·`$( )`·`bash -c` 안, 다른 명령의 인자인 `gradlew`(`timeout 60 ./gradlew`), `bash`·`sh`가 아닌 `shell:`, `shell:` 없이 Windows일 수 있는 runner(Windows 라벨, `${{ matrix.os }}` 같은 식, `linux`·`macos` 라벨 없는 self-hosted)에서 도는 단계 — 기본 셸이 `pwsh`다(Linux·macOS runner의 기본은 `bash -e`, `container:` job은 `sh -e`이고 둘은 같게 읽는다). Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-m`·`-v`·`--version`·`-h`·`-?`·`--help`·`--status`·`--stop`·`--foreground`, 묶음 `-qm`·`-qv` 포함)과 Gradle이 거부하는 짧은 옵션 묶음(`-mx`)·값을 받지 않는 옵션에 붙인 값(`-m=yes`)도 세지 않는다. 판독기의 Gradle 옵션 표는 `GradleCommandLineTest`가 build-logic을 돌리는 Gradle의 `--help`와 대조하므로, Gradle을 올려 옵션이 늘면(9.2의 `--task-graph`) 그 테스트가 실패한다. 단계를 부르지만 세지 않은 명령은 다른 빌드로 읽힌 것까지 실패 메시지에 이유와 함께 적는다(r9). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src`도 `cd src`도 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다. 확실히 따라갈 수 없는 디렉터리 이동(`cd "$VAR"`, `cd -`, `cd ~`, 절대 경로, `pushd`, `if`/`for`/`case`·`{ }`·서브셸 안의 `cd`, `||`·`|`로 이은 `cd`, 다른 명령과 `&&`로 묶인 `cd` 다음 줄) 뒤의 명령도 세지 않고, 실패 메시지에 그 명령과 이유를 적는다. 단계를 `./gradlew ci \| tee log`(기본 셸), `./gradlew ci \|\| true`, `./gradlew ci \|\| exit 1`, `if ./gradlew ci; then` 같은 모양으로만 부르거나, 조건부 `exit 0` 뒤, `-v`·`--help`를 붙여, 요청형 trigger·호출되지 않는 `workflow_call` workflow·조건부 job을 `needs`로 기다리는 job·`shell:` 없는 Windows runner에서만 부르는 자기 workflow도 실패한다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 두거나 같은 셸에서 `cd <상대 경로>`로 옮긴 뒤 부른다. 단계 명령은 혼자 한 줄로 두고, 로그를 파이프로 남기려면 `shell: bash`나 앞 줄 `set -o pipefail`을 둔다. Windows runner에서는 `shell: bash`를 둔다. 단계는 매 push·pull request·schedule에 도는 workflow와 job에서, 재사용 workflow라면 그런 job이 조건 없이 부르게 한다. Gradle을 올려 `GradleCommandLineTest`가 실패하면 새 옵션을 값 옵션·플래그·작업 없이 끝나는 옵션 중 하나로 판독기 표에 넣는다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c`, `70fb80bf`(2026-11-04 소유자 결정), r9, r10(RR6-04-01~06) · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../strictlane/WorkflowGradleInvocations.java`, `.../strictlane/ShellScript.java`, `.../strictlane/GradleCommandLineTest.java`(test), `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | +| B-36 | 빌드 검사 강화: `modules.json`에 없는 `build.gradle`이 있으면 `verifyCleanArchitectureDependencies` 실패. `verifyStrictLaneStages --dry-run`은 모든 strict lane이 workflow가 실행하는 단계(`:ci` `:mainCheck` `:integrationCheck` `:performanceCheck` `:releaseCheck`)에 속해야 하고 `.github/workflows`를 읽는다. 명령의 빌드는 `working-directory`(단계·job·workflow `defaults`)에서 시작해 같은 `run:` 셸이 그 앞에서 실행한 `cd <상대 경로>`(`cd src && ./gradlew …`, `cd src; ./gradlew …`, 앞 줄의 `cd src`)를 따라간 뒤 `-p`를 붙인 디렉터리로 정하고(`70fb80bf`(2026-11-04 소유자 결정)), `workflow_dispatch`로만 시작하는 workflow의 명령은 세지 않으며, 축약한 `-x`도 Gradle처럼 맞춰 본다(RR2-04-04). 붙여 쓴 `-x`·`-p`도 Gradle처럼 읽는다(RR3-04-02). `run:` 스크립트를 bash 문법으로 읽고(heredoc·여러 줄 문자열·함수 본문 안의 `cd`는 따라가지 않음), 세지 않는 명령은 이유를 셋으로 나눠 적는다(r10). (1) 실패해도 단계가 실패하지 않을 수 있음: `\|\| exit <0 아닌 값>` 밖의 `\|\|`(`\|\| true` 등), pipefail 없는 파이프 왼쪽, `!`, `&`, `if`·`while` 조건, 스크립트 마지막이 아닌 `&&` 목록의 앞쪽, `set +e` 뒤, `exit 0` 하는 `EXIT`·`ERR` trap 뒤. (2) 돌지 않을 수 있음: `\|\|` 뒤, 마지막이 아닌 `&&` 목록의 뒤쪽, `if`·`while`·`for`·`case`·함수 본문 안, 최상위 `exit`·`exec <명령>`·`set -n` 뒤, 조건부이거나 부른 함수 안의 `exit 0`·인자 없는 `exit`·값을 모르는 `exit`·`exec`·`set -n` 뒤, 요청으로만 시작하는 workflow(`workflow_dispatch`·`repository_dispatch`·`issue_comment`·`types: [labeled]`인 `pull_request`·`workflow_run` 등; `push`·`pull_request`·`pull_request_target`·`merge_group`·`schedule`·`release`는 센다), change trigger가 모두 `paths`·`paths-ignore` 필터를 단 workflow(그 경로 밖 변경에는 돌지 않는다, 2026-11-06 소유자 결정), `releaseCheck` 밖의 단계에서는 태그 push(`branches` 없는 `tags`·`tags-ignore`)나 `release`로만 시작하는 workflow(2026-11-07 소유자 결정), 세는 job이 `uses: ./.github/workflows/<파일>`로 부르지 않는 `workflow_call` 재사용 workflow, 조건부이거나 `continue-on-error`인 job을 `needs`로 기다리는 job(자기 `if:`가 `always()`·`!cancelled()`면 센다). (3) 실패하면 단계도 실패하지만 검사가 읽지 않음: `\|\| exit 1`·`\|\| { …; exit 1; }`, `{ }`·`( )`·`$( )`·`bash -c` 안, 다른 명령의 인자인 `gradlew`(`timeout 60 ./gradlew`), `bash`·`sh`가 아닌 `shell:`, `shell:` 없이 Windows일 수 있는 runner(Windows 라벨, `${{ matrix.os }}` 같은 식, `linux`·`macos` 라벨 없는 self-hosted)에서 도는 단계 — 기본 셸이 `pwsh`다(Linux·macOS runner의 기본은 `bash -e`, `container:` job은 `sh -e`이고 둘은 같게 읽는다). Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-m`·`-v`·`--version`·`-h`·`-?`·`--help`·`--status`·`--stop`·`--foreground`, 묶음 `-qm`·`-qv` 포함)과 Gradle이 거부하는 짧은 옵션 묶음(`-mx`)·값을 받지 않는 옵션에 붙인 값(`-m=yes`)도 세지 않는다. 판독기의 Gradle 옵션 표는 `GradleCommandLineTest`가 build-logic을 돌리는 Gradle의 `--help`와 대조하므로, Gradle을 올려 옵션이 늘면(9.2의 `--task-graph`) 그 테스트가 실패한다. 단계를 부르지만 세지 않은 명령은 다른 빌드로 읽힌 것까지 실패 메시지에 이유와 함께 적는다(r9). `verifyEnvKeys`: lane 계약 json의 `APP_` 밖 키는 `SPRING_`·`MANAGEMENT_`·`SERVER_`이거나 `secret://…/`가 가리키는 변수여야 하고, 레지스트리 `property:` 행은 그 property가 설정 metadata에 있어야 읽히는 것으로 친다(`@ConditionalOnProperty`로만 읽는 스위치는 `META-INF/additional-spring-configuration-metadata.json`에 선언, RR2-04-05). SpotBugs 신뢰도 HIGH → MEDIUM | 등록 안 한 leaf, 단계에 안 걸린 자기 lane, 자기 코드의 MEDIUM 발견이 `ci`·`qualityCheck`를 막는다. `working-directory: src`도 `cd src`도 없이 `./gradlew`를 부르는 자기 workflow 단계는 실행으로 세지 않는다. 확실히 따라갈 수 없는 디렉터리 이동(`cd "$VAR"`, `cd -`, `cd ~`, 절대 경로, `pushd`, `if`/`for`/`case`·`{ }`·서브셸 안의 `cd`, `||`·`|`로 이은 `cd`, 다른 명령과 `&&`로 묶인 `cd` 다음 줄) 뒤의 명령도 세지 않고, 실패 메시지에 그 명령과 이유를 적는다. 단계를 `./gradlew ci \| tee log`(기본 셸), `./gradlew ci \|\| true`, `./gradlew ci \|\| exit 1`, `if ./gradlew ci; then` 같은 모양으로만 부르거나, 조건부 `exit 0` 뒤, `-v`·`--help`를 붙여, 요청형 trigger·`paths` 필터 trigger로만 시작하는 workflow·`releaseCheck`가 아닌 단계를 태그 push·`release`로만 시작하는 workflow·호출되지 않는 `workflow_call` workflow·조건부 job을 `needs`로 기다리는 job·`shell:` 없는 Windows runner에서만 부르는 자기 workflow도 실패한다 | leaf를 등록하거나 지운다. 자기 lane은 단계에 건다. 단계를 부르는 workflow 명령에 `working-directory`를 두거나 같은 셸에서 `cd <상대 경로>`로 옮긴 뒤 부른다. 단계 명령은 혼자 한 줄로 두고, 로그를 파이프로 남기려면 `shell: bash`나 앞 줄 `set -o pipefail`을 둔다. Windows runner에서는 `shell: bash`를 둔다. 단계는 매 push·pull request·schedule에 도는(`paths`·`paths-ignore` 필터 없는) workflow와 job에서(`releaseCheck`만 태그 push·`release` workflow에서), 재사용 workflow라면 그런 job이 조건 없이 부르게 한다. Gradle을 올려 `GradleCommandLineTest`가 실패하면 새 옵션을 값 옵션·플래그·작업 없이 끝나는 옵션 중 하나로 판독기 표에 넣는다. SpotBugs 발견은 고치거나 이유를 단 제외로 | `1400dc15`, `34565130`, `bbe944bd`, `5786126c`, `70fb80bf`(2026-11-04 소유자 결정), r9, r10(RR6-04-01~06), RR7-05-01(2026-11-06 소유자 결정), 태그·릴리스 workflow(2026-11-07 소유자 결정) · `src/build-logic/.../ModuleRegistry.java`, `.../strictlane/StrictLaneStagesPlugin.java`, `.../strictlane/WorkflowGradleInvocations.java`, `.../strictlane/ShellScript.java`, `.../strictlane/GradleCommandLineTest.java`(test), `.../quality/QualityConventionsPlugin.java`, `src/build.gradle` | | B-37 | app-bootstrap 테스트 lane 분리: 저장소 파일을 읽는 테스트는 태그 `document-contract`(main 단계) 또는 `repository-contract`(`check`)여야 하고, 일반 `test` lane에는 `ca.repository.root`가 없다 | app-bootstrap에 둔 자기 테스트가 저장소 파일을 읽으면 `test`에서 실패 | 태그를 단다 | `1400dc15` · `src/app-bootstrap/build.gradle` | | B-40 | 테스트 코드 정적 분석 `testQualityCheck`: SpotBugs·FindSecBugs를 main 밖 모든 source set(test, testFixtures, integrationTest, systemTest 등)에 돌린다. 테스트용 제외 목록은 `config/spotbugs/exclude-test.xml`(보안 범주·내부 상태 노출·생성자 예외·반환값 null 역참조·아키텍처 위반 fixture). 분석 classpath가 그 source set의 runtime classpath로 넓어졌고, 분석이 불완전하면(빠진 클래스) 실패한다. main 빌드는 `mainCheck`(`qualificationCheck`), optional 빌드는 `ci` | 자기 테스트 코드의 SpotBugs 발견(예: `CountDownLatch.await` 반환값 무시, 공유 변수 비원자 쓰기, 닫지 않은 `Statement`)이 main 단계를 막는다. 테스트 classpath에 없는 타입을 참조하면 `SpotBugs analysis incomplete` | 고치거나, 클래스·메서드로 좁힌 Match를 이유와 함께 `exclude-test.xml`에 더한다. 빠진 타입은 그 테스트 suite 의존성에 넣는다 | `2678955c` · `src/build-logic/.../quality/QualityConventionsPlugin.java`, `src/config/spotbugs/exclude-test.xml`, `src/build.gradle` | | B-42 | shared-contract 패키지 규칙 `SHARED_CONTRACT_CONTAINS_ONLY_OPERATIONAL_CONTRACT_PACKAGES`가 실제로 검사한다. 대상은 `dev.caskeleton.shared..`뿐이고, 허용은 목록의 패키지(`concurrency digest error metrics observability ratelimit request response retry runtime security tracing`)와 그 아래, 뿌리 패키지에는 `package-info`만이다. 전에는 뿌리를 허용 목록에 넣고 접두어로 비교해서 모듈 안은 아무것도 잡지 못했고, 다른 leaf의 `..shared..` 패키지를 잡았다 | `dev.caskeleton.shared`에 목록에 없는 패키지나 뿌리 클래스를 둔 파생 서비스는 architectureTest 실패. 다른 leaf의 `shared` 패키지는 더는 걸리지 않는다 | 업무 개념이면 그것을 소유하는 모듈로 옮긴다. 운영 계약이면 `ForbiddenApiArchitectureTest.SHARED_CONTRACT_PACKAGES`와 shared-contract CLAUDE.md 「Responsibility」에 함께 더한다 | r10 · `src/app-bootstrap/src/architectureTest/.../ForbiddenApiArchitectureTest.java`, `SharedContractPackageRuleTest.java` | +| B-43 | 성능 lane 단언 상시화: `performance()` lane은 convention이 테스트 JVM에 `performance.assertions.enabled=true`를 넣는다. 빌드가 `-P`·`GRADLE_OPTS`(`-Dorg.gradle.project.…`)로 `true` 아닌 값을 주거나, lane `systemProperty`·`jvmArgs`(`-D…`)·task 설정이 테스트 JVM 값을 `true` 아닌 값으로 덮으면 테스트 전에 실패한다. 성능 lane은 `rejectSkipped` 없이도 skip된 테스트가 있으면 실패한다. httpclient·Mongo leaf의 속성 선언과 `integration-main.yml` `performance-check`·`release.yml` `httpclient-release-gate`의 `GRADLE_OPTS` 줄을 지웠다. 측정만 하는 모드는 만들지 않았다(JMH가 그 용도) | `performanceCheck`·`::performanceTestLaneCheck`가 `is a performance lane, and this build sets performance.assertions.enabled=false`, `its test JVM would get performance.assertions.enabled=false`, `forbids skipped tests … a skipped test is a bound nobody measured` 중 하나로 실패 | `-Pperformance.assertions.enabled=false`를 지운다. 자기 lane의 그 `systemProperty`·`jvmArgs` 줄을 지우고, 그 속성을 읽던 테스트는 항상 단언하게 고친다. 성능 lane의 skip은 없애거나 그 테스트를 다른 lane으로 옮긴다. `GRADLE_OPTS=-Dorg.gradle.project.performance.assertions.enabled=true`·`-P…=true`는 받아 주므로 그대로 둬도 된다 | B4(2026-11-06) · `src/build-logic/.../strictlane/StrictTestLanePlugin.java`, `.../strictlane/StrictTestLaneConventionTest.java`(test), `docs/testing/TESTING_STRATEGY.md` 6절 | +| B-44 | `docs/registries/error-codes.yaml`에서 `log_level` 칸을 지웠다. 행에 `log_level`이 있으면 `OperationalErrorRegistryContractTest.noRegistryRowCarriesALogLevel`(태그 `document-contract`, `mainCheck`)이 실패한다. 칸을 읽는 코드는 없었고 값 대부분이 실제 로그 레벨과 달랐다. 레벨은 실패 종류·경로가 정한다(`ServerFailureLog`, 보안 필터 `AuthErrorResponseWriter`) | 자기 행에 `log_level`이 남은 서비스는 `mainCheck` 실패(`… rows with a log_level; the code decides the level, not the registry`와 그 행의 code 목록) | 자기 행에서 `log_level:` 줄을 지운다. 레벨을 바꾸려면 그 실패를 로그로 남기는 코드를 고친다. 자기 설계서가 "행마다 `log_level`을 채운다"고 적었으면 그 문장도 지운다 | 설계 메모 2026-11-06 7절 결정 1·1-b · `docs/registries/error-codes.yaml` 머리말, `src/app-bootstrap/src/test/.../contract/OperationalErrorRegistryContractTest.java` | ### 3.5 모듈 registry·새 leaf @@ -116,6 +124,19 @@ |---|---|---|---|---| | B-38 | 새 leaf: `adapter-inbound-messaging`(`:adapter:inbound:messaging`, 이벤트 소비+inbox, 기본 조립에 없음), `composition-durable-operation`(`:composition:durable-operation`, `/operations`). 새 간선: `application-objectstorage`·`adapter-outbound-persistence-mongo`·`adapter-outbound-identifier`·`adapter-outbound-redis-sdk` → `shared-contract`, `adapter-inbound-web` → `adapter-outbound-support`, `sample-portfolio` → `adapter-outbound-support`, `app-bootstrap` → 두 새 leaf. 지운 간선: `composition-fileserver-platform` → `adapter-outbound-identifier`. `app-bootstrap/build.gradle`에 `runtimeOnly project(':composition:durable-operation')` 추가 | 자기 leaf를 더한 서비스는 `modules.json`·`app-bootstrap/build.gradle`에서 merge 충돌. 충돌을 풀다 durable-operation 줄을 빠뜨리면 `/operations` 조립이 없다(`DurableOperationConfig`가 app-bootstrap에서 빠졌기 때문) | 두 파일을 손으로 합친다. 합친 뒤 `architectureCheck`로 간선을 확인 | `1400dc15`, `5786126c` · `src/config/architecture/modules.json`, `src/app-bootstrap/build.gradle` | +### 3.6 저장소 배치 — 폴더·파일이 지워지거나 옮겨졌다 + +소유자 결정(2026-11-07, design-docs `repo-structure/README.md` 3.1절)으로 저장소 배치를 정리했다. 파생 서비스가 +고치지 않은 파일이면 병합이 그대로 지우거나 옮긴다. 고친 파일이면 "수정 대 삭제"나 이름 바뀜 충돌이 난다. + +| # | 무엇이 바뀌었나 | 파생 서비스 증상 | 할 일 | 근거 | +|---|---|---|---|---| +| B-49 | 샘플 모듈 삭제: `src/sample-portfolio`, `src/Dockerfile.sample`, registry `sample-portfolio` 행, 루트 `build.gradle`의 샘플 태스크·단계(`sampleWebContractCheck`, `:sample-portfolio:*` 의존, strict lane 단계 `:sample-portfolio:check`), `ci-quality-gates.yml`의 `sample-portfolio` job, `SampleRuntimeDefaultsContractTest`, spotbugs 제외의 샘플 클래스. 샘플에만 있던 검사(OpenAPI 스냅숏 `openapiCheckSnapshot`, Date 헤더, 가상 스레드 MDC 전파)도 함께 없어졌다 | 샘플을 고쳐 쓰던 서비스: 병합 때 "수정 대 삭제" 충돌. 샘플을 이미 지운 서비스: 충돌 없음 | 샘플을 이미 지웠으면 할 일 없음. 고쳐 쓰고 있으면 자기 leaf로 옮기고 registry 행·빌드 줄을 자기 것으로 둔다. 위 검사가 필요하면 자기 기능 leaf에 둔다 | `ab5982e9` | +| B-50 | `infra/`에서 15개 삭제. 쓰는 곳이 없던 12개(`infra/httpclient/**`, `infra/jpa/postgres/README.md`, `infra/jpa/toxiproxy/`, `infra/messaging/{kafka,postgres,toxiproxy,tls}/`, `infra/notification/toxiproxy/`)와 운영 인프라 셋(`infra/fileserver/nginx/nginx.conf`, `infra/fileserver/kubernetes/pvc-certification-job.yaml`, `infra/jpa/roles/runtime-roles.sql`). `release.yml`의 `fileserver-pvc-certification` job도 지웠고, fileserver 지원 표에서 "Kubernetes ReadWriteOnce PVC — Limited" 주장을 「주장하지 않음」으로 옮겼다 | 그 파일을 배포에 쓰던 서비스: 병합이 파일을 지운다. 고쳐 쓰던 서비스: "수정 대 삭제" 충돌 | 그 파일은 자기 인프라 repo로 옮긴다. 지켜야 할 조건은 `docs/fileserver/operations.md` 「운영 환경이 지켜야 할 조건」, `docs/fileserver/storage-certification.md`, `docs/jpa/security.md` 「역할과 권한」·「서버 설정」에 있다 | `a025f244` | +| B-51 | compose 정리. 루트 `docker-compose.yml`·`docker-compose.local.yml`·`docker-compose.infra.yml`을 개발 환경 `compose.yaml` 하나로 합쳤다(app은 `local` 런타임, 뒷단 서비스는 capability profile `jpa`·`redis`·`kafka`·`mongo`·`objectstorage`·`auth`·`mail`). 보조 파일은 `compose/`(keycloak realm·entrypoint, minio init, Redis ACL, mailpit 인증서 폴더). 테스트 lane fixture는 그 lane을 가진 leaf로 옮겼다: `docker-compose.dev.yml`·`docker-compose.prod-smoke.yml`·`docker-compose.tls.yml`·fileserver overlay·smoke 스크립트·스키마 적용 스크립트·lane 계약 JSON(`src/config/runtime/compose-profile-contracts.json`) → `src/app-bootstrap/compose-lanes/`, Redis topology compose → `src/adapter/outbound/redis-sdk/compose/`, NFS compose → `src/adapter/outbound/fileserver/compose/nfs/`. `infra/`는 없어졌다. lane 계약의 `composeProfile`(문자열)은 `composeProfiles`(목록)로 바뀌었고 `appMemoryLimit`이 생겼다. smoke는 lane 중 컨테이너가 재시작하거나 메모리로 죽으면 실패한다. `scripts/bootstrap-local.sh`는 인자를 받지 않는다 | `docker compose -f docker-compose.yml -f docker-compose.local.yml …`을 쓰던 스크립트·문서가 "no such file"로 실패. 옛 compose 파일에 서비스를 더했으면 수정 대 삭제 충돌. lane 계약을 고쳐 쓰던 서비스는 `composeProfile` 키를 smoke 스크립트가 읽지 않는다 | 명령을 `docker compose …`(루트 `compose.yaml`)와 profile로 바꾼다. 더한 서비스는 `compose.yaml`에 capability profile을 달아 옮기고, lane 전용이면 `src/app-bootstrap/compose-lanes/lane-services.yaml`에 둔다. 경로를 적은 workflow·문서를 위 새 경로로 고친다 | `50cd7154` | +| B-52 | `src/` 배치 정리. 들여온 플랫폼 넷을 `src/platforms/` 아래로 옮겼다: `src/messaging` → `src/platforms/messaging`, `src/grpc` → `src/platforms/grpc`, `src/grpc-advanced` → `src/platforms/grpc-advanced`, `src/optional-platforms` → `src/platforms/optional-build`(빌드 이름 `optional-platforms`는 그대로). registry `source_path`만 바뀌고 Gradle 경로(`:messaging:*`, `:grpc:*`)는 그대로다. optional 빌드는 `./gradlew -p platforms/optional-build …`로 부른다. `src/config/`에서 기능 하나가 주인인 데이터를 그 leaf의 `release/`로 옮겼다: `config/jpa/*` → `adapter/outbound/persistence-jpa/release/`, `config/messaging/**` → `adapter/outbound/messaging/release/`, `config/mongodb/release-contracts.json` → `adapter/outbound/persistence-mongo/release/` | `-p optional-platforms`를 부르는 workflow·스크립트가 "Project directory … does not exist"로 실패. 옮긴 폴더를 고쳐 쓰던 서비스는 이름 바뀜 충돌(Git이 이동으로 알아보면 자동 병합). `rootProject.file('config/jpa/…')`처럼 옛 경로를 읽던 자기 빌드 줄은 파일 없음 | workflow·스크립트의 `-p`와 경로를 새 위치로 고친다. 자기 leaf를 `src/messaging` 아래에 더했다면 `src/platforms/messaging` 아래로 옮기고 registry `source_path`를 고친다 | `8d69e599` | +| B-53 | 새 PR 검사 `python3 scripts/check-repo-layout.py`(`ci-quality-gates.yml`): 저장소 루트와 `src/` 최상위의 추적 항목이 허용 목록 안에 있어야 하고, registry `source_path`가 허용된 `src/` 폴더 아래여야 한다 | 자기 최상위 폴더(예: `infra/`, `src/<서비스 전용 폴더>`)를 둔 서비스는 PR 게이트가 실패한다 | 그 폴더가 정말 필요하면 스크립트의 `ROOT_ALLOWED`·`SRC_ALLOWED`와 자기 `CLAUDE.md` 지도에 같은 변경으로 더한다. 아니면 그 내용을 주인 leaf나 `docs/`로 옮긴다 | 커밋 「최상위 폴더 허용 목록 검사를 더한다」 | + ## 4. DB 마이그레이션 ### 4.1 새 버전과 영향 @@ -128,7 +149,7 @@ | notification (`flyway_jpa_notification_history`, notification-platform 선택 시) | V11 | `notification_reconciliation_job.claimed_until timestamptz`, `claim_fence bigint NOT NULL DEFAULT 0` + CHECK | 기존 job은 fence 0, lease 없음 | 그 표를 건드린 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V10에 남음(exit 70) | `34565130`, 3차 수정(RR-02-09) | | 〃 | V12 | `notification_suppression`의 `(tenant_id, normalized_target_hmac, reason)` 중복 행을 **삭제**(만료 없는 것 > 늦은 만료 > 이른 `effective_at` > 이른 `created_at` > 작은 id 순으로 하나 남김) 후 UNIQUE `uk_notification_suppression_target` | 지운 행의 `SuppressionId`는 더 이상 조회되지 않는다. 되돌리려면 백업 필요 | 그 표를 건드린 트랜잭션이 열려 있어 5초 안에 잠금(행 잠금 포함)을 못 잡으면 실패·롤백(삭제도 롤백), V11에 남음(exit 70) | `1400dc15`, 3차 수정(RR-02-09) | | 〃 | V13 | `notification_request.acceptance varchar(40) NOT NULL DEFAULT 'ACCEPTED'` + CHECK(`ACCEPTED`, `DROPPED_AS_DUPLICATE`) | 기존 요청은 모두 `ACCEPTED` | 그 표를 건드린 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V12에 남음(exit 70) | `5786126c`, 3차 수정(RR-02-09) | -| sample (`flyway_sample_schema_history`, sample-portfolio를 남긴 경우) | V8_1 | 유일 인덱스 `uq_poster_title_ci ON poster (upper(title))` | 없음 | 대소문자만 다른 제목이 있으면 `poster has titles that differ only by case or repeat: ...`로 실패. `poster`에 쓴 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V8에 남음 | `34565130`, 3차 수정(RR-02-09) | +| sample (`flyway_sample_schema_history`, sample-portfolio를 남긴 경우. **샘플 삭제(B-49)로 템플릿에서 사라졌다**) | V8_1 | 유일 인덱스 `uq_poster_title_ci ON poster (upper(title))` | 없음 | 대소문자만 다른 제목이 있으면 `poster has titles that differ only by case or repeat: ...`로 실패. `poster`에 쓴 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V8에 남음 | `34565130`, 3차 수정(RR-02-09) | | grpc-ledger (optional-platforms, history 표 확인 못 함) | V002 | 부분 인덱스 `ix_grpc_operation_ledger_finished_completed_at` (일반 `CREATE INDEX`) | 없음 | 큰 ledger면 만드는 동안 쓰기가 멈춘다. 파일 주석은 손으로 `CONCURRENTLY`를 먼저 돌리라고 한다. ledger에 쓴 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V001에 남음 | `1400dc15`, 3차 수정(RR-02-09) | | 〃 | V003 | `grpc_operation_ledger.claim_attempt BIGINT NOT NULL DEFAULT 1` + CHECK > 0 | 기존 행은 첫 시도(1) | ledger를 건드린 트랜잭션이 열려 있어 5초 안에 잠금을 못 잡으면 실패·롤백, V002에 남음 | `bbe944bd`, 3차 수정(RR-02-09) | @@ -151,10 +172,13 @@ `GRANT … REFERENCES ON`과 `REINDEX (CONCURRENTLY) …`는 더 이상 거부하지 않는다. 자기 스트림 검사가 새로 실패하면 그 파일은 Flyway가 거부하거나(`mixed=false`) 상한 없이 도는(`mixed=true`) 파일이다. 아직 배포 전이면 문장을 나누고, 이미 배포했으면 규칙 이전 목록에 더한다(r9, 재리뷰 RR4-02-01). -- **번호 충돌**: 템플릿이 이제 postgresql V20~V22, notification V11~V13, sample V8_1, grpc V002·V003을 쓴다. 파생 서비스가 같은 + 재리뷰 round7(RR7-03-05) 수정부터는 `.sql.conf`가 `executeInTransaction=true`를 정한 파일의 `VACUUM FULL`·비동시 + `REINDEX SCHEMA|DATABASE|SYSTEM`도 앞의 `SET LOCAL`과 상관없이 같은 이유로 거부한다. 그런 파일은 PostgreSQL이 배포 때 + `25001`로 거부하므로 배포된 적이 없다. 새로 걸리면 그 문장을 마이그레이션에서 빼 운영 절차로 옮긴다. +- **번호 충돌**: 템플릿이 이제 postgresql V20~V22, notification V11~V13, grpc V002·V003을 쓴다(sample V8_1은 샘플과 함께 사라졌다, B-49). 파생 서비스가 같은 위치에 같은 번호를 두었다면 Flyway가 같은 버전 두 개로 실패한다. 자기 마이그레이션은 템플릿과 떨어진 번호대로 옮긴다 (이미 적용된 파일 이름을 바꾸면 checksum·history가 어긋나므로 운영 DB에 적용된 것이면 DB 담당과 정한다). -- **migration-on-startup=false로 운영하는 서비스**: `infra/postgres/apply-capability-streams.sh`가 바뀌었다(stream을 +- **migration-on-startup=false로 운영하는 서비스**: `infra/postgres/apply-capability-streams.sh`(지금 `src/app-bootstrap/compose-lanes/postgres/apply-capability-streams.sh`, B-51)가 바뀌었다(stream을 `/flyway/streams/`에서 먼저 찾음). 운영자가 직접 적용한다. ### 4.2 이 브랜치의 이전 V21(과 3차 수정 전 V20·V22·V11~V13·V8_1·V002·V003)을 적용한 DB @@ -236,10 +260,16 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | 멱등성(lease가 지난 실행) | lease가 지난 `EXECUTING` 기록을 claim이 만나면 기록을 바꾸지 않고 500 `IDEMPOTENCY_RECOVERY_REQUIRED`로 답한다. 그 실행의 주인이 늦게 부른 `complete`·`markFailed`는 기록된다. 전에는 두 저장소 모두 기록을 `ABANDONED`로 바꿔(PostgreSQL은 `last_transition_kind` `EXPIRED_EXECUTION`) 늦은 결과를 거절했고 첫 요청도 500이었다. 이미 끝난 lease의 `renew`는 두 저장소 모두 거절한다(Redis는 전에 받아들였다). 남의 lease 지난 실행을 `inspect`하면 `ABANDONED`(전에는 `IN_PROGRESS_OTHER`) | 30s를 넘는 정상 요청이 이제 결과를 남기고 정상 응답을 받는다. 같은 키 재전송은 500을 받은 뒤 재생을 받을 수 있다. 직접 구현한 store는 `IdempotencyStoreContract`의 바뀐 시간 케이스로 확인한다. 운영자는 `EXECUTING` 기록을 지우지 않는다 — 살아 있는 실행의 늦은 결과가 기록을 못 찾아(`ABSENT`) 사라진다(`docs/runbooks/idempotency-unavailable.md`) | `70fb80bf`(2026-11-04 소유자 결정) · `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java` | | 멱등성(lease가 끝난 시작, r9) | lease가 지난 `CLAIMED`는 주인도 시작할 수 없다(`LEASE_EXPIRED`). executor는 작업을 돌리지 않고 503 `IDEMPOTENCY_UNAVAILABLE`(실행 전 거부, 메시지 `the claim's processing lease ran out before the action started`)로 답하고, 다음 같은 키 요청이 그 claim을 넘겨받아 실행한다. 전에는 Redis가 시작해 작업을 돌렸고 그동안 다른 요청은 lease가 지난 실행으로 500을 받았다. PostgreSQL은 `NOT_OWNER`로 거절해 500 `IDEMPOTENCY_RECOVERY_REQUIRED`였다. | claim과 시작 사이가 lease(기본 30s)보다 길었던 드문 요청이 500 대신 503(같은 키 재전송)을 받는다. 클라이언트는 `error.code`로 이미 가르므로 바꿀 것이 없다. 운영자는 이 503에서 저장소 장애를 찾지 않는다(runbook) | r9(재리뷰 README 15 남음, RR5-01-02·03) · `IdempotencyExecutor.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java` | | 멱등성(같은 attempt의 재시도, r10) | lease가 지나 시작을 거절당한 claim과 재시도 가능 실패 기록은 같은 attempt로 다시 claim해도 넘겨받는다(`TakenOverClaimed`, attempt+1). 전에는 두 저장소가 그 claim을 재생해(`ReplayedAcquire`) 시작이 다시 거절되거나(503, 기록이 사라질 때까지) 시작할 수 없는 기록이라 500 `IDEMPOTENCY_RECOVERY_REQUIRED`였다. 효과 불명으로 포기한 기록은 같은 attempt에도 `RecoveryRequired`(PostgreSQL은 전에 `ReplayedAcquire`). Redis는 이미 실행 중인 기록에 같은 attempt의 다른 핸들(넘겨받기 전 핸들, 재생받은 현재 핸들)로 온 시작을 `ALREADY_STARTED_SAME_OPERATION`으로 확인하지 않는다 — 전에는 executor가 작업을 한 번 더 돌렸다(PostgreSQL은 전부터 거절). in-memory fake는 재시도 가능 실패 기록에 다른 요청 본문이 오면 넘겨주지 않고 `FingerprintMismatch` | attempt를 재시도 사이에 들고 있다가 503 뒤 같은 attempt로 다시 부르는 호출자(재시도 래퍼, 메시지 소비자)가 이제 실행된다. 요청마다 새 attempt를 만드는 호출자(템플릿의 HTTP 경로)는 바뀌는 것이 없다. 같은 attempt를 두 호출이 동시에 쓰는 것은 여전히 가려내지 못한다 — 재시도는 앞 호출이 돌아온 뒤에. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다 | r10(라운드6 RR6-02-01) · `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java` | +| 멱등성(전이의 operation id·release·inspect, 2026-11-06) | owner token이 같아도 호출이 claim과 다른 operation id를 대면 PostgreSQL·in-memory fake도 다섯 전이(start·renew·complete·fail·release)를 `OPERATION_CONFLICT`로 거절하고 기록을 바꾸지 않는다(전에는 적용했다. Redis는 전부터 거절). in-memory fake의 claim은 같은 token·다른 operation에 `OwnerOperationConflict`(전에는 `InProgress`), inspect는 `OPERATION_CONFLICT`(전에는 `IN_PROGRESS_OTHER`). PostgreSQL·fake의 inspect는 완료된 기록에도 `OPERATION_CONFLICT`(전에는 응답을 재생). PostgreSQL complete는 같은 operation id를 쓴 다른 attempt에 `NOT_OWNER`(전에는 `ALREADY_COMPLETED_SAME_RESULT`). Redis release는 기록이 없으면 `ABSENT`(전에는 `ALREADY_RELEASED_SAME_OPERATION`)이고 핸들 revision을 본다: 같은 attempt가 넘겨받기 전 핸들로 release하면 `NOT_OWNER`(전에는 지금의 claim을 지웠다) | 템플릿의 호출자(`IdempotencyExecutor`)는 늘 claim의 operation id를 넘기고 release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르며 전이마다 다른 operation id를 넘기던 코드는 이제 `OPERATION_CONFLICT`를 받는다 — `IdempotencyOwner.claimOperationId()`를 넘긴다. Redis release의 `ALREADY_RELEASED_SAME_OPERATION`을 기다리던 코드는 `ABSENT`도 "해제됨"으로 읽는다. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다 | 2026-11-06(소유자 결정 "(a)로 진행", 라운드6 02 Declined) · `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `RedisIdempotencyStoreAdapter.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java` | +| 멱등성(이미 적용된 전이의 재전송, 2026-11-06·11-07) | 이미 적용된 전이를 "이미 처리됨"으로 확인받는 것은 그 전이를 적용한 핸들(기록보다 revision이 하나 낮고 기록의 마지막 전이가 그 전이인 핸들)뿐이다. 같은 attempt가 넘겨받기 전 핸들로, 넘겨받은 뒤 적용된 complete·markFailed를 다시 보내면 `NOT_OWNER`(전에는 Redis가 `ALREADY_COMPLETED_SAME_RESULT`·`ALREADY_MARKED_SAME_OPERATION`, PostgreSQL이 `ALREADY_COMPLETED_SAME_RESULT`·`OPERATION_CONFLICT`). PostgreSQL은 renew가 돌려준 핸들로 다시 renew하면 한 번 더 renew한다(전에는 `OPERATION_CONFLICT`). 넘겨받기 전 핸들의 renew는 `NOT_OWNER`, release는 `NOT_OWNER`(전에는 둘 다 `OPERATION_CONFLICT`). in-memory fake는 적용한 핸들이 start·renew·markFailed를 다시 보내면 `ALREADY_STARTED_SAME_OPERATION`·`ALREADY_RENEWED_SAME_OPERATION`(다른 lease면 `OPERATION_CONFLICT`)·`ALREADY_MARKED_SAME_OPERATION`(전에는 `NOT_OWNER`). release한 핸들로 start하면 PostgreSQL은 `NOT_OWNER`, Redis·fake는 `ABSENT`이고 계약은 둘 다 받는다(동작 변경 없음, Javadoc만). Redis는 renew를 적용한 핸들로 start하면 `NOT_OWNER`(전에는 `ALREADY_STARTED_SAME_OPERATION`). 적용한 핸들이 markFailed를 다른 disposition으로 다시 보내면 셋 다 `OPERATION_CONFLICT`이고 기록된 실패는 그대로다(전에는 셋 다 `NOT_OWNER`). retention만 다르면 셋 다 `ALREADY_MARKED_SAME_OPERATION`이고 처음 retention이 남는다(전에는 PostgreSQL만 `OPERATION_CONFLICT`) | 템플릿의 호출자(`IdempotencyExecutor`)는 넘겨받기 전 핸들로 다시 보내지 않고 renew·release를 부르지 않아 HTTP 동작은 같다. store 포트를 직접 부르며 heartbeat로 renew를 이어 부르는 코드는 PostgreSQL에서 두 번째 renew부터 거절당하던 것이 이제 된다. 직접 구현한 store는 `IdempotencyStoreContract`의 새 케이스로 확인한다. fake로 lost reply를 흉내 내던 테스트는 이제 "이미 처리됨"을 받는다. Redis 기록 hash에 `lastKind` 필드가 생긴다(claim·renew·전이 프로그램이 쓴다) | 2026-11-06(소유자 결정 「넘겨받기 전 핸들의 재전송」「해제된 핸들로 start」) · 2026-11-07(소유자 결정 「적용한 핸들의 markFailed 재전송 인자」, 재리뷰 round8 RR8-04-01·02) · `src/adapter/outbound/cache-redis/.../idempotency/IdempotencyScripts.java`, `src/adapter/outbound/persistence-jpa/.../postgresql/PostgreSqlIdempotencyStore.java`, `src/application-core/src/testFixtures/.../IdempotencyStoreContract.java`, `InMemoryIdempotencyStore.java`, `IdempotencyStartOutcome.java`, `IdempotencyFailOutcome.java` | | 빌드 단계(HTTP client) | `httpClientFailureInjectionTest`(Toxiproxy 장애 주입)가 `mainCheck`에서 빠졌다. `integrationCheck`에만 있고, main push·nightly의 `integration-main.yml` `integration-check` job이 돌린다 | main push마다 같은 lane이 `main-check`·`integration-check` 두 job에서 두 번 돌던 것이 한 번이 된다. 로컬에서 `mainCheck`만 돌리면 이 lane은 돌지 않는다(`integrationCheck`로 돌린다) | r9 · `src/adapter/outbound/httpclient/build.gradle` | | 서버 로그(GraphQL·gRPC·STOMP) | carrier로 답한 실패를 web과 같은 줄(shared-contract `ServerFailureLog`)로 ERROR에 남긴다: persistence 실패는 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. gRPC는 ` (method=…)`, GraphQL은 ` (executionId=…)`를 붙인다. gRPC는 인식 못 한 실패(`INTERNAL_ERROR`)도 `unhandled failure on …`로 남긴다. 클라이언트가 취소한 호출은 남기지 않고, 서비스가 `CANCELLED` status로 끝낸 살아 있는 호출은 남긴다. raw status는 넘겼든 던졌든 설명을 남기지 않는다(원인 예외가 있으면 그것만 붙인다). `IllegalArgumentException`(`BAD_PARAMETER`)은 web과 같은 WARN 한 줄 `request refused as BAD_PARAMETER by <예외 타입>`(메시지 없음)으로 남긴다. STOMP `@MessageMapping` 실패는 Spring의 `Unhandled exception from message handler method`(예외 전체) 대신 같은 줄로 남는다 | ERROR 로그가 늘어난다(전에는 gRPC가 아무것도 남기지 않았다). GraphQL·gRPC·STOMP는 잘못된 입력마다 WARN 한 줄이 생긴다. STOMP에서 Spring 문구로 경보를 걸었다면 고친다. `IDEMPOTENCY_RECOVERY_REQUIRED`의 scope digest를 모든 전송에서 찾을 수 있다(`docs/runbooks/idempotency-unavailable.md`) | r9 · `src/shared-contract/.../error/ServerFailureLog.java`, `GrpcExceptionHandlingInterceptor.java`, `GraphQlWireErrorMapper.java`, `StompHandlerFailureLog.java` | -| sample-portfolio | 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | -| Flyway 잠금 | Flyway의 PostgreSQL 마이그레이션 잠금을 트랜잭션 대신 세션에 둔다. Spring Boot의 Flyway는 module-defaults `spring.flyway.postgresql.transactional-lock: false`, 템플릿이 직접 만드는 Flyway(멱등성·알림·sample stream, schema-per-tenant, testkit `MigrationContractRunner`)는 `FlywaySchemaPolicy.configure()`, messaging inbox stream은 같은 값을 직접 넣는다. 운영 코드의 `Flyway.configure()` 직접 호출은 `JpaProductionArchitectureTest`가 거부한다 | Flyway 기본값에서는 동시 인덱스 마이그레이션이 Flyway 자신의 열린 트랜잭션을 기다려 끝나지 않았다. 이제 끝난다. 마이그레이션은 잠금을 잡은 연결 하나로 돈다. transaction 모드 PgBouncer 뒤에서는 잠금 해제가 다른 서버 연결로 가 다음 배포가 기다릴 수 있으니 마이그레이션은 직접 연결이나 session 모드 pool로 돌린다. 배포 도구는 이 repo 밖이라 2절 15번으로 맞춘다 | 재리뷰 round6 RR6-03-01 · `persistence-jpa.yml`, `.../migration/FlywaySchemaPolicy.java`, `docs/jpa/migration-guide.md` "Who may change the schema"·"Concurrent index builds" | +| 서버 로그(STOMP 거부·감싼 carrier, 2026-11-07) | `@MessageMapping` 앞에서 Spring이 거부한 메시지를 WARN 한 줄 `request refused as by <예외 타입>`으로 남긴다: 읽지 못한 payload(`MessageConversionException`)·비었거나 검증에 걸린 payload(`MethodArgumentNotValidException`)는 `VALIDATION_FAILED`, 변환되지 않는 `@DestinationVariable`·`@Header`(`ConversionFailedException`)는 `BAD_PARAMETER`. 전에는 ERROR에 예외 메시지(받은 JSON 조각·값)까지 남겼다. 응답을 쓰지 못한 변환 실패는 그대로 ERROR. 네 전송 모두 감싼 carrier를 그 carrier 줄로 남긴다(감싼 persistence 실패는 분류만, SQL 원인 없음) | ERROR 경보가 클라이언트의 잘못된 메시지에 울리지 않는다. 그 실패를 찾던 로그 검색은 WARN으로 바꾼다 | r8-f1(재리뷰 RR7-01-06·RR7-01-05) · `src/adapter/inbound/websocket/.../stomp/StompHandlerFailureLog.java`, `src/shared-contract/.../error/ServerFailureLog.java` `refused` | +| sample-portfolio | **샘플 삭제(B-49)로 템플릿에서 사라졌다.** 익명 쓰기 401, 포스터 제목 대소문자 무시 유일(409 `POSTER_ALREADY_EXISTS`), 관리자도 남의 work log 수정 불가, 샘플 이벤트 tenant `global` | sample을 남긴 서비스만 | `34565130`, `1400dc15` | +| Flyway 잠금 | Flyway의 PostgreSQL 마이그레이션 잠금을 트랜잭션 대신 세션에 둔다. Spring Boot의 Flyway는 module-defaults `spring.flyway.postgresql.transactional-lock: false`, 템플릿이 직접 만드는 Flyway(멱등성·알림·sample stream, schema-per-tenant, testkit `MigrationContractRunner`)는 `FlywaySchemaPolicy.configure()`, messaging inbox stream은 같은 값을 직접 넣는다. 운영 코드의 `Flyway.configure()` 직접 호출과 설정 객체 직접 생성(`new FluentConfiguration()`·`new ClassicConfiguration()`·그 하위 클래스, round7 RR7-03-06)은 `JpaProductionArchitectureTest`가 거부한다 | Flyway 기본값에서는 동시 인덱스 마이그레이션이 Flyway 자신의 열린 트랜잭션을 기다려 끝나지 않았다. 이제 끝난다. 마이그레이션은 잠금을 잡은 연결 하나로 돈다. transaction 모드 PgBouncer 뒤에서는 잠금 해제가 다른 서버 연결로 가 다음 배포가 기다릴 수 있으니 마이그레이션은 직접 연결이나 session 모드 pool로 돌린다. 배포 도구는 이 repo 밖이라 2절 15번으로 맞춘다 | 재리뷰 round6 RR6-03-01 · `persistence-jpa.yml`, `.../migration/FlywaySchemaPolicy.java`, `docs/jpa/migration-guide.md` "Who may change the schema"·"Concurrent index builds" | +| 실패한 동시 인덱스 마이그레이션 복구 | `docs/runbooks/migration-failed.md`에 「Recover a failed concurrent index migration」을 더했다: 진행 중인 빌드가 없는지 보고, 원인(중복 행, 문장을 붙잡던 열린 트랜잭션)을 정리하고, 실패한 빌드·재빌드가 남긴 무효 인덱스를 `DROP INDEX CONCURRENTLY`로 지우고, 그 버전의 실패 이력 행(`success = false`)만 지운 뒤 다시 배포한다. 실패한 문장이 `DROP INDEX CONCURRENTLY`면 남은 무효 인덱스는 지우지 않는다. 그 마이그레이션이 지우려던 인덱스라 다시 배포한 같은 문장이 지운다. 「Do not」의 이력 수정 금지에 이 한 가지 예외를 적었다. `flyway repair`는 계속 쓰지 않는다 | 전에는 안내가 "`DROP INDEX` 하나"였고, 그대로 하면 남은 실패 이력 때문에 다음 배포가 validate에서 다시 멈췄다. 실패한 drop의 인덱스를 손으로 지우면 다시 배포한 문장이 `42704`(없는 인덱스)로 또 실패한다. 동시 인덱스 마이그레이션을 쓰는 서비스의 운영자는 이 절차로 복구한다 | 재리뷰 round7 RR7-03-03, round8 RR8-03-01, 소유자 결정 2026-11-06 · `docs/jpa/migration-guide.md` "Concurrent index builds", `PostgreSqlConcurrentIndexMigrationIntegrationTest` | +| 성능 lane(HTTP client·Mongo) | httpclient `LargeBodyResourceTest`의 힙 상한(32 MiB 스트리밍 중 힙 증가 16 MiB 미만)을 매번 단언한다. 전에는 `-Pperformance.assertions.enabled=true`일 때만 단언하고 아니면 건너뛴다는 줄만 찍었다. Mongo `MongoResourceBudgetLaneTest`는 표준 gate 전체(p99 500ms, pool 대기 250ms, 힙 512 MiB, examined/returned 10, spill 금지)를 Gradle 밖 실행에서도 단언한다(B-43) | 손으로 돌린 `performanceCheck`가 상한을 실제로 재므로, 전에는 통과하던 느린 기계에서 실패할 수 있다 | B4(2026-11-06) · `LargeBodyResourceTest`, `MongoResourceBudgetLaneTest` | +| 보안 필터 로그 레벨 | 보안 필터(`AuthErrorResponseWriter`)의 `security failure` 줄을 5xx(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)면 ERROR, 4xx면 WARN으로 남긴다. 전에는 모두 WARN이었다. 다른 경로가 5xx를 ERROR로 남기는 규칙(`ServerFailureLog`)과 같아졌다 | ERROR로 거르는 로그 경보·대시보드에 JWKS 장애와 인증 설정 오류가 새로 잡힌다. 401·403은 그대로 WARN | 설계 메모 2026-11-06 7절 결정 2 · `src/adapter/inbound/web/.../auth/AuthErrorResponseWriter.java`, `docs/design/2026-11-06-error-code-log-level-design.md` | ## 6. 따라오는 순서 @@ -247,7 +277,7 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur | 단계 | 할 일 | 게이트 | |---|---|---| -| 0. 준비 | 운영·스테이징 DB 백업. 작업 브랜치를 따로 만든다. 자기 마이그레이션 번호가 4.1절 번호와 겹치는지 본다. 운영 DB 사본에 4.3절 Step 1 쿼리(필요하면 V8_1 중복 제목 확인)를 돌려 둔다 | — | +| 0. 준비 | 운영·스테이징 DB 백업. 작업 브랜치를 따로 만든다. 자기 마이그레이션 번호가 4.1절 번호와 겹치는지 본다. 운영 DB 사본에 4.3절 Step 1 쿼리를 돌려 둔다 | — | | 1. merge·의존성 | `git fetch upstream` 후 merge. 충돌 예상 파일: `config/architecture/modules.json`, `app-bootstrap/build.gradle`, `docs/registries/env-keys.yaml`, `.env.example`, `application*.yml`, API surface 스냅샷, `gradle.lockfile`. 자기 의존성을 바꿨으면 `./gradlew ::resolveAndLockAll --write-locks` | `./gradlew verifyDependencyLocks` | | 2. 컴파일·아키텍처 | 3.1절(B-01~B-11) 고치기. 3.4절 규칙 위반 고치기 | `./gradlew architectureCheck`, `./gradlew :app-bootstrap:architectureTest`, 고친 leaf마다 `./gradlew :check` | | 3. PR 게이트 전체 | 자기 strict lane을 단계에 건다. SpotBugs MEDIUM 발견 처리 | `./gradlew ci`, `./gradlew verifyStrictLaneStages --dry-run` | @@ -287,6 +317,8 @@ V21 실패의 분류는 `docs/runbooks/migration-failed.md` "Classify the failur - CORS가 켜져 있으면 `Retry-After`·`X-Request-Id`·`X-Correlation-Id`·`traceparent` 등이 `Access-Control-Expose-Headers`에 있다(§3). - 새 코드: `REQUEST_TIMEOUT`(503, retryable), web-advanced를 쓰는 서비스는 10종(3.3절 B-32). +- 분산 락 timeout은 409 `LOCK_ACQUISITION_TIMEOUT`(retryable, `Retry-After: 1`)이다. 전에는 500 `INTERNAL_ERROR`였다(3.3절 B-45). +- DB 일시 실패 넷(`DB_UNAVAILABLE` 등)에 레지스트리 값대로 `Retry-After`가 붙는다(3.3절 B-47). GraphQL `@Argument` 값이 타입에 맞지 않으면 `BAD_PARAMETER`다(B-48). - 프론트 계약 문서(`clean-architecture-frontend-template` `docs/architecture/backend-api-and-server-state-contract.md` §4.1·§6)는 `docs/web/http-contract.md`를 가리켜야 한다. - 프론트 세션에 넘긴 인계 문서(세션 scratchpad라 지워질 수 있음): diff --git a/docs/web/advanced-capabilities.md b/docs/web/advanced-capabilities.md index 96da4536..da72f415 100644 --- a/docs/web/advanced-capabilities.md +++ b/docs/web/advanced-capabilities.md @@ -2,7 +2,7 @@ The Advanced capabilities live in their own leaf, `adapter:inbound:web-advanced` (`src/adapter/inbound/web-advanced`, package `dev.caskeleton.adapter.inbound.web.advanced`). No -default composition carries it: `app-bootstrap` and `sample-portfolio` do not depend on it. A +default composition carries it: `app-bootstrap`은 이 leaf에 의존하지 않는다. A service that wants one of these capabilities adds the leaf as `implementation` in its own adapter leaf and calls the types directly. diff --git a/docs/web/repository-adaptation.md b/docs/web/repository-adaptation.md index c3b43f84..8e233558 100644 --- a/docs/web/repository-adaptation.md +++ b/docs/web/repository-adaptation.md @@ -1,7 +1,7 @@ # Web platform — repository adaptation The inbound HTTP API execution platform design -(`docs/web-superpowers-package/docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design.md`) +(`docs/history/packages/web-superpowers-package/docs/superpowers/specs/2026-08-13-web-inbound-http-api-execution-platform-design.md`) was written against a standalone repository. Four of its assumptions do not hold here, and this document records what each became and why, so a reader comparing the design to the tree is not left guessing whether a difference is a decision or a mistake. @@ -69,8 +69,9 @@ than silently absorbed. ## 5. Sample application -The design's `examples/web-platform-sample` is the existing `sample-portfolio` leaf, which already -carries the OpenAPI drift gate and the contract lanes the design's sample is specified to provide. +설계의 `examples/web-platform-sample`에 해당하는 모듈은 없다. 그 역할을 하던 샘플 leaf는 2026-11-07에 +지웠고, 그 안의 OpenAPI 드리프트 검사와 실서버 계약 lane도 함께 사라졌다. 예시는 `docs/manual/`과 +`scripts/new-feature.sh` 출력이 맡는다. ## 6. Idempotency: the design's store SPI is already owned by `application-core` diff --git a/docs/work/README.md b/docs/work/README.md new file mode 100644 index 00000000..85ec8261 --- /dev/null +++ b/docs/work/README.md @@ -0,0 +1,77 @@ +# 작업 매뉴얼 + +이 폴더는 이 repo에서 하는 모든 일의 절차서다. 사람과 AI 세션이 같은 절차를 쓴다. +읽는 순서는 하나다: 루트 `CLAUDE.md`(지도) → 이 README → 맡은 일의 playbook 하나. +규칙의 정본은 `AGENTS.md`와 registry(`src/config/architecture/modules.json`)다. 이 폴더는 규칙을 다시 쓰지 않고, 일하는 순서를 정한다. + +## 1. 어떤 playbook인가 + +| 맡은 일 | playbook | +| --- | --- | +| 새 업무 기능이나 새 capability 모듈을 만든다 | [new-feature.md](new-feature.md) | +| 있는 코드를 리뷰·수정·리팩터링·최적화한다. 구조·테스트 구조를 바꾼다 | [improve.md](improve.md) | +| 바꾸기 전에 대안을 비교하고 소유자 결정을 받는다 | [research-design.md](research-design.md) | +| 매뉴얼·안내 문서를 쓰거나 고친다 | [docs-writing.md](docs-writing.md) | +| 게이트를 돌린다, 릴리스한다, 파생 서비스에 템플릿 변경을 넘긴다 | [operate.md](operate.md) | +| 큰 일을 나눠 다른 세션에 맡긴다 | [delegate.md](delegate.md) | + +둘에 걸리면 이렇게 고른다. 결정이 먼저 필요하면 research-design이다. 동작이 바뀌는 코드가 있으면 new-feature나 improve다. 문서만 바뀌면 docs-writing이다. + +## 2. 크기 정하기 + +- 크기는 작음·중간·큼 셋이다. 정의와 크기별로 할 단계는 design-docs `conventions/work-thinking-order.md` 2절이 정본이다. +- 요약: 작음은 파일 몇 개·새 결정 없음·되돌리기 쉬움, 중간은 leaf(또는 문서 폴더) 하나 안의 여러 파일이나 소유자 없이 정할 작은 결정 하나, 큼은 새 체계·아키텍처·공개 계약·소유자 결정이 필요한 일이다. +- brief(작업 지시문)에 크기가 있으면 그대로 한다. 올릴 수는 있고 내릴 수는 없다. 올리면 이유를 보고에 쓴다. +- brief가 없으면 스스로 정한다. 망설여지면 큰 쪽이다. +- 이 repo에서 "경계"는 registry의 leaf 하나다. 파일 수가 아니라 바뀌는 경계와 영향으로 정한다. +- 아래는 파일이 하나여도 큼이다: 공개 계약(HTTP wire 계약 `docs/web/http-contract.md`, 오류 코드 레지스트리, API surface 스냅숏, env 키), 파생 서비스가 따라 고쳐야 하는 변경, 새 leaf, 보안 정책. +- 큰 일은 만들기 전에 멈추고 소유자 검토를 받는다([research-design.md](research-design.md)). 소유자가 그 변경을 이미 정했으면(결정 색인 행, 소유자 원문) 그 결정이 소유자 검토다. 출처와 시각을 보고에 적고 만든다. 결정이 다루지 않은 범위만 멈추고 묻는다. + +## 3. 모든 작업의 공통 단계 + +1. 기준 커밋을 고정한다. `git rev-parse HEAD`를 산출물과 보고에 적는다. +2. 이미 정한 것을 읽는다: [reference/decisions.md](reference/decisions.md), `docs/reviews/`에서 가장 최근 리뷰 README의 결정·남은 것 절. 정한 것은 다시 묻지 않는다. +3. 소유 leaf를 찾는다. registry의 `source_path`로 정하고, 가장 가까운 `src/**/CLAUDE.md`를 읽는다. +4. 스킬을 고른다. 정본은 `AGENTS.md` 「Superpowers Workflow」다. playbook에 작업별 스킬이 있다. +5. 자기 worktree와 자기 브랜치에서 일한다. 다른 세션과 같은 checkout을 쓰지 않는다. +6. 무거운 실행(Gradle, Docker, 테스트, 게이트)은 [operate.md](operate.md) 「실행 위치」대로 한다. +7. 일이 다른 leaf·계층이나 brief 범위를 넘어야 하면 거기서 멈추고 묻는다(5절). +8. 완료를 말하기 전에 검증한다(`superpowers:verification-before-completion`). 돌리지 못한 검증은 못 돌렸다고, 이유와 함께 쓴다(HARD-STOP 6). + +## 4. 커밋 + +- 기본 정책은 `human-only`다(`AGENTS.md`). 에이전트는 stage·commit·amend·push하지 않는다. +- 예외는 하나다. brief 7절이 허용한 것만 그 작업의 자기 브랜치에 한다. 커밋과 push는 따로 허용된다. 커밋만 허용됐으면 push하지 않는다(desktop 검증은 [operate.md](operate.md) 4.1절 「push 전에 검증하기」). +- 그때도 main 병합, main·다른 브랜치 push, force push, PR 병합은 하지 않는다. 그것은 소유자가 한다. +- 메시지 형식은 design-docs `conventions/commit-and-pr.md`를 따른다. AI 꼬리말과 자리표시자(`TBD`, `TODO`, 채우지 않은 칸)를 넣지 않는다. +- 커밋 하나에 논리 변경 하나다(같은 문서 3.1절). 수정 묶음도 결함(또는 같은 원인 하나)마다 커밋을 나누고, 동작 변경을 위한 리팩터링(규칙을 상수로 빼기 등)은 앞 커밋으로 나눈다. 나눈 커밋마다 그 커밋이 바꾼 것의 검사가 통과해야 한다([operate.md](operate.md) 4.1절 「push 전에 검증하기」). + +## 5. 막혔을 때 + +- 소유자만 정할 수 있는 것(공개 계약, 파생 서비스 동작, 보안 정책, 새 leaf, 되돌리기 비싼 선택)은 근거와 권하는 안을 붙여 한 번 묻고, 그 항목만 멈춘다. +- brief를 준 쪽이 있으면 그쪽에 묻는다. 없으면 소유자에게 묻는다. +- 묻는 형식: 항목 · 선택지 · 권하는 안과 이유 · 정할 사람. + +## 6. 보고 + +- 맨 앞에 결과(완료 / 부분 / 못 함)와 브랜치·커밋을 쓴다. +- 그다음 변경, 확인(명령 · 실행 위치 · rc · 로그 경로), 범위 밖에서 본 것(위치와 내용, 고치지 않음), 남은 문제를 쓴다. 남은 문제를 숨기지 않는다. +- 보고는 쉬운 한국어로 쓴다. 코드·명령·로그 인용만 원문 그대로 둔다. +- 숫자(테스트 수, 실패 수, 태스크 이름)는 로그에서 옮긴다. 기억으로 쓰지 않는다. 테스트 수는 성공한 Gradle 로그에 없으니 결과 XML 사본에서 센다([reference/gates.md](reference/gates.md) 4절). +- 사고 순서 흔적 칸을 둔다(`conventions/work-thinking-order.md` 3절). 다른 세션이 맡긴 일이면 design-docs `conventions/delegation-loop.md` 5절 양식을 쓴다. + +## 7. 필요할 때만 읽는 문서 + +| 문서 | 내용 | +| --- | --- | +| [reference/gates.md](reference/gates.md) | 게이트 목록, 바꾼 것에 맞는 게이트, 결과 기록 형식, 거짓 통과 막기 | +| [reference/review-criteria.md](reference/review-criteria.md) | 결함 정의, 심각도, 증거·통제 수준, 점검 항목, 리뷰 문서 양식 | +| [reference/defect-patterns.md](reference/defect-patterns.md) | 반복해서 나온 결함의 모양과 막는 기준 | +| [reference/decisions.md](reference/decisions.md) | 이미 정한 결정의 색인, 결정을 다시 여는 조건과 기록하는 법 | +| [evidence.md](evidence.md) | 이 매뉴얼의 규칙이 나온 사건과 지난 리뷰 ID | + +## 8. 이 폴더를 고칠 때 + +- 분량 상한: 지도 120줄, 이 README 80줄, playbook 150줄, 진입 경로(지도 + README + playbook 하나) 350줄. `reference/`는 상한이 없다. +- 본문에 지난 리뷰 ID·묶음 이름·번호만 쓴 결정을 넣지 않는다. 내용과 날짜를 쓰고 ID는 [evidence.md](evidence.md)로 옮긴다. 새 세션이 처음 읽는 `AGENTS.md`와 `src/**/CLAUDE.md`도 같다. 모듈 README·설계 문서·`docs/reviews/**`는 ID를 둔다. +- 이 폴더, 루트 `CLAUDE.md`, `AGENTS.md`, `src/**/CLAUDE.md`를 고친 뒤 `python3 scripts/check-work-docs.py`가 통과해야 한다. 절차는 [docs-writing.md](docs-writing.md)다. diff --git a/docs/work/delegate.md b/docs/work/delegate.md new file mode 100644 index 00000000..ded7c1bd --- /dev/null +++ b/docs/work/delegate.md @@ -0,0 +1,122 @@ +# 총괄 — 큰 일을 나눠 다른 세션에 맡긴다 + +총괄 세션이 일을 나누고, brief를 쓰고, 결과를 대조하고, 합치는 절차다. 공용 절차(brief 양식, 보고 양식, 대조, 교훈 정리, 장부, 지표, cold-read 시험)의 정본은 design-docs `conventions/delegation-loop.md`다. 이 playbook은 그것을 다시 쓰지 않고, 이 repo의 일을 나누는 법만 더한다. + +## 1. 언제 쓰나 + +- 일이 커서 여러 세션으로 나눠야 할 때: 전체 리뷰, 영역별 수정 묶음, 리뷰와 수정과 확인 리뷰의 반복, 여러 playbook에 걸친 일. +- 세션 하나가 끝까지 할 수 있는 일이면 이 playbook이 아니다. 그 일의 playbook을 쓴다. +- 맡은 쪽(하위 세션)은 이 playbook이 아니라 brief가 가리킨 playbook을 따른다. + +## 2. 받아야 할 것 + +- 소유자의 목표와 이미 정한 결정. 큰 일이면 소유자가 계획을 검토한 시각. +- 결과가 올라갈 브랜치와 그 최신 커밋(기준 커밋). +- 커밋 허용과 자기 브랜치 push 허용. brief 7절에 따로 적는다. push 없이도 desktop 검증은 된다([operate.md](operate.md) 4.1절 「push 전에 검증하기」). main 병합·main push는 소유자가 한다. +- 마감과 보고 받을 방법. + +## 3. 크기와 사고 순서 + +- 크기는 총괄이 정해 brief에 적는다. 정의는 design-docs `conventions/work-thinking-order.md` 2절이다. +- 큰 일은 하위 세션이 1~5단계와 대안 비교까지만 하고 멈추게 brief를 쓴다. 소유자 검토 뒤 만들기를 다시 맡긴다. +- 총괄 자신의 선행 사례는 지난 라운드의 나누는 법이다: 가장 최근 리뷰 README의 영역 표와 처리 표, [evidence.md](evidence.md) 2절. +- 스킬: `delegate`(소유자 환경의 실행판)가 있으면 쓴다. 정본과 다르면 정본이 맞다. + +## 4. 절차 + +### 4.1 맡기고 닫는 순서 + +design-docs `conventions/delegation-loop.md` 3절 순서대로 한다: 크기 → 나누기(4.2절) → 기준 커밋 → brief(그 문서 4절 양식, 60줄 이하) → 하위 세션 띄우기 → 보고 대조(그 문서 6절) → 합치기 → 교훈 정리(그 문서 7절) → 장부 한 줄(그 문서 8절) → 소유자 보고. + +이 repo에서 더할 것: + +- brief의 「작업 종류」는 이 repo의 `docs/work/<종류>.md`다. 「이미 아는 것」에는 [reference/decisions.md](reference/decisions.md)의 결정을 **내용으로** 옮긴다. 검증 명령은 [reference/gates.md](reference/gates.md)와 빌드 파일에서 실제 태스크 이름을 확인해 쓴다. +- 검증 칸에는 실행 위치와 증거 위치를 쓴다: desktop worktree, `flock /tmp/claude-gates/heavy.lock`, 로그 `~/<작업 이름>-logs/`([operate.md](operate.md) 4.1절). 7절에는 커밋 허용과 자기 브랜치 push 허용을 따로 쓴다. +- 수정 묶음 brief에는 보고의 「새로 가정하는 것」 칸을 요구한다. 확인 리뷰 brief에는 그 칸과 「정한 기본값」부터 보라고 적고, 지난 라운드에서 열린 채 넘어온 「Declined to judge」와 README 남은 항목을 다시 판정시킬지도 적는다. +- 수정 보고를 받으면 「정한 기본값」을 리뷰 README 처리 표와 [reference/decisions.md](reference/decisions.md) 기본값 행으로, 「범위 밖에서 본 것」을 README 남은 항목으로 옮긴다([reference/review-criteria.md](reference/review-criteria.md) 10절 「확인 리뷰 라운드의 README 절」). 옮기지 않은 기본값은 확인 리뷰가 볼 곳이 없다. +- 리뷰 brief에는 쓸 심각도 체계([reference/review-criteria.md](reference/review-criteria.md) 3절)와 "발견마다 이번 수정이 만들었나 / 이전부터"를 요구한다. +- 독립 리뷰어 둘([improve.md](improve.md) 4.1절의 세 경우)이면 범위·기준 커밋·심각도 체계가 같은 brief 둘을 쓰고, 두 세션을 함께 띄운다. 다른 칸은 셋이다: 정본 리뷰어인지(ID를 매기고 리뷰 폴더에 커밋한다), 출력 위치(다른 쪽은 보고에 두고 `B-NN-MM`), 5절에 "자기 리뷰를 끝내기 전에 상대 리뷰의 브랜치·문서·보고·노트를 읽지 않는다". +- 두 리뷰가 끝나면 총괄이 합친다. 같은 결함(같은 원인·같은 위치)끼리 짝짓고, 다른 쪽에만 있는 결함은 정본 리뷰어에게 보내 탐침으로 다시 확인한 뒤 다음 번호로 넣게 한다. 그 라운드 색인 절은 총괄이 쓰고 대응표(`B-NN-MM` → 정본 ID)를 둔다. +- 겹침 비율(두 리뷰가 모두 찾은 결함 수 / 합친 결함 수)을 그 라운드 색인 절과 design-docs `delegation-loop/metrics.md`의 M11 칸에 적는다. 2~3라운드 기록이 쌓이면 소유자가 이 방식을 다시 본다. +- 대조할 때: 보고의 태스크 이름·테스트 수를 desktop 로그에서 grep으로 찾는다. High·Important 이상은 총괄이 코드에서 직접 다시 확인한다. +- 리뷰 결과를 받으면 `python3 scripts/check-review-index.py docs/reviews/<폴더>`로 색인이 빠짐없는지 본다. 색인 절을 총괄이 쓰기 전에는 리뷰어 보고의 표를 `--extra-index <파일>`로 넘겨 본다. 수정 묶음은 색인에서 배정한다. +- 교훈을 보낼 곳: 그 playbook의 「자주 하는 실수」, 코드 결함 모양은 [reference/defect-patterns.md](reference/defect-patterns.md), 거짓 통과는 [reference/gates.md](reference/gates.md) 6절, 근거는 [evidence.md](evidence.md). + +### 4.2 나누는 법 — 이 repo + +영역은 가장 최근 리뷰 README의 영역 표를 다시 쓴다. 없으면 아래를 쓴다. 영역 하나에 하위 세션 하나다. + +| 영역 | 경로 | +| --- | --- | +| core·application | `src/domain-core`, `src/application-*`, `src/shared-contract` | +| inbound 전송 | `src/adapter/inbound/*`, `src/platforms/grpc/*`·`src/platforms/grpc-advanced/*`(optional 빌드) | +| persistence | `src/adapter/outbound/persistence-*`, 마이그레이션 | +| outbound capability | 그 밖의 `src/adapter/outbound/*`, 멱등성 store | +| messaging | `src/platforms/messaging/*`, `src/adapter/outbound/messaging` | +| bootstrap·build·CI | `src/app-bootstrap`, `src/composition/*`, `src/build-logic`, `src/build.gradle`, `.github/` | +| 보안(영역을 가로질러) | 인증·인가 체인, 비밀, 공개 경로 | +| 문서 | `docs/` | + +두 세션이 동시에 만지면 손으로 풀어야 하는 파일이다. 한 세션만 맡기거나, 총괄이 합칠 때 직접 고친다. + +| 파일 | 왜 | +| --- | --- | +| `docs/upgrade/` 안내 문서 | 묶음마다 행을 더해 번호가 겹친다 | +| `docs/reviews/<폴더>/README.md` | 처리 표·결정의 답·게이트 기록·남은 것은 총괄이 쓴다. 리뷰어는 자기 라운드 색인 절 하나만 쓴다([improve.md](improve.md) 4.1절 7단계) | +| `src/config/architecture/modules.json`, `src/settings.gradle` | registry 하나가 모든 leaf를 정한다 | +| `src/gradle/libs.versions.toml`, lockfile | 의존성을 바꾸면 lockfile 전체가 바뀐다 | +| `src/build.gradle`, `src/app-bootstrap/build.gradle` | 라이프사이클과 기본 조립 | +| `docs/registries/*.yaml` | 오류 코드·env 키·지표를 여러 기능이 함께 쓴다 | +| `docs/architecture/*-api-surface.txt`, `docs/security/public-paths-snapshot.txt` | 생성되는 스냅숏이다 | +| `AGENTS.md`, 루트 `CLAUDE.md`, `docs/work/` | 모든 세션이 읽는다 | +| `.github/workflows/*` | 단계 검사가 workflow 전체를 읽는다 | + +나눌 때 지킬 것: + +- 두 묶음이 같은 파일을 건드리지 않게 나눈다. +- 묶음마다 그 시점 최신 기준에서 시작한다. +- 묶음 크기 상한을 지킨다([improve.md](improve.md) 4.4절: 영역 하나, 발견 8건 이하, 확인 리뷰당 추가 1,500줄 이하). +- 전 leaf의 import를 바꾸는 묶음은 나머지를 합친 뒤 혼자 마지막에 한다. +- 같은 결함을 두 영역이 보면 한 묶음에만 배정한다. +- 합칠 때는 하위 브랜치를 모아 [reference/gates.md](reference/gates.md) 3절 묶음을 돌린다. 합치기와 그 게이트도 하위 세션에 맡길 수 있다. + +### 4.3 소유자 환경 + +하위 세션을 띄우는 법, 하위 세션 보고가 총괄에게 전달되는 길이, 공유 노트 폴더, 프론트 repo 일의 경로 같은 소유자 환경 규칙은 design-docs `conventions/delegation-loop.md` 11절 한 곳에 있다. 다시 쓰지 않는다. 이 repo에서 더할 것은 둘이다. + +- Agent 도구(세션 안의 하위 에이전트)는 이 repo의 `.claude/settings.json`이 막는다. 스킬이 하위 에이전트를 띄우라고 하면 그 단계는 그 세션이 직접 하거나, 이 playbook대로 별도 세션에 맡긴다. 막혔다고 Agent로 우회하지 않는다. +- 실행 위치(desktop, 공유 잠금, desktop worktree)는 [operate.md](operate.md) 4.1절이다. +- 하위 세션은 공유 노트 폴더의 다른 노트를 먼저 읽는다. 독립 리뷰어 둘은 노트 파일 이름을 서로 다르게 정해 주고, brief에 상대 노트를 읽지 말라고 쓴다. + +## 5. 완료 기준 + +- 하위 세션마다 brief가 양식대로이고 자리표시자가 없다. +- 보고를 diff·커밋·로그와 대조했고 불일치를 셌다. +- 합친 트리에서 라운드 끝 게이트가 통과했다(desktop 로그). +- 리뷰·수정 반복이면 [improve.md](improve.md) 4.5절 멈춤 기준이 모두 참이다. +- 교훈 정리와 장부 한 줄을 끝냈다. +- 소유자 보고에 변경 / 확인(명령·결과·커밋) / 남은 문제가 있다. + +## 6. 하지 말 것 + +- 하위 세션의 일을 대신 하지 않는다. 대조에 필요한 읽기와 확인만 직접 한다. +- 보고를 그대로 믿지 않는다. 보고는 E0 증거다. +- 같은 파일을 두 세션에 맡기지 않는다. +- 하위 세션에 main 병합·main push, force push, 다른 브랜치 push를 허용하지 않는다. +- brief에 결정 번호만 쓰지 않는다. 내용을 쓴다. + +## 7. 막혔을 때 + +- 소유자만 정할 수 있는 것은 근거와 권하는 안을 붙여 소유자에게 한 번 묻는다. 그 결정에 기대는 묶음만 멈추고 나머지는 계속한다. +- 하위 세션이 묻는 질문에는 답하고, 질문 원문과 "답이 매뉴얼에 있었나"를 적어 둔다. 장부의 질문 수가 된다. + +## 8. 보고 형식 + +소유자에게는 변경 / 확인 / 남은 문제 세 칸으로 쓴다. 하위 세션 보고 양식과 대조표는 design-docs `conventions/delegation-loop.md` 5·6절이다. 소유자가 이미 아는 외부 일(PR 병합, CI runner 켜기)은 남은 문제와 섞지 않는다. + +## 9. 자주 하는 실수 + +- 영역 문서의 ID를 색인에 손으로 옮기다 빠뜨린다. 색인 검사 스크립트를 돌린다. +- 묶음을 너무 크게 만들어 마감 안에 검증 보고가 오지 않는다. 묶음 크기 상한을 지킨다. +- 하위 세션이 적은 태스크 이름을 확인하지 않고 소유자에게 옮긴다. +- 같은 범위를 두 리뷰에 따로 맡기고(비교 시험 등) ID를 매길 쪽을 정하지 않아, 같은 ID가 다른 결함을 가리킨다. brief에 ID를 매길 리뷰 하나를 정한다(규칙은 [reference/review-criteria.md](reference/review-criteria.md) 10절 「ID」). diff --git a/docs/work/docs-writing.md b/docs/work/docs-writing.md new file mode 100644 index 00000000..7d0147bd --- /dev/null +++ b/docs/work/docs-writing.md @@ -0,0 +1,86 @@ +# 문서 작성 — 매뉴얼과 안내 문서를 쓰고 고친다 + +읽은 사람이 묻지 않고 그대로 일할 수 있는 문서를 쓰는 절차다. 매뉴얼은 시험하기 전까지 초안이다. + +## 1. 언제 쓰나 + +- `docs/work/`, `docs/manual/`, 루트·leaf `CLAUDE.md`, 모듈 README, runbook, 안내 문서를 쓰거나 고칠 때. +- 이것은 아니다. + - 리뷰 문서 → [improve.md](improve.md)(리뷰 양식은 [reference/review-criteria.md](reference/review-criteria.md) 10절) + - 설계서·ADR → [research-design.md](research-design.md) + - 코드 동작이 바뀌어 문서를 따라 고치는 일 → 그 코드 변경의 playbook(같은 변경에서 고친다) + +## 2. 받아야 할 것 + +- 독자: 누가, 무엇을 하려고 읽나. 사람인가, 이력 없는 세션인가, 파생 서비스 개발자인가. +- 그 문서가 가리킬 정본: 규칙이 이미 어디에 있나. +- 위치와 분량 상한. +- 시험 방법: cold-read 시험을 누가 하나(보통 맡긴 쪽이 따로 한다). + +## 3. 크기와 사고 순서 + +- 오타·깨진 링크·한 문장 정정은 작음이다: 목적 한 줄, 대상 확인, 검증. +- 새 안내 문서나 playbook 하나는 중간이다. +- 문서 체계(매뉴얼 구성, 진입 경로)를 바꾸는 일은 큼이다. 소유자 검토가 먼저다. +- 선행 사례: 같은 독자를 둔 이 repo의 문서(`docs/manual/`, `docs/work/`)와, 그 문서를 읽고 일한 기록(보고, cold-read 시험 기록). +- 스킬: `technical-writing-best-practices`, `documentation-and-adrs`. 사람이 터미널에서 따라 하는 절차서면 `writing-practitioner-guides`. + +## 4. 절차 + +1. 독자와 목적을 한 문장으로 쓴다: "<누가> 이 문서만 읽고 <무엇을> 끝낸다". +2. 정본을 찾는다. 규칙이 이미 `AGENTS.md`, registry, leaf `CLAUDE.md`, `docs/web/http-contract.md`, `docs/registries/`에 있으면 다시 쓰지 않고 가리킨다. 정본과 다르면 정본이 맞다. +3. 위치를 정한다. 문서 위치 규칙은 `docs/README.md`다. 여러 repo나 소유자 운영에 걸친 내용은 이 repo가 아니라 design-docs에 둔다. +4. 결론을 먼저 쓴다. 한 문장에 개념 하나, 처음 나온 용어는 그 자리에서 한 줄로 푼다. 흐름이 있으면 화살표 도식을 먼저 둔다. 표는 둘 이상을 비교할 때만 쓴다. +5. 절차는 한 줄에 한 단계, 동사로 시작한다. 명령은 실제로 있는 것만 쓴다. 태스크 이름은 `src/build.gradle`이나 leaf `build.gradle`에서, 경로는 `ls`로 확인한다. +6. 지난 일을 근거로 쓸 때는 날짜, 무엇이 일어났나, 숫자를 한 줄로 쓴다. 리뷰 ID·묶음 이름·번호만 쓴 결정은 매뉴얼 본문에 쓰지 않는다. 걷어낸 ID 중 근거로 남길 것은 어느 문서에서 왔든 [evidence.md](evidence.md)에 원래 문서·문장과 함께 모은다. 걷어낸 문서 묶음(예: `docs/manual/`, 진입 문서)마다 절 하나를 두고, 같은 묶음을 다시 걷어내면 그 절에 표를 더한다. ID가 무엇을 가리키는지는 evidence.md 머리말 「표기」로 찾는다. 번호의 원래 문서가 이 repo에 없으면 그 번호가 가리키는 규칙 이름과 코드 위치를 근거로 적고, 원래 문서가 repo에 없다고 쓴다. +7. 링크: repo 안 문서는 상대 링크로 쓴다. repo 밖 문서(design-docs 등)와 `file:line`은 링크가 아니라 코드 표기로 쓴다. 링크 검사(lychee)가 따라가지 못하기 때문이다. +8. 숫자를 복제하지 않는다. leaf 개수, 테스트 수처럼 코드가 정하는 값은 쓰는 순간 낡는다. 정본을 가리킨다. +9. 그 문서를 읽는 테스트가 있는지 찾는다: `grep -rn -e '<파일 이름>' -e '<폴더 경로>' src --include=*.java`. 있으면 그 테스트가 기대하는 문장을 지키고, 그 lane을 desktop에서 돌린다([reference/gates.md](reference/gates.md) 2절). 없으면(주석만 걸리는 것도 없음이다) lane은 돌리지 않고, grep 명령과 결과를 보고에 적는다. brief가 돌릴 lane을 정했으면 그 lane을 돌린다(지도 3절: brief가 먼저다). +10. `docs/work/`, 루트 `CLAUDE.md`, `AGENTS.md`, `src/**/CLAUDE.md`를 바꿨으면 `python3 scripts/check-work-docs.py`를 돌린다. 분량 상한, 본문 이력 ID 0(앞의 넷 모두), playbook 뼈대, 상대 링크를 본다. +11. 리뷰 폴더 README를 만들거나 고쳤으면 `python3 scripts/check-review-index.py docs/reviews/<폴더>`를 돌린다. +12. 다른 문서는 같은 스크립트의 모드로 본다: 상대 링크는 `--links <파일 또는 폴더>`(PR에서는 lychee가 다시 본다), 이력 ID는 `--history <파일 또는 폴더>`. + - 이력 검사 패턴을 더하면 오탐을 시험한다. 잡아야 할 이력 문장과 잡지 말아야 할 보통 문장을 시험 파일로 만들어 `--history`로 돌린다. `docs/reviews/**` 밖 전체(`git ls-files '*.md' ':!docs/reviews'`)에도 돌려 새로 걸린 줄을 모두 읽는다. 검사 대상 파일의 오탐은 패턴을 좁혀 없애고, 대상 밖의 오탐은 보고에 적는다. + - 기본 검사를 넓히는 커밋은 그 검사가 새로 잡는 문서를 고친 커밋 뒤에 둔다(또는 같은 커밋). 그래야 어느 커밋에서도 기본 모드가 rc=0이다. +13. 매뉴얼·playbook·진입 경로를 새로 만들거나 크게 바꿨으면 cold-read 시험을 한다. 정본은 design-docs `conventions/delegation-loop.md` 10절이다. 혼자 하는 일이면 최소한 자가 점검을 한다: 지도부터 읽어 그 문서만으로 실제 일 하나의 brief를 써 보고, 막힌 곳을 고친다. + +**playbook을 새로 만들 때의 뼈대** (모든 playbook이 같은 제목을 쓴다. 검사 스크립트가 본다): + +`1. 언제 쓰나` · `2. 받아야 할 것` · `3. 크기와 사고 순서` · `4. 절차` · `5. 완료 기준` · `6. 하지 말 것` · `7. 막혔을 때` · `8. 보고 형식` · `9. 자주 하는 실수`(10줄 이하) + +## 5. 완료 기준 + +- 독자 한 문장이 있고, 문서가 그 독자의 일을 처음부터 끝까지 다룬다. +- 문서의 명령·태스크 이름·경로가 기준 커밋에 실제로 있다. +- 정본을 복사한 문장이 없다. 가리키는 줄만 있다. +- `docs/work/`·루트 `CLAUDE.md`·`AGENTS.md`·`src/**/CLAUDE.md`를 바꿨으면 `scripts/check-work-docs.py`가 rc=0이다. +- 그 문서를 읽는 document-contract lane이 있으면 rc=0이다(desktop 로그). +- 매뉴얼을 새로 만들었거나 진입 경로를 바꿨으면 cold-read 시험이나 자가 점검 결과가 보고에 있다. + +## 6. 하지 말 것 + +- 정본의 규칙을 문서에 다시 쓰지 않는다. 갈라진 복사본이 된다. +- 계획서를 나중에 고치지 않는다. 계획의 기록이 아니라 결과를 계획처럼 보이게 만든 글이 된다(`docs/README.md`). +- 리뷰 영역 문서를 리뷰 뒤에 고치지 않는다. 처리 결과는 리뷰 README에 쓴다. +- 소유자 환경 규칙(실행 위치, 세션 도구)을 여러 곳에 쓰지 않는다. [operate.md](operate.md) 「실행 위치」와 [delegate.md](delegate.md) 「소유자 환경」에만 둔다. +- 분량 상한을 넘기지 않는다. 넘으면 같은 문서에서 한 줄을 빼거나 `reference/`로 내린다. + +## 7. 막혔을 때 + +- 정본끼리 다른 말을 하면 어느 쪽이 맞는지 정하지 않는다. 두 위치와 차이를 적어 묻는다. +- 소유자 파일(전역 `~/.claude/CLAUDE.md`, 사용자 설정·스킬, design-docs)을 고쳐야 하면 승인을 받고 고친다. + +## 8. 보고 형식 + +[README](README.md) 6절에 더해 적는다. + +- 바꾼 문서와 줄 수, 분량 상한 대비. +- 검사 결과: `check-work-docs.py`, `check-review-index.py`, 링크 검사, document-contract lane의 rc와 로그 경로. +- cold-read 시험이나 자가 점검: 써 본 brief, 막힌 곳, 고친 것. +- 정본과 다른 곳을 찾았으면 그 위치. + +## 9. 자주 하는 실수 + +- 지난 리뷰 ID로 이유를 대신한다. 내용과 날짜를 쓴다. +- 저장소 밖 문서를 상대 링크로 써서 링크 검사가 실패한다. 코드 표기로 쓴다. +- 없는 태스크 이름이나 옛 경로를 쓴다. 쓰기 전에 빌드 파일과 `ls`로 확인한다. +- `--history` 결과 0을 이력이 없다는 증거로 쓴다. 검사는 아는 꼴만 잡는다. 걷어낸 뒤 `grep -n -e 리뷰 -e 라운드 -e 결정 <파일>`로 남은 괄호를 한 번 더 읽고, 못 잡은 꼴은 검사 패턴에 더한다. diff --git a/docs/work/evidence.md b/docs/work/evidence.md new file mode 100644 index 00000000..7fc6ff72 --- /dev/null +++ b/docs/work/evidence.md @@ -0,0 +1,369 @@ +# 근거와 이력 + +`docs/work/` 본문은 지난 리뷰를 모르는 사람도 읽을 수 있게 썼다. 그래서 규칙이 나온 사건과 지난 리뷰 ID는 본문에 넣지 않고 여기에 모았다. 본문을 따르는 데 이 문서는 필요 없다. 규칙의 이유를 확인하거나 규칙을 바꾸려 할 때 읽는다. + +표기: `1101/05-01`은 `docs/reviews/2026-11-01-maturity-review/`의 발견 05-01이다. `1103/RR6-01-05`는 `docs/reviews/2026-11-03-rereview/`의 발견이다. 접두어와 문서: `RR-`는 1차 재리뷰(폴더 바로 아래 `01`~`07` 영역 문서)와 round2의 `01`~`03` 영역 문서(1차 번호를 이어 썼다), `RR2-`는 round2의 `04` 영역 문서, `RR3-`~`RR7-`는 round3~round7이다. `1101` README, `1103` README는 각 폴더의 `README.md`다. 「결정 N」은 `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」의 N번이다. + +더 오래된 표기: + +- 「1라운드」·「2라운드」·「3라운드」: `1101` README 13·14·15.1절의 수정 라운드(2026-11-01~03). `r2-05a`, `r3-I`처럼 `r<라운드>-<묶음>`은 그 라운드의 수정 묶음 이름이다. `r9-a`, `r10-02`는 `1103` README 16·17절의 묶음이다. +- `P`·`W-P`: 2026-09-25 리뷰 후속 작업(`docs/reviews/2026-09-25-review-followup-status.md`)의 묶음 이름(Wave n의 묶음 N). 같은 문서는 2026-09-24 리뷰들의 발견을 `S-#`, `S-lead-`, `X-#`, `X-P-`, `G-3a`처럼 부른다. 그 행을 찾으면 내용과 처리 묶음이 있다. +- `MSG-`·`BOOT-`·`JPA-`·`MNG-`·`GQL-`·`NTF-` + 세 자리: 2026-11 전의 모듈 리뷰(`docs/reviews/2026-08-14-messaging-module-code-review.md`, `2026-09-07-app-bootstrap-module-code-review.md` 등)의 발견이다. +- `D`: 문맥에 따라 둘이다. 이 매뉴얼의 설계 결정(design-docs `delegation-loop/02-design.md` 13절, D1~D14)이거나, leaf `CLAUDE.md`가 이름을 댄 설계 기록(`feature-*-contract` 등)의 결정 번호다. 그 설계 기록들은 이 repo에 없다(10절). + +## 1. 이 매뉴얼이 나온 곳 + +- 조사와 설계: design-docs `delegation-loop/01-research.md`(1~5단계), `delegation-loop/02-design.md`(6단계, 4·5·6·7·10절). 2026-11-06 소유자가 결정 D1~D14를 모두 권하는 안대로 승인했다. +- 공통 정본: design-docs `conventions/work-thinking-order.md`(작업 사고 순서), `conventions/delegation-loop.md`(위임 루프 운영). +- 재료: 옛 개선 매뉴얼 브랜치 `claude/improvement-manual-6ae516`(커밋 `3b66358e`, `319cff91`, `06477350`, 2026-11-05). 병합하지 않고 설계 10절 표대로 옮겼다(결정 D12). +- 옛 매뉴얼을 버린 이유(2026-11-06 소유자 판정): 조사 없이 만들었다, 범위가 리뷰·수정뿐이다, 본문 159줄에 지난 리뷰 ID가 있다, 진입 분량이 717줄이다, 시험한 적이 없다. + +옛 매뉴얼에서 옮긴 곳: + +| 옛 위치 | 새 위치 | +| --- | --- | +| README 「정본 표」, 적용 범위 | `docs/work/README.md` 1·7절, 각 playbook | +| 결정 M-5(저장소 밖 문서는 코드 표기), M-6(소유자 환경 규칙은 한 절에만) | `docs-writing.md` 4절, `operate.md` 4.1절 | +| 결정 M-3(심각도 두 체계) | `reference/review-criteria.md` 3절 | +| 결정 M-4(결정 표는 색인) | `reference/decisions.md` 머리말 | +| 결정 M-7(커밋 정책은 두고 예외만) | `docs/work/README.md` 4절, `AGENTS.md` 커밋 문장 | +| 결정 M-8(개선 제안도 닫는다) | `reference/review-criteria.md` 1절 | +| 결정 M-9(분업과 "Minor도 고친다"의 저장소 안 정본) | `improve.md` 4.5절, `delegate.md` | +| 결정 M-1(위치 `docs/improvement/`), M-2(프론트와 장 번호 맞추기) | 버림. 위치는 `docs/work/`, 두 repo는 장 번호 대신 같은 playbook 파일 이름을 쓴다 | +| 01장 판정표, 0절 공통 단계, 1~6절 | `docs/work/README.md` 3절, `improve.md` | +| 02장 | `reference/review-criteria.md`(지난 예는 이 문서 5절) | +| 03장 | `reference/review-criteria.md` 9절 | +| 04장 P1~P11 | `reference/defect-patterns.md` 「막는 기준」 | +| 05장 | `reference/review-criteria.md` 7절, `improve.md` 4.2·4.3절 | +| 06장 | `reference/review-criteria.md` 8절, `reference/gates.md` 5절, 기준선은 이 문서 6절 | +| 07장 | `reference/gates.md`, `operate.md` | +| 08장 | `reference/decisions.md` | +| 09장 | `delegate.md`, `improve.md` 4.4·4.5절, design-docs `conventions/delegation-loop.md` | +| 부록 결함 패턴 | `reference/defect-patterns.md` + 이 문서 4절 | + +## 2. 규칙과 사건 + +| 규칙(본문 위치) | 사건 | 근거 | +| --- | --- | --- | +| 무거운 실행은 desktop에서, 공유 잠금으로 (`operate.md` 4.1) | 2026-11-05 하위 세션 넷이 노트북에서 Gradle을 돌려 노트북 부하가 22까지 올랐다 | `1103` README 17.1절, design-docs `delegation-loop/01-research.md` 4.2절 | +| 진입 분량 상한, 본문 이력 ID 금지 (`docs/work/README.md` 8절) | 옛 개선 매뉴얼은 진입 717줄, 이력 ID가 든 본문 159줄 | `01-research.md` 4.1절 | +| 색인은 기계로 대조한다 (`improve.md` 4.1) | 원래 리뷰 색인이 119건이었다. 06 영역 문서의 `NN-10`~`NN-14` 5건이 색인과 모든 수정 묶음에서 빠졌다. 실제는 124건 | `1101` README 12절 정정, `1103` README 1절, `1103/RR-05-10` | +| 「새로 가정하는 것」 칸, 수정 묶음 크기 상한 (`improve.md` 4.4, 8절) | round6 발견 25건 중 17건(68%)을 직전 수정 커밋이 만들었다. 짝 프론트 1106 리뷰도 25건 중 16건(64%) | `01-research.md` 4.3절, design-docs `delegation-loop/02-design.md` 4.3절 | +| 보고한 태스크가 로그에 있는지 확인 (`improve.md` 9절, `gates.md` 4절) | 묶음 보고가 없는 태스크 `:adapter:outbound:persistence-jpa:documentContractTest`를 적었다 | `1103` README 17.2절 | +| 성능 lane은 상한을 매번 단언하고, 끄는 값은 테스트 전에 실패한다 (`gates.md` 5절) | r10 desktop 게이트의 `performanceCheck`가 `-Pperformance.assertions.enabled=true` 없이 돌아, httpclient 시간 단언 없이 통과했다. 그 전에는 JPA pool lane이 같은 속성 뒤에 숨어 상한을 비교하지 않았다(`PoolLaneClaimTest`). 2026-11-06 빌드가 강제하게 바꿨다 | desktop `~/r10-logs/gates.sh`, `docs/testing/TESTING_STRATEGY.md` PERFORMANCE 문단, 커밋 `e6b6e18e` | +| 캐시에서 가져온 결과는 지금 통과한다는 증거가 아니다. 기준 상태와 시간·환경에 민감한 테스트는 `--rerun`으로 (`operate.md` 9절, `gates.md` 6절) | 2026-11-06 B3 desktop `ci` rc=0은 캐시 결과였다(태스크 701개 중 403개를 캐시에서). 그 사이 httpclient `CircuitBreakerStatusAccountingTest` 2건은 기준 커밋 `3d73b6f1`에서도 10번 중 10번 실패하고 있었다 | desktop `~/b3-logs/ci.log`, 2026-11-06 총괄 전달 | +| 묶음을 너무 크게 만들지 않는다 (`delegate.md` 4.2) | 알림·파일 서버를 한 묶음(r2-05a)으로 묶었다가 마감 안에 검증 보고가 오지 않아 합치지 못했다. 다음 라운드(r3-a)에 다시 올려 합쳤다 | `1101` README 14.3절, 16절 | +| 두 묶음이 같은 파일을 건드리지 않게 (`delegate.md` 4.2) | 2라운드 묶음 r2-06이 10개 파일 충돌로 처음부터 다시 작업했다 | `1101` README 14.1절 | +| 전 leaf import를 바꾸는 묶음은 마지막에 혼자 (`improve.md` 6절, `delegate.md` 4.2) | r3-G | `1101` README 15.1절 | +| 묶음마다 그 시점 최신 기준에서 시작 (`delegate.md` 4.2) | 3라운드가 2라운드보다 충돌이 적었다 | `1101` README 16.1절 | +| 합친 트리는 따로 검증 (`improve.md` 4.4, `gates.md` 3절) | 두 묶음의 수정이 한 트리에서 처음 만나 `BC_IMPOSSIBLE_INSTANCEOF`가 생겼다. 최종 게이트에서 드러난 2건 | `1101` README 16.1절, `1103` README 6.1절 | +| 캐시로 통과한 것은 그렇게 적는다 (`gates.md` 4절) | `ci`가 434초에서 51초로 준 것은 캐시 재사용이었다 | `1101` README 16.2절 | +| 같은 결함은 한 묶음에만 (`delegate.md` 4.2) | 같은 runbook 문장을 두 리뷰가 적어 한 번 고쳤다(`1103/RR6-01-07`, `1103/RR6-02-03`) | `1103` README 17절 | +| RED가 머신에 따라 통과하지 않게 (`improve.md` 7절) | watchdog RED 테스트가 공용 풀 병렬도 1인 머신에서 옛 코드도 통과시켰다 | `1103/RR4-03-01`, `1103` README 16절 r9-b | +| 실 vendor 결함은 실 vendor에서 RED (`improve.md` 4.2) | 새 실 PostgreSQL 테스트 3개의 수정 전 실패를 실 PostgreSQL로 확인하지 않았다 | `1101` README 14절 r2-04 | +| Agent 도구를 쓰지 않는다 (`delegate.md` 4.3) | 하위 세션 시작이 막히자 Agent 하위 에이전트로 우회했다. 지난 라운드는 사용량 한도 때문에도 하위 에이전트 없이 진행했다 | `01-research.md` 4.2절, `1101` README 16절, `1103` README 6절 | +| 예전 멈춤 기준을 거둠 (`improve.md` 4.5) | 2026-11-05 소유자 지시 "보고할 때 남은 문제가 없어야 한다". "새 Important 0이면 멈춤"(9.1절), "Minor는 기록만"(11.1절)을 거뒀다 | `1103` README 16절 | +| 종료 조건은 repo마다 (`improve.md` 4.5) | 2026-11-05 소유자 원문 "각자 유지" | 2026-11-05 총괄 세션 전달 | + +## 3. 수정 묶음 크기 (`improve.md` 4.4) + +추가 줄은 `git show --shortstat`의 insertions다(테스트·문서 포함). + +| 수정 커밋 | 고친 것 | 추가 줄 | 다음 확인 리뷰 | 그 리뷰의 발견 | +| --- | --- | --- | --- | --- | +| `01a8a2a70..5786126c`(커밋 3개) | 원래 리뷰 발견 | +60,167 | 1차 재리뷰 | Important 27, Minor 41 | +| `bbe944bd` | 1차 재리뷰 발견 + 색인에서 빠졌던 5건 | +13,479 | round2 | Important 7, Minor 22 | +| `1885bf8d` | 2차 재리뷰 결함 29건 | +5,495 | round3 | Important 0, Minor 19 | +| `f40c03c6` | Minor 19건(영역 묶음 4개) | +1,877 | round4 | Important 0, Minor 7 | +| `70fb80bf` | 소유자가 다시 정한 기본값 3가지 | +906 | round5 | Important 0, Minor 9 | +| `45d2a478` | 기록만 했던 결함 전부(영역 묶음 4개) | +5,420 | round6 | Important 2, Minor 23(17건은 이 커밋이 만듦) | +| `6e992970` | round6 결함 25건(영역 묶음 4개) | +5,143 | 아직 없음 | — | + +읽는 법: 추가 2,000줄 아래 두 번은 다음 발견이 7·9건, 5,000줄 위 네 번은 19·25·29·68건이었다. 상한(묶음 8건, 확인 리뷰당 1,500줄)은 이 표에서 정한 판단 값이다. 위임 루프 지표(라운드당 새 결함, 수정이 만든 결함 비율)로 다시 맞춘다. + +## 4. 결함 패턴의 근거 (`reference/defect-patterns.md`) + +| 패턴 | 근거 | +| --- | --- | +| A1 갈라진 복사본 | `1101/01-03`, `1101/01-07`, `1101/04-06`, `1101/05-09`, `1101/07-06`, `1101/01-11`, `1103/RR-01-14`, `1101` README 16.3절(템플릿 패키지 목록 두 곳), `1103` README 16절 r9-c(버전 정규식 사본) | +| A2 문서와 코드 불일치 | `1101/02-01`, `1101/07-11`, `1101/03-04`, `1101/06-11`, `1103/RR-01-03`, `1103/RR-01-11`, `1103/RR5-01-01`, `1103/RR6-02-05`, `1103/RR6-03-05`, `1103/RR6-04-05` | +| A3 선언과 실행이 떨어져 있다 | `1101/05-15`, `1101/03-11`, `1101/02-03`, `1101/07-06`, `1103/RR-06-01`, `1103/RR2-04-03`, `1103` README 6.1절(`redis.capability.*` 6개) | +| A4 결과 불명을 확실함으로 | `1101/05-01`, `1101/04-01`, `1101/06-01`, `1101/05-17`, `1101/05-11`, `1103/RR-02-03`, `1103/RR-01-11`, `1101` README 4절 원인 1 | +| A5 중복·경쟁을 코드 순서로 | `1101/09-02`, `1101/04-08`, `1101/04-02`, `1101/03-10`, `1101/04-13`, `1103/RR-03-01`, `1103/RR-02-04` | +| A6 주장하는 것을 보지 않는 테스트 | `1101/05-08`, `1101/02-02`, `1101/01-05`, `1103` README 14절(`CountDownLatch` 7건), `1103/RR4-03-01`, `1103/RR6-01-08`, `1103/RR6-02-02` | +| A7 거짓 통과 게이트 | `1101/08-01`, `1101/04-04`, `1101/03-12`, `1103/RR-06-02`, `1103/RR-06-03`, `1103/RR-04-05`, `1103` README 14절(테스트 SpotBugs 53개), `1103/RR3-04-02`, `1103/RR6-04-01`, r10 desktop `performanceCheck`(2절) | +| A8 로그로 새는 입력값·원인 | `1103/RR6-01-05`, `1103/RR6-01-06`, `1103` README 16절 r9-a, `1101/02-11`, `1101/01-04` | +| A9 이름만 보는 허용·거부 | `1103/RR-07-02`, `1103/RR2-04-02`, `1103/RR2-04-01`, `1101/07-14` | +| A10 글로만 있는 규칙 | `1103/RR-01-02`, `1101/04-03`, `1101/05-16` | +| A11 샘플·fixture가 운영과 다르게 조립 | `1101/07-03`, `1101/09-03`, `1101/09-08`, `1101/07-04`, `1101/01-02`, `1101/07-09` | +| A12 수정이 새 결함을 만든다 | `1103` README 1절(Important 27), 9절, `1103/RR6-01-01`(회귀), `1101` README 16.1절, `1103` README 6.1절, round6 68%(2절) | +| A13 합치는 과정의 누락 | `1101` README 12절 정정, `1101` README 14.1절(충돌 처리 목록) | +| A14 타이밍에 기댄 약속 | `1103` README 16.1절(`ClientRuntimeRegistry.close`), `1103/RR3-03-01`, `1101/05-06` | +| A15 사라지는 외부 공급원 | `1101/05-09`, `1101/08-04` | +| A16 상한 없는 자원 | `1101/03-06`, `1101/03-09`, `1101/04-10`, `1101/02-09`, `1101/04-12` | + +## 5. 리뷰 기준의 예 (`reference/review-criteria.md`) + +**결함의 모양(1절)**: 이름과 다른 동작 `1101/05-03`(`ONLY_IF_SOURCE_REVISION_NEWER`가 조건 없이 덮어씀), HARD-STOP 위반 `1101/07-08`(기본 조립 루트가 선택 capability를 앎), 갈라진 복사본 `1101/01-03`(`TenantId` 3벌)·`1101/04-06`(SQLState 표 2벌), 막지 못하는 게이트 `1101/05-08`(소유자 검사를 지워도 442개 통과)·`1101/08-01`(어떤 workflow도 돌리지 않는 strict lane 14개), 틀린 조치를 시키는 문서 `1103/RR-05-01`(DEAD 재발행 SQL을 따르면 다시 DEAD), 기본값 뒤에 숨은 위험 `1101/02-03`(JWT audience가 비면 검증을 건너뜀). + +**성격(2절)**: 구조적 위험 `1101` README 6절, 미검증 `1103` README 10.3절(CI runner가 꺼져 있다). + +**심각도(3절)**: 전체 리뷰 체계는 `1101` README 12절. High 예 `1101/05-01`, `1101/04-02`, `1101/02-03`. Medium 예 `1101/04-06`, `1101/04-05`. Low 예 `1101/07-11`. 확인 리뷰 체계는 `1103` README 2절 이후 모든 round, Important 기준은 `1103` README 11절, Minor 예는 `1103/round4/review.md`·`round6/`. "이번 커밋 / 이전부터"는 `1103/round6/04-build-logic.md` 「결론」. Minor도 고친다는 규칙은 `1103` README 16절, High·Important 재확인은 `1101` README 2절. + +**증거 수준(4절)**: 이전 결과를 쓰지 않은 예 `1101/09-performance-measurement.md` 1절, 섞인 증거 수준 표기 예 `1103/round6/03-persistence.md` RR6-03-01. + +**통제 수준(5절)**: M0 예 2026-11-01 시점 JPA 양방향 연관관계 금지(`1101/04-03`), M1 예 `@SystemInvoked`를 bean으로 등록하지 말라는 주석(`1103/RR-01-02`), M4 예 DB 유일 제약(`1101/09-02` 수정 뒤). + +**28개 관점(6절)의 지난 예**: 1 `1101/05-03` · 2 `1101/07-08`, `1101/08-05` · 3 `1101/01-07` · 4 `1101/01-01`, `1101/07-09` · 5 `1101/02-03`, `1103/RR-07-02` · 6 `1101/04-01`, `1101/06-01`, `1101/05-01` · 7 `1103/RR-05-01`, `1103` README 6.1절 · 8 `1103` README 16절 r9-a, `1101/01-04` · 9 `1101/04-06`, `1101/07-11` · 10 `1101/05-08`, `1101/02-02` · 11 `1101/09-02`, `1103/RR-02-09` · 12 `1101/04-02`, `1101/03-10` · 13 `1101/03-06`, `1101/03-09` · 14 `1101/09-01`, `1101/09-02` · 15 `1101/02-03`, `1101/07-03`, `1103/RR6-01-05` · 16 `1101/05-09`, `1101/09-09` · 17 `1101/02-01`, `1101/02-02` · 18 `1101/07-04`, `1101/06-02` · 19 `1101/05-15`, `1101/07-06` · 20 `1103/RR-01-01`, `1103/RR-01-03` · 21 `1101/08-01`, `1103/RR-06-02`, `1103` README 14절 · 22 `1101/04-13` · 23 `1101/01-03`, `1101/01-12` · 24 `1101/05-21` · 25 `1101/01-10` · 26 `1101/04-16` · 27 `1101/07-08`, `1101/05-19` · 28 `1101/03-10`, `1101/06-03`. + +**시나리오(6절)의 지난 추적**: `1101/01-core-and-feature-pattern.md` 4.1·4.2·4.4절, `1101/09-performance-measurement.md` 5.1~5.3절, `1101/05-05`·`05-06`·`05-01`, `1101/04-01`·`04-05`, `1103/RR-03-03`, `1101/06-01`, `1103/RR-03-02`, `1103/RR-02-09`·`RR-02-10`, `1101/04-02`·`03-10`, `1101/05-08`, `1101/03-01`·`02-09`, `1101/06-02`·`07-07`, `1101/08-build-ci-test.md` 4절. + +**테스트 점검표(7절)**: `1103/RR6-01-08`, `1101/02-02`, `1101/05-08`, `1103` README 14절, `1103/RR6-02-02`, `1103/RR6-01-03`, `1103` README 17절 r10-01, `1103` README 16.1절. fake 예 `1103/RR-01-04`, `1103` README 17절 r10-02(손 사본 20건 삭제, skip 17 → 0). + +**리뷰 문서 양식(10절)**: 전체 리뷰 README는 `1101` README 절 순서, 영역 문서는 `1101/01-core-and-feature-pattern.md`, 확인 리뷰 문서는 `1103/round6/*.md`, 확인 리뷰 발견 필드는 `1103/round6/03-persistence.md` RR6-03-01, 전체 리뷰 발견 필드는 `1101/08-build-ci-test.md` 08-01. + +## 6. 성능 기준선 (`improve.md` 4.3) + +잰 커밋과 함께만 쓴다. 현재 HEAD에서 다시 잰 값이 아니다. 성능 작업을 시작하면 현재 커밋에서 다시 재고 이 표와 비교한다. + +| 측정 | 값 | 커밋·출처 | +| --- | --- | --- | +| 기본 조합 bootJar / 기동 중앙값 / 빈 수 | 41.4 MB / 3.44 s / 407 | `01a8a2a70`, `1101/09-performance-measurement.md` 3.1절 | +| 샘플 bootJar / 기동 중앙값 / 빈 수 | 99.0 MB / 8.05 s / 603 | 같음 | +| 필터 체인만 지나는 요청 | 27,130 rps, p50 0.51 ms | 같은 문서 3.4절 (d) | +| 샘플 단건 조회 | 5,521 rps, p50 2.70 ms, SQL 7개 | 같은 문서 3.2·3.3절 | +| 샘플 목록 20건 | 829 rps, p50 15.54 ms, SQL 46개 | 같음(수정 전) | +| 샘플 목록 20건(수정 뒤) | SQL 46 → 6, 765 → 2,528 rps | `1101` README 14절 r2-09(묶음 보고 — E0, 다시 재지 않음) | +| 관측 기능 비용 | 처리량 약 3% | 같은 문서 3.4절 (b) | +| 가상 스레드 | 처리량 차이 없음(병목은 커넥션 10개와 DB 왕복) | 같은 문서 3.3절 | +| 설정만 바꾼 실험 | `hibernate.default_batch_fetch_size=100`만으로 목록 처리량 2.9배 | 같은 문서 3.4절 | +| 게이트 시간(desktop, 12코어·31GB) | `ci`+`verifyDependencyLocks` 5분 42초, `mainCheck` 8분 8초, `integrationCheck` 17분 10초 | `2c692554`, `1103` README 17.2절 | + +측정 스크립트(`run-app.sh`, `Load.java`, `sqlcount.sh`)는 그때 scratchpad에 두었고 repo에는 없다. 다시 재려면 `1101/09-performance-measurement.md` 「측정 명령 (다시 돌리는 법)」으로 다시 만든다. + +## 7. 리뷰 색인 대조 결과 (2026-11-06) + +`scripts/check-review-index.py`를 지난 리뷰 폴더 두 곳에 돌린 결과다(기준 커밋 `3d73b6f1`). + +| 폴더 | 명령 | 영역 문서 발견 | 색인에 있음 | 없음 | rc | +| --- | --- | --- | --- | --- | --- | +| `docs/reviews/2026-11-01-maturity-review/` | `--index-heading "12. 발견 색인"` | 124 | 124 | 0 | 0 | +| `docs/reviews/2026-11-03-rereview/` | README 전체 | 157 | 135 | 22 | 1 | + +- 2026-11-01 폴더: 지금은 모두 있다. 같은 검사를 사고 시점 커밋 `34565130`의 폴더에 돌리면 `NN-10`~`NN-14` 5건을 "자리표시자 영역"으로 잡고 rc=1로 실패한다. 이 검사가 그 사고를 막았을 것이다. +- 2026-11-03 폴더의 22건은 처리되지 않은 발견이 아니라 README가 ID로 적지 않은 발견이다. + - `RR-05-10`(색인 누락 5건 자체에 대한 발견)은 README 1절 정정과 6.1절이 내용으로 다룬다. + - `RR-07-05`(CSRF 제외 규칙의 이유)는 README 6절 r4-f 행이 내용으로 다룬다. + - 나머지 20건은 round6 Minor다(`RR6-01-02`~`06`·`08`·`09`, `RR6-02-02`·`04`·`05`, `RR6-03-02`~`05`, `RR6-04-01`~`06`). README 17절은 영역별 건수만 적었고, r10 묶음이 영역 단위로 고쳤다. +- 이 검사는 "색인에 이름이 있나"만 본다. 고쳤는지는 처리 표와 확인 리뷰가 본다. 앞으로의 리뷰 README는 모든 ID를 이름으로 적는다(`improve.md` 4.1절 7단계). + +## 8. `docs/manual/`에서 걷어낸 이력 ID (2026-11-06, 2026-11-07) + +`docs/manual/` 본문에서 리뷰 ID와 번호만 쓴 결정을 걷어냈다. 문장의 뜻은 그대로이고, 괄호 안 근거만 여기로 옮겼다. 줄 번호는 걷어내기 전 기준 커밋 `06f520e6`의 줄이다. + +| 원래 위치 | 원래 괄호 | 지금 본문 | 근거 | +| --- | --- | --- | --- | +| `docs/manual/05-idempotency.md:57` | "재리뷰 2026-11-04 RR5-01-05, 라운드6 RR6-02-05, 정본 `docs/web/http-contract.md` 2절" | 정본 가리킴만 남겼다 | `1103/RR5-01-05`(PostgreSQL 기본 모양에서는 lease 상황이 생기지 않는다, `round5/review.md`), `1103/RR6-02-05`(매뉴얼 첫 문장이 PostgreSQL 항목과 어긋났다, `round6/02-idempotency-outbound.md`) | +| `docs/manual/05-idempotency.md:78` | "라운드6 RR6-02-01" | "2026-11-05 확인 리뷰가 찾아 고쳤다" | `1103/RR6-02-01`(`LEASE_EXPIRED`로 거절당한 attempt를 다시 보내도 503만 받았다, `round6/02-idempotency-outbound.md`). 수정 커밋 `6e992970`(2026-11-05), `1103` README 17절 r10-02 | +| `docs/manual/05-idempotency.md:81` | "재리뷰 2026-11-04 RR-01-11·RR-03-11" | `IdempotencyStoreContract` 가리킴만 남겼다 | `1103/RR-01-11`(lease가 지난 실행 기록을 Redis가 넘겨받아 다시 실행했다, `round2/01-core-app-inbound.md`), `1103/RR-03-11`(replay TTL이 lease보다 짧으면 key가 lease 도중 사라졌다, `round2/03-outbound.md`). 수정 커밋 `1885bf8d`(2026-11-04) | +| `docs/manual/05-idempotency.md:84` | "RR3-03-02, 2026-11-04 소유자 결정" | "2026-11-04 소유자 결정" | `1103/RR3-03-02`(서버가 기억하는 기간 문서가 `failure-retention`을 빠뜨렸다, `round3/03-outbound.md`) | +| `docs/manual/07-authorization.md:98`, `:115` | "D4 문단", "D4 실패" | "권한 선언 검사 문단", "쓰기 유스케이스의 권한 선언 검사 실패" | D4는 인증·인가 계약 설계(`feature-authentication-authorization-contract`)의 결정 번호로, 규칙 `MUTATING_USE_CASES_DECLARE_REQUIRED_PERMISSION`을 가리킨다. 그 설계 문서는 이 repo에 없다. `ApplicationBoundaryArchitectureTest`의 주석 "D1 / D4"와 `1101/01-core-and-feature-pattern.md` 「ArchUnit D4」가 같은 번호다 | +| `docs/manual/08-testing.md:38` | "소유자 결정 5" | "2026-09-25 소유자 결정" | `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」 5번(`@DisplayName`은 한국어) | +| `docs/manual/09-outbox-events.md:78` | "재리뷰 2차 RR-02-10" | runbook 가리킴만 남겼다 | `1103/RR-02-10`(tenant scope가 바뀌는 배포의 rolling 구간에서 새 번호가 옛 버전이 쓴 번호보다 작다, `round2/02-persistence-messaging.md`) | +| `docs/manual/09-outbox-events.md:89` | "재리뷰 RR-05-03" | runbook 가리킴만 남겼다 | `1103/RR-05-03`(끝나지 않는 재시도 행을 운영자가 구분·처분할 수단이 없었다, `05-messaging.md`) | + +- `RR-01-11`·`RR-02-10`·`RR-03-11`은 2차 재리뷰(`round2/`) 문서의 발견이다. 그 문서들은 1차 번호에 이어 `RR-` 접두어를 그대로 썼다(머리말 「표기」). + +2026-11-07에 남은 19줄을 같은 방식으로 걷어냈다. 16줄은 2026-11-06 검사 패턴을 넓힌 뒤 드러난 줄이다(9절 T4-1). 3줄(아래 표에서 「손으로 찾음」)은 그 패턴도 못 잡아 `docs-writing.md` 9절대로 grep으로 찾았고, 그 꼴을 잡는 패턴 셋을 `scripts/check-work-docs.py`에 더했다. 줄 번호는 걷어내기 전 기준 커밋 `73d39212`의 줄이다. 「1라운드」는 `1101` README 13절 「조치 현황 (개선 순서 1~3)」으로, 리뷰 직후 2026-11-01에 한 첫 수정이다(같은 날 밤 13.1절 게이트, 14절 「2라운드」가 이어졌다). 영역 문서 이름은 `docs/reviews/2026-11-01-maturity-review/` 안의 파일이다. + +| 원래 위치 | 원래 괄호 | 지금 본문 | 근거 | +| --- | --- | --- | --- | +| `docs/manual/README.md:59` | "리뷰 2026-11-01 01-01·07-09" | "2026-11-01 성숙도 리뷰" | `1101/01-01`(새 기능을 어느 leaf에 두는지 세 가지 모양이 있고 고르는 기준이 없다, `01-core-and-feature-pattern.md`), `1101/07-09`(새 기능을 만들 때 따라 할 예시가 세 갈래다, `07-bootstrap-composition-config.md`) | +| `docs/manual/README.md:68`, `:70` | 제목 "1라운드 수정으로 생긴 패턴 (리뷰 README 13절)", 본문 "리뷰 뒤 1라운드" | 제목 "리뷰 뒤 첫 수정으로 생긴 패턴", 본문 "2026-11-01 성숙도 리뷰 뒤 같은 날 한 첫 수정" | `1101` README 13절. 표의 패턴 행은 13절 각 행의 수정 내용이다 | +| `docs/manual/03-placement.md:40` (손으로 찾음) | "리뷰 01 영역 5.2절" | 괄호를 지웠다. 다시 볼 조건 문장이 내용 전부다 | `01-core-and-feature-pattern.md` 5.2절 「새 기능의 배치」 표의 「7. 바뀔 조건」 | +| `docs/manual/03-placement.md:54` (손으로 찾음) | "sample P30 결정과 같다" | "`sample-portfolio`도 2026-09-29에 이 배치로 옮겼다" | P30은 2026-09-25 리뷰 후속 작업 Wave 3 라운드 4의 묶음 이름이다. 그 묶음이 `S6-#10a`(sample 패키지가 종류별·기능별로 섞였다)를 고쳐 sample application을 기능별 패키지로 옮겼다(`docs/reviews/2026-09-25-review-followup-status.md` `S6-#10a` 행, 커밋 `8bbf1bf01`, 2026-09-29). `07-bootstrap-composition-config.md` 07-09 「근거」의 "P30 결정"도 같은 것이다 | +| `docs/manual/04-persistence.md:131` | "리뷰 README 13.2, 09-02" | "2026-11-01 샘플에 포스터 제목 유일 제약을 더할 때" | `1101/09-02`(포스터 제목 중복 규칙이 동시 요청에서 깨지고 검사 쿼리가 순차 스캔이다, `09-performance-measurement.md`). 번호 선택은 `1101` README 13.2절 「09-02 마이그레이션 번호」 행 | +| `docs/manual/05-idempotency.md:88` | "리뷰 02-01 결정" | "2026-11-01 소유자 결정" | `1101/02-01`("처리 중" 409의 클라이언트 행동이 코드·문서·짝 계약에서 서로 다르다, `02-inbound-web.md`). 고른 안은 `1101` README 5절 (A), 소유자 결정은 15절 「처리 중 409」 행 "소유자 결정(11-01)" | +| `docs/manual/05-idempotency.md:93` (손으로 찾음) | "리뷰가 찾은 반복 원인 1번", "(05-01, 04-01, 06-01)" | "2026-11-01 성숙도 리뷰가 찾은 반복 원인 첫째", "알림 발송·DB 커밋·메시지 relay 세 경계" | `1101` README 4절 1번. `1101/05-01`(알림 attempt를 "시작 안 함(확정)"으로 저장한 채 provider를 부른다), `1101/04-01`(커밋 중 끊김을 재시도 가능으로 답한다), `1101/06-01`(재시도 가능한 거부를 즉시 DEAD로 보낸다) | +| `docs/manual/05-idempotency.md:104` | "리뷰 05-17" | "2026-11-01 성숙도 리뷰가 Redis 연결 수립 실패에서 찾았다" | `1101/05-17`(Redis 연결 실패를 결과 불명으로 보고하고, 시간 초과된 연결을 pool에 돌려준다, `05-outbound-capabilities.md`). README 4절 1번의 "반대 방향" | +| `docs/manual/06-errors.md:46` | "리뷰 01-04" | 괄호를 지웠다 | `1101/01-04`(`IllegalArgumentException` 하나가 입력 오류와 서버 조립 오류를 함께 뜻하고, web은 둘 다 로그 없이 400으로 바꾼다, `01-core-and-feature-pattern.md`) | +| `docs/manual/07-authorization.md:28` | "1라운드 07-03 수정" | "2026-11-01부터. 전에는 샘플이 인증 체인 자동 설정을 빼자 권한 검사도 함께 빠졌다" | `1101/07-03`(실행 중인 샘플에서 `@RequiresPermission`이 아무 일도 하지 않았다, `07-bootstrap-composition-config.md`). 수정은 `1101` README 13절 `07-03+09-03` 행 | +| `docs/manual/07-authorization.md:51` | "1라운드 02-03 수정" | "2026-11-01부터. 전에는 비어 있으면 검증을 건너뛰었다" | `1101/02-03`(JWT audience 검증이 기본으로 꺼져 있고 모든 client의 role을 합친다, `02-inbound-web.md`). 수정은 13절 `02-03+07-05` 행 | +| `docs/manual/07-authorization.md:146` | "리뷰 01-06" | 괄호를 지웠다 | `1101/01-06`(`@RequiresPermission`은 application 계약인데 검사는 web leaf가 켜 주는 AOP에만 있다, `01-core-and-feature-pattern.md`) | +| `docs/manual/08-testing.md:49` | "리뷰 01-05의 lock fake" | "2026-11-01 성숙도 리뷰가 분산 lock 포트 계약 테스트 안의 fake에서 찾았다" | `1101/01-05`(application-core 포트 절반이 fake·adapter 공유 계약 밖에 있다, `01-core-and-feature-pattern.md`). lock fake는 그 근거 칸의 `DistributedLockPortContractTest.java:46` private 클래스다 | +| `docs/manual/08-testing.md:74` | "1라운드 08-01" | "2026-11-01부터. 전에는 어떤 workflow도 돌리지 않는 strict lane이 14개 있었다" | `1101/08-01`(CI가 실행하지 않는 strict lane 14개, `08-build-ci-test.md`). 수정은 13절 `08-01+08-04+03-12` 행 | +| `docs/manual/09-outbox-events.md:38` | "리뷰 06-10" | 괄호를 지웠다 | `1101/06-10`(이벤트 payload 버전을 올리는 방법과 호환성 검사가 없다, `06-messaging.md`. 색인 누락을 정정하며 붙은 번호) | +| `docs/manual/09-outbox-events.md:64` | "리뷰 06-06" | 괄호를 지웠다 | `1101/06-06`(application EventId 문법과 platform MessageId(UUID)가 다르다, `06-messaging.md`) | +| `docs/manual/09-outbox-events.md:73` | "리뷰 06-07" | 괄호를 지웠다 | `1101/06-07`(샘플이 aggregate 순서 번호를 벽시계로 만든다, `06-messaging.md`) | +| `docs/manual/09-outbox-events.md:86` | "1라운드 06-01·06-03" | "2026-11-01부터. 전에는 broker가 몇 분만 멈춰도 행이 대량으로 DEAD가 됐다" | `1101/06-01`(다시 시도하면 될 거부를 relay가 즉시 DEAD로 보낸다), `1101/06-03`(broker가 몇 분만 멈춰도 행이 대량으로 DEAD가 된다), 둘 다 `06-messaging.md`. 수정은 13절 `06-01+06-03` 행 | + +- 더한 패턴 셋: 앞말 없이 나열한 발견 번호(`05-01, 04-01`, `01-01·07-09`), 리뷰 영역 번호(`리뷰 01 영역`, `01 영역 5.2절`), 리뷰 후속 묶음 번호(`P30`, `W3-P30`. P50 이상은 백분위수라 잡지 않는다). 홀로 선 `NN-NN` 하나는 보통 범위나 장 번호일 수 있어 여전히 잡지 않는다. + +## 9. cold-read 시험 1회차 빈틈 처리 (2026-11-06~07) + +2026-11-06 이력 없는 세션 6개에 이 매뉴얼만 주고 실제 일을 시켰다(기준선 1개는 옛 매뉴얼). 6개 모두 일은 끝냈지만 매뉴얼에서 답을 못 찾은 곳이 1~9건씩 나와 모두 불합격이었다. 아래는 시험 기록(design-docs `delegation-loop/trials/2026-11-06-*.md`)의 「질문」·「위반」 표와 각 세션 공유 노트(`~/.config/Claude/side-session-notes/local_fcd89c34-c754-4c5b-a38f-fa322834286f/`)의 「매뉴얼에서 답을 못 찾은 곳」을 한 줄씩 처리한 결과다. 기준 커밋 `2c8a359d`. 2026-11-07 운영 playbook 시험(T6, `trials/2026-11-07-integration-gates.md`, 1회차 수정 전 매뉴얼로 돌림)의 빈틈 6건을 T6 행으로 더했다. + +- 세션: T1 `c-t1-r10-review`(확인 리뷰), B `c-t1-baseline`(같은 리뷰를 옛 매뉴얼로, 기준선), T2 `c-t2-circuit-breaker`(결함 수정), T3 `c-t3-error-codes`(조사·설계 → 구현), T4 `c-t4-manual-ids`(문서), T5 `c-t5-idempotency-opid`(결함 수정), T6 `c-t6-integration-gates`(합친 브랜치 전체 게이트). +- 출처 칸: `기록 N`은 시험 기록 「질문」 표의 N번, `노트 N`은 공유 노트의 N번이다. T3 노트는 1단계 `1-N`, 2단계 `2-N`이다. +- 처리 칸: 고침(고친 곳) / 고치지 않음(이유) / 소유자 결정 필요. 기준선(B)은 새 매뉴얼에도 해당하는 것만 고쳤다. + +| # | 출처 | 빈틈 | 처리 | +| --- | --- | --- | --- | +| T1-1 | 기록 1, 노트 1 | 상한을 넘어 나눈 확인 리뷰를 한 세션이 차례로 해도 되나 | 고침 — `improve.md` 4.4절: 나누는 것은 맡긴 쪽, brief 하나로 받으면 차례로, 단위마다 문서 하나 | +| T1-2 | 노트 2 | 영역 pathspec이 파일 단위로 안 갈림, 수정 커밋 안의 리뷰 기록을 상한에서 빼나 | 고침 — `improve.md` 4.4절: 리뷰 기록 `docs/reviews/**` 제외, 테스트 파일은 지키는 코드의 영역 | +| T1-3 | 기록 2, 노트 3 | 수정 보고에 「새로 가정하는 것」 칸이 없을 때 | 고침 — `improve.md` 4.1절 2단계: 커밋 본문 「위험·한계」와 처리 표 「결정」에서 뽑고 뽑은 곳을 적는다 | +| T1-4 | 기록 3, 노트 4 | 지난 라운드 색인 누락으로 색인 검사가 처음부터 rc=1 | 고침 — `improve.md` 4.1절 8단계: 이번 색인 절에 「색인 보완」 한 줄 | +| T1-5 | 기록 4, 노트 5 | 리뷰 README를 누가 쓰나: `delegate.md`(총괄)와 `improve.md`(리뷰어)가 다름 — **모순** | 고침 — `improve.md` 4.1절 7단계, `delegate.md` 4.2절 표, `reference/decisions.md` 2.1 「리뷰 README 분담」: 리뷰어는 자기 라운드 색인 절 하나, 나머지는 총괄 | +| T1-6 | 기록 5, 노트 6 | 지난 라운드 영역을 나눌 때 영역 번호 | 고침 — `reference/review-criteria.md` 10절 「ID」: 그 라운드 영역 표의 순번, 나누면 뒤에 새 번호, 「범위」에 대응 | +| T1-7 | 기록 6, 노트 7 | 클래스 이름으로 고르는 strict lane에서 탐침 돌리기 | 고침 — `improve.md` 9절(자주 하는 실수): 기존 클래스에 메서드로, `-Werror` 주의 | +| T1-8 | 기록 7, 노트 8 | `--rerun`이 바로 앞 태스크에만 걸림 | 고침 — `operate.md` 9절, `reference/gates.md` 6절: 태스크마다 붙인다 | +| T1-9 | 노트 9 | 지난 라운드 Declined 30건이 닫힌 기록 없음, 확인 리뷰어가 다시 판정하나 | 고침 — `improve.md` 4.1절 9단계(brief가 맡겼을 때만), `delegate.md` 4.1절(확인 리뷰 brief에 적는다) | +| T1-10 | 기록 8, 노트 10 | 같은 범위를 두 리뷰가 같은 라운드 ID로 씀 | 고침 — `reference/review-criteria.md` 10절 「ID」(정본 리뷰 하나, 다른 쪽은 새 ID와 대응표), `delegate.md` 9절 | +| T1-11 | 기록 9, 노트 11 | 다른 브랜치 병합을 기다리는 Declined는 닫힌 것인가 | 고침 — `improve.md` 4.5절 2: 합친 트리에서 확인할 때까지 열림 | +| B-1 | 기록 1, 노트 1 | 한 리뷰어가 모든 영역을 볼 때 문서 모양 | 고침 — `reference/review-criteria.md` 10절 「위치」: `roundN/NN-<영역>.md`, 영역마다 하나 | +| B-2 | 기록 2, 노트 2 | 리뷰어가 리뷰 README에 쓰나 | 고침 — T1-5와 같은 곳 | +| B-3 | 기록 3, 노트 3 | strict lane 탐침, 탐침에도 `-Werror` | 고침 — T1-7과 같은 곳 | +| B-4 | 기록 4, 노트 4 | 확인 리뷰에 넣을 「이전부터」 결함의 경계 | 고침 — `improve.md` 4.1절 3단계: 읽은 주변 코드에서 본 것은 적고, 그 밖을 찾아 나서지 않는다 | +| B-5 | 기록 5, 노트 5 | 앞 라운드 Declined가 닫히지 않은 채 시작 | 고침 — T1-9와 같은 곳 | +| B-6 | 기록 6, 노트 6 | 리뷰 스킬은 하위 에이전트를 쓰라 하고 매뉴얼은 금지 — 모순 | 고치지 않음 — 새 매뉴얼에 답이 있다: `improve.md` 3절 끝 줄, `delegate.md` 4.3절. 새 매뉴얼로 같은 리뷰를 한 T1은 묻지 않았다 | +| B-7 | 기록 7, 노트 7 | 리뷰 기록 문서도 document-contract lane 대상인가 | 고침 — `reference/gates.md` 2절, `docs-writing.md` 4절 9단계: 읽는 테스트를 파일·폴더로 찾고, 없으면 돌리지 않고 grep 결과를 적는다 | +| T2-1 | 기록 1 | push한 커밋은 못 고치고 desktop은 push된 것만 받는다. 커밋 본문에 desktop 결과를 넣으려면 | 고침 — `operate.md` 2절·4.1절 「push 전에 검증하기」(패치와 트리 해시)·9절, design-docs `conventions/delegation-loop.md` 11절 「실행 위치」 | +| T3-1 | 기록 1, 노트 1-1 | 「파일 하나여도 큼」 표면에 대한 설계 메모만 쓰는 일의 크기 | 고침 — design-docs `conventions/work-thinking-order.md` 2.1절, `research-design.md` 3절, 스킬 `research-first` | +| T3-2 | 기록 5, 노트 1-2 | push 허용: `docs/work/README.md` 4절·`decisions.md`는 "커밋·push", 정본 11절은 "push는 소유자" — **모순** | 고침 — 커밋과 push를 brief 7절이 따로 허용한다: `docs/work/README.md` 4절, `reference/decisions.md` 2.1, `delegate.md` 2·4.1·6절, 루트 `CLAUDE.md` 5절, design-docs `conventions/delegation-loop.md` 2·3·4.1·11절, 스킬 `delegate` | +| T3-3 | 기록 2, 노트 1-3 | 탐침을 생략해도 되는 기준 | 고침 — `research-design.md` 4절 3단계 | +| T3-4 | 기록 3, 노트 1-4 | 파생 서비스 영향을 어떻게 확인하나 | 고침 — `research-design.md` 4절 5단계, design-docs `conventions/delegation-loop.md` 11절 「세션」(파생 서비스 위치) | +| T3-5 | 기록 4, 노트 1-5 | 조사·설계에서 범위 밖 결함을 어디에 적나 | 고침 — `docs/work/README.md` 6절: 모든 보고에 「범위 밖에서 본 것」 | +| T3-6 | 기록 4, 노트 1-6 | 하위 세션이 Slack 브리핑을 하나 | 고침 — design-docs `conventions/delegation-loop.md` 4.1절 7절 칸·11절 「보고」, `reference/decisions.md` 2.1 「하위 세션 보고」: 전역 규칙 그대로, brief가 "Slack 말고"면 안 보냄 | +| T3-7 | 기록 4, 노트 2-1 | push 전에 RED를 보려면 desktop에 무엇을 보내나 | 고침 — `operate.md` 4.1절 「push 전에 검증하기」 RED 줄 | +| T3-8 | 기록 4, 노트 2-2 | 커밋 본문 「검증」 칸과 push 순서 | 고침 — T2-1과 같은 곳 | +| T3-9 | 기록 4, 노트 2-3 | `git add -p` 없이 한 파일을 두 커밋으로 나눠 stage | 고침 — design-docs `conventions/delegation-loop.md` 11절 「커밋과 병합」(패치 hunk를 지우고 `git apply --cached`) | +| T4-1 | 기록 1, 노트 「스크립트가 못 잡는 이력 ID」 | `--history`가 "리뷰 NN-NN"·"N라운드 NN-NN"을 못 잡아 0이 나와도 16줄 남음 | 고침 — `scripts/check-work-docs.py` 패턴 셋, `docs-writing.md` 9절. 새로 드러난 `docs/manual/` 16줄은 고치지 않음 — 이번 범위 밖, 2회차 시험 과제 | +| T4-2 | 기록 2 | 바꾼 문서를 읽는 테스트가 없을 때 무엇을 돌리나 | 고침 — B-7과 같은 곳 | +| T4-3 | 기록 3 | 이 문서 머리말의 ID 표기가 실제(2차 재리뷰도 `RR-`)와 다름 — **모순** | 고침 — 이 문서 머리말 「표기」(접두어별 문서), 8절 끝 줄 | +| T4-4 | 기록 4 | 원래 문서가 repo에 없는 결정 번호 | 고침 — `docs-writing.md` 4절 6단계 | +| T4-5 | 기록 5 | 하위 세션이 Slack 브리핑을 하나 | 고침 — T3-6과 같은 곳 | +| T5-1 | 기록 1 | 설계서 둘과 포트 Javadoc이 서로 다를 때 무엇을 따르나 | 고침 — `improve.md` 7절: 결정이 없으면 고르지 않고 양쪽 근거로 묻는다 | +| T5-2 | 기록 2 | 소유자 지시로 생긴 큰 변경도 따로 멈춰야 하나 | 고침 — design-docs `conventions/work-thinking-order.md` 2.3절, 스킬 `research-first` | +| T5-V | 기록 「위반」 1 | 총괄 보고를 영어로 씀 | 고침 — `docs/work/README.md` 6절, design-docs `conventions/delegation-loop.md` 5·11절. 훅으로는 막지 않는다(보고 문장은 도구 호출이 아니라 훅이 볼 수 없다) | +| T6-1 | 기록 1, 노트 1 | `reference/gates.md` 3절 묶음에 경로 필터 PR lane과 main job(configuration-cache, compose smoke, http3, notification)이 없어 "workflow와 같은 명령"이 성립하지 않음 | 고침 — `reference/gates.md` 3절 (가) 늘 도는 것(main job·optional 빌드·태그 단계 명령 더함) | +| T6-2 | 기록 2, 노트 2 | 합친 트리가 어떤 경로 필터 lane을 켜는지 정하는 절차, "바뀐 영역의 lane"의 정의 | 고침 — `reference/gates.md` 3절 (나): `git diff --name-only`를 `on.pull_request.paths`(glob)와 `pr-adapters.yml` `emit` 줄(정규식)에 맞춘다 | +| T6-3 | 기록 3, 노트 3 | 집계 태스크 전체가 실제로 돌았음을 보이는 법(`--rerun`은 앞 태스크 하나만) | 고침 — `reference/gates.md` 3절 「실제로 돌았음을 보이기」(새 worktree, `--no-build-cache`, FROM-CACHE 0)·6절, `operate.md` 9절 | +| T6-4 | 기록 4, 노트 4 | lychee 대체 명령이 lychee 범위보다 좁음, buf·dependency review 대체 안내 없음 | 고침 — `reference/gates.md` 2절 링크 검사(lychee와 같은 glob을 `git ls-files`로), 3절 (다) 로컬 도구가 없는 job 표 | +| T6-5 | 기록 5, 노트 5 | compose bind mount가 `tmp/heap-dumps`를 root 소유로 만들어 `git worktree remove`가 실패 | 고침 — `operate.md` 4.1절(compose `down` 뒤 컨테이너로 폴더를 지운다) | +| T6-6 | 기록 6, 노트 6 | `reference/gates.md` 4절 기록 형식이 "게이트 하나 = Gradle 명령 하나"를 가정 | 고침 — `reference/gates.md` 4절(한 줄 = 명령 하나, 여러 명령 job은 순번, 「실제 실행」 칸) | + +- 기준선과 새 매뉴얼의 리뷰 발견은 8건 중 1건만 겹쳤다. 이를 근거로 확인 리뷰를 독립 리뷰어 둘로 할지 소유자에게 물었고, 2026-11-07 소유자가 세 경우에만 둘로 하는 안을 골랐다(소유자 원문 "(c)로 받기"). 넣은 곳: `improve.md` 4.1절 「독립 리뷰어 둘」·4.5절 1, `delegate.md` 4.1·4.3절, `reference/review-criteria.md` 10절 「ID」, `reference/decisions.md` 2.1, design-docs `conventions/delegation-loop.md` 3절 5·9절 M11, `delegation-loop/metrics.md`. +- 「자주 하는 실수」에 넣은 줄: `improve.md`(strict lane 탐침), `operate.md`(`--rerun` 범위를 기존 줄에 더함, push 뒤 검증), `docs-writing.md`(`--history` 0을 믿음), `delegate.md`(두 리뷰의 ID). + +## 10. 진입 문서에서 걷어낸 이력 ID (2026-11-07) + +2026-11-07 소유자가 이력 ID 0 규칙을 진입 문서로 넓혔다: `AGENTS.md`와 `src/**/CLAUDE.md`다(`1103` README 19.4절 ③의 (b)). 모듈 README·설계 문서·`docs/reviews/**`는 넓히지 않는다. 새 세션이 처음 읽는 규칙 문서에서만 ID가 이해를 막고, 나머지는 같은 repo의 리뷰 문서로 따라갈 수 있어서다. `scripts/check-work-docs.py` 기본 모드가 이제 이 문서들을 본다. + +걷어낸 줄은 87줄이다. 넓힌 범위에서 옛 패턴이 74줄을 잡았고, 그중 2줄은 날짜로 쓴 소유자 결정을 잘못 잡은 것이었다. 새 패턴과 줄바꿈 검사가 15줄을 더 잡았다. 줄 번호는 기준 커밋 `83948d58`의 줄이다. `feature-*-contract` 같은 설계 기록은 이 repo에 없다(`git ls-files`로 0건). 그래서 그 번호의 근거 칸은 가리키는 규칙과 코드 위치를 적는다. + +| 원래 위치 | 원래 괄호 | 지금 본문 | 근거 | +| --- | --- | --- | --- | +| `AGENTS.md:83`, `:202` | "소유자 결정 4", "소유자 결정 5" | "2026-09-25 소유자 결정" | 결정 4(`verifyEnvKeys`는 app-bootstrap 태스크, 구현은 build-logic `ca.config-contract`), 결정 5(`@DisplayName`은 한국어). 결정 색인 2.7·2.1 | +| `AGENTS.md:267`, `src/adapter/outbound/cache-redis/CLAUDE.md:197`~`198` | "리뷰 05-18", "review finding 05-18" | "2026-11-03 정함", "decided 2026-11-03" | `1101/05-18`(설정 prefix·바인딩 방식이 capability 기준 4와 다르다, `05-outbound-capabilities.md`). 결정은 `1101` README 15절(2026-11-03, 위임), 결정 색인 2.6 「Redis prefix 예외」 | +| `src/adapter/inbound/graphql/CLAUDE.md:76`, `:130` | "owner decision 25", "소유자 결정 25" | "owner decision 2026-09-25", "2026-09-25 소유자 결정" | 결정 25(GraphQL DataLoader 키 실패는 등록된 `ApiErrorCode`만 노출). 결정 색인 2.3 | +| `src/adapter/inbound/graphql/CLAUDE.md:104` | "servlet 단일 스택(D4)" | 괄호를 지웠다 | D4는 servlet 단일 스택 결정의 번호다. 결정 9 행의 "D4를 outbound에도 적용"이 같은 번호다(`2026-09-25-review-followup-status.md` 「소유자 결정」). D4를 적은 원래 설계 기록은 이 repo에 없다 | +| `src/adapter/inbound/web/CLAUDE.md:45`~`46`(줄바꿈으로 갈림), `src/adapter/outbound/support/CLAUDE.md:30` | "review 2026-11-01 07-10" | "since 2026-11-01" | `1101/07-10`(설정 오타·죽은 키가 기동에서도 게이트에서도 안 잡히는 곳이 있다, `07-bootstrap-composition-config.md`). 그 수정이 `app.security`를 `StrictSettingsBinder`로 묶었다 | +| `src/adapter/inbound/web/CLAUDE.md:136`, `:143`, `:154`, `:161`, `:163`, `:164` | "D2", "D3", "D3 / SBMS-C3", "D5", "D6", "D7" | 괄호를 지웠다. S1~S5는 이 문서의 항목 이름이라 남겼다 | 설계 기록 `feature-schema-serialization-contract`(이 repo에 없음)의 결정 번호. 규칙은 각 항목 본문, `JacksonSerializationPolicyTest`, ArchUnit `no_bigdecimal_double_constructor`가 가진다 | +| `src/adapter/inbound/web/CLAUDE.md:191` | "C3 / C7 / D9" | "C3 / C7" | 설계 기록 `feature-business-rule-validation-contract`(이 repo에 없음)의 결정 번호. 규칙은 `BusinessRuleValidationContractTest`와 누출 테스트 | +| `src/adapter/outbound/persistence-jpa/CLAUDE.md:222` | "persistence-multi-db-extensibility D3" | 괄호를 지웠다 | 설계 기록 `persistence-multi-db-extensibility`(이 repo에 없음)의 결정 번호. 규칙은 같은 문장의 ArchUnit `PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL`·`PERSISTENCE_RDBMS_STAYS_NEUTRAL_OF_H2` | +| `src/adapter/outbound/persistence-jpa/CLAUDE.md:239` | "review 09-05" | 괄호를 지웠다. 이유는 같은 문단 끝 문장(시작마다 `SHOW TRANSACTION ISOLATION LEVEL` 왕복)이 적는다 | `1101/09-05`(트랜잭션마다 `SHOW TRANSACTION ISOLATION LEVEL` 왕복 1회, `09-performance-measurement.md`) | +| `src/adapter/outbound/persistence-jpa/CLAUDE.md:246` | "review 04-10" | "since 2026-11-01" | `1101/04-10`(기본 쓰기·읽기 트랜잭션에 시간 제한이 없다, `04-persistence.md`) | +| `src/adapter/outbound/persistence-jpa/CLAUDE.md:251` | "review RR-03-03" | 지웠다 | `1103/RR-03-03`(JPA 경로에서 트랜잭션 마감 초과가 분류되지 않고 500이 된다, `03-persistence.md`) | +| `src/adapter/outbound/persistence-jpa/CLAUDE.md:265`, `:277`, `:367` | "D12 of …", "… D1", "D9 of …" | 설계 기록 이름만 남겼다 | `feature-application-port-usecase-contract`의 D12(`inNew` 풀 크기 제약), `feature-persistence-failure-baseline`의 D1(영속성 실패 번역 계약), `feature-architecture-enforcement-rules`의 D9(MapStruct 생성 mapper 예외). 셋 다 이 repo에 없다 | +| `src/adapter/outbound/persistence-jpa/CLAUDE.md:309` | "review 04-06" | "before 2026-11-01 a hand-kept second table had already drifted" | `1101/04-06`(SQLState 분류표가 두 벌이고 이미 갈라졌다, `04-persistence.md`) | +| `src/adapter/outbound/persistence-jpa/CLAUDE.md:318` | "review 04-05" | 지웠다 | `1101/04-05`(`@Version` 충돌이 변환되지 않고 500 INTERNAL_ERROR로 나간다, `04-persistence.md`) | +| `src/adapter/outbound/persistence-jpa/CLAUDE.md:340`, `:341`, `:343`, `:348`, `:349`, `:357`, `:361` | "D3", "D2", "D6", "D1", "D4", "D5" | 지웠다 | 설계 기록 `feature-persistence-auditing-contract`(같은 문서 「Persistence auditing contract」 절 제목이 이름을 댄다, 이 repo에 없음)의 결정 번호. 규칙은 `AuditableEntity`와 ArchUnit `domain_is_pure`가 가진다 | +| `src/application-core/CLAUDE.md:40`, `:42`, `:44`, `:242`, `:250`, `:332` | "D3", "ArchUnit D11", "per D12", "(D11)", "(D12)" | D11 하나는 ArchUnit 규칙 이름 `application_does_not_depend_on_application_context`로 바꿨다. 나머지는 지웠다 | 설계 기록 `feature-application-port-usecase-contract`(이 repo에 없음)의 결정 번호: D3 `TransactionPort`, D11 콜백 시그니처와 `ApplicationContext` 금지, D12 `inNew` 풀 크기(문자열 키 bean 조회의 정적 분석 사각지대 문장도 같은 번호를 썼다) | +| `src/application-core/CLAUDE.md:174` | "review 2026-11-01 01-10 (b)" | "weighed in the 2026-11-01 maturity review" | `1101/01-10`(application-core 한 이름공간에 커널·플랫폼 기능·업무 기능이 섞인다, `01-core-and-feature-pattern.md`)의 대안 (b) | +| `src/application-core/CLAUDE.md:288`, `:290` | "re-review RR5-01-02·03", "re-review 2026-11-04 RR-01-11, RR-03-11, RR3-03-04" | 앞은 "owner decision 2026-11-04"만 남겼다. 뒤 줄은 지웠다 | `1103/RR5-01-02`(`renew`·`inspect` 결과 값의 뜻이 하나씩 늘었다)·`RR5-01-03`(포트 javadoc의 "주인의 마지막 보고를 기록이 갖는다"가 동작과 다르다), `round5/review.md`. `1103/RR-01-11`(lease가 지나면 Redis 저장소가 작업을 다시 돌린다, `round2/01-core-app-inbound.md`), `1103/RR-03-11`(replay TTL이 lease보다 짧으면 key가 lease 도중 사라진다, `round2/03-outbound.md`), `1103/RR3-03-04`(watchdog·계약으로 바뀐 뒤 옛 표현이 남은 문서, `round3/03-outbound.md`) | +| `src/application-core/CLAUDE.md:293`, `:297` | "owner decision 2026-11-06" | 그대로 | 걷어낼 ID가 아니다. 옛 패턴 `owner decision \d+`가 날짜를 번호로 잡은 오탐이라 패턴을 고쳤다(아래) | +| `src/application-core/CLAUDE.md:311`, `:317`, `:319`, `:322`, `:326`, `:336` | "D1", "D3", "D4", "D5", "D2", "query-bypass D1" | 항목 이름만 남겼다(Purity guardrail, Strict ceremony, Transaction, Capability) | 설계 기록 `feature-application-query-bypass-contract`(같은 문서 「Read / query path」 절 제목, 이 repo에 없음)의 결정 번호. D1은 ArchUnit `query_ports_do_not_leak_domain_jpa_or_web_types`가 지킨다 | +| `src/adapter/outbound/cache-redis/CLAUDE.md:137`, `:138`, `src/adapter/outbound/httpclient/CLAUDE.md:93` | "review 2026-11-01 05-16", "review 2026-11-03 RR-04-05" | "since 2026-11-01", "until 2026-11-03", httpclient는 지웠다 | `1101/05-16`(capability 완료 기준 5가 영역 전체에서 지켜지지 않는다, `05-outbound-capabilities.md`), `1103/RR-04-05`(Redis 멱등성 계약의 실서버 실행이 어느 게이트에도 없다, `04-outbound-capabilities.md`) | +| `src/adapter/outbound/cache-redis/CLAUDE.md:186`~`187`(줄바꿈으로 갈림) | "review 2026-11-03 README §4, RR-04-02" | "decided 2026-11-03" | `1103/RR-04-02`(캐시 조건부 쓰기가 멱등성·rate-limit·lease와 SCRIPT lane을 나눠 쓴다, `04-outbound-capabilities.md`). 결정은 `1103` README 4절(위임), 결정 색인 2.4 「Redis 연결 예산」 | +| `src/adapter/outbound/cache-redis/CLAUDE.md:190` | "RR-04-10" | 지웠다 | `1103/RR-04-10`(`DEGRADED` 정렬 순서를 상태를 내지 않는 leaf가 싣는다, `04-outbound-capabilities.md`) | +| `src/adapter/outbound/httpclient/CLAUDE.md:27` | "decision 9 (2026-09-25)" | "the 2026-09-25 owner decision" | 결정 9(httpclient reactive 스택 삭제). 결정 색인 2.7 | +| `src/adapter/outbound/identifier/CLAUDE.md:22` | "review 2026-11-01 06-06" | 지웠다 | `1101/06-06`(application EventId 문법과 platform MessageId(UUID)가 다르다, `06-messaging.md`) | +| `src/adapter/outbound/identifier/CLAUDE.md:24` | "README, review 05-21" | "README" | `1101/05-21`(identifier leaf: 이름·문서가 내용과 맞지 않는다, `05-outbound-capabilities.md`) | +| `src/adapter/outbound/identifier/CLAUDE.md:32`, `src/adapter/outbound/persistence-mongo/CLAUDE.md:53`~`54`(줄바꿈), `src/messaging/CLAUDE.md:33`, `src/grpc/CLAUDE.md:44`, `src/grpc-advanced/CLAUDE.md:21`, `src/shared-contract/CLAUDE.md:34` | "review 2026-11-01 01-11"(shared-contract는 "…, decision in the review README §15") | 지웠다. shared-contract는 "decided 2026-11-03" | `1101/01-11`(공용 다이제스트 헬퍼가 있는데 복사본이 남아 있고, 일부 leaf는 registry 때문에 복사가 강제된다, `01-core-and-feature-pattern.md`). 결정은 `1101` README 15절(2026-11-03, 위임), 결정 색인 2.2 「edge 없는 복사본」 | +| `src/adapter/outbound/messaging/CLAUDE.md:42` | "owner decision 29" | "owner decision 2026-09-25" | 결정 29(messaging 카드 검증기의 YAML 라이브러리는 테스트에서만). 결정 색인 2.6 | +| `src/adapter/outbound/persistence-fileserver/CLAUDE.md:15`, `src/adapter/outbound/persistence-notification/CLAUDE.md:9` | "review 04-16" | 지웠다 | `1101/04-16`(notification·fileserver leaf에 가까운 안내 문서가 없고 패키지가 평평하다, `04-persistence.md`) | +| `src/adapter/outbound/persistence-fileserver/CLAUDE.md:26` | "review 04-17" | 지웠다 | `1101/04-17`(미리 정한 UUID + primitive `long` version이라 `save()`가 merge로 동작한다, `04-persistence.md`) | +| `src/adapter/outbound/persistence-fileserver/CLAUDE.md:58`~`59` | "added in review 2026-11-03 RR-01-04" | "added on 2026-11-03" | `1103/RR-01-04`(application-fileserver 저장 포트 9개 중 7개는 공유 계약이 없다, `01-core-application.md`) | +| `src/adapter/outbound/persistence-fileserver/CLAUDE.md:64` | "review 04-04" | 지웠다 | `1101/04-04`(실 PostgreSQL lane 9개가 어떤 게이트·workflow에서도 돌지 않는다, `04-persistence.md`) | +| `src/adapter/outbound/persistence-notification/CLAUDE.md:20` | "review RR-03-09" | 지웠다 | `1103/RR-03-09`(notification 엔티티의 변경 메서드가 public이 됐다, `03-persistence.md`) | +| `src/adapter/outbound/persistence-notification/CLAUDE.md:40` | "owner decision 33" | "owner decision 2026-09-25" | 결정 33(caller 트랜잭션 guard: `persistence-jpa` edge, `CallerTransaction` 하나). 결정 색인 2.2 | +| `src/adapter/outbound/support/CLAUDE.md:32` | "review 15절, r3-I" | "decided 2026-11-03" | `1101` README 15절(2026-11-03) 「선택 숫자 설정의 빈 env 값 (r3-I 발견)」 행. r3-I는 3라운드 수정 묶음이다. 결정 색인 2.6 「빈 env 값」 | +| `src/app-bootstrap/CLAUDE.md:49` | "BOOT-006 / BOOT-007" | 리뷰 문서 경로만 남겼다 | `docs/reviews/2026-09-07-app-bootstrap-module-code-review.md`의 BOOT-006(패키지 분류가 두 축으로 섞이고 `Settings` 배치 규칙이 없다), BOOT-007(같은 분해 문제를 두 방식으로 푼다) | +| `src/messaging/CLAUDE.md:29` | "S7-#5b" | "2026-09-25 리뷰 후속 작업에서 나눴다" | `2026-09-25-review-followup-status.md` S7-#5b 행(한 leaf가 relay 로직·PG repository·admin journal을 함께 가졌다, W3-P18에서 완료) | +| `src/messaging/CLAUDE.md:38`, `src/grpc/CLAUDE.md:50`, `src/grpc-advanced/CLAUDE.md:25`, `src/shared-contract/CLAUDE.md:31`~`32` | "MSG-023 §6.2", "MSG-023" | "2026-08-14 messaging 모듈 리뷰 뒤 소유자가 정한 배치" 등 | `docs/reviews/2026-08-14-messaging-module-code-review.md` MSG-023(module 이름·폴더 구조와 canonical 정책 문서가 실제 구조를 설명하지 못한다). vendored 플랫폼은 Clean Architecture 계층이 아니라는 결정은 `1101/06-messaging.md` 머리의 "소유자 결정 유지" 줄 | +| `src/messaging/CLAUDE.md:43` | "review 2026-11-01 06-01" | 지웠다 | `1101/06-01`(다시 시도하면 될 거부를 relay가 즉시 DEAD로 보낸다, `06-messaging.md`) | +| `src/messaging/CLAUDE.md:66` | "재리뷰 2026-11-03 RR-05-07" | "2026-11-03" | `1103/RR-05-07`(vendored 제품 안에 두 재시도 규칙이 생겼고 고른 이유가 제품 쪽에 없다, `05-messaging.md`) | +| `src/messaging/CLAUDE.md:98`, `:113`, `src/grpc/CLAUDE.md:98` | "MSG-015", "MSG-015 cutover는 끝났다(2026-09-28, 소유자 결정 7)", "MSG-015(bridge 부재)" | "cutover 완료", "application bridge cutover는 2026-09-28에 끝났다(2026-09-25 소유자 결정)", "bridge 부재(2026-08-14 messaging 모듈 리뷰)" | MSG-015(기존 application/runtime과 신규 platform 사이에 semantic bridge와 cutover 권한이 없다, 같은 messaging 리뷰). 결정 7(outbox append를 canonical `OutboxAppendPort`로 통일) | +| `src/messaging/CLAUDE.md:140` | "MSG-022" | 지웠다 | MSG-022(experimental adapter가 class 이름 문자열로 오류를 추측한다, 같은 messaging 리뷰) | +| `src/grpc/CLAUDE.md:167`, `:169` | "03-11 (b)", "The review", "re-review 2026-11-03, RR-02-07" | "option (b)", "The 2026-11-01 maturity review", "(b) was chosen on 2026-11-03" | `1101/03-11`(`app.grpc.platform.operation-ledger-enabled`가 검증만 통과시키고 key를 처리하는 코드가 없다, `03-inbound-realtime-graphql-grpc.md`)의 대안 (a)·(b), `1103/RR-02-07`(같은 문제를 다시 본 발견, `02-inbound-transports.md`). 고른 안은 ADR-GRPC-004 | +| `src/grpc/CLAUDE.md:185` | "re-review RR-02-04" | ADR 이름만 남겼다 | `1103/RR-02-04`(ledger에 시도 구분이 없어 takeover 뒤 옛 owner의 기록이 새 시도를 덮는다, `02-inbound-transports.md`) | +| `src/grpc-advanced/CLAUDE.md:64` | "리뷰 2026-09-24 S5-lead-4" | "2026-09-25 리뷰 후속 작업에서 삭제했다" | `2026-09-25-review-followup-status.md` S5-lead-4 행(release·promotion gate가 websocket·grpc에도 반복되는지, W3-P16에서 삭제). 같은 ID가 `docs/runbooks/grpc-advanced-capabilities.md`와 `docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md`에 남아 있다(검사 대상 밖) | +| `src/shared-contract/CLAUDE.md:27` | "review X2-P1-5, X2-P1-4b, X1-#9" | "moved here in the 2026-09-25 review follow-up" | `2026-09-25-review-followup-status.md`의 X2-P1-5(SHA-256 보일러플레이트 → `Sha256`), X2-P1-4b(서명 헬퍼만 shared-contract로), X1-#9(Backoff 계산식 10개 → `Backoff`). 셋 다 W3-P19 | + +`scripts/check-work-docs.py`에 더하고 고친 것(2026-11-07): + +- 기본 검사 대상: `AGENTS.md`와 `src/**/CLAUDE.md`(build 출력 밖)를 더했다. `AGENTS.md`는 링크 검사에도 더했다(lychee 범위 밖이다). +- 새 패턴 넷: 모듈 리뷰 발견(`MSG-023`, `BOOT-006` — 접두어는 `docs/reviews/`에서 세 자리 번호로 쓰인 여섯), 리뷰 후속 발견(`S6-#10a`, `X2-P1-5`, `S5-lead-4`), 고른 대안이 붙은 발견 번호(`03-11 (b)`), 영어 리뷰 README 절(`review README §15`). 「결정 N」 패턴에 영어 `decision 9`를 더했다. +- 고친 오탐: 날짜로 쓴 결정(`owner decision 2026-11-06`, `소유자 결정 2026-11-07`)은 잡지 않는다. +- 줄바꿈 검사: 한 줄에서 안 걸려도 다음 줄과 이었을 때 줄 경계를 넘는 ID(`(review` ↵ `2026-11-01 07-10)`)를 잡는다. 이번에 2줄(web·persistence-mongo)이 이 꼴이었다. persistence-fileserver·cache-redis의 갈린 괄호는 둘째 줄의 `RR-` 접두어가 따로 잡혔다. +- 오탐 시험(`docs-writing.md` 4절 12단계): 잡아야 할 문장 10개는 모두 잡혔다. 잡지 말아야 할 문장 8개 중 하나가 걸렸다: 일부러 만든 "line 10-12 (b)"(콜론 없는 줄 범위 뒤 대안 표시)다. repo에는 그 꼴이 없어 그대로 뒀다. `docs/reviews/**` 밖 전체에 돌리면 새로 125줄이 걸린다. 모두 검사 대상 밖(모듈 README, ADR, `docs/httpclient/` 등)의 실제 ID이고, 검사 대상 안의 오탐은 0이다. + +## 11. cold-read 시험 2회차 빈틈 처리 (2026-11-07) + +2026-11-07 round7 수정과 통합, round8 확인 리뷰를 시험으로 돌렸다. 이력 없는 세션 9개가 1회차 수정을 넣은 매뉴얼(기준 `73d39212`, 통합과 리뷰는 `83a12f66`)로 일했다. 9개 모두 일은 끝냈고, 매뉴얼에서 답을 못 찾은 곳이 52건 나왔다(1회차 35건). 코드 수정 과제에서 같은 질문이 되풀이됐다. 아래는 공유 노트(`~/.config/Claude/side-session-notes/local_fcd89c34-c754-4c5b-a38f-fa322834286f/`)의 「매뉴얼에서 답을 못 찾은 곳」과 시험 기록(design-docs `delegation-loop/trials/2026-11-07-*.md`)의 「질문」 표를 한 줄씩 처리한 결과다. 기준 커밋 `83948d58`. + +- 세션과 출처 번호: F1 `r8-f1-transport-errors`, F2 `r8-f2-arch-rules`, F3 `r8-f3-persistence`, F4 `r8-f4-idempotency`, F5 `r8-f5-small-fixes`(결함 수정 다섯), M `c-t4-2-manual-ids`(문서), I `r8-integration`(통합과 전체 게이트), A `r8-review-a`(정본 확인 리뷰어), B `r8-review-b`(다른 확인 리뷰어). `F1-3`은 F1 시험 기록 「질문」 표의 3번이다(노트의 순서와 같다). A는 노트 1~5와 2차의 추가 1건(A-6), B는 노트 11절의 1~5다. B의 시험 기록 「질문」 표는 "노트에 절이 없음"이라고 적었지만 노트 11절에 다섯 건이 있다. +- 두 세션 이상이 같은 질문을 했으면 한 행으로 묶고 「세션」 칸에 수를 적었다. 묶은 행이 먼저다. +- 처리 칸: 고침(고친 곳) / 고치지 않음(이유) / 소유자 결정 필요. 「고침(기본값)」은 이 수정이 정하고 결정 색인에 기본값으로 남긴 것이다(소유자가 뒤집을 수 있다). +- 수정 과제의 답(round8 발견을 어떻게 고칠지)은 매뉴얼에 쓰지 않았다. 다음 시험이 그 과제다. + +| # | 출처 | 세션 | 빈틈 | 처리 | +| --- | --- | --- | --- | --- | +| R2-1 | F1-3, F2-3, F3-2, F4-5 | 4 | desktop에서 `spotlessApply`로 고친 형식을 노트북 트리로 가져오는 절차가 없다. 첫 GREEN이 형식 위반으로 실패한 세션도 있다 | 고침 — `operate.md` 4.1절 「push 전에 검증하기」(형식 맞추기 명령 세 줄, 두 트리 해시 대조, 그 트리에서 게이트) | +| R2-2 | F1-6, F3-6, F5-2, M-4 | 4 | 커밋 단위가 두 문서에서 다르다(`commit-and-pr.md` "논리 변경 하나", `improve.md` "묶음마다 커밋 하나") — **모순**. 리팩터링 추출을 따로 커밋하나, 나눈 중간 커밋도 검증하나, 검사를 넓히는 커밋은 언제 두나 | 고침(기본값) — `docs/work/README.md` 4절(논리 변경마다, 리팩터링은 앞 커밋, 커밋마다 그 검사), `improve.md` 4.4절(묶음은 브랜치 하나), `operate.md` 4.1절(중간 커밋은 바뀐 leaf `check`, 무거운 묶음은 마지막 트리), `docs-writing.md` 4절 12단계(검사를 넓히는 커밋은 문서 커밋 뒤), `reference/decisions.md` 2.1 「커밋 단위」(기본값) | +| R2-3 | F4-6, F3-4, I-2 | 3 | 테스트 수를 어디서 세나(성공한 Gradle 로그에 없다). 같은 worktree의 다음 실행이 결과 XML을 덮어써 다시 셀 수 없다 | 고침 — `reference/gates.md` 4절 「테스트 수 세기」(복사와 세는 명령, desktop에서 시험), `operate.md` 4.1절, `docs/work/README.md` 6절 | +| R2-4 | F2-1, F3-1, F4-3 | 3 | RED가 없는 수정(문서를 동작에 맞춤, 계약만 넓힘)은 무엇을 증거로 남기나 | 고침 — `improve.md` 4.2절 3단계 아래 줄, 5절, 8절 RED 칸, design-docs `conventions/work-thinking-order.md` 1절, 스킬 `research-first` 4절 | +| R2-5 | A-2, B-1, I-4 | 3 | 수정 세션의 「범위 밖에서 본 것」이 README 남은 항목인지, 다음 확인 리뷰의 입력인지, 누가 판정하나(Declined와 같은 취급인가) | 고침(기본값) — `improve.md` 4.1절 9단계, `reference/review-criteria.md` 10절(확인 리뷰 문서 「넘어온 항목 판정」, 「확인 리뷰 라운드의 README 절」 끝 문단), `delegate.md` 4.1절, `reference/decisions.md` 2.1 「넘어온 「범위 밖」 항목」, design-docs `conventions/delegation-loop.md` 6절 | +| R2-6 | F1-4, F4-7 | 2 | 앞 실행(같은 worktree의 UP-TO-DATE, 같은 트리 해시의 이전 실행)을 통과 증거로 써도 되나 | 고침 — `reference/gates.md` 4절 「앞 실행을 증거로 쓰기」. 3절 「실제로 돌았음을 보이기」가 4절을 가리킨다 | +| R2-7 | F1-2, F2-2 | 2 | brief의 "pull request 단계 게이트"가 어느 명령들인지 한 곳에 없다 | 고침 — `reference/gates.md` 3절 「단계별 묶음」 표(PR·main·라운드 끝). F2가 찾지 못한 buf job은 3절 (다)에 이미 있다(F2가 읽은 `73d39212` 뒤에 더해졌다) | +| R2-8 | F1-5, F4-2 | 2 | "같은 원인의 다른 자리를 찾는다"와 "범위 밖 결함을 고치지 않는다"의 경계 | 고침 — `improve.md` 4.2절 5단계(brief 영역 안이고 공개 동작이 그대로면 함께 고친다. 아니면 「범위 밖」에 권하는 안과 적는다) | +| R2-9 | F4-4, F5-3 | 2 | 소유자가 이미 정한 큰 변경도 따로 멈추나. 규칙이 스킬과 design-docs에만 있고 repo 매뉴얼에 없다 | 고침 — `docs/work/README.md` 2절(정본 `conventions/work-thinking-order.md` 2.3절과 같은 뜻) | +| R2-10 | F2-4, F5-1 | 2 | 아직 릴리스하지 않은 업그레이드 안내 행이 같은 표면을 다룰 때 고치나 더하나, 머리 「커밋:」 목록, `!` | 고침(기본값) — `improve.md` 4.2절 7단계 아래 줄, `reference/decisions.md` 2.7 「아직 합치지 않은 업그레이드 안내」 | +| R2-11 | A-4, B-4 | 2 | 탐침이 그 source set에 없는 의존성을 써야 할 때 `build.gradle`·lockfile을 바꿔도 되나(A는 바꾸지 않고 E1, B는 버릴 worktree에서 바꿈) | 고침 — `reference/gates.md` 2절 「탐침」 셋째 줄(버릴 worktree에서만, 바꾼 줄을 적는다, 안 하면 E1), `improve.md` 4.1절 5단계 | +| R2-12 | F1-1 | 1 | `improve.md` 7절 "응답 코드를 바꾸면 묻는다"가 레지스트리가 이미 약속한 응답으로 코드를 맞추는 경우(500→409)에도 해당하나 | 고침(기본값) — `improve.md` 7절 첫 줄, `reference/decisions.md` 2.3 「약속한 응답으로 맞추기」 | +| R2-13 | F1-7 | 1 | 결정 색인 2.3절 표에 날짜 칸이 없다 | 고침 — `reference/decisions.md` 2절 머리(날짜는 「누가」나 「출처」 칸에). 기존 행은 이미 출처 칸에 날짜가 있어 표 모양은 두었다 | +| R2-14 | F2-5 | 1 | 리뷰 권장안과 다른 안을 고르면 누가 확인하나 | 고침 — `improve.md` 3절 대안 줄, 8절 「정한 기본값」 칸(보고에 적어 확인 리뷰와 맡긴 쪽이 본다. 공개 동작이 다르면 묻는다) | +| R2-15 | F3-3 | 1 | 임시 RED 메서드에도 Error Prone 규칙(`CheckReturnValue`)이 오류로 걸린다 | 고침 — `improve.md` 9절 strict lane 탐침 줄 | +| R2-16 | F3-5 | 1 | 이미 문서화된 규칙을 검사가 더 엄하게 지키게 바꾸면 「파생 서비스가 따라 고쳐야 하는 변경」(큼·`!`)인가 | 고침(기본값) — `improve.md` 4.2절 7단계(`!`와 안내 행은 단다, 크기는 올리지 않는다), `reference/decisions.md` 2.7 「검사를 더 엄하게 하는 수정」 | +| R2-17 | F3-7 | 1 | ArchUnit fixture도 `testQualityCheck`(SpotBugs)가 분석하고, Lombok 클래스를 상속한 fixture는 실패한다 | 고침 — `reference/gates.md` 2절 표(「테스트 코드(ArchUnit fixture 포함)」)와 그 아래 줄 | +| R2-18 | F3-8 | 1 | optional 빌드 leaf의 RED·탐침에 main 리소스 임시 파일(임시 마이그레이션)을 두는 법 | 고침 — `improve.md` 4.2절 3단계(임시 파일은 main 리소스든 그 worktree에만) | +| R2-19 | F4-1 | 1 | brief의 "같은 핸들"이 넘겨받기 전 핸들인지 적용한 핸들인지 정해지지 않았다 | 고침 — brief를 쓰는 규칙: design-docs `conventions/delegation-loop.md` 4.2절(결정을 옮길 때 대상이 둘 이상으로 읽히면 경우마다 적는다). repo 매뉴얼이 아니라 brief 문구의 빈틈이다 | +| R2-20 | M-1 | 1 | brief 완료 기준(대조 테스트 통과)과 playbook(읽는 테스트가 없으면 lane을 돌리지 않음)이 다르다 | 고침 — `docs-writing.md` 4절 9단계, `reference/gates.md` 2절(brief가 lane을 정했으면 돌린다) | +| R2-21 | M-2 | 1 | 이력 표기 정의가 없다(「1라운드」, `P30`·`W3-P30`) | 고침 — 이 문서 머리말 「더 오래된 표기」 | +| R2-22 | M-3 | 1 | 걷어낸 ID의 근거를 이 문서 어느 절에 더하나. 9절 T4-1 행을 고치나 | 고침 — `docs-writing.md` 4절 6단계(문서 묶음마다 절 하나, 다시 걷어내면 그 절에 표). T4-1 행은 기록이라 두었다(8절 둘째 표가 그 결과다) | +| R2-23 | M-5 | 1 | 새 이력 패턴의 오탐을 어떻게 시험하고 어디까지 받아들이나 | 고침 — `docs-writing.md` 4절 12단계 아래 줄. 이번 패턴 추가에 그대로 적용했다(10절 끝) | +| R2-24 | I-1 | 1 | `mainCheck` 안 `verifyFeatureScaffold`의 중첩 빌드에는 `--no-build-cache`가 넘어가지 않아 FROM-CACHE 0을 만들 수 없다 | 고침 — `reference/gates.md` 3절 「실제로 돌았음을 보이기」 아래 줄(바깥 0, 중첩 빌드 N을 따로 적는다) | +| R2-25 | I-3 | 1 | 라운드 끝 묶음의 태그 단계 범위(`release.yml`의 다른 gate job) | 고침(기본값) — `reference/gates.md` 3절 「단계별 묶음」 아래 줄, `reference/decisions.md` 2.7 「라운드 끝 태그 단계 범위」 | +| R2-26 | I-5 | 1 | 확인 리뷰 README 안의 하위 절 순서, 처리 표 칸(`improve.md` 8절과 brief가 다름) | 고침 — `reference/review-criteria.md` 10절 「확인 리뷰 라운드의 README 절」(여덟 절의 순서, 처리 표 칸, brief가 먼저) | +| R2-27 | I-6 | 1 | `trivy-fs` job은 trivy를 내려받아 설치한다. 설치까지 하나 | 고침(기본값) — `operate.md` 4.1절(설치 단계는 따라 하지 않는다), `reference/gates.md` 3절 (다) 표, `reference/decisions.md` 2.1 「desktop 도구 설치」, design-docs `conventions/delegation-loop.md` 11절 | +| R2-28 | A-1 | 1 | 독립 리뷰어 둘일 때 정본 리뷰어의 색인 검사: 매뉴얼은 rc=0을 요구하고 README 색인 절은 총괄이 쓰게 한다 — **모순**(발견 `1103/RR8-06-01`) | 고침 — `scripts/check-review-index.py --extra-index`, `improve.md` 4.1절 7·8단계와 5절, `delegate.md` 4.1절, `reference/decisions.md` 2.1 「리뷰 README 분담」. 시험: 정본 리뷰어 커밋 `27260ad0`의 리뷰 폴더에 옵션 없이 rc=1(180 중 172), 리뷰어 A의 색인 표(`r8-review-a-probes/index-table.md`)를 넘기면 rc=0(180/180). 리뷰가 권한 "임시 사본" 절차 대신 옵션을 골랐다: 복사·붙이기 단계 없이 명령 하나로 같은 대조를 한다 | +| R2-29 | A-3 | 1 | 확인 리뷰 범위에 결함 수정이 아닌 커밋(매뉴얼 수정)이 섞이면 그것도 보나("그 수정만 본다") | 고침 — `improve.md` 4.1절 3단계(brief 범위의 커밋을 본다, 결함 수정이 아닌 커밋은 영역 하나로) | +| R2-30 | A-5 | 1 | strict lane에 `--tests` 필터로 탐침만 돌려도 되나 | 고침 — `reference/gates.md` 2절 「탐침」 둘째 줄(`requires` lane은 필터 없이. `StrictTestLanePlugin`의 required 검사가 고른 클래스가 다 돌지 않으면 실패시킨다) | +| R2-31 | A-6 | 1 | 두 리뷰의 「이번 수정 / 이전부터」 분류가 다를 때 어느 쪽을 쓰나 | 고침 — `reference/review-criteria.md` 10절 「ID」 끝 줄(정본 리뷰어가 근거를 붙여 정하고 차이를 대응표에) | +| R2-32 | B-2 | 1 | 확인 리뷰가 수정 세션의 「정한 기본값」을 어떻게 다루나, README·결정 색인으로 옮겨졌는지 누가 보나(round8 Important 회귀 하나가 옮겨지지 않은 기본값에서 나왔다) | 고침 — `improve.md` 4.1절 2단계(옮겨지지 않은 공개 동작 기본값은 발견), `delegate.md` 4.1절(총괄이 옮긴다), `reference/review-criteria.md` 10절, design-docs `conventions/delegation-loop.md` 6절 | +| R2-33 | B-3 | 1 | 상한을 넘는 범위를 brief가 노트 하나로 받았을 때 문서 모양 | 고침 — `improve.md` 4.4절(출력 파일 하나면 그 안에 단위마다 절) | +| R2-34 | B-5 | 1 | 탐침 rc를 읽는 법(결함 동작을 단언한 탐침과 약속을 단언한 탐침이 섞임) | 고침 — `reference/gates.md` 2절 「탐침」 첫 줄, `reference/review-criteria.md` 10절 「실행한 명령과 결과」 칸 | + +- 합계: 52건, 34행. 고침 34행(그중 기본값 7행), 고치지 않음 0, 소유자 결정 필요 0. +- 소유자 결정(2026-11-07)으로 한 일: 이력 ID 0 규칙을 진입 문서로 넓혔다(10절, 결정 색인 2.1 「이력 ID 0 규칙의 범위」). +- 「자주 하는 실수」에 넣은 줄: `improve.md`(탐침의 Error Prone을 기존 줄에 더함). diff --git a/docs/work/improve.md b/docs/work/improve.md new file mode 100644 index 00000000..5918448e --- /dev/null +++ b/docs/work/improve.md @@ -0,0 +1,143 @@ +# 개선 — 리뷰, 결함 수정, 리팩터링, 성능, 구조, 테스트 구조 + +이미 있는 코드를 평가하거나 고치는 일의 절차다. 핵심은 하나다: 리뷰 → 수정 → 확인 리뷰를 발견이 0이 될 때까지 돈다. + +## 1. 언제 쓰나 + +| 지금 상태 | 작업 | +| --- | --- | +| 무엇이 틀렸는지 아직 모른다 | 리뷰 | +| 계약(이름·Javadoc·문서·레지스트리·테스트 이름이 약속한 것)과 다른 동작이 확인됐다 | 결함 수정 | +| 동작은 맞는데 구조 비용이 크다 | 리팩터링 | +| 숫자로 잰 비용이 크다 | 성능 최적화 | +| leaf·패키지·허용 의존이 바뀐다 | 구조 변경 | +| 테스트가 이름이 말한 것을 증명하지 못한다 | 테스트 구조 개선 | + +- 새 업무 기능은 [new-feature.md](new-feature.md)다. +- 고치기 전에 소유자 결정이 필요하면 [research-design.md](research-design.md)가 먼저다. + +## 2. 받아야 할 것 + +- 리뷰: 범위(전체 / 영역 / 커밋 범위 `..`와 pathspec), 쓸 심각도 체계(전체 리뷰용인지 확인 리뷰용인지). +- 수정: 고칠 발견 목록(ID, 위치)과 리뷰 문서 경로. +- 공통: 기준 커밋, 브랜치, 커밋 허용 여부, 검증할 게이트. +- 그 발견에 필요한 소유자 결정이 났는지. [reference/decisions.md](reference/decisions.md)에 없고 brief에도 없으면 그 발견만 멈추고 묻는다. + +## 3. 크기와 사고 순서 + +- 보통 중간이다: 확인 리뷰 하나, 수정 묶음 하나. +- 큼: 전체 리뷰, 구조 변경, 공개 계약을 바꾸는 수정. 큰 일은 1~5단계 결과와 대안을 소유자가 먼저 본다. +- 이 작업에서 선행 사례는 둘이다: 같은 원인이 남은 다른 자리, 그리고 [reference/defect-patterns.md](reference/defect-patterns.md)의 같은 모양. +- 대안은 고치는 법 2~3개를 비교한다. 고른 것과 버린 것을 커밋 본문에 쓴다. 리뷰의 권장안을 버리면 버린 이유를 커밋 본문에, 고른 안을 보고 「정한 기본값」에 적는다(확인 리뷰와 맡긴 쪽이 본다). 고른 안의 공개 동작이 권장안과 다르면 7절대로 묻는다. +- 스킬: 리뷰는 `superpowers:requesting-code-review`의 리뷰어 지침과 바뀐 경계의 영역 스킬, 결함 수정은 `superpowers:systematic-debugging` → `superpowers:test-driven-development`, 리팩터링은 `refactor`·`codebase-design`, 성능은 `performance-optimization`, 구조 변경은 `superpowers:brainstorming` → `superpowers:writing-plans`. 리뷰 결과를 받아 고칠 때는 `superpowers:receiving-code-review`. +- 스킬이 하위 에이전트를 띄우라고 하면 그 단계는 이 세션이 직접 한다. 나눠야 하면 [delegate.md](delegate.md)대로 별도 세션에 맡긴다. + +## 4. 절차 + +### 4.1 리뷰 + +1. 범위를 고정한다. 확인 리뷰는 pathspec과 `git diff --stat .. -- ` 결과를 문서에 적는다. +2. 확인 리뷰는 수정 보고의 「새로 가정하는 것」 칸부터 본다. 가정마다 다른 코드·설정·운영에서 참인지 확인한다. 그 칸이 없으면(보고가 repo에 없거나 옛 양식) 수정 커밋 본문의 「위험·한계」와 리뷰 README 처리 표의 「결정」 칸에서 가정을 뽑고, 뽑은 곳을 문서 「범위」 절에 적는다. 보고의 「정한 기본값」도 읽는다. 공개 동작을 바꾸는 기본값이 결정 색인과 README 처리 표 어디에도 없으면 발견으로 적는다. +3. 그다음 수정 diff와, diff가 바꾼 동작의 주변 코드를 읽는다. 확인 리뷰는 저장소 전체가 아니라 brief 범위의 커밋만 본다. 결함 수정이 아닌 커밋(매뉴얼 수정 등)도 범위에 있으면 영역 하나로 따로 본다. 읽은 주변 코드에서 본 결함은 이전부터 있었어도 발견으로 적고 「이전부터」로 표시한다. 그 밖을 찾아 나서지 않는다. +4. 전체 리뷰는 게이트를 먼저 한 번 돌려 결과를 적고([reference/gates.md](reference/gates.md)), 영역을 나눈다([delegate.md](delegate.md) 「나누는 법」). +5. 의심 결함은 별도 worktree의 임시 테스트(탐침)로 확인한다. 탐침 코드는 고칠 때 옮겨 쓸 수 있게 남기고(소유자 환경에서는 공유 노트 폴더, design-docs `conventions/delegation-loop.md` 11절), worktree는 지운다. 탐침의 단언과 rc 읽기, 의존성 더하기, strict lane 필터는 [reference/gates.md](reference/gates.md) 2절 「탐침」이다. +6. 발견을 [reference/review-criteria.md](reference/review-criteria.md) 양식으로 적는다. 발견마다 증거 수준과 "이번 수정이 만들었나 / 이전부터 있었나"를 적는다. +7. 리뷰 폴더 README에 이번 라운드의 색인 절 하나를 더한다: 발견 ID, 심각도, 한 줄 내용, 결정이 필요한 질문. 발견 ID를 모두 이름으로 적는다. 범위(`A~B`)와 이어 쓰기(`A·07`)는 된다. 건수만 쓰지 않는다. README의 다른 절(처리 표, 결정의 답, 라운드 끝 게이트)은 맡긴 쪽이 쓴다. 한 라운드를 여러 리뷰 세션이 나눠 보면(독립 리뷰어 둘 포함) 색인 절도 맡긴 쪽이 쓰고, 리뷰어는 README를 고치지 않고 보고에 같은 표를 둔다. +8. `python3 scripts/check-review-index.py docs/reviews/<폴더>`를 돌려 rc=0을 본다. 색인 절이 따로 있으면 `--index-heading "<절 제목>"`을 붙인다. 색인 절을 맡긴 쪽이 쓰면 보고의 색인 표만 담은 파일을 `--extra-index <파일>`로 넘겨 rc=0을 본다. 그때 옵션 없이 돌린 rc=1은 맡긴 쪽이 색인 절을 쓰면 닫히니, 보고에 두 결과를 함께 적는다. 지난 라운드 색인에서 빠진 ID 때문에 처음부터 rc=1이면, 빠진 ID를 이번 색인 절에 「색인 보완」 한 줄로 이름만 적는다. 지난 영역 문서는 고치지 않는다. +9. 판단하지 않은 항목은 「Declined to judge」에 위치와 이유를 적는다. 맡긴 쪽이 다음 묶음에 배정하거나 결정으로 닫는다. 지난 라운드에서 넘어온 항목(열린 Declined, 수정 세션의 「범위 밖에서 본 것」을 README가 남은 항목으로 옮긴 것)은 brief가 맡겼을 때만 다시 판정하고, 문서에 「넘어온 항목 판정」 절을 둔다. 맡기지 않았으면 건수와 위치만 적는다. + +**독립 리뷰어 둘.** 아래 셋 중 하나면 같은 범위를 서로 결과를 보지 않는 리뷰어 둘이 따로 리뷰하고 맡긴 쪽이 합친다([delegate.md](delegate.md) 4.1절). + +- 멈추는 확인 리뷰: 리뷰어 하나가 0을 냈으면 멈추기 전에 두 번째 리뷰어가 같은 범위를 본다(4.5절 1). +- 수정 diff가 추가 1,000줄 이상인 확인 리뷰(상한 1,500줄에 가까움. 세는 법은 4.4절). +- Critical·Important(전체 리뷰는 High)를 고친 수정의 확인 리뷰. +- 리뷰어는 자기 문서를 끝내기 전에 다른 리뷰어의 브랜치·문서·보고·노트를 읽지 않는다. 리뷰 폴더에 문서를 커밋하는 것은 brief가 정한 정본 리뷰어뿐이다. 다른 리뷰어는 같은 양식을 보고에 두고, ID 자리에 임시 번호 `B-NN-MM`을 쓴다. + +### 4.2 결함 수정 + +1. 원인 경로를 확인한다. 증상이 아니라 원인을 적는다. +2. RED: 결함을 재현하는 테스트를 먼저 쓰고, 수정 전 코드에서 실패하는 것을 실행으로 본다. 실패 메시지가 그 결함을 말해야 한다. 컴파일 오류나 준비 실패는 RED가 아니다. +3. 수정과 테스트를 이미 같이 썼으면, 기준 커밋에 테스트만 얹은 임시 worktree에서 RED를 본다. 실 DB·Redis가 필요한 결함은 실 vendor lane에서 본다. RED용 임시 파일은 테스트든 main 리소스(임시 마이그레이션 등)든 그 worktree에만 둔다. + - RED가 없는 수정도 있다. 문서를 동작에 맞추면, 문서의 주장을 그대로 단언하는 임시 테스트가 기준 커밋에서 실패하는 것을 RED로 쓴다. 이름·설명 문제처럼 테스트로 옮길 수 없으면 틀린 문장과 실제 동작의 출처를 적는다. 동작은 두고 계약만 넓히면 새 케이스가 기준 커밋에서도 통과함을 보이고 「지키는 테스트」로 적는다. 보고 RED 칸에는 "RED 없음 — 이유"를 쓴다. +4. 가장 작은 수정으로 GREEN을 본다. +5. 같은 원인의 다른 자리를 찾는다. 경계마다 다시 구현된 규칙은 한 곳만 고치면 다른 곳에서 다시 갈라진다. 찾은 자리가 brief 영역 안이고 공개 동작이 바뀌지 않으면 함께 고치고 보고에 적는다. 공개 동작이 바뀌거나 brief 영역 밖이면 고치지 않고 「범위 밖에서 본 것」에 권하는 안과 함께 적는다. 묶음 상한(4.4절)도 지킨다. +6. 그 동작을 설명하는 문서를 같은 변경에서 고친다: `docs/web/http-contract.md`, `docs/registries/`, runbook, `docs/manual/`, leaf README·`CLAUDE.md`, Javadoc. 고친 뒤 옛 표현을 grep으로 찾는다. +7. 파생 서비스가 따라 고쳐야 하면 `docs/upgrade/`의 안내에 행을 적고, 커밋 제목에 `!`와 `BREAKING CHANGE:` 꼬리말을 단다. 문서에 이미 적힌 규칙을 검사가 더 엄하게 지키게 되어 그 규칙을 어기던 코드가 새로 실패하는 것도 여기에 든다(규칙은 이미 정해져 있어 크기는 올리지 않는다). + - 안내의 범위(머리 「범위」)가 아직 main에 합쳐지지 않았으면 파생 서비스는 그 행을 받기 전이다. 같은 표면의 행이 있으면 그 행을 고쳐 최종 동작을 적고, 머리 「커밋:」 목록에 이번 커밋을 더한다. main에 합쳐진 안내는 고치지 않고 새 행을 더한다. +8. 영향 leaf의 `check`와 그 코드를 지키는 lane을 돌린다([reference/gates.md](reference/gates.md) 2절, 실행 위치는 [operate.md](operate.md)). + +### 4.3 리팩터링, 성능, 구조, 테스트 구조 + +- 리팩터링: 지킬 동작·타입·실패·진단을 "보존 조건"으로 적는다. 그 조건을 지키는 테스트가 지금 통과하는지 먼저 본다. 리팩터링과 동작 변경을 한 커밋에 섞지 않는다. +- 복사본을 합칠 때: 정본 하나를 정하고 나머지를 지운다. 못 지우면 이유를 가까운 `CLAUDE.md`에 적고, 두 벌이 같은지 보는 대조 테스트를 둔다. +- 성능: 숫자 없이 시작하지 않는다. 기준선 측정 → 원인 좁히기 → 변경 하나 → 같은 조건으로 재측정 → 회귀 테스트로 고정. 조건은 review-criteria.md 「성능 측정」, 지난 기준선은 [evidence.md](evidence.md)다. 지난 숫자는 현재 커밋에서 다시 잰다. +- 구조 변경: 설계서(`docs/design/`)와 계획서(`docs/history/plans/`)를 먼저 둔다. review-criteria.md 「leaf 변경 체크리스트」를 따른다. ArchUnit 규칙을 바꾸면 잡혀야 할 위반 fixture와 통과해야 할 허용 fixture를 둘 다 둔다. +- 테스트 구조: 지금 테스트가 증명하는 것(이름, 단언, skip 수)을 적는다. 고친 뒤 지키려는 production 코드를 일부러 망가뜨려 테스트가 실패하는지(변이) 본다. 옮겼으면 lane별 테스트 수를 전후로 비교한다. + +### 4.4 수정 묶음의 크기 + +- 묶음 하나는 리뷰 영역 하나 안이고 발견 8건 이하다. 묶음마다 브랜치 하나이고, 커밋은 논리 변경마다 나눈다([README](README.md) 4절). +- 확인 리뷰 하나가 보는 수정 diff는 추가 1,500줄 이하다(`git diff --shortstat ..`, 테스트 포함, lockfile·스냅숏 같은 생성 파일과 리뷰 기록 `docs/reviews/**` 제외). 넘으면 확인 리뷰를 나눈다. 묶음 커밋이 따로 있으면 커밋별로, 한 커밋에 여러 영역이 섞였으면 영역 pathspec별로(`git diff --shortstat .. -- `) 나눠 각각 상한 안이 되게 한다. 테스트 파일은 그 테스트가 지키는 코드의 영역에 넣는다. +- 나누는 것은 맡긴 쪽이 brief로 한다. 상한을 넘는 범위를 brief 하나로 받았으면, 한 세션이 나눈 단위를 차례로 보고 단위마다 문서 하나를 쓴다. brief가 출력 파일 하나를 정했으면(정본이 아닌 리뷰어의 노트 등) 그 파일 안에 단위마다 절 하나를 둔다. 그렇게 했다고 보고에 적는다. +- 왜: 지난 수정 라운드에서 추가 줄이 2,000줄 아래면 다음 확인 리뷰 발견이 9건 이하였고, 5,000줄을 넘으면 19건 이상이었다([evidence.md](evidence.md) 「수정 묶음 크기」). 상한 값은 판단이다. 라운드당 새 결함 수로 다시 맞춘다. +- 묶음을 합친 트리는 따로 검증한다([reference/gates.md](reference/gates.md) 「라운드 끝」). 두 묶음의 수정은 한 트리에서 처음 만날 때 새 결함을 만든다. + +### 4.5 멈춤 기준 — 이 repo는 하나다 + +리뷰 → 수정 → 확인 리뷰는 아래 넷이 모두 참일 때만 멈춘다. + +1. 마지막 확인 리뷰의 발견이 심각도와 상관없이 0이다. 서로 보지 않은 리뷰어 둘이 모두 0이어야 한다(4.1절 「독립 리뷰어 둘」). Minor도 기록만 하지 않고 고친다. +2. 열린 「Declined to judge」가 0이다. 다른 브랜치가 처리했지만 아직 합치지 않은 항목은 합친 트리에서 확인할 때까지 열린 것으로 센다. +3. 합친 트리에서 라운드 끝 게이트가 모두 통과했다. +4. 리뷰 README의 남은 항목이 0이다. 결정으로 닫은 항목은 결정 위치를 적었다. + +- 다른 멈춤 기준은 이 repo에서 쓰지 않는다. "새 Important가 0이면 멈춤"과 "Minor는 기록만"은 소유자가 거뒀다. 짝 프론트 repo는 자기 기준을 쓴다(소유자 결정 "각자 유지"). +- 코드로 닫을 수 없는 것은 소유자 결정이 필요한 항목뿐이다. 근거와 권하는 안을 붙여 질문으로 보고하고, 답을 받으면 다시 고친다. + +## 5. 완료 기준 + +- 리뷰: 모든 발견이 양식대로이고 증거 수준이 있다. 색인 검사가 rc=0이다(색인 절을 맡긴 쪽이 쓰면 `--extra-index`로 본 rc). 결정이 필요한 항목마다 선택지와 권하는 안이 있다. +- 결함 수정: 수정 전 실패(RED)와 수정 뒤 통과(GREEN) 로그가 있다. RED가 없는 수정은 "RED 없음 — 이유"와 대신한 증거가 있다(4.2절 3단계). 같은 원인의 다른 자리를 확인했다. 해당 게이트가 rc=0이다(desktop 로그 경로). 보고에 「새로 가정하는 것」이 있다. +- 리팩터링: 보존 조건 테스트가 전후 모두 통과하고 `architectureCheck`가 통과한다. 지운 코드를 가리키는 문서·주석이 grep으로 0이다. +- 성능: 전후 숫자가 같은 조건에서 나왔다. 회귀 테스트가 어떤 단계에 속한다(`verifyStrictLaneStages --dry-run` 통과). +- 구조 변경: `architectureCheck`, `verifyDependencyLocks`, `ci`, `mainCheck`가 통과한다. 문서에 leaf 개수를 적지 않았다. +- 테스트 구조: 변이가 잡혔다. 새 lane이 단계에 속한다. `testQualityCheck`가 통과한다. +- `docs/work/`, 루트 `CLAUDE.md`, `AGENTS.md`, `src/**/CLAUDE.md`를 고쳤으면 `python3 scripts/check-work-docs.py`가 rc=0이다. + +## 6. 하지 말 것 + +- 리뷰 중에 코드를 고치지 않는다. 리뷰는 읽기 전용이다. +- 이전 라운드의 실행 결과나 묶음 보고의 "통과"를 현재 증거로 쓰지 않는다. 바뀐 커밋에서 다시 돌린다. +- 정한 결정을 결함으로 다시 올리지 않는다. 전제가 틀렸다는 새 증거가 있을 때만 근거와 함께 다시 연다. +- 범위 밖 결함을 고치지 않는다. 버리지도 않는다. 위치와 함께 「Declined to judge」나 보고의 「범위 밖에서 본 것」에 적는다. +- 같은 결함을 여러 번 세지 않는다. 두 영역이 같은 결함을 적으면 색인에서 하나로 합친다. +- 어딘가에 적용된 마이그레이션 파일을 고치지 않는다. +- 전 leaf의 import를 바꾸는 이동을 다른 묶음과 동시에 하지 않는다. 나머지를 합친 뒤 혼자 마지막에 한다. + +## 7. 막혔을 때 + +- 고치는 법이 공개 동작(응답 코드, 기동 실패 조건, env 키, 파생 서비스 동작)을 바꾸면 고치기 전에 멈추고 묻는다. 형식은 [README](README.md) 5절이다. 레지스트리·`docs/web/http-contract.md`·Javadoc이 이미 약속한 응답으로 코드를 맞추는 것은 결함 수정이라 묻지 않는다(4.2절 7단계의 안내 행은 적는다). 약속한 곳끼리 다르면 셋째 줄대로 한다. +- RED를 만들 수 없으면(실 vendor가 없다, 머신에 따라 통과한다) 그 사실과 이유를 보고하고 그 발견만 멈춘다. +- 계약을 적은 곳끼리(설계서, 포트 Javadoc, 모듈 README, 테스트) 다르게 말하고 [reference/decisions.md](reference/decisions.md)에 결정이 없으면, 어느 쪽도 고르지 않는다. 양쪽 근거를 표로 붙이고 권하는 안과 함께 묻는다. 그 발견만 멈춘다. + +## 8. 보고 형식 + +[README](README.md) 6절에 더해, 고친 발견마다 아래 칸을 쓴다. 리뷰 README의 처리 표에 그대로 옮길 수 있게 쓴다. + +| 칸 | 적을 것 | +| --- | --- | +| 발견 | 고친 발견의 ID와 한 줄 내용(brief와 리뷰 문서에서는 ID를 쓴다) | +| 상태 | 완료 / 부분(무엇이 남았나) / 못 함(이유) | +| RED | 수정 전 실패한 테스트 이름과 수, 로그 경로. 없으면 "RED 없음 — 이유"와 대신한 증거 | +| 검증 | 명령, 테스트 수, rc, 로그 경로 | +| 처리 내용 | 바꾼 것, 고치다 새로 찾아 고친 것 | +| 새로 가정하는 것 | 이 변경이 다른 코드·설정·운영에 새로 기대는 것. 확인 리뷰가 여기서 시작한다 | +| 정한 기본값 | 소유자가 확인할 것. 리뷰 권장안과 다른 안을 골랐으면 그것도 | +| 범위 밖에서 본 것 | 위치와 내용. 고치지 않았다 | + +## 9. 자주 하는 실수 + +- 색인을 손으로 옮기다 발견이 빠진다. 색인 검사 스크립트를 돌린다. +- 보고에 없는 태스크 이름을 적는다. 로그에서 태스크 이름을 grep해 확인한다. +- 묶음별 검증으로 합친 트리 검증을 대신한다. 라운드 끝 게이트를 따로 돌린다. +- strict lane에 돌릴 탐침을 새 클래스로 만들어 lane이 고르지 않는다. lane은 `build.gradle`의 `requires`(클래스 이름)나 `tag`로 테스트를 고른다. 탐침은 그 lane이 고르는 기존 클래스에 메서드로 넣는다. 탐침도 `-Werror`와 Error Prone으로 컴파일되니 경고를 남기지 않는다(예: 반환값을 버린 `catchThrowable`은 `CheckReturnValue` 오류다). diff --git a/docs/work/new-feature.md b/docs/work/new-feature.md new file mode 100644 index 00000000..de926738 --- /dev/null +++ b/docs/work/new-feature.md @@ -0,0 +1,79 @@ +# 새 기능 — 업무 기능과 capability 모듈 만들기 + +이 playbook은 입구다. 만드는 순서와 판단 지점은 개발 매뉴얼 [`docs/manual/`](../manual/README.md)이 정본이다. 여기에는 크기, 완료 기준, 하지 말 것만 더한다. + +## 1. 언제 쓰나 + +- 새 업무 기능(도메인 개념, 유스케이스, endpoint)을 더할 때. +- 새 capability 모듈(의존성 한 줄로 켜지는 부가 기능)을 만들 때. +- 아니면 다른 playbook이다. + - 있는 기능의 결함·구조를 고친다 → [improve.md](improve.md) + - 어디에 둘지, 어떤 저장소를 쓸지 같은 결정이 먼저 필요하다 → [research-design.md](research-design.md) + - 있는 capability를 켜거나 끈다(`runtimeOnly` 한 줄) → 이 playbook의 4절 3단계에서 `docs/manual/10-capabilities.md`만 따른다 + +## 2. 받아야 할 것 + +- 기능 이름(PascalCase, 예: `Invoice`)과 경로 이름이 규칙대로 안 될 때의 경로(`--path`). +- 요구사항: 무엇을 저장하나, 누가 호출하나, 어떤 권한인가, 재전송될 수 있는 쓰기인가. +- 저장소 선택(어떤 persistence leaf, 마이그레이션 번호대). 서비스마다 달라 사람이 정한다(`docs/manual/04-persistence.md`). brief에 없으면 묻는다. +- 공개 계약(HTTP 경로, 오류 코드, env 키)을 새로 만드는지. 만들면 크기는 큼이다. +- 기준 커밋, 브랜치, 커밋 허용 여부. + +## 3. 크기와 사고 순서 + +- 업무 기능 하나는 보통 중간이다: 계층 leaf 여러 곳에 파일이 생기지만 판단은 매뉴얼이 정해 둔 범위 안이다. +- 큼: 새 capability 모듈, 새 leaf, 새 공개 계약, 파생 서비스가 따라 고쳐야 하는 변경. 큰 일은 설계와 소유자 검토가 먼저다([research-design.md](research-design.md)). +- 선행 사례는 생성 명령의 출력 하나다. 개별 기법의 예시는 `docs/manual/`이 실제 코드(fileserver, durable operation)로 가리킨다. +- 스킬: 설계가 바뀌면 `superpowers:brainstorming`, 여러 단계면 `superpowers:writing-plans`, 구현은 `superpowers:test-driven-development`. + +## 4. 절차 + +1. `docs/manual/README.md`를 읽는다. 처음이면 01 → 02 → 03장을 읽는다. +2. 배치를 정한다(`docs/manual/03-placement.md`). 기본은 계층 leaf 안 `` 패키지다. 이름이 템플릿 패키지(`src/application-core/CLAUDE.md` 「Package ownership」)와 겹치지 않는지 본다. +3. capability 모듈이면 `docs/manual/10-capabilities.md`와 `AGENTS.md` 「부가 기능(capability) 모듈 규칙」의 완료 기준 7개를 먼저 읽는다. 새 leaf가 생기면 [reference/review-criteria.md](reference/review-criteria.md) 「leaf 변경 체크리스트」를 따른다. +4. 뼈대를 만든다: `scripts/new-feature.sh `(`docs/manual/01-generator.md`). 이 명령은 끝에 Gradle `spotlessApply`를 돈다. 노트북에서는 `--no-format`으로 파일만 만들고, 포맷은 desktop에서 `./gradlew spotlessApply`로 한다([operate.md](operate.md) 「실행 위치」). +5. `docs/manual/02-new-feature.md`의 순서대로 채운다: domain-core → application-core → outbound adapter → inbound adapter → app-bootstrap 조립. 안쪽부터 만들면 각 단계가 앞 단계만 보고 컴파일된다. +6. 기능에 필요한 장만 더 읽는다: 저장(04), 재시도될 쓰기(05), 오류(06), 권한(07), 테스트 배치(08), 이벤트(09). +7. 동작은 테스트를 먼저 쓴다. 포트마다 fake 하나와 공유 계약(`XxxRepositoryContract`)을 포트 소유 leaf의 `testFixtures`에 두고, 실제 adapter도 같은 계약을 실 DB lane에서 상속한다. +8. 건드린 leaf마다 `check`, 경계를 넘었으면 `architectureCheck`, 바뀐 표면의 검사를 desktop에서 돌린다([reference/gates.md](reference/gates.md) 2절). +9. `docs/manual/11-checklist.md`를 한 줄씩 확인한다. +10. 매뉴얼과 코드가 다른 곳을 찾았으면 매뉴얼을 고치는 변경을 따로 낸다(정본이 맞다). + +## 5. 완료 기준 + +- `docs/manual/11-checklist.md`의 항목이 모두 참이다. 아닌 항목은 이유를 보고에 적었다. +- 건드린 leaf의 `check`와 `architectureCheck`가 desktop에서 rc=0이다. 로그 경로가 보고에 있다. +- 공개 경로·env 키·의존성을 바꿨으면 `verifyPublicPathSnapshot`·`:app-bootstrap:verifyEnvKeys`·`verifyDependencyLocks`가 rc=0이다. +- 저장 adapter가 있으면 공유 계약을 실 DB lane에서 상속하고, 그 lane이 어떤 단계에 속한다(`verifyStrictLaneStages --dry-run`). +- capability 모듈이면 완료 기준 7개가 모두 참이고, 모듈 README에 세 가지(제공하는 것, 추가할 한 줄, 필요한 env 키)가 있다. +- 생성 명령의 템플릿이나 패키지 규칙을 바꿨으면 `verifyFeatureScaffold`가 통과한다. + +## 6. 하지 말 것 + +- `AGENTS.md` HARD-STOP을 어기지 않는다. 특히 controller가 repository를 부르거나, inbound DTO가 application으로 들어가거나, 업무 규칙이 mapper·filter·설정에 들어가는 것. +- 한 leaf에 모든 계층을 두지 않는다. onboarding 테스트 fixture도 따라 하지 않는다. +- 업무 코드를 템플릿 패키지에 넣지 않는다. +- 저장 adapter를 `persistence-jpa` leaf 안에 만들지 않는다. 서비스 전용 persistence leaf에 둔다. +- 한 단계가 다른 leaf나 계층을 고쳐야 하면 범위를 조용히 넓히지 않는다. 거기서 멈추고 설계를 다시 본다(7절). +- bootstrap에 capability 이름·스위치 목록·scan 정규식을 넣지 않는다. 모듈이 자기 `AutoConfiguration.imports`로 켜진다. +- 노트북에서 Gradle을 돌리지 않는다. + +## 7. 막혔을 때 + +- 저장소 선택, 공개 계약, 권한 매핑처럼 매뉴얼이 "사람이 정한다"고 한 것은 근거와 권하는 안을 붙여 한 번 묻고 그 부분만 멈춘다([README](README.md) 5절). +- 매뉴얼의 판단 지점이 이 기능에 맞지 않으면(기본값도 예외도 해당 없음) 멈추고 묻는다. 새 판단 지점은 매뉴얼에 더할 후보로 보고한다. + +## 8. 보고 형식 + +[README](README.md) 6절에 더해 적는다. + +- 만든 기능과 배치: leaf별 패키지와 주요 타입. +- 읽은 매뉴얼 장과 그 장에서 고른 기본값·예외. +- 정한 것(소유자 확인 대상): 경로, 권한 이름, 오류 코드, 마이그레이션 번호. +- 11장 체크리스트 결과: 참이 아닌 항목과 이유. + +## 9. 자주 하는 실수 + +- 한 leaf에 모든 계층을 둔다. 생성 명령의 출력을 따른다. +- 생성 명령을 노트북에서 기본 옵션으로 돌려 Gradle이 노트북에서 돈다. `--no-format`을 쓴다. +- 역할 → 권한 매핑을 빠뜨려 쓰기 API가 모든 요청에 403이다. `docs/manual/07-authorization.md`를 본다. diff --git a/docs/work/operate.md b/docs/work/operate.md new file mode 100644 index 00000000..9487fe83 --- /dev/null +++ b/docs/work/operate.md @@ -0,0 +1,141 @@ +# 운영 — 게이트 실행, desktop 검증, 릴리스, 파생 서비스 + +검증을 실제로 돌리고, 릴리스하고, 템플릿 변경을 파생 서비스에 넘기는 절차다. 무엇을 돌릴지는 [reference/gates.md](reference/gates.md)가 정하고, 이 playbook은 어디서 어떻게 돌리는지 정한다. + +## 1. 언제 쓰나 + +- 다른 playbook의 검증 단계에서 Gradle·Docker·테스트·게이트를 돌릴 때(4.1·4.2절). +- 여러 묶음을 합친 트리를 라운드 끝 게이트로 검증할 때. +- 릴리스 태그 전 확인을 할 때(4.3절). +- 템플릿 변경을 파생 서비스가 받을 수 있게 준비할 때(4.4절). +- 게이트 자체(build-logic, workflow)를 고치는 일은 [improve.md](improve.md)다. + +## 2. 받아야 할 것 + +- 대상 브랜치와 커밋 sha. desktop은 push된 브랜치나, 노트북이 보낸 패치(4.1절 「push 전에 검증하기」)를 받는다. +- 자기 브랜치 push 허용 여부. brief 7절이 push를 허용하지 않았으면 패치로 검증한다. main push는 허용되지 않는다. +- 돌릴 게이트 목록(없으면 [reference/gates.md](reference/gates.md) 2절로 정한다)과 로그를 둘 이름. + +## 3. 크기와 사고 순서 + +- 게이트를 돌리고 기록하는 일은 보통 작음이다: 목적 한 줄, 대상 확인, 실행과 기록. +- 라운드 끝 전체 묶음, 첫 실행이 실패해 원인을 찾는 일은 중간이다. 실패 원인 찾기는 `superpowers:systematic-debugging`. +- 릴리스와 파생 서비스 쪽 병합은 소유자가 정한다. + +## 4. 절차 + +### 4.1 실행 위치 — 소유자 환경 + +> 이 절은 이 repo 소유자의 기계에 묶인 규칙이다. 공용 정본은 design-docs `conventions/delegation-loop.md` 11절이다. 다른 환경(파생 서비스 등)은 이 절만 자기 환경으로 바꾼다. + +- 노트북에서는 git, grep, 파일 읽기, 문서 편집, `python3 scripts/*.py` 검사만 한다. **Gradle, Docker, Testcontainers, 테스트, 게이트, 성능 측정은 desktop에서 돌린다.** +- desktop의 Gradle·Docker 실행은 모두 공유 잠금 `flock /tmp/claude-gates/heavy.lock`으로 감싼다. 짝 프론트 repo도 같은 desktop에서 같은 잠금을 쓴다. +- desktop의 기존 checkout `~/workspace/clean-architecture-backend-template`은 여러 세션이 함께 쓴다. 그 `stash@{0}`는 소유자의 보관분이다. 건드리지 않는다. `git stash pop`·`drop`·`clear`와 이름 없는 `git stash`를 쓰지 않는다. +- design-docs repo는 노트북 `~/workspace/desktop-server-git/design-docs`에 있다. + +절차: + +```bash +# 1) 노트북: 검증할 변경을 자기 브랜치에 커밋하고 push한다(brief가 허용한 경우) +git push origin <자기 브랜치> + +# 2) desktop: 기존 checkout을 건드리지 않게 따로 worktree를 만든다 +ssh desktop +cd ~/workspace/clean-architecture-backend-template +git fetch origin +git worktree add ~/workspace/<작업 이름> origin/<자기 브랜치> +mkdir -p ~/<작업 이름>-logs +uptime # 다른 빌드가 돌고 있는지 부하를 본다 + +# 3) 공유 잠금 아래에서 한 번에 하나씩 돌리고 rc와 로그를 남긴다 +cd ~/workspace/<작업 이름>/src +flock /tmp/claude-gates/heavy.lock ./gradlew <게이트> --console=plain > ~/<작업 이름>-logs/<게이트>.log 2>&1; echo "rc=$?" + +# 4) 끝나면 worktree를 지운다 +cd ~/workspace/clean-architecture-backend-template +git worktree remove ~/workspace/<작업 이름> +``` + +- 로그는 desktop `~/<작업 이름>-logs/`에 남기고, 보고에 그 desktop 경로와 rc를 쓴다. 같은 worktree의 다음 실행이 결과 XML을 덮어쓰니, 명령이 끝날 때마다 그 태스크의 `build/test-results/<태스크>/`를 로그 폴더로 복사한다(세는 법은 [reference/gates.md](reference/gates.md) 4절). +- RED 확인용 임시 worktree도 같은 방법으로 만들고 끝나면 지운다. +- workflow job이 도구를 내려받아 설치하는 단계(`curl … | sh`, setup action)는 desktop에서 따라 하지 않는다. 소유자 기계를 바꾸는 일이다. 이미 설치된 도구로만 돌리고, 없으면 못 돌림으로 적는다. +- compose를 띄웠으면 지우기 전에 `docker compose … down`을 한다. bind mount 폴더(dev lane overlay `src/app-bootstrap/compose-lanes/dev.yaml`의 `tmp/heap-dumps`)는 Docker가 root로 만들어 `git worktree remove`가 Permission denied로 실패한다. compose가 이미 받은 이미지(`compose.yaml`의 `redis:7.4`)로 폴더를 지운 뒤 다시 지운다: `docker run --rm --pull=never -v "$PWD/tmp:/t" redis:7.4 rm -rf /t/heap-dumps`. +- Python 검사 스크립트는 노트북에서 돌려도 된다. 보고 증거로 쓸 때는 desktop worktree에서 한 번 더 돌린다. + +**push 전에 검증하기.** push한 커밋은 고쳐 쓰지 않는다. 그래서 커밋 본문에 desktop 결과를 쓰거나 push가 허용되지 않았으면, 커밋 전에 바꾼 것을 패치로 보내 같은 트리에서 돌린다. + +```bash +# 노트북: 커밋할 파일만 stage하고(git status로 확인) 트리 해시를 적어 둔다 +git add <바꾼 파일>... && git status --short && git write-tree +# desktop: 기준 커밋(push된 커밋)에서 worktree를 만든다 +ssh desktop 'cd ~/workspace/clean-architecture-backend-template && git fetch origin && git worktree add --detach ~/workspace/<작업 이름> <기준 커밋>' +# 노트북: 패치를 보내 얹는다. 마지막 줄이 위 트리 해시와 같아야 한다 +git diff --cached --binary <기준 커밋> | ssh desktop 'cd ~/workspace/<작업 이름> && git apply --index && git write-tree' +``` + +- 그다음 위 3) 4)대로 돌리고 지운다. 결과를 본문에 적어 커밋한 뒤 `git rev-parse HEAD^{tree}`가 같은 해시인지 본다. 같으면 desktop이 돌린 트리가 그 커밋이다. +- RED는 같은 방법으로 테스트 파일만 stage해 보낸다. 한 파일의 일부만 stage하는 법은 design-docs `conventions/delegation-loop.md` 11절 「커밋과 병합」이다. +- 형식 맞추기(`spotlessApply`)도 Gradle이라 desktop에서 돈다. 패치를 얹은 worktree에서 돌리고, 바뀐 파일을 노트북에 가져와 두 트리 해시가 같은지 본다. 그 뒤의 게이트는 이 트리에서 돌린다. + +```bash +ssh desktop 'cd ~/workspace/<작업 이름>/src && flock /tmp/claude-gates/heavy.lock ./gradlew spotlessApply --console=plain' +ssh desktop 'cd ~/workspace/<작업 이름> && git diff --binary' | git apply --index && git write-tree # 노트북 +ssh desktop 'cd ~/workspace/<작업 이름> && git add -A && git write-tree' # 같은 해시여야 한다 +``` + +- 검증한 트리를 커밋 여럿으로 나누면 중간 커밋마다 그 커밋의 트리를 같은 방법으로 보내 그 커밋이 바꾼 leaf의 `check`(문서·스크립트만 바꿨으면 그 검사)를 돌린다. PR 단계 묶음 같은 무거운 게이트는 마지막 트리에서 한 번 돌린다. + +### 4.2 게이트 실행과 기록 + +1. [reference/gates.md](reference/gates.md) 2절로 돌릴 게이트를 고른다. 라운드 끝이면 3절의 (가) 늘 도는 것, (나) 바뀐 파일로 켜지는 것, (다) 로컬 도구가 없는 것 전체다. +2. 잠금을 얻은 뒤 1분 부하를 적고 돌린다. 한 번에 하나씩이다. +3. 첫 실행이 실패하면 원인을 찾아 고치고 다시 돌린다. 첫 실행과 다시 돌린 결과를 둘 다 적는다. +4. 결과를 [reference/gates.md](reference/gates.md) 4절 형식으로 적는다: 게이트, rc, 시간, 직전 부하, 로그 경로, 대상 커밋. +5. 보고한 태스크 이름과 테스트 수가 로그에 있는지 grep으로 확인한다. + +### 4.3 릴리스 + +- 릴리스는 `v*` 태그 push로 시작한다(`.github/workflows/release.yml`). 태그와 push는 소유자가 한다. +- 태그 전에 그 커밋에서 `./gradlew :releaseCheck -PgitRevision= --console=plain`을 desktop에서 돌린다. sha 없이 돌리면 설계대로 실패한다. +- 태그는 PR 게이트와 main 단계를 이미 통과한 main 커밋에서 자른다. 그래서 `releaseCheck`는 `ci`를 다시 돌리지 않는다. +- 이미지 서명·SBOM은 workflow가 한다(cosign keyless). + +### 4.4 파생 서비스에 템플릿 변경 넘기기 + +- 파생 서비스는 이 템플릿을 받아 도메인을 채운 repo다. 템플릿 변경을 두 방식으로 받는다: 기준 커밋을 적은 tracked snapshot에 3-way로 반영하거나(`template.lock.json`), `git merge upstream/main`을 한다. +- 템플릿 쪽에서 할 일: 파생 서비스가 따라 고쳐야 하는 변경은 `docs/upgrade/`의 안내에 행을 더하고 커밋 제목에 `!`를 단다. 안내 문서 형식은 `docs/upgrade/2026-11-maturity-review.md`다. +- 파생 서비스가 유지할 게이트와 지워도 되는 템플릿 전용 게이트는 `docs/ci-cd/template-vs-consumer.md`다. +- 파생 서비스의 동기화는 루트 `CLAUDE.md`를 걸러낸다. 그래서 파생 서비스는 자기 `CLAUDE.md` 지도에서 `docs/work/README.md`를 가리켜야 한다. `docs/work/`는 걸러지지 않는다. +- `.claude/settings.json`(Agent 도구 금지)은 추적 파일이라 함께 넘어간다. 한 설정 단계에서 deny된 도구는 다른 단계(`settings.local.json`, 사용자 설정)의 allow로 풀리지 않는다(Claude Code 권한 문서 「Settings precedence」). 파생 서비스가 Agent 도구를 쓰려면 그 파일을 자기 repo에서 고친다. +- 파생 서비스 쪽 병합과 그 게이트는 그 repo의 일이다. 템플릿 세션이 파생 서비스 repo를 고치지 않는다. + +## 5. 완료 기준 + +- brief가 요구한 게이트마다 rc, 시간, 직전 부하, desktop 로그 경로, 대상 커밋이 있다. +- 못 돌린 게이트는 이유가 있다. 캐시로 통과한 것과 집계가 뺀 lane을 적었다. +- desktop에 만든 worktree를 지웠다(`git worktree list`에 없다). 기존 checkout의 브랜치와 `stash@{0}`가 그대로다. +- 노트북에서 Gradle·Docker를 돌리지 않았다. + +## 6. 하지 말 것 + +- 노트북에서 Gradle·Docker·테스트를 돌리지 않는다. +- 잠금 없이 desktop에서 무거운 명령을 돌리지 않는다. +- desktop 기존 checkout에서 브랜치를 바꾸거나 stash를 꺼내지 않는다. 자기 worktree를 쓴다. +- 다른 브랜치나 main에 push하지 않는다. 태그를 만들지 않는다. +- 첫 실행 실패를 지우고 두 번째 성공만 보고하지 않는다. + +## 7. 막혔을 때 + +- desktop에 접속할 수 없거나 잠금이 오래 풀리지 않으면 기다린 시간과 상태(`uptime`, 잠금을 쥔 프로세스)를 적어 묻는다. 노트북에서 대신 돌리지 않는다. +- 게이트가 이 일과 무관해 보이는 이유로 실패하면 같은 게이트를 기준 커밋에서 돌려 원래 있던 실패인지 가린다. 원래 있던 실패면 보고하고 그 게이트만 멈춘다. + +## 8. 보고 형식 + +[README](README.md) 6절에 더해 [reference/gates.md](reference/gates.md) 4절 표를 붙인다. desktop 정리 결과(지운 worktree, checkout 브랜치, `stash@{0}` 상태)를 한 줄로 적는다. + +## 9. 자주 하는 실수 + +- desktop 기존 checkout에서 브랜치를 바꿔 다른 세션의 작업을 방해한다. 자기 worktree를 만든다. +- 짧게 끝난 실행을 통과로 적는다. 캐시 재사용인지, 태스크가 실제로 돌았는지 로그로 확인한다. +- 빌드 캐시에서 가져온 테스트 결과를 지금 이 환경에서 통과한 증거로 쓴다. 기준 상태를 확인하거나 시간·환경에 민감한 테스트를 볼 때는 그 태스크를 `--rerun`으로 다시 돌린다. `--rerun`은 바로 앞 태스크 하나에만 걸린다. 태스크마다 붙인다(`:a:test --rerun :b:test --rerun`). `ci` 같은 집계 태스크는 새 worktree에서 `--no-build-cache`로 돌린다([reference/gates.md](reference/gates.md) 3절). +- 커밋하고 push한 뒤 desktop에서 돌려, 결과를 커밋 본문에 못 넣는다. push 전에 패치로 검증한다(4.1절). diff --git a/docs/work/reference/decisions.md b/docs/work/reference/decisions.md new file mode 100644 index 00000000..d7dc02c1 --- /dev/null +++ b/docs/work/reference/decisions.md @@ -0,0 +1,233 @@ +# 결정 색인 + +이미 정한 것을 한곳에서 찾는 색인이다. 결정의 원문은 「출처」 칸의 문서에 있고, 원문이 정본이다. 이 표와 원문이 다르면 원문이 맞고 이 표를 고친다. 이 문서는 지난 리뷰 ID와 결정 번호를 출처로 쓴다(매뉴얼 본문에는 쓰지 않는다). + +```text +작업 시작 ─> 이 색인에서 주제를 찾는다 ─> 있으면: 원문을 읽고 그대로 따른다 + └> 없으면: 소유자 몫인가? ─> 그렇다: 묻는다(3절) + └> 아니다: 정하고 기록한다(3절) +``` + +## 1. 결정을 다시 묻지 않는 규칙 + +1. 작업을 시작하기 전에 이 색인과 원문을 읽는다. 표에 있는 주제면 그 결정대로 한다. brief에도 결정의 **내용**을 옮겨 적는다. +2. 다시 열 수 있는 경우는 셋뿐이다. + - 결정의 전제가 코드나 측정으로 틀렸다고 확인됐다. + - 두 결정이 서로 충돌한다. + - 결정이 `AGENTS.md` HARD-STOP과 충돌한다. +3. 다시 열 때는 "다시 따져 본 것"과 권하는 안을 붙여 소유자에게 묻는다. 예: 2026-11-04 소유자가 수정 묶음의 기본값 셋을 다시 물었을 때, 총괄은 각각 근거를 다시 따져 적었고 소유자가 다시 정했다(`docs/reviews/2026-11-03-rereview/README.md` 15절). +4. 위임·기본값으로 정한 것은 보고에 따로 적는다. 소유자가 뒤집을 수 있게 한다. +5. 뒤집힌 결정은 원문에서 지우지 않는다. 취소선이나 "→ N절에서 바꿈"으로 새 위치를 가리킨다. +6. 리뷰어는 정한 결정을 결함으로 다시 올리지 않는다. + +## 2. 색인 + +「누가」 칸: **소유자**는 소유자가 직접 정했다. **위임**은 소유자가 "지금 정하고 진행하라"고 맡겨 총괄이 정했다(소유자가 뒤집을 수 있다). **기본값**은 수정 묶음이 정하고 처리 표에 남겼다(소유자 확인 대상). **총괄 지시**는 소유자 환경을 운영하려고 총괄 세션이 정한 작업 규칙이다. **정책**은 `AGENTS.md`에 적힌 규칙이다. + +「결정 N」은 `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」의 N번, `1101`은 `docs/reviews/2026-11-01-maturity-review/README.md`, `1103`은 `docs/reviews/2026-11-03-rereview/README.md`다. + +날짜 칸은 2.1 표에만 있다. 2.2~2.7 표에 행을 더할 때는 날짜를 「누가」 칸(예: "기본값(2026-11-07)")이나 「출처」 칸 끝에 쓴다. + +### 2.1 작업 방식 + +| 주제 | 결정 | 누가 | 날짜 | 출처 | +| --- | --- | --- | --- | --- | +| 커밋 정책 기본 | `human-only`. 에이전트는 stage·commit·amend·push하지 않는다 | 정책 | — | `AGENTS.md` 「Gradle 정책 권위」 끝 | +| 커밋 예외 | brief 7절이 허용한 것만 그 작업의 자기 브랜치에 한다. 커밋과 push는 따로 허용된다. 커밋만 허용됐으면 push하지 않는다. main 병합·main 또는 다른 브랜치 push·force push는 하지 않는다 | 소유자(2026-11-06), 커밋과 push를 나눠 읽는 것은 기본값(2026-11-06) | 2026-11-06 | design-docs `conventions/delegation-loop.md` 11절 「커밋과 병합」, `docs/work/README.md` 4절, `docs/work/evidence.md` 9절 | +| 리뷰 README 분담 | 리뷰어는 리뷰 폴더 README에 자기 라운드의 색인 절 하나만 쓴다. 처리 표·결정의 답·라운드 끝 게이트·남은 것은 총괄이 쓴다. 한 라운드를 여러 리뷰 세션이 나눠 보면(독립 리뷰어 둘 포함) 색인 절도 총괄이 쓰고, 리뷰어는 보고의 색인 표를 `check-review-index.py --extra-index`로 대조해 rc=0을 보인다 | 기본값 | 2026-11-06, 2026-11-07 | `docs/work/evidence.md` 9·11절 | +| 이력 ID 0 규칙의 범위 | `docs/work/`·`docs/manual/` 본문에 더해 진입 문서 `AGENTS.md`와 `src/**/CLAUDE.md`. 모듈 README·설계 문서·`docs/reviews/**`는 넓히지 않는다. `check-work-docs.py` 기본 모드가 진입 문서까지 본다 | 소유자 | 2026-11-07 | 2026-11-07 총괄 세션 전달(소유자 결정), `1103` 19.4절 ③, `docs/work/evidence.md` 10절 | +| 커밋 단위 | 커밋 하나에 논리 변경 하나(`conventions/commit-and-pr.md` 3.1절). 수정 묶음은 브랜치 하나이고 결함(또는 같은 원인)마다 커밋을 나눈다. 나눈 커밋마다 그 커밋이 바꾼 leaf `check`를 돌리고, 무거운 묶음은 마지막 트리에서 | 소유자(2026-11-07, 기본값 확인) | 2026-11-07 | `docs/work/evidence.md` 11절 | +| 넘어온 「범위 밖」 항목 | 수정 세션의 「범위 밖에서 본 것」은 총괄이 README 남은 항목으로 옮기고(멈춤 기준 4가 센다), 다음 확인 리뷰가 brief를 받아 판정한다. 「정한 기본값」은 처리 표와 이 색인 기본값 행으로 옮긴다 | 소유자(2026-11-07, 기본값 확인) | 2026-11-07 | `docs/work/evidence.md` 11절 | +| desktop 도구 설치 | workflow job이 도구를 내려받아 설치하는 단계는 desktop에서 따라 하지 않는다. 설치된 도구로만 돌리고 없으면 못 돌림 | 소유자(2026-11-07, 기본값 확인) | 2026-11-07 | `docs/work/operate.md` 4.1절 | +| 하위 세션 보고 | 총괄에게도 쉬운 한국어로 쓴다. Slack 브리핑은 전역 `~/.claude/CLAUDE.md` 규칙이 하위 세션에도 그대로 적용된다. brief 7절에 "Slack 말고"가 있으면 보내지 않는다 | 기본값(전역 규칙의 적용 범위를 적음) | 2026-11-06 | design-docs `conventions/delegation-loop.md` 11절 「보고」 | +| 커밋 예외(지난 것) | `refactor/review-followup`에 Wave마다 커밋(2026-09-25), 리뷰 수정을 `refactor/maturity-review-2026-11`에 커밋·push(2026-11-03) | 소유자 | 2026-09-25, 2026-11-03 | 결정 1, `1101` 17절 | +| 리뷰 발견 처리 | Minor도 기록만 하지 않고 고친다. 보고할 때 남은 문제가 0이어야 한다. 수정이 새 결함을 만들면 리뷰·수정을 0까지 반복한다 | 소유자 | 2026-11-05 | `1103` 16절 | +| 옛 멈춤 기준 | "새 Important 0이면 멈춤", "Minor는 기록만" — 거둠 | 위임 → 소유자가 거둠 | 2026-11-05 | `1103` 9.1·11.1·16절 | +| 두 repo의 종료 조건 | 각자 유지한다. 백엔드는 발견이 0이 될 때까지, 짝 프론트는 자기 매뉴얼의 조건 | 소유자 | 2026-11-05 | 2026-11-05 총괄 세션 전달(소유자 원문 "각자 유지") | +| 무거운 실행 위치 | 노트북에서 Gradle·Docker를 돌리지 않는다. desktop에서 브랜치를 받아 돌린다 | 소유자 | 2026-11-05 | `1103` 17.1절 | +| desktop 공유 잠금 | desktop의 Gradle·Docker 실행은 `flock /tmp/claude-gates/heavy.lock`으로 감싼다. 프론트와 부하·포트(4173·4174)가 겹치지 않게 | 총괄 지시 | 2026-11-05 | 2026-11-05 총괄 세션 brief, design-docs `conventions/delegation-loop.md` 11절 | +| 세션 분업 | 총괄 세션은 지휘만, 실제 작업은 하위 세션 | 소유자 | 2026-11-05 | design-docs `conventions/delegation-loop.md` 2절 | +| 하위 에이전트 | Agent 도구(세션 안의 하위 에이전트)를 쓰지 않는다. 막는 장치는 두 템플릿 repo의 프로젝트 설정(`.claude/settings.json`) | 소유자 | 2026-11-06 | design-docs `delegation-loop/02-design.md` 13절 D5 | +| 매뉴얼 체계 | 짧은 지도(`CLAUDE.md`) + 작업 종류별 playbook(`docs/work/`) + 예외 없는 규칙은 훅·게이트. repo 스킬 없이 시작 | 소유자 | 2026-11-06 | 같은 문서 D1, D4 | +| 크기별 생략 | 작음·중간·큼으로 사고 순서 단계를 줄인다. 크기는 맡기는 쪽이 정하고 맡은 쪽은 올리기만 한다 | 소유자 | 2026-11-06 | 같은 문서 D2, design-docs `conventions/work-thinking-order.md` | +| 매뉴얼 검사 장치 | 이력 ID·분량 검사와 리뷰 색인 검사는 Gradle 밖 `scripts/`(`check-work-docs.py`, `check-review-index.py`) | 소유자 | 2026-11-06 | 같은 문서 D6 | +| 규칙 ID | 규칙마다 ID(`R-…`)는 아직 붙이지 않는다. 원장이 생길 때 붙인다 | 소유자 | 2026-11-06 | 같은 문서 D7 | +| 옛 개선 매뉴얼 | 브랜치 `claude/improvement-manual-6ae516`은 병합하지 않고 재료로만 쓴다 | 소유자 | 2026-11-06 | 같은 문서 D12 | +| 개선 매뉴얼을 먼저(지난 것) | 다음 개선 작업 전에 repo마다 개선 매뉴얼을 만든다 → 2026-11-06 「매뉴얼 체계」로 바뀜 | 소유자 | 2026-11-05 | 2026-11-05 총괄 세션 brief | +| 스킬 | 리뷰·수정에 알맞은 스킬을 쓴다 | 소유자 | 2026-11-05 | `1103` 2절 | +| `@DisplayName` 언어 | 한국어(기본값 영어를 거부) | 소유자 | 2026-09-25 | 결정 5, `AGENTS.md` 테스트 작성 규칙 2 | +| 학습 문서(지난 것) | 삭제된 코드를 설명하는 학습 문서(지금 `docs/history/study/*.ko.md`, `docs/history/packages/*-superpowers-package/`)는 현재 코드에 맞게 갱신 → 2026-11-07 갱신하지 않고 기록으로 보관(머리 블록만 단다)으로 바뀜 | 소유자 | 2026-09-25 | 결정 6, design-docs `repo-structure/README.md` 3.2절 | +| 문서 체계 | 문서를 수명으로 나눈다. 살아 있는 문서는 제자리에 두고 한국어로 옮긴다. 기록은 `docs/history/`, 설계서는 `docs/design/`, 결정 기록은 `docs/adr/`에 둔다. 폴더 이름은 짝 프론트와 같이 쓴다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절, 적용은 `docs/README.md` | +| 한국어의 범위 | 살아 있는 문서는 본문까지 한국어로 쓴다. 기록 문서는 맨 위에 한국어 머리 블록(상태·작성일·요약·현재 정본)을 달고 본문은 원문 그대로 둔다. 상태는 한국어 고정 어휘다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절 | +| 문서 검사 | 언어·머리 블록·참조·숫자 검사를 PR에서 실패로 둔다(`scripts/check-docs.py`, workflow `docs-check`) | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절, `docs/README.md` 「문서 검사」 | +| 학습 문서 | `docs/history/study/`에 기록으로 보관한다. 코드에 맞춰 갱신하지 않고 머리 블록만 단다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절 | +| 문서 규칙 정본 | design-docs `conventions/docs-system.md`(두 템플릿 공통). 이 repo의 적용은 `docs/README.md`에 적는다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절 | +| 레지스트리 yaml 설명 칸 | 번역한다. 그 칸을 읽는 테스트를 먼저 찾는다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절 | +| 짝 프론트 문서 체계 적용 | 백엔드 번역을 끝낸 뒤 한다. 프론트 README와 `docs/README.md`만 먼저 같이 한다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절 | +| README 필수 절 | 루트 README는 「프로젝트 구조」 절과 「문서 지도」 절을 둔다 | 소유자 | 2026-11-07 | design-docs `repo-structure/README.md` 3.2절, `docs/README.md` | +| client 오류 문구 | 한국어. `Category`별 문구 표 하나를 shared-contract에 | 소유자 | 2026-09-25 | 결정 11 | +| 확인 리뷰 독립 리뷰어 둘 | 세 경우에 서로 결과를 보지 않는 리뷰어 둘이 같은 범위를 리뷰하고 총괄이 합친다: 반복을 멈추기 직전 확인 리뷰(리뷰어 하나가 0을 내면 두 번째가 본다), 수정 diff가 상한에 가까운 리뷰("가까움"은 추가 1,000줄 이상 — 기본값), Critical·Important를 고친 수정의 리뷰. 그 밖은 하나. 2~3라운드 두 리뷰의 겹침 비율을 기록하고 그 결과로 언제나 하나·언제나 둘로 옮길지 다시 본다 | 소유자 | 2026-11-07 | 2026-11-07 총괄 세션 전달(소유자 원문 "(c)로 받기"), `docs/work/improve.md` 4.1·4.5절, `docs/work/delegate.md` 4.1절 | + +### 2.2 구조·조립 + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| outbox relay·멱등성 executor 조립 | app-bootstrap이 아니라 별도 `composition:*` 모듈 | 소유자 | 결정 3 | +| 새 leaf | `composition:durable-operation`, `adapter:inbound:messaging` 등록 승인 | 위임 | `1101` 15절 | +| edge 없는 복사본 | 템플릿 leaf는 `shared-contract` edge를 더해 정본을 쓴다. vendored(`messaging:*`·`grpc:*`)는 복사본을 두고 family `CLAUDE.md`에 이유 | 위임 | `1101` 15절(01-11) | +| caller 트랜잭션 guard | `persistence-notification`·`persistence-fileserver` → `persistence-jpa` edge, `CallerTransaction` 하나 | 소유자 | 결정 33 | +| id 포트 | notification·fileserver id 포트를 domain `IdFactory`로 옮기지 않음(보류) | 소유자 | 결정 34 | +| 소비자 없는 필드 | principal tenant, GraphQL Spring Security resolver, 가명화 키 분리는 하지 않음(보류) | 소유자 | 결정 35 | +| notification `TenantId` | 통합하지 않음. 차이와 이유는 그 타입 Javadoc | 위임 | `1101` 15절(01-03) | +| 생성 명령 | JPA adapter를 만들지 않음(서비스 전용 persistence leaf가 기본), 생성된 쓰기 API는 역할 매핑 전 403 | 위임 | `1101` 15절(r2-10) | +| `@SystemInvoked` | bean으로 등록돼 있으면 기동 실패, inbound adapter가 직접 부르지 못하게 ArchUnit | 위임 | `1103` 4절(RR-01-02) | +| 시스템 호출 경로 | 사용자가 닿는 전송(web·GraphQL·gRPC·WebSocket)만 `@SystemInvoked`에 닿지 못한다. 메시지 소비자·스케줄러는 `@SystemCaller(reason)` 표시로 허용 | 위임 | `1103` 9.1절(RR-01-12), 10절 r5-b | +| 배치 규칙 검사 | 저장소 루트와 `src/` 최상위 허용 목록을 `scripts/check-repo-layout.py`로 PR에서 막는다. 리뷰 기준에도 넣는다(매뉴얼 보강 작업) | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 10.3절 | +| `src/` 배치 | 들여온 플랫폼 넷(`messaging`, `grpc`, `grpc-advanced`, optional 빌드)을 `src/platforms/` 아래로 묶는다. registry `source_path`만 바꾸고 Gradle 경로는 그대로 둔다. `build-logic`·`gradle`·`config`는 Gradle 루트 표준이라 남기고, `composition`은 조립 계층이라 옮기지 않는다. `config/`에서 기능 하나가 주인인 데이터 파일은 그 leaf로 보낸다. Gradle 루트를 저장소 루트로 옮길지는 CI 재편 때 다시 본다 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.1절 | +| 개발 compose 파일 | 저장소 루트에 `compose.yaml` 하나. 뒷단 서비스는 capability 이름 profile로 고르고, 마운트하는 보조 파일은 `compose/`에 둔다. 테스트 lane fixture는 그 lane을 가진 leaf로 보낸다(compose lane → app-bootstrap `compose-lanes/`, Redis topology → redis-sdk, NFS → fileserver). `docker-compose.dev.yml`은 `dev` 배포 프로필이 뜨는지 보는 lane fixture로 app-bootstrap에 둔다 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.3절 | +| 인프라 실행 파일 | nginx 설정, Kubernetes PVC job, DB 역할 SQL은 이 repo에서 지우고, 기능이 운영 환경에 요구하는 조건만 그 기능 문서에 적는다. 아무도 쓰지 않는 infra 폴더 파일도 지운다. 지운 목록은 `docs/upgrade/2026-11-maturity-review.md` B-50 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.3절 | +| 샘플 모듈 | 샘플 leaf와 샘플 전용 Dockerfile을 폴더째 지운다(지운 경로는 `docs/upgrade/2026-11-maturity-review.md` B-49). 역할은 옮기지 않는다. 샘플 안에만 있던 템플릿 검사(OpenAPI 스냅숏, Date 헤더, 가상 스레드 MDC)도 함께 지운다. 예시는 매뉴얼과 생성 명령 출력이 맡는다 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절, `repo-structure/01-backend-layout.md` 6.2절 | +| 기능 끝까지 도는 fixture | 업무 기능 하나가 끝까지 도는 별도 fixture를 두지 않는다. durable operation 조립 테스트가 같은 경로를 실제 PostgreSQL로 본다 | 소유자(2026-11-07) | design-docs `repo-structure/README.md` 3.1절 | + +### 2.3 계약·오류 + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| HTTP 오류 응답 | Envelope 하나. fileserver problem+json도 Envelope로, tus 프로토콜 헤더만 유지 | 소유자 | 결정 2 | +| 처리 중 409 | `IDEMPOTENT_IN_FLIGHT`는 `retryable=true` + `Retry-After: 2`, 계약 문서에 고정 | 소유자 | `1101` 5절(02-01), 15절 | +| Envelope null 필드 | 백엔드가 생략(`NON_NULL`) | 소유자 | `1101` 5절(02-02) | +| `INTERNAL_ERROR` retryable | `false`. 일시적 실패는 전용 코드가 retryable을 가진다 | 소유자 | 결정 28 | +| 새 오류 코드 소유 | 코드를 쓰는 leaf의 enum. 계약은 `docs/web/http-contract.md` §4 | 위임 | `1101` 15절 | +| correlation ID | 규칙 밖이면 서버가 새 값으로 교체 | 위임 | `1101` 15절(02-11) | +| JSON 아닌 본문 상한 | 전역 상한 없음. 엔드포인트가 직접 둔다 | 위임 | `1101` 15절(02-09) | +| GraphQL 복잡도 | 크기 미선언 list = 20, `first`·`last` 둘 다면 큰 쪽, per-parent 경고 임계 10 | 위임 | `1101` 15절(03-01·03-03) | +| GraphQL DataLoader 키 실패 | 등록된 `ApiErrorCode`만 노출 | 소유자 | 결정 25 | +| Draft-12 offset 불일치 | problem 문서는 프로토콜 예외로 유지 | 소유자 | 결정 12 | +| 알림 category 생략 | 거부(400), 판정은 유스케이스 | 소유자 | 결정 13 | +| 오류 코드 로그 레벨 | `error-codes.yaml`에 `log_level` 칸을 두지 않는다. 레벨은 실패 종류·경로가 정한다(`ServerFailureLog`, 보안 필터 `AuthErrorResponseWriter`). 칸이 다시 생기면 `OperationalErrorRegistryContractTest`가 실패한다. 보안 필터는 5xx(`AUTH_JWKS_UNAVAILABLE`·`INTERNAL_AUTH_MISCONFIGURATION`)를 ERROR, 4xx를 WARN으로 남긴다. 401 서명·issuer·audience 불일치는 WARN | 소유자 | 2026-11-06, `docs/design/2026-11-06-error-code-log-level-design.md` 10절 | +| 감싼 carrier를 전송이 읽는 법 | web·GraphQL·STOMP·gRPC 네 전송 모두 원인 사슬의 첫 carrier를 본다. 감싼 carrier의 응답이 500 `INTERNAL_ERROR` 대신 그 carrier의 코드가 된다. 그보다 먼저 답하는 것은 아래 「GraphQL 판정 순서」(등록 매핑)와 「인자 변환 단계의 감싼 carrier」 두 행이다 | 소유자 | `1103` 18.4절(RR7-01-05), 2026-11-06 | +| GraphQL 판정 순서 | 플랫폼 거부 → 실패 자신이 carrier → 등록된 application 매핑 → 원인 사슬의 첫 carrier → 거부된 인자(`IllegalArgumentException`, 인자 binder의 `BindException`) → 가림(`INTERNAL_ERROR`). 앱이 등록한 실패는 carrier를 원인으로 들어도 등록한 코드로 답한다(web에서 앱의 도메인 advice가 먼저 받는 것과 같다). 실패 자신이 carrier인 타입(예: `LockAcquisitionTimeoutException`)을 등록한 매핑은 쓰이지 않는다. 로그 줄은 어느 단계가 답하든 원인 사슬의 첫 carrier로 정한다 — 등록 매핑이 답해도 그 안의 서버 쪽 carrier 줄은 남는다 | 소유자(2026-11-07). 로그 줄도 소유자(2026-11-07, 기본값 확인) | `1103` 19.4절 ①(RR8-01-01), 2026-11-07 총괄 세션 전달 | +| 인자 변환 단계의 감싼 carrier | 「감싼 carrier를 전송이 읽는 법」은 인자 변환 단계를 덮지 않는다. web `MethodArgumentTypeMismatchException`·`HttpMessageNotReadableException`과 GraphQL `@Argument` binder 실패는 원인에 carrier가 있어도 `BAD_PARAMETER`·`VALIDATION_FAILED`다. STOMP는 `@DestinationVariable`·`@Header`의 `ConversionFailedException`과 받은 메시지가 실린 `MessageConversionException`을 원인 사슬의 carrier보다 먼저 거부로 보고 WARN 한 줄(타입만)을 남긴다. 요청 형식 오류의 코드는 전송이 정한다 | 소유자(2026-11-07) | `1103` 19.4절 ④(round8/01 「Declined to judge」), 2026-11-07 총괄 세션 전달 | +| `Retry-After` 값 | web `RetryAfterAdvisor` 표는 레지스트리 `retry_after_seconds` 칸과 코드마다 같다. 빠져 있던 7개(`DB_UNAVAILABLE` 5, `DB_SERIALIZATION_FAILURE` 1, `DB_DEADLOCK` 1, `DB_IDLE_IN_TX_TIMEOUT` 2, `OUTBOX_PUBLISH_FAILED` 30, `JOB_EXECUTOR_REJECTED` 5, `JOB_TIMEOUT` 10)를 채웠고, `OperationalErrorRegistryContractTest`가 둘을 대조한다 | 소유자 | 2026-11-07 총괄 세션 전달(소유자 원문 "권하는 안대로"), r8-f1 보고 「범위 밖」 1 | +| GraphQL 인자 변환 실패 | Spring GraphQL 인자 binder의 `BindException`(`@Argument` 값이 파라미터 타입으로 바뀌지 않음)은 `BAD_PARAMETER`(`REQUEST`)로 답하고, WARN 한 줄(예외 타입만, 입력값 없음)을 남긴다. web이 바뀌지 않는 경로 변수에 답하는 것과 같다 | 소유자 | 2026-11-07 같은 전달, r8-f1 보고 「범위 밖」 2 | +| 약속한 응답으로 맞추기 | 레지스트리·`docs/web/http-contract.md`·Javadoc이 이미 약속한 응답으로 코드를 맞추는 것은 결함 수정이다. 고치기 전에 묻지 않고, 응답이 바뀌니 업그레이드 안내 행은 적는다. 약속한 곳끼리 다르면 묻는다 | 소유자(2026-11-07, 기본값 확인) | `docs/work/improve.md` 7절, `docs/work/evidence.md` 11절 | +| STOMP 필수 header 누락 | 필수 header·destination 변수가 없을 때 Spring이 던지는 `MessageHandlingException`은 ERROR 그대로 둔다. 메시지에 입력값이 없고, Spring이 같은 타입으로 서버 실패(handler의 `Error` 등)도 감싸서 타입만으로는 클라이언트 탓을 가를 수 없다 | 기본값(2026-11-07) | 2026-11-07 총괄 지시, r8-f1 보고 「범위 밖」 3 | + +### 2.4 멱등성 + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| complete 단계 연결 포화 | `UNAVAILABLE` 현재 동작 유지 + 문서화 | 소유자 | 결정 24 | +| complete 단계 저장소 실패 | "결과 불명"으로 따로 알린다(실행 전 503과 구분). 같은 키 재전송은 서버가 판정 | 위임 | `1103` 4절(RR-02-03) | +| lease 지난 실행 중 기록 | PostgreSQL·Redis store가 같은 계약: 작업을 다시 돌리지 않고 "회복 필요" | 위임 | `1103` 9.1절(RR-01-11) | +| Redis key TTL | claim·renew 모두 key TTL ≥ max(replay TTL, processing lease), 설정 검사 | 위임 | `1103` 9.1절(RR-03-11) | +| 늦은 완료 | 늦게 끝난 첫 시도의 완료는 **기록한다**(묶음 기본값 "버린다"를 뒤집음). 다시 실행은 여전히 하지 않음 | 소유자 | `1103` 15절 ① | +| 보존 기간 관계 | `failure-retention < replay-ttl`이면 기동 실패 | 소유자 | `1103` 15절 ③ | +| 같은 attempt 재claim | lease 지난 `CLAIMED`·`FAILED_RETRYABLE`을 넘겨받는다. 같은 attempt를 두 호출이 동시에 쓰는 것은 호출자 계약 | 기본값 | `1103` 17절 r10-02 | +| 다른 핸들의 시작 답 | PostgreSQL도 Redis와 같게 `NOT_OWNER`/`NOT_CLAIMED`로 답한다 | 기본값 | `1103` 17절 r10-02 | +| 전이의 operation id | owner token이 같아도 호출의 operation id가 기록된 claim의 operation id와 다르면 다섯 전이(start·renew·complete·fail·release) 모두 `OPERATION_CONFLICT`로 거절하고 기록은 그대로 둔다. PostgreSQL·in-memory fake를 Redis에 맞췄다. 그래서 `OPERATION_CONFLICT`는 "claim과 다른 id"와 "같은 id·다른 인자" 두 뜻이다 | 소유자(2026-11-06) | 2026-11-06 총괄 세션 전달(소유자 원문 "(a)로 진행"), `IdempotencyStoreContract` | +| 같은 token·다른 operation의 claim·inspect | claim은 진행 중인 기록에 `OwnerOperationConflict`, inspect는 상태와 상관없이(완료된 기록도) `OPERATION_CONFLICT`. 거절이 안전한 쪽을 골랐다 | 기본값(2026-11-06) | 위 결정과 같은 전달의 판단 원칙, `IdempotencyStoreContract` | +| complete 재생 판정 | 완료 확인은 같은 owner token에만 준다. 같은 operation id를 쓴 다른 attempt의 늦은 complete는 `NOT_OWNER`. → 아래 「넘겨받기 전 핸들의 재전송」이 적용한 핸들 하나로 좁혔다 | 기본값(2026-11-06) | Redis TRANSITION에 맞춤, `IdempotencyStoreContract` | +| 기록 없는 release | 저장소 셋 다 `ABSENT`로 답한다(확인할 수 없는 해제를 확인하지 않는다). Redis release도 핸들 revision을 본다. release한 기록을 지울지 남길지는 저장소가 정하므로 release 재시도 답은 `ABSENT`(Redis·fake)와 `ALREADY_RELEASED_SAME_OPERATION`(PostgreSQL)으로 갈린다 | 기본값(2026-11-06) | JPA 설계 22.2 "affected row가 0이면 성공으로 간주하지 않는다", `IdempotencyStoreContract` | +| Redis 연결 예산 | 캐시 조건부 쓰기는 멱등성·lease와 다른 연결 예산(SCRIPT lane) | 위임 | `1103` 4절(RR-04-02) | +| 넘겨받기 전 핸들의 재전송 | 같은 attempt를 넘겨받기 전의 핸들이 이미 일어난 complete·markFailed를 다시 보내면, 그 전이를 실제로 적용한 핸들에게만 "이미 처리됨"으로 확인하고 그 밖의 핸들은 거절한다. Redis TRANSITION 주석의 원래 의도를 뒤집는다. 적용: 적용한 핸들은 기록보다 revision이 하나 낮고 기록의 마지막 전이가 그 전이인 핸들이고, 거절은 `NOT_OWNER`다. 같은 규칙을 start·renew·release에도 맞췄다. 마지막 전이 종류 조건은 2026-11-07에 더했다: renew를 적용한 핸들의 start를 Redis만 "이미 시작됨"으로 확인해 호출자가 작업을 다시 돌렸다 | 소유자(적용 조건 보완도 소유자 2026-11-07, 기본값 확인) | t5 보고 「남은 문제」, 2026-11-06, `1103` 19절(RR8-04-02), `IdempotencyStoreContract` | +| 적용한 핸들의 markFailed 재전송 인자 | 적용한 핸들이 markFailed를 다른 disposition으로 다시 보내면 `OPERATION_CONFLICT`이고 기록된 실패는 그대로다(「전이의 operation id」의 "같은 id·다른 인자"). retention만 다르면 "이미 처리됨"(`ALREADY_MARKED_SAME_OPERATION`)이고 처음 retention이 남는다. retention은 complete의 replay TTL처럼 결과를 얼마나 보관하나일 뿐 결과를 바꾸지 않아 비교하지 않는다. PostgreSQL fail digest에서 retention을 뺐다. 전에는 다른 disposition에 세 저장소 모두 `NOT_OWNER`, 다른 retention에 PostgreSQL만 `OPERATION_CONFLICT`였다 | 소유자(2026-11-07) | `1103` 19.4절 ② (a), RR8-04-01, `IdempotencyFailOutcome`, `IdempotencyStoreContract` | +| 해제된 핸들로 start | 계약은 `ABSENT`와 `NOT_OWNER`를 둘 다 받는다. 포트 Javadoc에 그렇게 적는다 | 소유자 | t5 보고 「남은 문제」, 2026-11-06, `IdempotencyStartOutcome`, `IdempotencyStoreContract` | + +### 2.5 영속성 + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| JPA 기본값 | 트랜잭션 제한 30초, JDBC batch 50, H2 운영 jar 제거, 격리 수준 Hikari 고정, upsert `DO NOTHING` 후 갱신 | 위임 | `1101` 15절(04) | +| 포트 시그니처 | claim에 lease·`claimFence`, fileserver `claimDue`·`markAbandoned`·`claimToken` | 위임 | `1101` 15절 | +| 마이그레이션 번호 | 스트림별 순번. ~~샘플은 운영 스트림과 합쳐 도는 테스트가 있어 `V8_1`.~~(샘플과 함께 사라짐, 2026-11-07) notification은 `V13` | 위임 | `1101` 15절 | +| V21 유일 인덱스 | 기존 중복이 있으면 마이그레이션 실패. runbook에 확인 쿼리 | 위임 | `1101` 15절 | +| 순서 번호 seed | counter가 없으면 전역 floor부터 | 위임 | `1103` 4절(RR-03-02) | +| 마이그레이션 잠금 | 강한 잠금을 거는 마이그레이션은 `SET LOCAL lock_timeout`, 같은 모양의 lane 테스트 | 위임 | `1103` 9.1절(RR-02-09) | +| Flyway PostgreSQL 잠금 | 세션 수준(`transactional-lock: false`). 전제: Hikari 직접 연결. transaction-mode PgBouncer 뒤에서는 깨진다 | 기본값 | `1103` 17절 r10-03(RR6-03-01) | +| persistence-jpa 설정 prefix | 플랫폼 자체는 `app.persistence-jpa.*`, 공유 기능은 기능 트리(`app.outbox`·`app.lock`·`app.realtime.replay`) | 소유자 | 결정 36 | +| 분산 lock·lease | 둘 다 capability로 유지, 공통 계약 테스트 | 소유자 | 결정 8 | +| 실패한 동시 인덱스 마이그레이션 복구 | runbook에 예외 하나를 둔다: 그 버전의 실패 이력 행(`success = false`)만 지우고 다시 배포한다. `flyway repair`는 계속 쓰지 않는다 | 소유자 | `1103` 18.4절(RR7-03-03), 2026-11-06 | + +### 2.6 샘플·메시징·보안·설정 + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| 포스터 업로드 abort·reconcile 경합 | ~~먼저 끝난 쪽이 이김(이미 게시됐으면 abort는 409)~~ 샘플과 함께 사라짐(2026-11-07) | 소유자 | 결정 22 | +| work log 권한·batch | ~~관리자도 남의 work log 수정 불가, `batchCreate` 상한 1000·한 트랜잭션~~ 샘플과 함께 사라짐(2026-11-07) | 위임 | `1101` 15절(09) | +| 이벤트 tenant·오류 코드 | ~~이벤트 tenant 범위 `global`, `WORKLOG_INVALID`~~ 샘플과 함께 사라짐(2026-11-07). `OPERATION_NOT_FOUND`는 남는다 | 위임 | `1101` 15절(01) | +| outbox append 모델 | canonical(`OutboxAppendPort`)로 통일, legacy 포트·legacy Kafka 발행 경로 삭제 | 소유자 | 결정 7 | +| Kafka 소비 | 지원. `MessageHandler` 하나 + starter-kafka가 consumer 조립 | 소유자 | 결정 10 | +| decode 타입 등록 | handler bean이 선언한 타입으로 decode 목록을 만든다 | 위임 | `1101` 15절(06-08 후속) | +| relay 재시도 | 재시도 가능 거부는 무한 재시도(5분 간격), 예산 설정 키 없음, 인증 오류는 경보로 | 위임 | `1101` 15절(06-01·06-03) | +| 끝나지 않는 재시도 | bridge가 원인 코드를 행에 남기고, 오래 재시도 중인 행 수·나이를 지표로, runbook에 park·재개 절차와 테스트된 SQL | 위임 | `1103` 4절(RR-05-03) | +| 카드 검증기 YAML | messaging leaf 테스트에서만 snakeyaml(main 금지) | 소유자 | 결정 29 | +| JWT audience·role | audience 필수, 자기 client role만(기존 배포는 env 하나를 채움) | 소유자 | `1101` 5절(02-03), 15절 | +| 데모 계정 | ~~`local`·`test`·`demo` 프로필이 명시적으로 켜졌을 때만(허용 목록). 각 프로필은 sample이 실제로 뜨는 프로필~~ 샘플과 함께 사라짐(2026-11-07) | 위임 | `1103` 4절(RR-07-02), 9.1절(RR2-04-02) | +| `fixture-` 값 거부 | 비밀로 분류된 키(`docs/registries/secrets-classification.yaml`)만 검사 | 위임 | `1103` 9.1절(RR2-04-01) | +| 파일 서버 인가 | 역할 검사(`file:*` 권한)와 소유자·tenant 검사(`ownerPrincipalId`)를 둘 다 | 소유자 | 결정 14, 결정 32 | +| cross-origin redirect | 호출자 헤더 전부 제거, 안전한 헤더만 유지 | 소유자 | 결정 23 | +| 개발 compose Redis | lane Redis에 ACL 계정, "기동 WARN 없음" 검사 유지 | 위임 | `1101` 15절(r3-J) | +| 서블릿 오류 디스패치 | 보안 체인이 ERROR 디스패치만 허용 | 기본값 | `1103` 6절 r4-b, 8절 | +| 설정 prefix | `app.*`로 통일, `APP_*` env 키 유지 | 소유자 | 결정 16 | +| Redis prefix 예외 | `app.redis.*`·`app.capabilities.*`·`app.rate-limit.*` 세 트리 유지, 네 번째 금지 | 위임 | `1101` 15절(05-18), `AGENTS.md` capability 기준 4 | +| 로그 설정 | logback이 `app.logging.*`을 읽음, `APP_CACHE_REDIS_TTL_JITTER` deprecated | 위임 | `1101` 15절(07) | +| 빈 env 값 | 선택 숫자 설정의 빈 값은 "미설정". 오타·모르는 키 거부는 그대로 | 위임 | `1101` 15절 | +| `APP_FLYWAY_ENABLED` | dev·prod에도 적용 | 위임 | `1101` 15절(r3-F) | +| 전송 상한 기본값 | gRPC 스레드 32·큐 256·동시 100·deadline 10s·drain 2s, ledger `claimTtl` 5m·보존 24h, WebSocket `max-connections` 1000(초과 시 1013) | 위임 | `1101` 15절(03-06·03-09·03-10) | + +### 2.7 빌드·게이트·capability + +| 주제 | 결정 | 누가 | 출처 | +| --- | --- | --- | --- | +| 빌드 게이트 | `verifyEnvKeys`는 app-bootstrap 태스크로 유지(구현은 build-logic `ca.config-contract`), JPA evidence manifest는 폐기하고 leaf 테스트로, redis topology lane 유지 | 소유자 | 결정 4 | +| API surface 단계 | PR(leaf `check` 안) | 소유자 | 결정 20 | +| PR `ci` 범위 | 변경 모듈만 돌리지 않음. 전체 실행 + Gradle 캐시(보류) | 소유자 | 결정 30 | +| 의존성 checksum | 추가 안 함(보류) | 소유자 | 결정 19 | +| build-logic 의존성 잠금 | 잠그지 않음 + 문서화(보류) | 소유자 | 결정 27 | +| 릴리스 이미지 서명 | cosign keyless, tag 릴리스에서 서명·검증 | 소유자 | 결정 31 | +| gRPC `.proto` | protobuf Gradle 플러그인 + Buf(CI) | 소유자 | 결정 18 | +| SpotBugs 신뢰도 | MEDIUM으로 내림. 패턴 단위 제외는 이유를 단다 | 위임 | `1101` 15절(08-07) | +| 테스트 코드 정적 분석 | `testQualityCheck`는 main 빌드 `mainCheck`, optional 빌드 `ci` | 위임 | `1103` 14절 | +| lane 정책과 캐시 | lane 정책 값(`rejectSkipped` 등)은 모두 캐시 입력 | 위임 | `1103` 4절(RR-06-02) | +| workflow 명령의 빌드 판정 | 같은 셸의 `cd <상대 경로>`도 따라간다 | 소유자 | `1103` 15절 ② | +| 성능 lane 단언 | 끄는 스위치 없음. convention이 `performance.assertions.enabled=true`를 넣고, 빌드·lane이 다른 값을 주거나 skip이 있으면 테스트 전에 실패. 손으로 돌리든 workflow든 같은 상한 | 소유자(2026-11-06 병합 승인) | design-docs `delegation-loop/02-design.md` 13절 D9, 커밋 `e6b6e18e`, `AGENTS.md` 「Gradle 정책 권위」 | +| 문서 파싱 검사 | 문서를 파싱해 대조하는 Gradle 검사를 두지 않는다(`verifyDocumentedLeafCount` 등 삭제). 문서와 코드 대조는 leaf의 document-contract lane | 정책 | `AGENTS.md` 「Gradle 정책 권위」 | +| MinIO 이미지 | `pgsty/minio` digest | 위임 | `1101` 15절(05-09) | +| Jackson 2 | 기본 jar에 남김(logstash encoder·springdoc 요구) | 위임 | `1101` 15절(09-11) | +| httpclient reactive | 삭제 | 소유자 | 결정 9 | +| SES 연동 | AWS SDK(sesv2) | 소유자 | 결정 17 | +| durable operation | HTTP 어댑터 추가, 설계 4개(서버 생성 id, payload 지문으로 재제출 판정, 고정 event type, 1일 보존) 승인 | 소유자 | 결정 15, 결정 26 | +| 알림 provider profile 소실 | 일반 재시도 정책 후 FAILED | 소유자 | 결정 21 | +| notification INGEST_ONLY | runtime 없이도 accept 때 route 이름 기록 | 위임 | `1101` 15절(r3-I) | +| 파일 서버 쿼터 | 상한 미설정 = 무제한, 동시 예약은 상한을 넘을 수 있음, 정리 worker 기본 켜짐 | 위임 | `1101` 15절(r2-05a) | +| objectstorage | provider type 하나 추가 | 위임 | `1101` 15절(05-16) | +| 에이전트가 원칙에서 바로 정한 것 | Kafka 주소 키 하나, composition이 persistence-jpa를 함께 가져옴 등 7건 | 기본값 | `docs/reviews/2026-09-25-review-followup-status.md` 「소유자 결정」 끝 목록 | +| 묶음별 기본값 | 각 라운드 처리 표의 「결정」 칸(예: SES replay 창 1h, Retry-After 30) | 기본값 | `1101` 13·14·16절, `1103` 6·10·12·15·16·17절 표 | +| 경로 필터 workflow와 단계 검사 | `paths:`·`paths-ignore:` trigger만 있는 workflow는 strict lane 단계 실행으로 세지 않는다 | 소유자 | `1103` 18.4절(RR7-05-01), 2026-11-06 | +| 검사를 더 엄하게 하는 수정 | 이미 문서에 적힌 규칙을 검사(ArchUnit·검사기)가 더 엄하게 지키게 되는 수정은 결함 수정이라 크기를 올리지 않는다. 규칙을 어기던 파생 서비스 코드가 새로 실패하므로 업그레이드 안내 행과 `!`·`BREAKING CHANGE:`를 단다. 새 규칙을 만드는 검사는 큼이다 | 소유자(2026-11-07, 기본값 확인) | `docs/work/improve.md` 4.2절 7단계, `docs/work/evidence.md` 11절 | +| 아직 합치지 않은 업그레이드 안내 | 안내 범위가 main에 합쳐지기 전이면 같은 표면의 행을 고쳐 최종 동작을 적고 머리 「커밋:」 목록을 늘린다. 합쳐진 안내는 고치지 않고 새 행 | 소유자(2026-11-07, 기본값 확인) | 같은 곳 | +| 라운드 끝 태그 단계 범위 | 라운드 끝은 PR·main 단계 전부와 `releaseCheck` 두 명령. `release.yml`의 다른 job은 릴리스 전에만 | 소유자(2026-11-07, 기본값 확인) | `docs/work/reference/gates.md` 3절 | +| 태그·릴리스 workflow와 단계 검사 | `push`에 `tags:`만 있거나(`branches`·`paths` 없이) `release` trigger만 있는 workflow는 `releaseCheck` 단계에서만 실행으로 센다. 다른 단계(pull request·main·nightly)로는 세지 않는다 | 소유자 | `1103` 18.4절(round7 05 Declined ①), 2026-11-07 | + +## 3. 새 결정을 기록하는 법 + +**누가 정하나** + +| 소유자에게 묻는다 | 직접 정하고 기록한다 | +| --- | --- | +| 공개 계약·wire 형식 변경, 파생 서비스 동작을 바꾸는 기본값, 보안 정책, 새 leaf, 커밋 정책, 되돌리기 비싼 선택, 비용이 드는 외부 일 | 기존 원칙에서 바로 따라 나오는 것, 결함 수정의 구현 방법, 문서 위치 | + +**묻는 법**: 항목 · 선택지 · 권하는 안과 이유 · 정할 사람을 한 표로 쓴다. + +**어디에 쓰나** + +| 결정의 종류 | 위치 | +| --- | --- | +| 리뷰 라운드에서 나온 결정 | 그 라운드 README의 「결정」 절. 항목 · 결정 · 이유 · 버린 대안 | +| 수정 묶음의 구현 기본값 | 처리 표의 「결정」 칸 | +| 되돌리기 비싼 아키텍처 선택 | `docs/adr/ADR-<영역>-<번호>-<제목>.md`(기존 번호를 잇는다) | +| 매뉴얼을 만들거나 고치며 정한 것 | 이 색인 + 근거는 `docs/work/evidence.md` | +| 여러 repo와 소유자 운영에 걸친 결정 | design-docs | + +**기록한 뒤**: 이 색인에 한 줄(주제 · 결정 · 누가 · 날짜 · 출처)을 더한다. diff --git a/docs/work/reference/defect-patterns.md b/docs/work/reference/defect-patterns.md new file mode 100644 index 00000000..d53b87d7 --- /dev/null +++ b/docs/work/reference/defect-patterns.md @@ -0,0 +1,131 @@ +# 결함 패턴 + +이 repo의 리뷰에서 반복해서 나온 결함을 **모양**으로 묶은 목록이다. 리뷰를 시작하기 전에 훑어보고, 고칠 때는 「막는 기준」을 따른다. 리뷰 README의 「반복되는 원인」에 이 번호(A1~)를 붙인다. 패턴마다 근거가 된 지난 발견은 [evidence.md](../evidence.md) 「결함 패턴의 근거」에 있다. + +계층·경계 규칙 자체의 정본은 `AGENTS.md`(HARD-STOP, 모듈 책임, 금지된 지름길)와 가장 가까운 `src/**/CLAUDE.md`다. 이 문서는 그 규칙을 다시 쓰지 않고, 고치거나 리뷰할 때 반복해서 틀린 곳만 적는다. + +## 패턴 + +### A1. 갈라진 복사본 + +- **모양**: 같은 규칙·표·정규식·상수·이미지 참조가 여러 곳에 있고 이미 다르다. +- **막는 기준**: 규칙·표·정규식·상수·이미지 참조는 한 곳에 둔다. 두 곳이 꼭 필요하면 하나를 정본으로 명시하고, 다른 하나가 정본과 같은지 보는 대조 테스트를 둔다. +- **볼 것**: 새로 쓴 상수·정규식·표가 이미 어딘가에 있는지 grep. 같은 판정을 두 클래스가 하는지. +- **장치**: 정본을 가져다 쓰기(예: 마이그레이션 버전 판정 정본 `VersionedMigrationFiles`를 grpc 빌드가 Sync 태스크로 가져온다), 대조 테스트(`TemplatePackageOwnershipDocumentTest`). 테스트 lane의 컨테이너 이미지는 `src/config/testing/container-images.properties` 한 곳이다(MinIO qualification 이미지만 objectstorage leaf 소유). + +### A2. 문서와 코드 불일치 + +- **모양**: 계약·runbook·매뉴얼·README·Javadoc·실패 메시지가 현재 동작과 다르다. +- **막는 기준**: 동작을 바꾸는 변경은 그 동작을 설명하는 모든 문서를 같은 변경에서 고친다. 대상: `docs/web/http-contract.md`, `docs/registries/`, runbook, 매뉴얼, leaf README·`CLAUDE.md`, Javadoc, 업그레이드 안내. 고친 뒤 옛 표현을 grep으로 찾아 남은 곳을 없앤다. +- **볼 것**: diff가 바꾼 동작의 키워드(오류 코드, 설정 키, 상태 이름)로 `docs/`, `src/**/README.md`, `src/**/CLAUDE.md`를 grep. +- **장치**: 일부만 있다. runbook 숫자와 상수를 비교하는 document-contract lane, runbook SQL을 실 PostgreSQL에서 그대로 실행하는 lane. 나머지는 리뷰가 본다. 이 repo는 문서 전체를 파싱하는 검사를 일부러 두지 않는다(`docs/testing/TESTING_STRATEGY.md` 8절). + +### A3. 선언과 실행이 떨어져 있다 + +- **모양**: 설정 키는 바인딩되지만 동작하지 않는다. 선언한 설정 bean이 조용히 바인딩되지 않는다. 레지스트리 행·지표를 아무 코드도 쓰지 않는다. +- **막는 기준**: 선언(설정 키, 레지스트리 행, 지표 이름, 옵션)마다 그것을 실행하는 코드가 있어야 한다. 실행 코드가 없으면 선언을 지운다. 동작하지 않는 옵션은 설정 키 자체를 두지 않는다(`AGENTS.md` capability 기준 3). +- **볼 것**: 새 설정 키를 읽는 곳, 새 레지스트리 행을 내보내는 곳, 문서가 말한 옵션의 분기. 기동 rule이 `static @Bean`이고 필드 주입이 없는지. +- **장치**: `StrictSettingsBinder`(모르는 키·오타 거부), `verifyEnvKeys`, 레지스트리와 코드를 대조하는 테스트(`ErrorCodeRegistryMappingTest`, `HeaderRegistryRuntimeAlignmentTest` 등). + +### A4. 결과 불명을 "확실함"으로 기록한다 + +- **모양**: 외부 효과의 결과를 모르는데 "시작 안 함", "재시도 가능", "확정 거부"로 기록한다. 또는 반대로 확실한 실패를 결과 불명으로 부풀린다. +- **막는 기준**: 외부 효과(DB 커밋, 알림 발송, broker 전송)의 결과를 모르면 "결과 불명"으로 기록·응답한다. 결과 불명을 자동으로 다시 실행하지 않는다. 확실히 실패한 것을 결과 불명으로 부풀리지 않는다. +- **볼 것**: 외부 호출 전후의 상태 기록 순서, 예외를 retryable·terminal·unknown으로 나누는 분기, 응답의 `retryable`. +- **장치**: 멱등성 공유 계약(`IdempotencyStoreContract` — PostgreSQL·Redis store가 같은 판정), `PersistenceExceptionTranslator`의 커밋 단계 분류, `docs/adr/ADR-JPA-003-completion-unknown.md`. + +### A5. 중복·경쟁을 코드 순서로 막는다 + +- **모양**: 조회 후 insert, 찾고 없으면 넣기, 트랜잭션 없는 `SKIP LOCKED`, lease 없는 claim, 프로세스 메모리에 둔 소유권. +- **막는 기준**: 유일성은 DB 유일 제약이 막고, adapter는 그 제약 위반만 기능 예외로 바꾼다. 여러 인스턴스가 집는 작업은 트랜잭션 안의 claim + lease로 소유권을 정한다. +- **볼 것**: 존재 확인 뒤 쓰기, 트랜잭션 밖 잠금, 메모리 안 소유권. +- **장치**: `CallerTransaction`(store는 호출자 트랜잭션을 요구), 동시 요청 통합 테스트(실 DB lane에서 동시 요청 N개 → 행 1개). 정본: `docs/manual/04-persistence.md`. + +### A6. 주장하는 것을 보지 않는 테스트 + +- **모양**: 이름이 말한 성질을 단언하지 않는다. 지키려는 코드를 지워도 통과한다. 시간 제한 대기의 결과를 버린다. 계약 케이스를 skip한다. +- **막는 기준**: [review-criteria.md](review-criteria.md) 7절 점검표. 변이로 확인한다. skip은 0이거나 설계 이유를 적는다. +- **장치**: 포트당 fake와 공유 계약 상속(`AGENTS.md` 테스트 작성 규칙 6), `rejectSkipped`. + +### A7. 거짓 통과 게이트 + +- **모양**: 어떤 단계도 돌리지 않는 lane·검사, 캐시가 옛 결과로 통과, 실패를 막지 못하는 workflow 명령을 실행으로 셈, 시간 단언을 끈 채 돈 performance lane. +- **막는 기준**: [gates.md](gates.md) 6절. 게이트 장치를 바꾸면 일부러 망가뜨린 입력으로 실패하는 것을 본다. +- **장치**: `verifyStrictLaneStages --dry-run`(두 빌드), lane 정책 값의 캐시 입력 선언, `testQualityCheck`, 성능 lane 단언 강제(strict lane convention이 `performance.assertions.enabled=true`를 넣고 다른 값·skip은 실패). 캐시에서 가져온 결과는 현재 통과의 증거가 아니다(필요하면 `--rerun`). + +### A8. 로그로 새는 입력값·원인 + +- **모양**: 클라이언트 입력이나 SQL 원인이 로그 메시지에 실린다. 서버 실패를 남기지 않거나 클라이언트 실패를 ERROR로 남긴다. +- **막는 기준**: 클라이언트 탓 실패(입력 오류)는 WARN 한 줄로 남기고 입력값을 싣지 않는다. 서버 실패는 전송마다 같은 실패 로그 줄(`ServerFailureLog`)을 쓰고, 원인 체인의 SQL·입력값을 메시지에 붙이지 않는다. 클라이언트가 보낸 식별자가 규칙 밖이면 서버가 새 값으로 바꾼다. +- **볼 것**: 새 `log.warn`·`log.error`의 인자, 예외 메시지에 사용자 입력을 넣는 곳, 전송별 예외 처리기. +- **장치**: `src/shared-contract/src/main/java/dev/caskeleton/shared/error/ServerFailureLog.java`(`refusedArgument` 포함), 비밀 분류 `docs/registries/secrets-classification.yaml`. + +### A9. 이름만 보는 허용·거부 + +- **모양**: 프로필·환경 이름 하나가 다르면 위험한 기능이 열린다. 허용한 값으로는 실제로 동작하지 않는다. +- **막는 기준**: 위험한 기능(데모 계정, 비밀 검사 면제 등)은 거부 목록이 아니라 허용 목록으로 연다. 허용 목록의 값마다 실제로 그 값으로 동작해야 한다. +- **볼 것**: 프로필·환경 이름 문자열 비교, 허용 값마다 실제로 기동하는 테스트가 있는지. +- **장치**: `SampleDemoProfilesStartupSystemTest`(허용 프로필마다 기동). + +### A10. 글로만 있는 규칙 + +- **모양**: "하지 마라", "반드시"가 주석·Javadoc·문서에만 있고 막는 장치가 없다(통제 M0~M1). +- **막는 기준**: 위반하면 데이터·권한이 깨지는 규칙은 기동 실패, ArchUnit, 타입으로 막는다. +- **볼 것**: "must not", "하지 않는다", "금지", "반드시"가 붙은 문장마다 막는 장치가 있는지. +- **장치**: 이유를 요구하는 표시(`@SystemCaller(reason)`), 기동 rule, ArchUnit. + +### A11. 샘플·fixture가 운영과 다르게 조립된다 + +- **모양**: 따로 조립한 앱(fixture·데모)이 자동 설정을 빼거나 런타임 기본값이 다르다. "따라 할 모양"으로 둔 fixture가 기동하지 않는다. +- **막는 기준**: 따로 조립한 앱은 운영과 같은 자동 설정과 런타임 기본값을 쓴다. 무엇을 빼면 이유와 대체 장치를 같은 곳에 적는다. 새 기능의 모양으로 둔 fixture는 실제로 기동되는 모양이어야 한다. +- **볼 것**: 그 앱의 `@SpringBootApplication(exclude=…)`, 그 앱의 `application.yml`과 기본 조합의 차이. +- **장치**: 기본 조합 전체 기동 lane(app-bootstrap `systemTest`, PR `check`). 이 모양이 처음 나온 샘플 모듈은 2026-11-07에 지웠다. + +### A12. 수정이 새 결함을 만든다 + +- **모양**: 고친 커밋에서 새 Important·회귀가 나온다. 두 수정이 한 트리에서 처음 만나 새 결함이 생긴다. +- **막는 기준**: 수정 보고에 「새로 가정하는 것」을 쓰고 확인 리뷰가 그 칸부터 본다. 수정 묶음 크기 상한을 지킨다([improve.md](../improve.md) 4.4절). 합친 트리를 라운드 끝 게이트로 따로 검증한다. +- **장치**: 확인 리뷰(수정 diff만), [gates.md](gates.md) 3절. + +### A13. 합치는 과정의 누락 + +- **모양**: 색인을 손으로 옮기다 발견이 빠진다. 손으로 푼 충돌이 한쪽 변경을 지운다. +- **막는 기준**: 색인은 영역 문서에서 기계로 대조한다. 두 묶음이 같은 파일을 건드리지 않게 나눈다([delegate.md](../delegate.md) 「나누는 법」). +- **장치**: `python3 scripts/check-review-index.py docs/reviews/<폴더>`. + +### A14. 타이밍에 기댄 약속 + +- **모양**: "스레드를 남기지 않는다", "시간 안에 끊는다"가 공용 풀이나 "보통은 끝나 있다"에 기댄다. +- **막는 기준**: 그런 약속은 join·종료 대기·전용 스레드로 보장한다. +- **볼 것**: `awaitTermination` 뒤 스레드 생존 확인, 시간 제한을 거는 실행기가 공용인지. +- **장치**: 부하·자원 한계 lane(`httpClientPerformanceTest` 등, `performanceCheck`). + +### A15. 사라지는 외부 공급원 + +- **모양**: 고정한 컨테이너 이미지를 더는 받을 수 없어 다른 lane 결과까지 가린다. +- **막는 기준**: 테스트 이미지는 한 곳에 digest로 고정하고, pull 실패는 따로 구분되는 메시지로 실패하게 한다. +- **장치**: `src/config/testing/container-images.properties`, `PinnedImageUnavailableException`, main 단계 `--continue`. + +### A16. 상한 없는 자원 + +- **모양**: 연결·구독·동시 호출·본문 크기·트랜잭션 시간·큐 길이에 상한이 없거나 코드에 드러나지 않는다. +- **막는 기준**: 상한이 있고 그 값이 코드나 설정에 드러난다. 상한을 넘으면 정해진 응답(예: WebSocket 1013, gRPC 즉시 닫기)을 준다. +- **정한 값**: [decisions.md](decisions.md) 「전송 상한 기본값」, JPA 기본 트랜잭션 제한 30초. JSON 아닌 본문 상한은 엔드포인트가 직접 둔다. + +## 코드에 결정을 드러내는 곳 + +고칠 때 "왜 이 모양인가"를 코드 가까이에 남긴다. 다음 리뷰가 같은 질문을 다시 하지 않게 하려는 것이다. + +| 경우 | 남기는 곳 | +| --- | --- | +| 규칙을 일부러 다르게 둔 타입 | 그 타입의 Javadoc | +| 정적 분석 제외 | 제외 항목 옆 이유(`src/config/spotbugs/exclude-test.xml` 등) | +| 규칙의 예외 경로 | 이유를 요구하는 표시(`@SystemCaller(reason)`) | +| 복사본을 남긴 이유 | 가까운 `CLAUDE.md`(예: `src/platforms/messaging/CLAUDE.md`) | +| 되돌리기 비싼 선택 | `docs/adr/ADR-<영역>-<번호>-<제목>.md` | + +## 패턴을 더하는 법 + +- 새 라운드에서 **두 건 이상**이 같은 모양이면 행을 더한다. 한 건이면 그 라운드 README에만 둔다. +- 모양은 원인 추측이 아니라 코드에서 실제로 본 모양을 쓴다. 근거 ID는 [evidence.md](../evidence.md)에 쓴다. +- 번호는 다시 매기지 않는다. 지운 패턴은 행을 남기고 "합침 → A"으로 적는다. diff --git a/docs/work/reference/gates.md b/docs/work/reference/gates.md new file mode 100644 index 00000000..423f6484 --- /dev/null +++ b/docs/work/reference/gates.md @@ -0,0 +1,210 @@ +# 게이트 + +무엇을, 언제, 어디서 돌리는지 정한다. 게이트 구성의 정본은 `src/build.gradle`의 라이프사이클과 `.github/workflows/`다. 이 문서와 그 둘이 다르면 그 둘이 맞고, 이 문서를 고친다. 실행 위치(desktop, 잠금)는 [operate.md](../operate.md) 「실행 위치」다. + +```text +작업 중 :check (+ 그 leaf의 관련 strict lane) +묶음 끝 + architectureCheck · 바뀐 표면의 검사(env 키·공개 경로·의존성 잠금) · 관련 lane +라운드 끝 합친 트리에서 3절 묶음 전체 — workflow가 PR·main에서 돌리는 것과 같은 명령 +``` + +## 1. 게이트 목록 + +명령은 모두 `src/`에서 실행한다. leaf의 Gradle path는 `src/config/architecture/modules.json`의 `gradle_path`에서 읽는다. leaf별 명령 목록을 문서에 적지 않는다. + +| 게이트 | 무엇 | 단계 | 정의·workflow | +| --- | --- | --- | --- | +| `./gradlew :check` | 그 leaf만: 컴파일, 테스트, Spotless, Checkstyle, Error Prone, API surface | 작업 중 | leaf 컨벤션 플러그인 | +| `architectureCheck` | 의존 방향, domain-core·shared-contract·application-* 순수성, Git이 옮길 수 있는 소스, ArchUnit | PR(`ci` 안) | `src/build.gradle` | +| `./gradlew :app-bootstrap:architectureTest` | 저장소 전체 ArchUnit suite만 | 작업 중 | app-bootstrap `architectureTest` source set | +| `qualityCheck` | SpotBugs, FindSecBugs(운영 코드) | PR(`ci` 안) | `src/build.gradle` | +| `testQualityCheck` | 같은 분석을 모든 테스트 source set에(`config/spotbugs/exclude-test.xml` 기준) | main(`mainCheck` 안), optional 빌드는 `ci` | `src/build.gradle` | +| `ci` | leaf `check`(API surface 포함) + `architectureCheck` + `qualityCheck` | PR | `ci-quality-gates.yml`: `./gradlew :ci :verifyDependencyLocks --warning-mode=fail` | +| `verifyStrictLaneStages --dry-run` | `explicitOnly`가 아닌 strict lane이 workflow가 실행하는 단계에 속하는가 | PR(두 빌드 각각) | `ci-quality-gates.yml`, optional 빌드는 `-p platforms/optional-build` | +| `-p platforms/optional-build ci` | gRPC 플랫폼 빌드 | PR | `ci-quality-gates.yml` | +| `bash scripts/verify-compose-profile-contracts.sh` | compose lane이 선언대로 렌더링되는가(저장소 루트에서) | PR | `ci-quality-gates.yml` | +| `python3 scripts/check-repo-layout.py` | 저장소 루트와 `src/` 최상위에 허용 목록 밖의 항목이 없는가, registry 경로가 허용 폴더 안인가. 아무도 가리키지 않는 compose·스크립트 파일은 경고 | PR | `ci-quality-gates.yml` | +| `python3 scripts/check-docs.py` | 살아 있는 문서의 언어, 기록·ADR 머리 블록, 문서의 인라인 코드 경로·Gradle 경로가 지금 있는가, 복사한 숫자(`docs/README.md` 「문서 검사」). 앞에 자기 시험 `python3 -m unittest discover -s scripts/tests`를 돈다 | PR·main push | `docs-check.yml`(경로 필터 없음) | +| `mainCheck` | `configContractCheck` + `qualificationCheck`(`testQualityCheck` 포함) + 공개 경로 스냅숏 + 전송·메시징 qualification lane + 생성 명령 왕복(`verifyFeatureScaffold`) + 모든 leaf의 `mainCheck`(document-contract lane 등) | main | `integration-main.yml`: `./gradlew :mainCheck --continue --warning-mode=fail` | +| `integrationCheck` | 선언된 strict integration lane 전체(실 컨테이너). 입력이 없는 lane은 빼고 이름을 댄다 | main·nightly | `integration-main.yml`, optional 빌드도 | +| `performanceCheck` | 선언된 performance lane 전체(부하·종료·풀·자원 한계, 실 서버와 컨테이너). 상한을 매번 단언한다. 손으로 돌리든 workflow든 같은 상한이다 | main·nightly | `integration-main.yml`, optional 빌드도. 5절 | +| `releaseCheck -PgitRevision=` | 릴리스 provenance + 공개 경로 스냅숏. sha 없이 돌리면 설계대로 실패한다 | 태그 | `release.yml` | +| `:app-bootstrap:verifyEnvKeys` | env 키 레지스트리와 profile YAML·`.env.example` | `mainCheck` 안(`configContractCheck`) | build-logic `ca.config-contract` | +| `verifyPublicPathSnapshot` | 기본 공개 경로가 `docs/security/public-paths-snapshot.txt`와 같은가 | `mainCheck`·`releaseCheck` 안 | `src/build.gradle` | +| `verifyDependencyLocks` | lockfile | PR | `ci-quality-gates.yml` | +| `:app-bootstrap:documentContractTest` | 문서와 코드를 대조하는 lane(태그 `document-contract`) | main(`mainCheck` 안) | `src/app-bootstrap/build.gradle` | +| `:app-bootstrap:repositoryContractTest` | 빌드 스크립트·workflow·compose를 읽는 계약(태그 `repository-contract`) | PR | `src/app-bootstrap/build.gradle` | + +- leaf의 `check`는 그 leaf만 본다. 저장소 전체 질문은 이름이 따로 있는 루트 태스크가 답한다. +- 전체 `test`·`check`·`ci`는 brief가 시킬 때 돌린다. +- 공개 경로 검사와 env 키 검사는 그 표면이 바뀌었을 때 돌린다. + +## 2. 바꾼 것에 맞춰 고르기 + +| 바꾼 것 | 추가로 돌릴 것 | +| --- | --- | +| 한 leaf 안의 코드 | 그 leaf `check` + 그 코드를 지키는 strict lane(실 DB 등) | +| leaf 경계·의존·registry | `architectureCheck`, `verifyDependencyLocks` | +| env 키 | `:app-bootstrap:verifyEnvKeys` | +| 공개 경로·보안 체인 | `verifyPublicPathSnapshot` | +| 의존성 | `verifyDependencyLocks` | +| 문서(`docs/**`, `CLAUDE.md`, README) | 그 문서를 읽는 document-contract lane(예: `:app-bootstrap:documentContractTest`) + 링크 검사(아래) + `python3 scripts/check-docs.py` | +| 파일·폴더·Gradle 프로젝트를 지우거나 옮김 | `python3 scripts/check-docs.py`(문서가 가리키던 경로가 사라진다) | +| `docs/work/`, 루트 `CLAUDE.md`, `AGENTS.md`, `src/**/CLAUDE.md` | `python3 scripts/check-work-docs.py` | +| 다른 매뉴얼에서 이력 ID를 걷어냄 | `python3 scripts/check-work-docs.py --history <파일 또는 폴더>` | +| build-logic·workflow | `-p build-logic check javadoc`, 두 빌드의 `verifyStrictLaneStages --dry-run` | +| 패키지 규칙, 생성 명령 템플릿 | `verifyFeatureScaffold`(`mainCheck` 안) | +| 마이그레이션 | persistence-jpa `check`, 잠금 대기 lane(`postgresqlMigrationLockWaitIntegrationTest`), 마이그레이션 lane | +| 테스트 코드(ArchUnit fixture 포함) | 그 leaf `testQualityCheck` | +| compose·Dockerfile | compose 검사 스크립트, 실제 `docker build`와 기동 | + +- ArchUnit 위반·허용 fixture도 `testQualityCheck`(SpotBugs)가 분석한다. 외부 라이브러리의 Lombok 클래스를 상속한 fixture는 SpotBugs가 `lombok.Generated`를 찾지 못해 실패한다(missing analysis class). 그런 상속 fixture는 두지 않는다. + +어떤 테스트가 그 문서를 읽는지는 `grep -rn -e '<파일 이름>' -e '<폴더 경로>' src --include=*.java`로 찾는다. 걸리는 테스트가 없으면(주석만 걸려도 없음이다) document-contract lane은 돌리지 않고 grep 명령과 결과를 보고에 적는다. 리뷰 기록(`docs/reviews/**`)도 같다. brief가 돌릴 lane을 정했으면 그 lane을 돌린다(brief가 먼저다). + +**탐침**: 의심 결함이나 RED를 보려고 별도 worktree에서 잠깐 돌리는 테스트다. 버릴 worktree에서만 돌리고 커밋하지 않는다. + +- 탐침마다 무엇을 단언했는지 적는다. 결함 동작을 단언했으면 rc=0이 확인이고, 약속(Javadoc·결정)을 단언했으면 실패가 확인이다. 둘이 섞이면 rc만으로 결과를 읽을 수 없다. +- strict lane에 `--tests`를 붙여 탐침만 돌려도 된다. 단 `requires`(클래스 이름)로 고르는 lane은 고른 클래스가 모두 돌지 않으면 실패한다(`StrictTestLanePlugin`의 required 검사). 그 lane은 필터 없이 돌린다. 필터 실행은 탐침의 증거일 뿐 lane 통과의 증거가 아니다. +- 탐침이 그 source set에 없는 의존성을 써야 하면 버릴 worktree에서만 `build.gradle` 한 줄을 더하고 `--write-locks`로 돌린다. 바꾼 줄(빌드 파일, lockfile)을 실행 기록에 적는다. 그렇게 하지 않기로 했으면 코드 읽기 증거(E1)로 판정한다. + +**링크 검사**: workflow `link-check.yml`(lychee)이 PR에서 `README.md`, `src/README.md`, `src/**/README.md`, `src/**/CLAUDE.md`, `docs/**/*.md`, `.github/**/*.md`를 검사한다. 루트 `CLAUDE.md`는 그 범위 밖이라 `scripts/check-work-docs.py`가 본다. lychee가 없는 곳에서는 저장소 루트에서 같은 범위의 상대 링크만 확인한다(외부 URL은 보지 못한다): + +```bash +python3 scripts/check-work-docs.py --links $(git ls-files ':(glob)README.md' ':(glob)src/**/README.md' ':(glob)src/**/CLAUDE.md' ':(glob)docs/**/*.md' ':(glob).github/**/*.md') +``` + +`--links docs`만 돌리면 `src/**/README.md`·`src/**/CLAUDE.md`·`.github/**/*.md`를 빠뜨린다. 저장소 밖 경로와 `file:line`은 링크로 쓰지 않는다(lychee가 따라가지 못한다). + +## 3. 라운드 끝 — 합친 트리의 전체 묶음 + +여러 묶음을 합친 트리는 workflow가 PR과 main push에서 돌리는 것을 모두 돌린다. 정본은 `.github/workflows/`다. (가)는 늘 도는 것, (나)는 바뀐 파일로 켜지는 것, (다)는 로컬에 도구가 없는 것이다. 한 번에 하나씩, 공유 잠금 아래에서 돌린다. + +**단계별 묶음.** brief가 단계 이름으로 게이트를 시키면 아래 줄을 돈다. + +| brief의 말 | 돌릴 것 | +| --- | --- | +| pull request 단계 게이트 | (가)의 `# PR` 줄과 `verify-compose-profile-contracts.sh`·`check-repo-layout.py`·`check-docs.py`(자기 시험 포함), (나)에서 `pull_request`로 켜지는 것, (다) | +| main 단계 | (가)의 `# main push` 줄과 `run-compose-runtime-smoke.sh`·`check-docs.py`(자기 시험 포함), (나)에서 main `push`로 켜지는 것 | +| 라운드 끝 | 위 둘 전부와 (가)의 `# 태그` 두 줄 | + +- 태그 두 줄(`releaseCheck`)은 합친 트리에서 provenance와 공개 경로 스냅숏이 깨지지 않았는지만 본다. `release.yml`의 다른 job(web·websocket·gRPC·httpclient·jpa·fileserver release gate, 이미지)은 릴리스 전에만 돈다([operate.md](../operate.md) 4.3절). 결과 표에 "태그 단계 — 라운드 끝 아님"으로 적는다. + +**실제로 돌았음을 보이기.** 새 detached worktree에서 시작하고 모든 Gradle 명령에 `--no-build-cache`를 붙인다. 로그마다 `grep -c 'FROM-CACHE' <로그>`가 0이어야 한다. UP-TO-DATE는 같은 worktree에서 앞 명령이 만든 출력일 때만 받아들인다(4절). `--rerun`은 바로 앞 태스크 하나에만 걸려 `ci` 같은 집계 태스크의 증거가 되지 않는다. + +- `mainCheck` 안의 `verifyFeatureScaffold`는 생성한 복사본에서 Gradle을 따로 띄워(`scripts/verify-feature-scaffold.sh`) 바깥의 `--no-build-cache`를 받지 않는다. 바깥 빌드는 FROM-CACHE를 만들 수 없으니 그 로그에 나온 FROM-CACHE는 중첩 빌드의 것이다. 「실제 실행」 칸에 "바깥 FROM-CACHE 0, 중첩 빌드 FROM-CACHE N(태스크 이름)"으로 적는다. + +(가) 늘 도는 것: + +```bash +cd src +# PR: ci-quality-gates.yml +./gradlew :ci :verifyDependencyLocks --warning-mode=fail --no-build-cache --console=plain +./gradlew :verifyStrictLaneStages --dry-run --console=plain +./gradlew -p platforms/optional-build ci --no-build-cache --console=plain +./gradlew -p platforms/optional-build :verifyStrictLaneStages --dry-run --console=plain +# main push: integration-main.yml +./gradlew :mainCheck --continue --warning-mode=fail --no-build-cache --console=plain +./gradlew :integrationCheck --continue --no-build-cache --console=plain +./gradlew :performanceCheck --continue --no-build-cache --console=plain +./gradlew -p platforms/optional-build performanceCheck --continue --no-build-cache --console=plain +./gradlew -p platforms/optional-build integrationCheck --no-build-cache --console=plain +./gradlew :adapter:outbound:httpclient:test -Phttp3.tests.enabled=true --no-build-cache --console=plain # 실험 job, 실패해도 workflow는 통과 +# 태그: release.yml (CI는 GITHUB_SHA로 커밋을 받는다. 손으로 돌릴 때는 -PgitRevision) +./gradlew :releaseCheck -PgitRevision="$(git rev-parse HEAD)" --no-build-cache --console=plain +./gradlew -p platforms/optional-build releaseCheck -PgitRevision="$(git rev-parse HEAD)" --no-build-cache --console=plain +cd .. +bash scripts/verify-compose-profile-contracts.sh +python3 scripts/check-repo-layout.py +python3 -m unittest discover -s scripts/tests # docs-check.yml(PR·main push): 문서 검사의 자기 시험 +python3 scripts/check-docs.py +bash scripts/run-compose-runtime-smoke.sh --matrix src/app-bootstrap/compose-lanes/compose-profile-contracts.json +``` + +- 여러 명령으로 된 main job 둘은 그 job의 `run` 줄을 차례로 그대로 돌린다: `integration-main.yml`의 `configuration-cache`(로그에 "Reusing configuration cache."가 있어야 한다), `notification-platform.yml`의 `pr`(main push마다 경로와 상관없이 돈다). +- 첫 실행이 실패하면 고치고 다시 돌린다. 둘 다 기록한다. +- 합친 뒤에만 드러나는 결함이 있다. 묶음별 검증으로 이 단계를 대신하지 않는다. + +(나) 바뀐 파일로 켜지는 것 — brief의 "바뀐 영역의 lane"은 이것이다: + +1. 바뀐 파일 목록을 만든다: `git diff --name-only <기준 커밋> <합친 커밋>`. +2. 그 목록을 두 종류의 패턴과 맞춘다. + - `on.pull_request.paths`가 있는 workflow(`grep -l 'paths:' .github/workflows/*.yml`). 패턴은 glob이다(`**`는 폴더 여러 단계). + - `pr-adapters.yml`의 `changes` job에 있는 `emit` 줄. lane(web·websocket·httpclient·jpa)마다 정규식이고, `grep -E`로 맞춘다. +3. 걸린 workflow·job의 `run` 줄을 그대로 돌린다. matrix가 있으면 값마다 한 번이다(예: jpa는 PostgreSQL 버전마다, httpclient는 transport마다). compose가 필요한 job은 그 job의 `docker compose … up`·`down` 단계도 같이 한다. +4. 걸리지 않은 workflow는 이름과 "경로 안 걸림"을, nightly·수동 전용 job은 "PR·main 단계 아님"을 결과 표에 적는다. + +(다) 로컬에 도구가 없는 것: + +| job | 로컬에서 | 대체가 못 보는 것 | +| --- | --- | --- | +| `link-check.yml`(lychee) | 2절 끝의 같은 범위 상대 링크 검사 | 외부 URL | +| `ci-quality-gates.yml` `grpc-proto-buf`(`buf lint`·`buf breaking`) | buf가 있으면 job의 `run` 줄 그대로. 없으면 못 돌림으로 적는다. diff에 `.proto`·`buf*.yaml`이 없으면 "해당 없음 — proto 변경 없음" | 전부 | +| `dependency-vulnerability.yml` `dependency-review`·`dependency-submission` | GitHub에서만 돈다. diff에 lockfile·`src/gradle/libs.versions.toml` 변경이 없으면 "해당 없음", 있으면 PR 결과를 보고 남은 문제로 적는다 | 전부 | +| `dependency-vulnerability.yml` `trivy-fs` | 이미 설치된 trivy가 있으면 job의 검사 줄 그대로. job이 trivy를 내려받아 설치하는 줄은 따라 하지 않는다([operate.md](../operate.md) 4.1절). 없으면 못 돌림 | 전부(못 돌렸을 때) | + +## 4. 결과 기록 + +| 단계 | 게이트(명령) | 결과 | 시간 | 실행 직전 1분 부하 | 실제 실행 | 로그 | +| --- | --- | --- | --- | --- | --- | --- | +| PR | `:ci :verifyDependencyLocks --warning-mode=fail --no-build-cache` | rc=0 | 6분 32초 | 0.39 | 태스크 756 executed, FROM-CACHE 0, 테스트 7298 실패 0 | desktop `~/<작업 이름>-logs/ci.log` | + +- 한 줄은 명령 하나다. 여러 명령으로 된 job(`configuration-cache`, notification `pr`)은 명령마다 한 줄을 쓰고 「게이트」 칸에 ` 1/7`처럼 순번을 붙인다. Gradle의 태스크 집계 줄은 명령마다 하나씩 나오므로 로그도 명령마다 나눈다. +- 「실제 실행」 칸은 로그의 `> Task` 줄에서 센다: executed(꼬리 없음), UP-TO-DATE, FROM-CACHE. 테스트 수는 그 명령이 새로 쓴 JUnit XML에서 센다. + +**테스트 수 세기.** 성공한 Gradle 로그(`--console=plain`)에는 테스트 수가 찍히지 않는다. 같은 worktree의 다음 실행(특히 `--tests` 필터 실행)은 같은 leaf의 XML을 덮어쓴다. 그래서 명령이 끝날 때마다 XML을 로그 폴더로 복사하고 사본에서 센다. + +```bash +cp -r /build/test-results/<태스크> ~/<작업 이름>-logs/<명령 이름>-xml +x=~/<작업 이름>-logs/<명령 이름>-xml +for k in tests skipped failures errors; do cat $(find "$x" -name 'TEST-*.xml') | grep -o ']*' | grep -o " $k=\"[0-9]*\"" | tr -dc '0-9\n' | awk -v k=$k '{s+=$1} END {print k"="s+0}'; done +``` + +**앞 실행을 증거로 쓰기.** 다시 돌리지 않고 앞 실행을 증거로 쓸 수 있는 것은 둘이다. + +- 같은 worktree에서 앞 명령이 만든 출력이라 이번 명령의 태스크가 UP-TO-DATE로 끝났다. 앞 명령의 로그와 XML 사본을 함께 적는다. +- 같은 트리 해시에서 돈 자기 실행 로그가 있다(맡은 발견이 이미 커밋된 수정에 들어 있을 때 등). 로그에 적힌 트리 해시와 지금 트리 해시를 함께 적는다. +- 트리가 다르거나 다른 세션 보고의 「통과」는 증거가 아니다(E0). 다시 돌린다. + +함께 적는다: + +- 대상 커밋 sha. 작업 트리가 커밋되지 않았으면 그렇다고 적는다. +- 못 돌린 것과 이유. 이유 없이 빠진 검증은 HARD-STOP 6 위반이다. +- 캐시로 통과한 것. 실행 시간이 짧으면 캐시 재사용인지 적는다. +- 집계가 뺀 lane. 입력이 없어 빠진 lane의 이름. +- 고친 테스트가 실제로 돌았는지. 큰 집계 안에서 몇 개가 돌았는지 테스트 수로. +- 보고한 태스크가 로그에 있는지. 로그에서 태스크 이름을 grep해 확인한다. + +## 5. 성능 lane + +- performance lane은 상한을 매번 단언한다. 측정만 하고 통과하는 모드는 없다. 정본은 `AGENTS.md` 「Gradle 정책 권위」와 `docs/testing/TESTING_STRATEGY.md`의 PERFORMANCE 문단이다. +- strict lane convention이 테스트 JVM에 `performance.assertions.enabled=true`를 넣는다. leaf나 lane은 이 값을 선언하지 않는다. +- 빌드(`-P`, `GRADLE_OPTS`)나 lane이 `true` 아닌 값을 주면 테스트 전에 실패한다. skip된 테스트가 하나라도 있어도 실패한다. `-Pperformance.assertions.enabled=true`는 받지만 줄 필요가 없다. +- 그래서 desktop에서 손으로 돌리는 `./gradlew performanceCheck`와 workflow가 같은 상한을 단언한다. +- 판정 없이 숫자만 보려면 JMH가 있는 leaf의 `./gradlew ::jmh`를 쓴다. 게이트가 아니다. +- 시간 단언은 다른 빌드가 돌지 않는 머신에서만 뜻이 있다. 그래서 performance lane은 PR·main 단계가 아니라 `performanceCheck`에 있다. + +회귀를 막는 장치: + +| 장치 | 고정하는 것 | 단계 | +| --- | --- | --- | +| 자원 한계 lane | Tomcat·Jetty 부하·느린 클라이언트·종료, HTTP client 풀·스트리밍·재시도, Hikari 풀 | `performanceCheck` | +| JMH 벤치마크 | `src/platforms/messaging/messaging-kafka/src/jmh`, `src/platforms/messaging/messaging-testkit/src/jmh`, `src/adapter/outbound/httpclient/src/jmh` | 명시 실행 | + +## 6. 게이트를 믿을 조건 — 거짓 통과 막기 + +초록이라는 사실만으로 그 게이트가 무언가를 막았다는 뜻은 아니다. + +| 거짓 통과 모양 | 지금의 장치 | +| --- | --- | +| 어떤 workflow도 돌리지 않는 lane | `verifyStrictLaneStages --dry-run`(PR) | +| optional 빌드를 보지 않음 | optional 빌드도 같은 검사 | +| 실패를 막지 못하는 workflow 명령을 실행으로 셈(`\|\| true`, pipefail 없는 파이프, `if` 조건 등) | `AGENTS.md` 「Gradle 정책 권위」의 세는 규칙 | +| lane 정책을 바꿨는데 캐시가 옛 결과로 통과 | lane 정책 값을 Test 입력으로 | +| 게이트 밖에서 실패한 채 방치된 검사 | `testQualityCheck`(`mainCheck`) | +| 실서버 계약이 어느 게이트에도 없음 | lane을 단계에 연결 | +| 시간 단언을 끈 채 performance lane 실행 | convention이 단언을 켜고, 끄는 값이나 skip이 있으면 테스트 전에 실패(5절) | +| 캐시에서 가져온 결과를 지금 통과한 것으로 셈 | 기준 상태 확인과 시간·환경에 민감한 테스트는 그 태스크를 `--rerun`으로 다시 돌린다. `--rerun`은 바로 앞 태스크 하나에만 걸리므로 태스크마다 붙인다. 집계 태스크는 새 worktree와 `--no-build-cache`로 돌리고 FROM-CACHE 0을 보인다(3절) | +| 외부 이미지가 사라져 다른 lane 결과까지 가림 | 테스트 이미지를 `src/config/testing/container-images.properties` 한 곳에 digest로 고정, main 단계는 `--continue` | + +게이트 장치 자체를 바꿨으면 일부러 망가뜨린 입력으로 실패하는 것을 본다. 판독기를 바꿨으면 바꾸기 전후로 실제 workflow의 판정이 같은지 비교한다. diff --git a/docs/work/reference/review-criteria.md b/docs/work/reference/review-criteria.md new file mode 100644 index 00000000..4db104b6 --- /dev/null +++ b/docs/work/reference/review-criteria.md @@ -0,0 +1,300 @@ +# 리뷰 기준 + +리뷰와 수정에서 무엇을 결함으로 보고, 어떻게 판정하고, 어떤 형식으로 적는지 정한다. [improve.md](../improve.md)가 필요할 때 이 문서의 절을 가리킨다. 지난 리뷰에서 실제로 나온 예는 [evidence.md](../evidence.md) 「리뷰 기준의 예」에 있다. + +공용 리뷰 가이드는 이 repo 밖에 있다: design-docs `conventions/template-maturity-review-guide.md`. 아래 「가이드 N절」은 그 문서의 절이다. 이 문서는 가이드 없이도 판정할 수 있게 썼다. 일반 설명이 더 필요할 때만 가이드를 읽는다. + +## 1. 결함이란 + +리뷰는 **약속과 실제 동작이 다른 곳**을 찾는다. 약속은 코드 이름, Javadoc, 문서, 레지스트리, 테스트 이름, 게이트가 한 것이다. 약속을 어긴 증거가 있으면 결함이고, 없으면 개선 제안이다. + +| 결함의 모양 | 증거 | +| --- | --- | +| 이름·Javadoc·문서가 말한 동작과 실제 동작이 다르다 | 코드 경로 또는 실행 결과 | +| `AGENTS.md` HARD-STOP을 어긴다 | 의존 방향 게이트, ArchUnit, 코드 | +| 같은 규칙·값·표가 두 곳 이상에 있고, 서로 다르거나 같게 지키는 장치가 없다 | 두 위치와 차이 | +| 테스트나 게이트가 통과하지만 막겠다고 한 것을 막지 못한다 | 변이 실험, 실행 그래프 대조 | +| 운영자·개발자에게 틀린 조치를 시키는 문서 | 문서대로 실행한 결과 | +| 위험한 동작이 기본값·설정 뒤에 숨어 있다 | 기본값과 그 효과 | + +**개선 제안**은 계약 위반 없이 이해나 비용을 줄일 여지다. 현재 선택과 대안을 비교해 적는다(가이드 41절). 받으면 고치고, 받지 않으면 이유를 결정으로 남긴다. 기록만 하고 열어 두지 않는다. + +다음 말은 결함 근거가 아니다. + +| 근거가 아닌 말 | 결함으로 적으려면 | +| --- | --- | +| "추상화가 많다" | 어느 wrapper가 무엇을 보호하지 않는지, 지우면 무엇이 유지되는지 | +| "운영 준비가 안 됐다" | 어떤 절차를 어떤 버전에서 실행한 증거가 없는지 | +| "업계 표준이 아니다" | 이 repo의 어느 계약을 어기는지 | + +## 2. 발견의 성격 + +| 성격 | 뜻 | +| --- | --- | +| 확인된 결함 | 현재 커밋의 코드·실행으로 계약 위반을 보였다. 정적 증거만으로도 확정할 수 있다 | +| 구조적 위험 | 인과 경로는 있으나 영향 확인이 남았다. 예: 다중 인스턴스 경쟁을 코드 경로로만 봤다 | +| 미검증 | 이 환경에서 확인할 수 없다. 예: 실제 CI runner 실행 | +| 개선 제안 | 1절 | + +## 3. 심각도 + +심각도 체계는 둘이다. 리뷰 종류로 고른다. + +**전체 리뷰 — Critical / High / Medium / Low, 우선순위 P0~P3** (가이드 35.2·35.3절) + +| 등급 | 이 repo에서 | +| --- | --- | +| Critical | 인증 없이 민감정보 접근, 실제 데이터의 비가역 대량 손상 | +| High | 지원 조건에서 업무 중복 실행, 결과 불명 작업의 재실행, 기본 조합에서 보안 검사가 꺼짐 | +| Medium | 피해가 제한되거나 변경 비용을 반복해서 올림 | +| Low | 가독성·편의, 제한된 문서 불일치 | + +우선순위는 고치는 순서다. P1은 해당 용도 도입 전 해결, P2는 계획적 개선, P3는 선택이다. + +**확인 리뷰 — Critical / Important / Minor** (`superpowers:requesting-code-review` 리뷰어 지침의 체계) + +| 등급 | 정의 | +| --- | --- | +| Critical | 전체 리뷰의 Critical과 같다 | +| Important | 현실적 조건에서 틀린 동작·보안·데이터·공개 계약, 또는 운영자에게 틀린 조치를 시키는 문서 | +| Minor | 그 밖의 결함. 예: 거짓 실패 쪽 검사, 좁은 조건의 불일치, 문구 | + +확인 리뷰 발견에는 "이번 수정이 만들었나 / 이전부터 있었나"를 적는다. 이번 수정이 만든 것은 회귀로 따로 센다. + +**심각도가 정하지 않는 것** + +- 고칠지 말지. 이 repo는 모든 발견을 고치거나 결정으로 닫는다([improve.md](../improve.md) 4.5절). 심각도는 고치는 순서와, 맡긴 쪽이 코드에서 다시 확인할 범위(High·Important 이상)만 정한다. +- 건수. 한 결함이 여러 관점에 걸치면 항목 하나에 관점 번호를 모두 붙인다. 두 영역이 같은 결함을 적으면 색인에서 합친다. + +## 4. 증거 수준 E0~E4 (가이드 35.5절) + +| 수준 | 이 repo의 증거 | 주장할 수 없는 것 | +| --- | --- | --- | +| E0 설명·주장 | README, `CLAUDE.md`, Javadoc, 리뷰 문서의 이전 실행 기록, 묶음 보고의 "통과" | 현재 커밋의 동작 | +| E1 정적 확인 | 현재 커밋의 코드·설정·`build.gradle`·workflow를 `file:line`으로 읽음, `--dry-run` 그래프 | 실행 결과 | +| E2 테스트 실행 | 이름을 댄 테스트, leaf `check`, `ci`가 현재 커밋에서 통과(명령, rc, 테스트 수) | 실 vendor, 부하, 장애 | +| E3 통합·실험 | Testcontainers 실 PostgreSQL·Redis·Kafka·MinIO lane, `java -jar`·compose 실제 기동, 부하·장애 주입·동시 요청 실험 | 운영 환경, 운영 기간 | +| E4 운영 관찰 | 이 템플릿에는 없다 | — | + +- 이전 라운드의 실행 결과는 현재 증거가 아니다. 바뀐 커밋에서 다시 돌린다. +- 묶음 보고의 "통과"는 E0다. 맡긴 쪽은 보고를 diff와 실행 로그에 대조한다. +- build cache로 통과한 실행은 그렇다고 적는다. 실행 시간이 짧으면 캐시 재사용인지 확인한다. +- 발견마다 증거 수준을 적는다. 섞이면 나눠 적는다. 예: "E3 — 명령 9·10, 잠금 동작은 E1". + +## 5. 통제 수준 M0~M4 (가이드 35.4절) + +| 수준 | 뜻 | 이 repo의 예 | +| --- | --- | --- | +| M0 | 지킬 수단이 없다 | — | +| M1 | 적혀만 있다 | "하지 마라"가 주석·문서에만 있다 | +| M2 | 구현되어 있다 | 코드 경로에 규칙이 있고 검사는 없다 | +| M3 | 자동 검증이 위반을 잡는다 | ArchUnit(`src/app-bootstrap/src/architectureTest/`), 공유 계약 테스트, `verifyStrictLaneStages` | +| M4 | 경계에서 강제한다 | Gradle 의존 방향 게이트(`verifyCleanArchitectureDependencies`), DB 유일 제약, 기동 실패 rule | + +- 확인하지 못한 것은 M0가 아니라 "미확인"이다. +- 위반하면 데이터·권한이 깨지는 규칙이 M1이면 결함으로 적는다. + +## 6. 28개 관점 — 이 repo에서 볼 곳 + +관점의 일반 설명은 가이드 1~28절이다. 판정 기호: O 충족 · P 부분 · X 미충족 · ? 미검증 · - 적용 제외 · > 다른 영역. 종합은 평균하지 않는다. 한 영역이라도 X면 X다. + +| # | 관점 | 볼 곳 | 이런 증거면 결함 | +| --- | --- | --- | --- | +| 1 | 코드 성숙도 | 바뀐 클래스와 호출자, 예외 경로 | 이름·Javadoc과 다른 동작, 항상 참·거짓인 조건 | +| 2 | 구조적 성숙도 | registry `allowed_dependencies`, ArchUnit, leaf `CLAUDE.md` | HARD-STOP 위반, registry 밖 leaf 디렉터리, 템플릿 패키지가 기능 패키지를 import | +| 3 | 변경 용이성 | 기능 하나를 더하거나 뺄 때 고칠 파일, `scripts/new-feature.sh` 왕복 | 같은 규칙을 여러 곳에서 바꿔야 함 | +| 4 | 인지 부하 | 따라 할 예시 수, 같은 질문에 답하는 문서 수 | 예시·규칙이 여러 갈래이고 고르는 기준이 없음 | +| 5 | 위험 가시성 | 기본값, 설정 검증, 기동 rule, 프로필 허용 목록 | 위험이 기본값 뒤에 숨음, 레지스트리 `required`인데 코드는 빈 값 허용 | +| 6 | 실패 성숙도 | 예외 분류, `retryable`, 결과 불명 | 결과 불명을 확실함으로, 재시도 가능을 확정 실패로 기록 | +| 7 | 운영 성숙도 | `docs/runbooks/`, `docs/registries/metrics.yaml`, 종료 순서 | runbook이 틀린 조치를 시킴, 레지스트리 지표를 아무 코드도 내보내지 않음 | +| 8 | 디버깅 가능성 | `ServerFailureLog`, correlation id, 오류 코드 | 서버 실패를 남기지 않음, 원인이 다른 실패를 같은 코드로 | +| 9 | 유지보수 성숙도 | 복사본, 죽은 코드, 낡은 주석 | 갈라진 복사본, 현재 동작과 다른 주석·문서 | +| 10 | 테스트 성숙도 | 7절 | 이름의 성질을 단언하지 않음, 변이 생존, 계약 밖 fake | +| 11 | 데이터 성숙도 | 마이그레이션 스트림, 유일 제약, `@Version`, 잠금 시간 제한 | 중복 규칙에 DB 제약 없음, 적용된 마이그레이션 수정, `lock_timeout` 없는 강한 잠금 | +| 12 | 동시성 성숙도 | claim·lease, `SKIP LOCKED`, 트랜잭션 경계 | 트랜잭션 없는 `SKIP LOCKED`, lease 없는 claim | +| 13 | 확장성 | 연결·구독·동시 호출·본문 크기 상한 | 상한이 없거나 코드에 드러나지 않음 | +| 14 | 성능 성숙도 | 8절 | 데이터 수에 비례하는 SQL 수(N+1), 순차 스캔 | +| 15 | 보안 성숙도 | 인증·인가 체인, `docs/security/public-paths-snapshot.txt`, `docs/registries/secrets-classification.yaml`, 로그 | 기본으로 꺼진 검증, 권한 검사 없는 경로, 로그로 새는 입력값 | +| 16 | 의존성 성숙도 | `src/gradle/libs.versions.toml`, lockfile, `src/config/testing/container-images.properties` | 사라진 외부 이미지, 운영 jar의 테스트용 드라이버 | +| 17 | API·계약 성숙도 | `docs/web/http-contract.md`, `docs/registries/error-codes.yaml`, `docs/architecture/*-api-surface.txt`, 짝 프론트 계약 | 코드·문서·짝 계약이 서로 다름 | +| 18 | 배포 성숙도 | `src/Dockerfile`, compose, `release.yml` | 빌드되지 않는 Dockerfile, relay를 모르는 종료 순서 | +| 19 | 설정 성숙도 | `StrictSettingsBinder`, `docs/registries/env-keys.yaml`, `config/module-defaults/<모듈>.yml`, `verifyEnvKeys` | 바인딩되지만 동작하지 않는 키, 한 설정을 두 곳에서 읽음 | +| 20 | 개발자 경험 | `scripts/new-feature.sh`, `docs/manual/`, 게이트 시간 | 매뉴얼·생성 명령대로 하면 게이트를 통과하지 못함 | +| 21 | Guardrail 성숙도 | ArchUnit, `verifyStrictLaneStages`, 기동 rule, 정적 분석 단계 | 거짓으로 통과하는 게이트, 어떤 단계도 돌리지 않는 검사 | +| 22 | 추상화 성숙도 | 포트·SPI가 보호하는 것 | adapter가 정책을 소유, 역할 없는 단계 | +| 23 | 일관성 | 같은 역할의 이름·모양·규칙 | 같은 개념이 여러 벌 | +| 24 | 네이밍·의미 | `src/application-core/CLAUDE.md` 「Naming convention」, `NamingConventionTest` | 이름과 내용이 다름 | +| 25 | 조직 확장성 | 파생 서비스가 upstream을 받을 때 겹치는 곳 | 기능 패키지가 템플릿 패키지와 섞임 | +| 26 | Ownership | leaf마다 가까운 `CLAUDE.md`·README | 안내 문서 없음, 패키지가 평평해 소유가 안 보임 | +| 27 | 삭제 가능성 | capability `runtimeOnly` 한 줄 제거 | 한 줄 지워도 흔적이 남음, bootstrap이 capability 이름을 앎 | +| 28 | 회복 가능성 | runbook SQL, DEAD·park, ledger 회수 | 영구히 막히는 key, 복구가 행마다 수작업 | + +**따라갈 시나리오** (가이드 31절). 전체 리뷰는 시나리오마다 요청 하나를 끝까지 따라가며 입력 신뢰 수준, 권한 판단 위치, 규칙 소유자, 트랜잭션 시작과 끝, 외부 부작용, 오류 변환을 적는다. 해당 기능이 없으면 적용 제외 사유를 한 줄 적는다. + +| 시나리오 | 따라갈 경로 | +| --- | --- | +| 정상 쓰기 요청 | 생성 명령으로 만든 기능, durable operation `POST /operations` | +| 중복·동시 요청 | 같은 호출자가 같은 작업을 동시에 `POST /operations`(payload fingerprint로 하나만 받는다), 멱등 키(`docs/manual/05-idempotency.md`) | +| 외부 응답 지연·유실 | httpclient 시간 예산·breaker, 알림 발송 attempt | +| DB 오류·경쟁 | `PersistenceExceptionTranslator`, `@Version`, 트랜잭션 마감 | +| 메시지 중복·역순 | outbox relay, inbox 재전달, aggregate 순서 번호 | +| 신·구 버전 공존 | 마이그레이션 잠금, 배포 중 섞인 인스턴스 | +| 여러 서버의 작업 실행 | 알림 정산 job claim, gRPC ledger claim | +| 다른 사용자 리소스 접근 | 파일 서버 소유자 검사, durable operation 소유자·tenant 검사 | +| 큰 입력·목록 조회 | 파일 서버 업로드 크기 한도, GraphQL 복잡도, JSON 아닌 본문 | +| 종료·재시작 | relay·platform 종료 순서, 종료 시간 예산 | +| 선택 어댑터 제거 | `src/app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄 제거 | + +## 7. 테스트가 증명해야 하는 것 + +정본: 테스트 작성 규칙은 `AGENTS.md` 「테스트 전략」, 테스트 분류·배치·source set은 `docs/testing/TESTING_STRATEGY.md`(기계 기준 `TestLaneCategory`), 새 기능의 테스트 배치는 `docs/manual/08-testing.md`다. + +| 점검 | 결함 모양 | +| --- | --- | +| 이름이 말한 성질을 단언하나 | 이름은 "X를 남기지 않는다"인데 준비가 다른 예외를 넣는다 | +| 부재 단언이 null과 "키 없음"을 구분하나 | `doesNotExist`가 null 필드도 통과 | +| 지키려는 코드를 지우면 실패하나(변이) | 검사를 지워도 전부 통과 | +| 시간 제한 대기의 반환값을 단언하나 | `CountDownLatch.await(timeout)` 결과를 버려 시간 초과에도 다음 단계로 감 | +| skip이 0이거나 설계 이유가 있나 | 계약 케이스가 조용히 skip | +| 규칙 테스트가 위반·허용 fixture를 둘 다 가지나 | 위반 fixture만 있어 거짓 양성을 못 봄 | +| `// when`이 하나인가 | 두 동작을 한 테스트가 봄 | +| 테스트 코드도 정적 분석을 통과하나 | 게이트 밖에서 실패한 채 방치 | +| 타이밍에 기대지 않나 | 부하가 높으면 실패하는 "스레드 없음" 단언 | + +fake와 공유 계약: 포트마다 hand-rolled fake 하나를 포트 소유 leaf의 `testFixtures`에 두고, fake와 실제 adapter가 같은 추상 계약(`XxxContract`)을 상속한다. 계약 밖 fake, 소비자 없는 fake, 계약과 겹친 adapter 손 사본 테스트는 만들지 않는다. fake 동작을 바꾸면 계약 케이스를 같이 바꾼다. 포트를 더하거나 계약을 옮기면 `docs/testing/TESTING_STRATEGY.md`의 현황표를 고친다. + +lane: 새 lane은 반드시 어떤 단계에 속한다(`verifyStrictLaneStages --dry-run`). 반드시 돌아야 하는 테스트는 `requires(클래스)` + `rejectSkipped`로 이름을 박는다. lane 정책 값은 Test 입력으로 선언한다. 저장소 파일을 읽는 테스트는 태그를 단다(문서와 대조하면 `document-contract`, 빌드 스크립트·workflow·compose를 읽으면 `repository-contract`). + +RED가 증거가 되려면: 실패 메시지가 그 결함을 말한다. 머신에 따라 통과하지 않는다. 실 vendor가 필요한 결함은 실 vendor에서 본다(단위 테스트로 대신했으면 그렇게 적는다). 기록은 테스트 이름과 실패 수로 쓴다. + +## 8. 성능 측정 + +이 템플릿에는 지연·처리량 목표가 없다. 그래서 요청당 비용(SQL 수, 지연, 처리량, CPU)과 그 비용이 데이터 수에 비례해 늘어나는지로 판정한다. + +| 지표 | 재는 법 | 결함 신호 | +| --- | --- | --- | +| 아티팩트 | bootJar 크기, `BOOT-INF/lib` 목록 | 운영 jar에 테스트용·중복 라이브러리 | +| 기동 | `Started … in`, 기동 3초 뒤 RSS·heap, 빈 수, 스레드 수 | 빈 수에 비해 긴 공백 한 곳 | +| 요청당 SQL 수 | PostgreSQL `log_statement='all'`로 요청 하나 전후의 문장 수 | 페이지 크기에 비례(N+1) | +| 지연·처리량 | 닫힌 루프 부하, p50·p95·p99·rps | 목록 처리량이 SQL 수 비율만큼 떨어짐 | +| 요청당 CPU | JFR `settings=profile`, 상위 프레임 | 한 라이브러리가 CPU의 큰 몫 | +| 데이터 증가 | 같은 요청을 행 수를 늘려 반복 | 행 수에 비례해 느려짐 | +| 게이트 시간 | 게이트별 rc·초, 테스트 결과 XML 합계 | 바뀐 것이 없는데 매번 다시 도는 lane | + +측정 조건(전후가 같아야 비교할 수 있다): + +- 머신: 다른 빌드가 돌지 않는다. 측정 직전 1분 load average를 회차마다 적는다. 15를 넘은 회차는 비교에 쓰지 않는다. +- JVM: 옵션을 고정하고 적는다(예: `-Xmx1g -XX:+ExitOnOutOfMemoryError`). +- DB: 자원을 제한한 컨테이너(예: `--cpus 4 --memory 1g`), 튜닝 없음. +- 데이터: 행 수를 정해 적는다. 측정 중 늘어나는 테이블은 행 수를 함께 적는다. +- 부하: 닫힌 루프 N 스레드, 앞 20%는 워밍업으로 버린다. 생성기가 같은 호스트면 한계로 적는다. +- 반복: 3회, 중앙값. 튀는 회차는 이유와 함께 빼고 적는다. +- 설정만 바꾼 실험으로 원인을 먼저 확인한다(코드는 그대로, 시스템 프로퍼티 하나만). +- 측정은 E3다. "운영에서 N배 빨라진다"고 쓰지 않는다. 꼬리 지연의 원인을 확인하지 않았으면 미검증으로 적는다. + +최적화를 고르는 순서는 비용이 작은 것부터다: 설정 → DB(인덱스, 유일 제약, 쿼리 모양) → 매핑·쿼리 코드(N+1, 불필요한 컬렉션 재작성) → 구조(캐시, 비동기, 새 인프라). 캐시를 넣으면 무효화와 경합을 함께 검증한다. 고친 비용은 SQL 수처럼 머신과 무관한 숫자로 먼저 고정한다. + +## 9. 구조 기준과 leaf 변경 체크리스트 + +- 모듈 구조는 디렉터리가 아니라 registry가 정한다. 폴더를 바꾸는 일은 registry를 바꾸는 일이다. +- 문서는 leaf 목록·개수·leaf별 명령을 적지 않는다. leaf 명령은 registry의 `gradle_path`에서 만든다. +- 새 업무 기능은 계층 leaf 안의 패키지가 기본이다(`docs/manual/03-placement.md`). +- 템플릿 패키지 목록은 `src/application-core/CLAUDE.md` 「Package ownership」 표 하나가 정본이다. 템플릿에 패키지를 더하면 같은 변경에서 표에 넣는다. +- capability는 자기 `AutoConfiguration.imports`로 켜진다. `app-bootstrap`은 capability 이름·스위치 목록·scan 정규식을 갖지 않는다. +- vendored family(`messaging:*`, 같은 방식의 `grpc:*`)는 `domain-core`·`application-core`·`shared-contract`에 의존하지 않는다. 그래서 남는 복사본은 이유를 family `CLAUDE.md`에 적고, 값이 같아야 하면 대조 테스트를 둔다. +- source set은 runtime·classpath·외부 인프라·JVM 옵션·실행 비용 중 하나가 다를 때만 나눈다. 공유 테스트 코드는 `src/testFixtures/java`다(`docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md`). +- 마이그레이션은 저장소마다 자기 디렉터리와 history table을 가진다. 번호는 스트림 안의 순번이다. 어딘가에 적용된 파일은 고치지 않는다(`src/adapter/outbound/persistence-jpa/src/test/resources/db/applied-migrations.sha256`이 해시를 고정한다). +- 문서 위치 규칙은 `docs/README.md`가 정본이다. + +leaf를 더하거나 옮기거나 지울 때 같은 변경에서 함께 바꾼다: + +- [ ] `src/config/architecture/modules.json`: ID, `source_path`, `gradle_path`, `allowed_dependencies` +- [ ] leaf `build.gradle`: `ca.java-library`·`ca.spring-library`·`ca.platform-module` 중 하나 +- [ ] lockfile(`verifyDependencyLocks`가 통과하게 다시 만든다) +- [ ] capability면 `src/app-bootstrap/build.gradle`의 `runtimeOnly` 한 줄과 자기 `AutoConfiguration.imports` +- [ ] leaf `CLAUDE.md`, capability면 README 세 가지(제공하는 것, 추가할 한 줄, 필요한 env 키) +- [ ] 템플릿 패키지를 더하거나 지우면 「Package ownership」 표 +- [ ] ArchUnit 규칙과 그 위반·허용 fixture +- [ ] 지운 leaf를 가리키던 문서·workflow·주석(grep으로 찾는다) +- [ ] 파생 서비스에 영향이 있으면 `docs/upgrade/`의 안내 행 + +검증은 [gates.md](gates.md) 2절의 "leaf 경계·의존·registry" 행이다. + +## 10. 리뷰 문서 양식 + +**위치**: 전체 리뷰는 `docs/reviews/-<종류>/README.md` + 영역 문서 `NN-<영역>.md`. 확인 리뷰는 그 폴더 아래 `roundN/NN-<영역>.md`, 영역마다 하나다. 한 리뷰어가 모든 영역을 봐도 영역마다 나눈다. 리뷰 문서는 리뷰 시점 기록이다. 수정 뒤에도 영역 문서를 고치지 않고 처리 결과는 README에 적는다. + +**전체 리뷰 README의 절** (가이드 36.5절 양식에 처리 현황·결정 기록을 더한 것): + +1. 사용 결정 — 용도별 사용 가능·조건부·보류와 막는 항목 +2. 차단 항목(High·P1) — 맡긴 쪽의 재확인 방법을 칸으로 +3. 확인된 강점 +4. 반복되는 원인 — [defect-patterns.md](defect-patterns.md) 번호를 붙인다 +5. 결정이 필요한 것 — 선택지, 권고, 승인자 +6. 미검증 — 무엇, 왜, 확인하려면 +7. 개선 순서 — 순서, 대상, 이유, 완료 기준 +8. 재검토 조건 +9. 리뷰 범위 — 기준 커밋, 게이트 결과 표, 영역 표 +10. 28개 관점 판정 +11. 발견 색인 — ID, 심각도, 우선순위, 한 줄 내용. 모든 ID를 이름으로 적는다 +12. 이후 라운드 — 처리 표, 합칠 때 생긴 충돌과 처리, 합친 뒤 게이트, 결정, 남은 것 + +**영역 문서**: 범위 → 지난 발견 재확인 → 새 발견 → 시나리오 추적 → 설계 선택 검토(가이드 41절) → 리팩터링 후보 → 28개 관점 판정표. + +**확인 리뷰 문서**: + +| 절 | 적을 것 | +| --- | --- | +| 범위 | pathspec, `git diff --stat` 결과, 함께 읽은 주변 코드, 수정 보고의 「새로 가정하는 것」·「정한 기본값」 | +| 불러온 스킬과 적용한 기준 | 스킬, 그 스킬의 기준, 그 기준으로 본 것 | +| 실행한 명령과 결과 | 명령, rc, 직전 1분 부하. 탐침이면 무엇을 단언했나(결함 동작 / 약속, [gates.md](gates.md) 2절 「탐침」) | +| 못 본 것 | 무엇과 이유 | +| 항목 재확인 | 고쳤다고 한 항목마다 닫힘 / 부분 / 안 닫힘 | +| 넘어온 항목 판정 | brief가 맡겼을 때만: 지난 라운드 Declined와 README 남은 항목마다 판정(결함 / 결함 아님 / 결정 필요)과 근거 | +| 결함 | `### · <심각도> · <한 줄 제목>` 아래 발견 필드 | +| Declined to judge | 판단하지 않은 것, 위치, 이유 | +| 결론 | Critical·Important·회귀 수, 결함 수와 "이번 수정 / 이전부터" 구분 | + +**확인 리뷰 라운드의 README 절**: 리뷰 폴더 README에 라운드마다 절 하나를 두고, 하위 절을 이 순서로 둔다. 앞의 다섯은 리뷰가 끝나면, 뒤의 셋은 수정과 합치기가 끝나면 쓴다. 누가 쓰는지는 [improve.md](../improve.md) 4.1절 7단계다. + +1. 결과 — 색인 표(ID, 심각도, 한 줄 내용, 이번 수정 / 이전부터, 증거, 결정이 필요한 질문) +2. 리뷰어 B와의 대응 — 독립 리뷰어 둘일 때만. `B-NN-MM` → 정본 ID, 겹침 비율 +3. 실행 — 리뷰어별 명령·결과·로그 위치 +4. 결정이 필요한 것 — 항목 · 선택지 · 권하는 안과 이유 · 정할 사람 +5. 넘어온 항목 판정 — 지난 라운드 남은 항목마다 판정과 위치 +6. 멈춤 기준 상태 — [improve.md](../improve.md) 4.5절 넷 +7. 처리 — 처리 표: 발견 · 상태 · 고친 커밋 · RED · 검증 · 정한 기본값. [improve.md](../improve.md) 8절 보고에서 옮긴다. brief가 다른 칸을 정하면 brief를 따른다 +8. 합친 트리와 게이트 — 병합 순서, 충돌과 처리, 라운드 끝 게이트 표([gates.md](gates.md) 4절), 못 돌린 것 + +수정 세션 보고의 「정한 기본값」은 7의 처리 표와 [decisions.md](decisions.md)(기본값 행)로, 「범위 밖에서 본 것」은 README 남은 항목(6의 넷째)으로 옮긴다. 옮긴 남은 항목은 다음 확인 리뷰가 brief를 받아 5에서 판정한다. + +**발견 하나의 필드** + +- 전체 리뷰: 가이드 36.3절 표 필드 전체(성격, 관련 관점, 근거, 발생 조건, 영향, 심각도, 확실성, 결정의 근거, 이해 비용, 최소 개선 방향, 대안 비교, 단순화의 보존 조건, 비용, 재검토 조건, 완료 기준, 검증 방법). 선택 비교가 필요 없는 단순 결함은 설계 선택 필드를 `적용 제외 — <이유 한 문장>`으로 둔다. +- 확인 리뷰: 위치(`file:line`, 문서·설정·코드를 나눠서), 무엇이 틀렸나(한 문장에 사실 하나), 발생 조건·영향, 테스트가 못 본 이유, 고치는 법(권장안·대안·RED 테스트 모양), 이번 수정 / 이전부터, 증거(E 수준과 명령 번호). + +**ID** + +- 라운드 안에서는 `NN-MM`(영역-순번)이다. 확인 리뷰는 라운드 접두어를 붙여 `RR-NN-MM`으로 쓴다(첫 재리뷰만 `` 없이). +- 라운드 밖(다른 문서, 커밋, 주석)에서는 리뷰 폴더 날짜의 월일을 붙인다: `MMDD/`(가이드 36.3절). +- 영역 번호 자리에 `NN` 같은 자리표시자를 남기지 않는다. 리뷰가 끝난 뒤 영역 접두어를 바꾸지 않는다. +- 영역 번호는 그 라운드 영역 표의 순번이다. 지난 라운드 번호와 맞추지 않아도 된다. 지난 라운드 영역 하나를 둘로 나누면 뒤에 새 번호를 잇고(04를 나누면 04·05), 「범위」 절에 지난 영역과의 대응을 적는다. +- 한 라운드의 ID는 리뷰 하나가 매긴다. 같은 범위를 두 리뷰가 따로 봤으면(독립 리뷰어 둘, [improve.md](../improve.md) 4.1절) brief가 정한 쪽이 정본이다. 다른 쪽은 임시 번호 `B-NN-MM`을 쓰고, 그 발견은 합칠 때 정본의 다음 번호로 새 ID를 받는다. 두 ID의 대응표를 README의 그 라운드 색인 절에 둔다. 다른 쪽 문서를 그대로 합치지 않는다(같은 ID가 다른 결함을 가리킨다). +- 두 리뷰가 같은 결함을 다르게 분류하면(심각도, 이번 수정 / 이전부터) 정본 리뷰어가 근거를 붙여 하나로 정하고, 다른 쪽 분류와 이유를 대응표에 적는다. +- ID는 리뷰 문서·brief·커밋에서 쓴다. 매뉴얼(`docs/work/`) 본문에는 쓰지 않는다. + +## 11. 판단을 적는 법 + +- 판단 발견(설계·구조·비용)은 반증할 수 있는 가정과 반론을 함께 적는다. "이 판단이 틀렸다면 어디서 드러나나"를 쓴다. +- 결정적 발견(컴파일 오류, 의존 위반, 비밀 노출, 실패한 테스트)은 규칙 → 증거 → 고치는 법 세 줄로 쓴다. 억지 반론을 만들지 않는다. +- 대안이 3~5개 있으면 그만큼 비교한다. 실제로 더 적으면 적게 쓴다. 의존 순서가 있는 변경은 의존 그래프 순서로 따진다. +- 인용 확인은 리뷰 수준에 따른다: `review-lite`는 확인하지 않는다, `review-standard`는 차단 발견의 인용을 확인한다, `audit-deep`·`regulated`는 결론에 쓰인 인용을 모두 확인한다. +- 리뷰 결과를 문서 파일로 남기는 경우: 위험이 높다, 차단 발견이 3건 이상이다, 아키텍처 결정이 있다, 요청자가 원한다, `regulated` 수준이다. 그 밖에는 짧은 결과 보고로 충분하다. + +## 12. 리뷰어가 하지 않는 것 + +- 코드를 고치지 않는다. 실험은 별도 worktree에서 하고 지운다. +- 이전 실행 결과를 현재 증거로 쓰지 않는다(4절). +- 같은 결함을 여러 번 세지 않는다(3절). +- 정한 결정을 결함으로 다시 올리지 않는다. 결정의 전제가 틀렸다는 새 증거가 있을 때만 근거와 함께 다시 연다([decisions.md](decisions.md) 1절). +- 범위 밖 결함을 버리지 않는다. 「Declined to judge」에 위치와 함께 적어 맡긴 쪽에 넘긴다. diff --git a/docs/work/research-design.md b/docs/work/research-design.md new file mode 100644 index 00000000..406489b5 --- /dev/null +++ b/docs/work/research-design.md @@ -0,0 +1,90 @@ +# 조사·설계 — 바꾸기 전에 대안을 비교하고 결정을 받는다 + +코드를 바꾸기 전에 무엇을 할지 정하는 일이다. 사고 순서(목적 → 선행 사례 → 방법 → 필요한 정보 → 격차 → 만들고 시험)의 정본은 design-docs `conventions/work-thinking-order.md`다. 이 playbook은 순서를 다시 쓰지 않고, 이 repo에서 어디를 보고 결과를 어디에 두는지만 정한다. + +## 1. 언제 쓰나 + +- 고치거나 만들기 전에 소유자 결정이 필요하다(공개 계약, 파생 서비스 동작, 보안 정책, 새 leaf, 되돌리기 비싼 선택). +- 리뷰가 "판단하지 않음"으로 남긴 항목을 어떻게 닫을지 정해야 한다. +- 큰 일의 1~5단계와 대안 비교를 소유자 검토용으로 만든다. +- 설계 메모 하나를 쓴다(예: 레지스트리의 칸 하나를 규범으로 둘지). +- 결정이 이미 [reference/decisions.md](reference/decisions.md)에 있으면 이 playbook이 아니다. 그 결정대로 [improve.md](improve.md)나 [new-feature.md](new-feature.md)로 간다. + +## 2. 받아야 할 것 + +- 정할 질문 한 문장과 누가 왜 묻는가(요청 원문). +- 크기와 결정할 사람. 큼이면 소유자 검토가 만들기 전에 있어야 한다. +- 산출물 위치(4절 6단계 기준과 다르면 brief를 따른다). +- 코드를 바꿔도 되는지. 기본은 바꾸지 않는다. + +## 3. 크기와 사고 순서 + +- 설계 메모 하나는 보통 중간이다: 선행 사례 2~3곳(내부 선례 포함), 대안 2~3개. 다루는 대상이 [README](README.md) 2절의 "파일 하나여도 큼" 표면(오류 코드 레지스트리 등)이어도 메모만 쓰고 바꾸지 않으면 중간이다. 큼은 그 메모를 적용하는 일이다(design-docs `conventions/work-thinking-order.md` 2.1절). +- 새 체계·아키텍처·공개 계약은 큼이다: 선행 사례 10~15곳, 대안 3~5개. 1~5단계 결과와 대안 비교를 소유자가 먼저 본다. +- 이 repo의 내부 선례를 찾는 곳: + - [reference/decisions.md](reference/decisions.md)와 그 출처 문서 + - `docs/reviews/`의 리뷰 README 「결정」 절과 영역 문서의 「Declined to judge」 + - `docs/adr/`(되돌리기 비싼 선택), `docs/design/`(설계서), `docs/history/plans/`(계획서) + - `git log --oneline -- <경로>`와 커밋 본문의 "고른 방법과 버린 대안" + - 가장 가까운 `src/**/CLAUDE.md`와 모듈 README +- 외부 선례: 쓰는 라이브러리의 공식 문서와 릴리스 노트(Spring Boot, Flyway, Hibernate 등), 같은 문제를 다룬 공개 저장소. 직접 쓴 글(1차)인지 정리한 글(2차)인지 표시한다. +- 스킬: `superpowers:brainstorming`, 결정 기록은 `documentation-and-adrs`, 공식 문서 확인은 `source-driven-development`. 큰 판단은 `doubt-driven-development`로 반론을 세운다. + +## 4. 절차 + +1. 목적을 한 문장으로 적고 성공 기준을 정한다. 요청 원문이 있으면 인용한다. +2. 이미 정한 것을 찾는다(3절의 내부 선례). 이미 정해져 있으면 멈추고 그 결정을 보고한다. +3. 현황을 확인한다. 주장마다 출처를 단다: `file:line`, 커밋, 명령 결과. 코드 읽기로 동작이 하나로 정해지지 않으면(분기, 동시성, 설정·외부 시스템에 따라 다름) 별도 worktree에서 탐침 테스트를 desktop으로 돌리고, 탐침 코드는 남기지 않는다. 분기 없는 경로이고 기존 테스트가 그 동작을 고정하면 탐침을 생략하고, 그 테스트 이름을 출처로 적는다. +4. 선행 사례 표를 만든다: 출처 · 1차/2차 · 그들이 한 것 · 실패와 비판 · 가져올 것. +5. 대안을 비교한다. 실제로 다른 대안 2~5개(크기에 맞게), 기준(효과, 비용, 되돌리기, 파생 서비스 영향, 기존 결정과 충돌), 권하는 안과 이유. 의존 순서가 있는 변경은 의존 그래프 순서로 따진다. 파생 서비스 영향은 파생 서비스 repo에서 바꿀 이름(키, 칸, 타입)을 `git grep`해 쓰는 곳을 센다. 소유자 환경의 파생 서비스 위치는 design-docs `conventions/delegation-loop.md` 11절이다. +6. 반증할 수 있는 가정을 적는다: "이 안이 틀렸다면 어디서 드러나나". 반론과 답도 적는다. +7. 산출물을 둔다. + - 이 repo에만 해당: 설계서 `docs/design/-<주제>-design.md`, 되돌리기 비싼 선택이면 `docs/adr/ADR-<영역>-<번호>-<제목>.md`(기존 번호를 잇는다). 둘 다 맨 위에 머리 블록을 단다(`docs/README.md`). + - 여러 repo나 소유자 운영에 걸침: design-docs. 템플릿 `docs/`는 파생 서비스로 복사되므로 로드맵·운영 설계는 여기에 두지 않는다. + - 짧은 설계 메모는 보고 본문으로 충분하다(brief가 파일을 요구하지 않으면). +8. 소유자 결정 목록을 쓴다: 항목 · 선택지 · 권하는 안과 이유 · 정할 사람. 한 번에 묻는다. +9. 멈추고 검토를 받는다. 승인을 받으면 승인 시각을 적는다. +10. 결정을 기록한다([reference/decisions.md](reference/decisions.md) 3절). 만들기는 [new-feature.md](new-feature.md)나 [improve.md](improve.md)로 넘긴다. + +## 5. 완료 기준 + +- 보고에 사고 순서 흔적이 있다. 크기에 맞는 단계가 있고, 생략한 단계는 이유가 한 줄 있다. +- 사실마다 출처(`file:line`, 커밋, 명령 결과)가 있다. 추정은 추정이라고 적었다. +- 대안 비교 표, 권하는 안, 반증할 수 있는 가정이 있다. +- 소유자 결정 목록이 있고, 질문을 보냈거나 승인 시각이 있다. +- brief가 허용하지 않았으면 코드가 바뀌지 않았다(`git diff --stat`에 문서만). + +## 6. 하지 말 것 + +- 소유자 검토 전에 만들지 않는다. 큰 일은 1~5단계와 대안 비교까지만 하고 멈춘다. +- 크기를 스스로 내리지 않는다. +- 이미 정한 결정을 다시 묻지 않는다. 다시 열 조건은 [reference/decisions.md](reference/decisions.md) 1절이다. +- "업계 표준이다", "추상화가 많다" 같은 말을 근거로 쓰지 않는다. 이 repo의 어느 계약·비용에 닿는지로 쓴다. +- 대안을 하나만 놓고 권하지 않는다. +- 탐침 코드를 제품 코드에 남기지 않는다. + +## 7. 막혔을 때 + +- 필요한 정보가 이 repo와 공개 자료에 없으면(운영 수치, 소유자의 계획) 그 칸을 "모름"으로 두고 질문 목록에 넣는다. +- 질문은 한 번에 모아 보낸다. 형식은 [README](README.md) 5절이다. 답이 올 때까지 그 결정에 기대는 단계만 멈춘다. + +## 8. 보고 형식 + +[README](README.md) 6절에 더해 적는다. + +```markdown +## 결론 (권하는 안 한 문장) +## 사고 순서 흔적 (크기: 중간) +1. 목적: 2. 선행 사례: 3. 방법: 4. 필요한 정보: 5. 격차: 6. 만들고 시험: +## 대안 비교 +| 대안 | 효과 | 비용 | 되돌리기 | 기존 결정과 충돌 | +## 반증할 수 있는 가정 / 반론과 답 +## 소유자가 정할 것 +| 항목 | 선택지 | 권하는 안과 이유 | 정할 사람 | +``` + +## 9. 자주 하는 실수 + +- 정리한 글(2차)을 원문처럼 인용한다. 원문을 찾아 확인하고 1차/2차를 표시한다. +- 지난 리뷰의 결정을 찾지 않아 같은 질문을 다시 한다. 결정 색인과 리뷰 README 「결정」 절부터 본다. +- 조사하다 바로 고친다. 고치는 일은 결정 뒤에 다른 playbook으로 한다. diff --git a/infra/fileserver/kubernetes/pvc-certification-job.yaml b/infra/fileserver/kubernetes/pvc-certification-job.yaml deleted file mode 100644 index 09a9ba38..00000000 --- a/infra/fileserver/kubernetes/pvc-certification-job.yaml +++ /dev/null @@ -1,127 +0,0 @@ -# Storage certification job. -# -# A PersistentVolumeClaim is not a filesystem contract. Whether an atomic rename, a same-file-store -# guarantee, or symlink refusal actually holds depends on the CSI driver, the StorageClass, the -# access mode, the backend, and the mount options — so this job records all five alongside the probe -# result. A certification without that tuple is not transferable to another cluster. -# -# The job writes a machine-readable result to the claim itself so the evidence lives with the volume -# it describes. -# -# kubectl apply -f infra/fileserver/kubernetes/pvc-certification-job.yaml -# kubectl logs job/fileserver-pvc-certification ---- -apiVersion: v1 -kind: PersistentVolumeClaim -metadata: - name: fileserver-certification - labels: - app.kubernetes.io/name: fileserver - app.kubernetes.io/component: certification -spec: - accessModes: - - ReadWriteOnce - resources: - requests: - storage: 1Gi - # Left unset on purpose: the certification is only meaningful for the class it actually ran on, - # so the operator names it explicitly rather than inheriting a cluster default. - storageClassName: "" ---- -apiVersion: batch/v1 -kind: Job -metadata: - name: fileserver-pvc-certification - labels: - app.kubernetes.io/name: fileserver - app.kubernetes.io/component: certification -spec: - backoffLimit: 0 - template: - metadata: - labels: - app.kubernetes.io/name: fileserver - app.kubernetes.io/component: certification - spec: - restartPolicy: Never - securityContext: - runAsNonRoot: true - runAsUser: 10001 - fsGroup: 10001 - containers: - - name: certify - image: eclipse-temurin:21-jdk - env: - - name: FILESERVER_STORAGE_ROOT - value: /var/lib/backend/files - - name: KUBERNETES_VERSION - valueFrom: - fieldRef: - fieldPath: metadata.annotations['certification.fileserver/kubernetes-version'] - - name: CSI_DRIVER - valueFrom: - fieldRef: - fieldPath: metadata.annotations['certification.fileserver/csi-driver'] - - name: STORAGE_CLASS - valueFrom: - fieldRef: - fieldPath: metadata.annotations['certification.fileserver/storage-class'] - - name: ACCESS_MODE - value: ReadWriteOnce - command: - - /bin/bash - - -c - - | - set -euo pipefail - ROOT="${FILESERVER_STORAGE_ROOT}" - mkdir -p "${ROOT}/staging" "${ROOT}/content" - - # Atomic rename within one file store is the property the publish path depends on. - echo probe > "${ROOT}/staging/probe" - if mv "${ROOT}/staging/probe" "${ROOT}/content/probe" 2>/dev/null; then - ATOMIC_MOVE=true - else - ATOMIC_MOVE=false - fi - - # Same device means a rename is a metadata operation rather than a copy. - STAGING_DEV=$(stat -c %d "${ROOT}/staging") - CONTENT_DEV=$(stat -c %d "${ROOT}/content") - [ "${STAGING_DEV}" = "${CONTENT_DEV}" ] && SAME_STORE=true || SAME_STORE=false - - # O_EXCL create is what makes a publish create-only rather than an overwrite. - if (set -o noclobber; echo x > "${ROOT}/content/excl") 2>/dev/null; then - ATOMIC_CREATE=true - else - ATOMIC_CREATE=false - fi - - cat > "${ROOT}/certification-result.json" </dev/null 2>&1"] - interval: 5s - timeout: 10s - retries: 20 diff --git a/infra/messaging/postgres/docker-compose.yml b/infra/messaging/postgres/docker-compose.yml deleted file mode 100644 index 05bc5435..00000000 --- a/infra/messaging/postgres/docker-compose.yml +++ /dev/null @@ -1,27 +0,0 @@ -# PostgreSQL 16 for the Outbox and Inbox. -# -# logical replication stays enabled so a CDC relay can be tried against the same database the polling -# relay uses. The repository ships no CDC relay (the Debezium mapping was removed on 2026-09-25). -services: - postgres: - image: postgres:16-alpine - container_name: messaging-postgres - ports: - - "5432:5432" - environment: - POSTGRES_DB: messaging - POSTGRES_USER: messaging - POSTGRES_PASSWORD: messaging - command: - - "postgres" - - "-c" - - "wal_level=logical" - - "-c" - - "max_replication_slots=4" - - "-c" - - "max_wal_senders=4" - healthcheck: - test: ["CMD-SHELL", "pg_isready -U messaging -d messaging"] - interval: 5s - timeout: 5s - retries: 20 diff --git a/infra/messaging/tls/README.md b/infra/messaging/tls/README.md deleted file mode 100644 index e57113c6..00000000 --- a/infra/messaging/tls/README.md +++ /dev/null @@ -1,35 +0,0 @@ -# TLS material - -Production profiles require TLS **and** hostname verification; `MessageSecurityValidator` fails -startup without either. - -No key material is committed here, and none should be. Certificates are issued by the deployment's -own PKI and mounted at runtime; a keystore in a repository is a credential in a repository, and -rotating it means a commit. - -## Local development - -The compose files in the sibling directories run plaintext listeners deliberately. They exist to -reproduce the *messaging* semantics locally, not the transport security, and running them with -`production: false` in the destination profile is what keeps the validator honest — a profile marked -`production: true` against a plaintext broker must fail, and that is a test, not an inconvenience. - -## Generating a local CA for TLS testing - -```bash -openssl req -x509 -newkey rsa:4096 -sha256 -days 30 -nodes \ - -keyout ca.key -out ca.crt -subj "/CN=messaging-local-ca" - -openssl req -newkey rsa:4096 -nodes -keyout broker.key -out broker.csr \ - -subj "/CN=localhost" - -openssl x509 -req -in broker.csr -CA ca.crt -CAkey ca.key -CAcreateserial \ - -out broker.crt -days 30 -sha256 \ - -extfile <(printf "subjectAltName=DNS:localhost,IP:127.0.0.1") -``` - -The `subjectAltName` is not optional. Hostname verification is required in production profiles, and -a certificate without a SAN fails it — which is the correct outcome, not something to work around by -disabling the check. - -Generated files are ignored by `.gitignore` in this directory. diff --git a/infra/messaging/toxiproxy/docker-compose.yml b/infra/messaging/toxiproxy/docker-compose.yml deleted file mode 100644 index e271af36..00000000 --- a/infra/messaging/toxiproxy/docker-compose.yml +++ /dev/null @@ -1,18 +0,0 @@ -# Toxiproxy, for the failures that matter most. -# -# The platform's hardest guarantee is that a lost confirmation is reported as AMBIGUOUS rather than -# guessed. A healthy broker will not lose one on request, so the chaos suite puts a proxy in front of -# it and severs the connection after the record was accepted but before the acknowledgement arrives. -services: - toxiproxy: - image: ghcr.io/shopify/toxiproxy:2.12.0 - container_name: messaging-toxiproxy - ports: - - "8474:8474" # control API - - "19092:19092" # proxied Kafka - - "15433:15433" # proxied PostgreSQL - healthcheck: - test: ["CMD", "/toxiproxy-cli", "list"] - interval: 5s - timeout: 5s - retries: 20 diff --git a/infra/notification/toxiproxy/docker-compose.yml b/infra/notification/toxiproxy/docker-compose.yml deleted file mode 100644 index ac103cad..00000000 --- a/infra/notification/toxiproxy/docker-compose.yml +++ /dev/null @@ -1,94 +0,0 @@ -# Toxiproxy fault injection for the notification delivery platform. -# -# Scope, stated up front: this is the *nightly and release* fault suite, not the PR gate. The PR -# suite runs against a loopback socket harness in-process — deterministic, no Docker, no provider -# sandbox — because a gate that needs infrastructure is a gate people learn to skip. What lives -# here are the faults that harness cannot produce: real TCP behaviour under latency, bandwidth -# starvation, and connection resets at a point the JVM's own socket layer decides. -# -# Usage: -# docker compose -f infra/notification/toxiproxy/docker-compose.yml up -d -# ./gradlew :adapter:outbound:notification:test -Dnotification.faultProxy=http://127.0.0.1:8474 -# -# The proxies below front *stub* upstreams, never a provider's real API. Pointing a toxic proxy at -# a live provider sends real notifications to real people from a test run, and adds a rate-limit -# incident on an account the team shares. -services: - toxiproxy: - image: ghcr.io/shopify/toxiproxy:2.11.0 - container_name: notification-toxiproxy - ports: - - "8474:8474" # control API - - "18081:18081" # -> ses-stub - - "18082:18082" # -> twilio-stub - - "18083:18083" # -> push-stub (APNs / FCM / Web Push) - networks: [notification-fault] - healthcheck: - test: ["CMD", "/toxiproxy-cli", "list"] - interval: 5s - timeout: 3s - retries: 10 - - # Deterministic upstreams. Each returns the provider's success shape and nothing else; the - # interesting behaviour is injected by the proxy in front of it, not by the stub. - ses-stub: - image: mendhak/http-https-echo:35 - environment: - HTTP_PORT: "8080" - networks: [notification-fault] - - twilio-stub: - image: mendhak/http-https-echo:35 - environment: - HTTP_PORT: "8080" - networks: [notification-fault] - - push-stub: - image: mendhak/http-https-echo:35 - environment: - HTTP_PORT: "8080" - networks: [notification-fault] - - # Creates the proxies and the toxics once the control API is up. Kept as a job rather than a - # README step so the topology is reproducible and reviewable rather than typed from memory. - provision: - image: ghcr.io/shopify/toxiproxy:2.11.0 - depends_on: - toxiproxy: - condition: service_healthy - networks: [notification-fault] - entrypoint: - - /bin/sh - - -c - - | - set -e - CLI="/toxiproxy-cli -h toxiproxy:8474" - $$CLI create -l 0.0.0.0:18081 -u ses-stub:8080 ses - $$CLI create -l 0.0.0.0:18082 -u twilio-stub:8080 twilio - $$CLI create -l 0.0.0.0:18083 -u push-stub:8080 push - - # Response loss after the request was committed: the provider received and acted on the - # message, and the answer never came back. This is the AMBIGUOUS case, and it is the one - # fault no provider's documentation describes. - $$CLI toxic add -t timeout -a timeout=0 -n response_loss --downstream --toxicity 0 ses - $$CLI toxic add -t timeout -a timeout=0 -n response_loss --downstream --toxicity 0 twilio - $$CLI toxic add -t timeout -a timeout=0 -n response_loss --downstream --toxicity 0 push - - # Latency past the adapter's own timeout, to prove the timeout is the adapter's decision - # rather than the socket's. - $$CLI toxic add -t latency -a latency=8000 -n slow --toxicity 0 ses - $$CLI toxic add -t latency -a latency=8000 -n slow --toxicity 0 twilio - $$CLI toxic add -t latency -a latency=8000 -n slow --toxicity 0 push - - # Partial write: the connection dies mid-body. Distinct from response loss, because the - # provider never got a complete request and the attempt is genuinely retryable. - $$CLI toxic add -t limit_data -a bytes=64 -n partial_write --upstream --toxicity 0 ses - $$CLI toxic add -t limit_data -a bytes=64 -n partial_write --upstream --toxicity 0 twilio - $$CLI toxic add -t limit_data -a bytes=64 -n partial_write --upstream --toxicity 0 push - - echo "proxies ready; toxics are registered at toxicity=0 and enabled per test" - $$CLI list - -networks: - notification-fault: - driver: bridge diff --git a/scripts/bootstrap-local.sh b/scripts/bootstrap-local.sh index 139b27c8..674f39fa 100755 --- a/scripts/bootstrap-local.sh +++ b/scripts/bootstrap-local.sh @@ -1,31 +1,33 @@ #!/usr/bin/env bash # The ordered local start-up: compile, Docker preflight, dependency wait, migrate-and-start, smoke. # -# scripts/bootstrap-local.sh # the `local` overlay (docker-compose.local.yml) -# scripts/bootstrap-local.sh # docker-compose..yml merged onto docker-compose.yml +# scripts/bootstrap-local.sh +# +# It runs the development stack, compose.yaml at the repository root: the application container in +# the `local` runtime and the PostgreSQL service of the `jpa` profile. Naming a service on the +# command line switches its profile on, so no --profile is needed here. # # This was the build-logic `ca.developer-bootstrap` plugin (`./gradlew bootstrap`). Starting # containers and probing an HTTP endpoint is not a build rule, so it is a script now (review # 2026-09-24 BUILD-O3-5). The four stages and their order are unchanged: the next stage starts only # when the previous one succeeded, and the app stage waits for startup Flyway through the compose # healthcheck before the smoke probe runs. +# +# Until 2026-11-07 it merged docker-compose.yml with docker-compose.local.yml and asked for a `db` +# service neither file had defined since the database moved to a third file, so the documented +# first run stopped at stage 2. set -euo pipefail readonly repository_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -readonly profile="${1:-local}" -readonly base_compose="${repository_dir}/docker-compose.yml" -readonly overlay="${repository_dir}/docker-compose.${profile}.yml" readonly health_endpoint="${BOOTSTRAP_HEALTH_ENDPOINT:-http://localhost:8080/api/healthcheck}" readonly smoke_timeout_seconds="${BOOTSTRAP_SMOKE_TIMEOUT_SECONDS:-60}" -if [[ ! -f "${overlay}" ]]; then - available="$(cd "${repository_dir}" && ls docker-compose.*.yml 2>/dev/null \ - | sed -e 's/^docker-compose\.//' -e 's/\.yml$//' | tr '\n' ' ')" - echo "bootstrap: '${profile}' names no overlay; expected $(basename "${overlay}") beside" \ - "docker-compose.yml. Available: ${available:-none}" >&2 +if [[ $# -gt 0 ]]; then + echo "bootstrap: takes no arguments; the stack is compose.yaml. Backing services by profile:" \ + "docker compose --profile up -d --wait (see the head of compose.yaml)" >&2 exit 64 fi -compose=(docker compose -f "${base_compose}" -f "${overlay}") +compose=(docker compose -f "${repository_dir}/compose.yaml") echo "bootstrap 1/4: compiling the default application composition" (cd "${repository_dir}/src" && ./gradlew :app-bootstrap:compileTestJava --console=plain) @@ -35,7 +37,7 @@ if ! docker info >/dev/null 2>&1; then exit 69 fi -echo "bootstrap 2/4: starting the ${profile} PostgreSQL dependency and waiting for readiness" +echo "bootstrap 2/4: starting the PostgreSQL dependency and waiting for readiness" "${compose[@]}" up -d --wait db echo "bootstrap 3/4: building and starting the app; startup Flyway finishes before health is ready" diff --git a/scripts/check-docs-exceptions.txt b/scripts/check-docs-exceptions.txt new file mode 100644 index 00000000..1bff4f87 --- /dev/null +++ b/scripts/check-docs-exceptions.txt @@ -0,0 +1,219 @@ +# scripts/check-docs.py의 예외 목록. 2026-11-07 기준선이고 줄기만 한다. +# +# - 이 목록에 새 줄을 더하면 검사가 실패한다. 줄마다 check-docs.py의 FROZEN에 지문이 있어야 한다. +# - 번역하거나 고쳐서 더는 걸리지 않는 줄은 지운다. 남겨 두면 검사가 실패한다. +# - 형식: <검사><탭><경로>[<탭><걸린 값>]. 「#」으로 시작하는 줄과 빈 줄은 읽지 않는다. + +# 언어: 아직 한국어로 옮기지 않은 살아 있는 문서와 ADR. 다음 단계(살아 있는 문서 번역, ADR 번역)에서 지운다. +language .github/dependency-vulnerability-policy.md +language .github/pull_request_template.md +language compose/keycloak/README.md +language compose/redis/acl/README.md +language docs/adr/ADR-BUILD-001-one-convention-for-shared-test-code.md +language docs/adr/ADR-GQL-001-graphql-context-and-storage-ownership.md +language docs/adr/ADR-GRPC-001-platform-family-and-registry-shape.md +language docs/adr/ADR-GRPC-002-schema-governance-without-protoc.md +language docs/adr/ADR-GRPC-003-three-axis-execution-evidence.md +language docs/adr/ADR-GRPC-004-retry-ownership-and-durable-idempotency.md +language docs/adr/ADR-GRPC-005-server-streaming-single-writer-and-resume.md +language docs/adr/ADR-GRPC-006-stable-discovery-and-kubernetes-routing.md +language docs/adr/ADR-GRPC-ADV-001-capability-promotion-is-per-capability.md +language docs/adr/ADR-JPA-001-domain-owns-persistence-model.md +language docs/adr/ADR-JPA-002-full-transaction-retry.md +language docs/adr/ADR-JPA-003-completion-unknown.md +language docs/adr/ADR-JPA-004-flyway-schema-source-of-truth.md +language docs/adr/ADR-JPA-005-postgresql-real-contract.md +language docs/adr/ADR-JPA-006-canonical-technical-audit.md +language docs/adr/ADR-MONGO-001-platform-boundary.md +language docs/adr/ADR-MONGO-002-bson-representation.md +language docs/adr/ADR-MONGO-003-transaction-retry.md +language docs/adr/ADR-MONGO-004-index-schema-admin-plane.md +language docs/adr/ADR-MONGO-ADV-001-capability-promotion.md +language docs/adr/ADR-WEB-ADV-001-streaming-is-live-delivery.md +language docs/adr/ADR-WEB-ADV-002-virtual-threads-do-not-remove-admission.md +language docs/adr/ADR-WEB-ADV-003-openapi-32-remains-experimental.md +language docs/adr/ADR-WS-001-platform-as-packages-and-its-boundaries.md +language docs/adr/ADR-WS-002-resume-and-cluster.md +language docs/adr/ADR-WS-003-stomp-and-broker-relay.md +language docs/compatibility/grpc-advanced-support-matrix.md +language docs/compatibility/grpc-support-matrix.md +language docs/fileserver/configuration.md +language docs/fileserver/design-deviations.md +language docs/fileserver/http-contract.md +language docs/fileserver/operations.md +language docs/fileserver/security.md +language docs/fileserver/storage-certification.md +language docs/fileserver/support-matrix.md +language docs/fileserver/upgrade-guide.md +language docs/httpclient/configuration-reference.md +language docs/httpclient/operations.md +language docs/httpclient/performance-baseline.md +language docs/httpclient/release-checklist.md +language docs/httpclient/repository-adaptation.md +language docs/httpclient/retry-and-ambiguity.md +language docs/httpclient/security.md +language docs/httpclient/streaming.md +language docs/httpclient/support-matrix.md +language docs/jpa/batch-write-guide.md +language docs/jpa/entity-mapping-guide.md +language docs/jpa/experimental-promotion-checklist.md +language docs/jpa/experimental-support-matrix.md +language docs/jpa/migration-guide.md +language docs/jpa/observability.md +language docs/jpa/postgresql-extensions.md +language docs/jpa/query-fetch-guide.md +language docs/jpa/repository-adaptation.md +language docs/jpa/runbooks.md +language docs/jpa/support-matrix.md +language docs/jpa/transaction-guide.md +language docs/mongodb/advanced/encryption.md +language docs/mongodb/advanced/multi-tenancy.md +language docs/mongodb/advanced/sharding.md +language docs/mongodb/advanced/signoff/README.md +language docs/mongodb/bson-mapping-guide.md +language docs/mongodb/consistency-transaction-guide.md +language docs/mongodb/document-modeling-guide.md +language docs/mongodb/query-aggregation-guide.md +language docs/mongodb/repository-adaptation.md +language docs/mongodb/runbooks/failover.md +language docs/mongodb/runbooks/unknown-commit.md +language docs/mongodb/schema-index-migration-guide.md +language docs/mongodb/security-observability.md +language docs/mongodb/support-matrix.md +language docs/notification/adr/NOTIF-ADR-001-durable-acceptance.md +language docs/notification/adr/NOTIF-ADR-002-event-ledger-projection.md +language docs/notification/adr/NOTIF-ADR-003-ambiguous-submission.md +language docs/notification/adr/NOTIF-ADR-004-fcm-fid-primary.md +language docs/notification/at-rest-threat-model.md +language docs/notification/callback-reconciliation.md +language docs/notification/configuration-reference.md +language docs/notification/delivery-evidence.md +language docs/notification/migration-guide.md +language docs/notification/module-mapping.md +language docs/notification/operations.md +language docs/notification/provider-runbooks.md +language docs/notification/security-privacy.md +language docs/notification/support-matrix.md +language docs/observability/log-fields.md +language docs/redis/command-policy.md +language docs/redis/operations.md +language docs/redis/support-matrix.md +language docs/redis/upgrade-guide.md +language docs/runbooks/adapter-adapter-disabled.md +language docs/runbooks/auth-audience-mismatch.md +language docs/runbooks/auth-claim-mapping-failed.md +language docs/runbooks/auth-issuer-mismatch.md +language docs/runbooks/auth-jwks-unavailable.md +language docs/runbooks/auth-kid-unknown.md +language docs/runbooks/auth-public-path-misconfiguration.md +language docs/runbooks/auth-token-expired.md +language docs/runbooks/auth-token-invalid-signature.md +language docs/runbooks/auth-token-malformed.md +language docs/runbooks/auth-token-missing.md +language docs/runbooks/authz-insufficient-permission.md +language docs/runbooks/authz-tenant-mismatch.md +language docs/runbooks/cache-stampede-lock-timeout.md +language docs/runbooks/cache-unavailable.md +language docs/runbooks/db-deadlock.md +language docs/runbooks/db-idle-in-tx-timeout.md +language docs/runbooks/db-query-canceled.md +language docs/runbooks/db-serialization-failure.md +language docs/runbooks/db-unavailable.md +language docs/runbooks/dependency-4xx-client.md +language docs/runbooks/dependency-5xx-server.md +language docs/runbooks/dependency-circuit-open.md +language docs/runbooks/dependency-connect-failed.md +language docs/runbooks/dependency-dns-failed.md +language docs/runbooks/dependency-timeout.md +language docs/runbooks/file-download-streaming-failure.md +language docs/runbooks/grpc-advanced-capabilities.md +language docs/runbooks/grpc-platform-operations.md +language docs/runbooks/idempotency-unavailable.md +language docs/runbooks/lock-acquisition-timeout.md +language docs/runbooks/management-actuator-forbidden.md +language docs/runbooks/migration-failed.md +language docs/runbooks/runtime-jvm-oom.md +language docs/runbooks/startup-profile-mismatch.md +language docs/runbooks/startup-required-adapter-disabled.md +language docs/runbooks/startup-validation-failed.md +language docs/runbooks/template.md +language docs/storage-capability-boundary.md +language docs/web/advanced-capabilities.md +language docs/web/openapi-32-compatibility.md +language docs/web/patch-contract.md +language docs/web/repository-adaptation.md +language docs/web/runbook.md +language docs/web/streaming-contract.md +language docs/web/virtual-thread-profile.md +language docs/websocket/runbook.md +language src/adapter/inbound/messaging/CLAUDE.md +language src/adapter/inbound/web-advanced/CLAUDE.md +language src/adapter/inbound/web/CLAUDE.md +language src/adapter/inbound/websocket/CLAUDE.md +language src/adapter/outbound/cache-redis/CLAUDE.md +language src/adapter/outbound/cache-redis/README.md +language src/adapter/outbound/fileserver/CLAUDE.md +language src/adapter/outbound/fileserver/README.md +language src/adapter/outbound/httpclient/CLAUDE.md +language src/adapter/outbound/httpclient/README.md +language src/adapter/outbound/identifier/CLAUDE.md +language src/adapter/outbound/messaging-kafka/CLAUDE.md +language src/adapter/outbound/messaging/CLAUDE.md +language src/adapter/outbound/notification/CLAUDE.md +language src/adapter/outbound/objectstorage/CLAUDE.md +language src/adapter/outbound/objectstorage/README.md +language src/adapter/outbound/persistence-fileserver/CLAUDE.md +language src/adapter/outbound/persistence-jpa/CLAUDE.md +language src/adapter/outbound/persistence-mongo/CLAUDE.md +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/ +reference docs/mongodb/consumer-leaf-guide.md :adapter:outbound:persistence-note:check +reference docs/web/http-contract.md docs/architecture/backend-api-and-server-state-contract.md +reference docs/work/operate.md :a:test +reference docs/work/operate.md :b:test +reference src/README.md .github/ci-gate-matrix.yml +reference src/README.md .github/scripts/verify-gate-matrix.sh + +# 숫자: 정본(src/gradle/libs.versions.toml, registry)이 정하는 값을 복사한 곳. 정본을 가리키게 고치면 지운다. +number docs/compatibility/grpc-support-matrix.md Spring Boot 4.0.8 +number docs/httpclient/repository-adaptation.md 19 leaf +number docs/httpclient/repository-adaptation.md Spring Boot 4.0.8 +number docs/jpa/repository-adaptation.md 19 leaf +number docs/jpa/repository-adaptation.md Spring Boot 4.0.8 +number docs/manual/01-generator.md 5 leaf +number docs/mongodb/repository-adaptation.md 19 leaf +number docs/mongodb/repository-adaptation.md Spring Boot 4.0.8 +number src/adapter/inbound/graphql/CLAUDE.md Spring Boot 4.0.0 +number src/adapter/inbound/graphql/README.md 19개 leaf +number src/adapter/inbound/graphql/README.md 24개 leaf +number src/adapter/inbound/graphql/README.md 43개 leaf +number src/adapter/inbound/grpc/CLAUDE.md Spring Boot 4.0.0 +number src/adapter/inbound/web/CLAUDE.md Spring Boot 4.0.0 +number src/adapter/inbound/websocket/CLAUDE.md Spring Boot 4.0.8 +number src/adapter/outbound/cache-redis/CLAUDE.md Spring Boot 4.0.0 +number src/adapter/outbound/fileserver/CLAUDE.md Spring Boot 4.0.0 +number src/adapter/outbound/httpclient/CLAUDE.md Spring Boot 4.0.0 +number src/adapter/outbound/identifier/CLAUDE.md Spring Boot 4.0.8 +number src/adapter/outbound/messaging/CLAUDE.md Spring Boot 4.0.8 +number src/adapter/outbound/notification/CLAUDE.md Spring Boot 4.0.0 +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 diff --git a/scripts/check-docs.py b/scripts/check-docs.py new file mode 100755 index 00000000..3e482356 --- /dev/null +++ b/scripts/check-docs.py @@ -0,0 +1,544 @@ +#!/usr/bin/env python3 +"""문서 검사 넷: 언어, 기록의 머리 블록, 참조, 복사한 숫자. 하나라도 걸리면 rc=1이다. + +규칙의 정본은 design-docs `conventions/docs-system.md`이고, 이 repo의 적용은 `docs/README.md` +「문서 수명과 언어」다. 이 스크립트는 그 규칙 중 기계로 볼 수 있는 것만 본다. + + language 살아 있는 문서(기록이 아닌 .md)는 한국어다. 판정은 보고 언어 훅 H11과 같다: + 코드·명령·인용·링크·URL·경로·파일 이름을 빼고, 영어 낱말이 3개 이상이고 + 한글 덩어리 비율이 0.3 미만이면 영어다. + head 기록(docs/design, docs/history, docs/adr, docs/notification/adr)의 .md는 맨 위에 + 머리 블록이 있다. 상태는 종류별 고정 어휘, 작성일은 날짜, 요약은 한국어, 현재 + 정본과 대체됨이 가리키는 경로는 지금 있다. + reference 살아 있는 문서의 인라인 코드 안 repo 경로(src/, docs/, scripts/, compose/, .github/로 + 시작. 2026-11-07에 지운 infra/ 아래 경로도 본다)와 Gradle 경로(:a:b)가 지금 트리와 + registry에 있다. 코드 블록과 「이력」으로 시작하는 인용 블록은 건너뛴다. 마크다운 + 링크는 lychee와 check-work-docs.py --links가 본다. + number 살아 있는 문서가 정본이 정하는 숫자를 복사하지 않는다: Spring Boot 버전, leaf 개수. + +예외 목록(scripts/check-docs-exceptions.txt)은 줄기만 한다. + - 목록의 줄은 아래 FROZEN(2026-11-07 기준선의 지문)에 있어야 한다. 목록에 새 줄을 더하면 실패한다. + - 목록의 줄이 더는 걸리지 않으면(번역했거나 고쳤으면) 그 줄을 지우라고 실패한다. + - FROZEN을 늘리는 것은 규칙을 바꾸는 일이다. 소유자 결정 없이 하지 않는다. 파일을 옮겨 경로만 + 바뀐 줄은 FROZEN에서 옛 지문을 새 지문으로 바꾼다. 지문은 그 줄(탭 포함)의 sha256 앞 16자다: + python3 -c 'import hashlib,sys; print(hashlib.sha256(sys.argv[1].encode()).hexdigest()[:16])' "<줄>" + + python3 scripts/check-docs.py # 넷 모두 + python3 scripts/check-docs.py --only head # 하나만 (language, head, reference, number) + python3 -m unittest discover -s scripts/tests # 이 검사의 시험 + +Gradle 밖에 둔다. 빌드는 문서를 파싱하지 않는다(AGENTS.md 「Gradle 정책 권위」). +""" + +from __future__ import annotations + +import datetime +import hashlib +import json +import re +import subprocess +import sys +from dataclasses import dataclass +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +EXCEPTIONS_FILE = "scripts/check-docs-exceptions.txt" +REGISTRY_FILE = "src/config/architecture/modules.json" +CHECKS = ("language", "head", "reference", "number") + +# 기록: 본문은 쓴 때의 원문이다. 머리 블록만 고친다. 종류는 폴더가 정한다. +RECORD_KINDS = [ + ("docs/design/", "설계서"), + ("docs/history/plans/evidence/", "증거"), + ("docs/history/plans/", "계획서"), + ("docs/history/packages/", "납품 패키지"), + ("docs/history/evidence/", "증거"), + ("docs/history/study/", "학습 문서"), + ("docs/adr/", "결정 기록"), + ("docs/notification/adr/", "결정 기록"), +] +# 리뷰도 기록이다. 머리 블록은 아직 요구하지 않는다(docs/README.md). +NOT_LIVING = ("docs/design/", "docs/history/", "docs/reviews/") +DECISION_PREFIXES = ("docs/adr/", "docs/notification/adr/") +# 살아 있는 문서 중 지운 것을 일부러 적는 곳: 제거 표, 파생 서비스용 변경 안내, 매뉴얼 규칙의 근거 기록. +# 참조·숫자 검사는 이 문서들을 보지 않는다(docs/README.md 「문서와 코드를 같은 변경에서 고친다」). +HISTORY_HOLDERS = ("docs/capability-status.md", "docs/upgrade/", "docs/work/evidence.md") + +STATUS = { + "설계서": ("제안", "채택", "구현됨", "보류", "폐기", "대체됨", "확인 안 함"), + "결정 기록": ("제안", "채택", "채택(보완)", "폐기", "대체됨"), + "계획서": ("실행 중", "끝남", "중단", "대체됨", "확인 안 함"), + "납품 패키지": ("보관",), + "증거": ("보관",), + "학습 문서": ("보관",), +} +HEAD_START = "" +HEAD_END = "" +RECORD_LABEL = "> **기록 · {kind}** 본문은 쓴 때의 원문이다. 지금 동작은 「현재 정본」을 읽는다." +DECISION_LABEL = "> **결정 기록** 본문은 결정한 때의 원문이다. 지금도 유효한지는 「상태」를, 지금 동작은 「현재 정본」을 읽는다." +HEAD_FIELDS = ("상태", "작성일", "요약", "현재 정본") +HEAD_OPTIONAL = ("대체", "대체됨") +HEAD_SEARCH_LINES = 20 + +# 2026-11-07 기준선. 예외 목록의 줄마다 sha256 앞 16자. 늘리지 않는다(맨 위 설명). +FROZEN: frozenset[str] = frozenset({ + "0176963415821bbe", "01984fd96d72b997", "02810bf817c5098f", "02f77e3cc483fa7b", "05fff3c3ff8a5c9a", + "06ea362843468b89", "0767d62996355ba0", "077f1849fe8bebcc", "07f88b24645a4899", "09f6eb7c3c494379", + "0a929e243076b4cb", "0d60ec2d41d698e3", "0d9db88d1d98c32b", "0f84458cb40e7c5e", "10894a287a405274", + "110ff8adc628d4e9", "115eed80f3bb629c", "14121ef25eb4aa46", "150219e901d062f4", "199044717780f929", + "1adc480d397a24fc", "1aedb5c86be16e62", "1ef3eec4c410622e", "1f3199d6bef7b3ab", "20a46563da0c570d", + "234a0dffc4f308bf", "23aa784e28c7f730", "24e61cd8377137f1", "26cdb5786cd3cef8", "26f59b7362b9e68d", + "29fa254236927dae", "2a0c27bb25080cdb", "2aa755121374e148", "2bcc75d4e1ebaa5d", "2e77660bd44c1d2c", + "2e7d24cb488ae4f9", "30c75a928243de75", "354c37493e90b01b", "3e867d0b440f18f5", "3fe449c9eca66d87", + "3ff905af6cc2df16", "4053b182a2b89223", "41f268d8aa836143", "4347c5b0dd84ec9b", "449fc1cac0f9380f", + "457310fef9d100a6", "4611a0bfd81bf42c", "462a63de89507bc6", "468248c165ce65f0", "47c9a2b490ceae84", + "4866a2abc9be3133", "48ca99496ac8265e", "494b23454cfaf902", "49d560912ccd3bd6", "49ee572590d74921", + "4c3afe5f9f4265d3", "4cef6042d25d7ce2", "4f4516913c6de5d6", "4f9b0fa57d925ddc", "50cecf0fd2f1ed1f", + "511ed51b27f98b9c", "52879b9f3cbdd66f", "52d9b8b42edf92c5", "52dd5ae3e9bfef22", "53f304d4f21e321e", + "5503b8002ae2673f", "55397a6480705e90", "561988b22b65f79f", "5640b6d1a24b9ad6", "56d9c8bc2e2d7a01", + "570b7b7be5396079", "57603aa52f880d03", "57c4df2758097604", "59e238f79e31e3db", "5acb4cacd9aa7a71", + "5b1f0d60cdd91b33", "5b783704ccce90b9", "5b833f85df94c6fd", "5caaf9a02506595e", "5cd2de3ab18314a9", + "5cda11b0371e8b48", "5e17fde0e8281e0b", "61241c19f875d528", "614d8160fecebe42", "62ac6e83f597894a", + "62ae3935928ec875", "62ae5138ca3f54bf", "29b4daf7b7befa61", "63887df3233e4e7f", "63bbbd89d07abcc5", + "63d3556d23363430", "6407c8198a2ce80f", "6669b8199b2f15be", "6710e607f9ae6ba2", "6c60928d93ca7831", + "6e57bc847800e849", "6f2fef4ed95b870d", "70f8b4b8cb326639", "7227a51a80d75567", "728afb0024d5da55", + "745fabbdac49b041", "74622ec18c9f9985", "74eab10487ee91a4", "7548695a3a57c058", "76030078f4c446ec", + "7698729bcfd126f7", "77ed807b2db1bdb4", "782bc48fcd75361c", "7846dce0563bde1f", "78b5bea3cfb3f84f", + "7a41c841fa3c71c3", "7b3944471a209cdc", "7ba95fb426152c3b", "814a101266f1e722", "8232460887910a0e", + "82b97043efd185d0", "83b56cb713adb544", "84ebb93c8c137862", "8559d433706ac279", "85e199be8e5a5df5", + "86c327f4147ec696", "8c3417a9291e07cf", "9031db861c91b202", "90697a358931eba2", "9084568d44e608c3", + "945be2a3aaccbb2c", "94c5248d3fe6f83f", "95feaea41a059d9a", "966dd5354d327ba4", "97c036827ae94466", + "97fed7ecb0c23137", "982773d6151ae295", "993631c9efdbaa48", "999cc41aeaa485d9", "9b976d47e8cca045", + "9db89af226707449", "9e9437780d412b86", "9ee05526226dd121", "9f6cb144b5b0013d", "a14aae022e52cabd", + "a2db3c73eea72747", "a6e2e42521f27aa8", "a7b7a83d8e7b5914", "a84c5847e6bc413a", "a9cdf0e474dfa4ca", + "ab9a1c81f4d00b17", "ac208a7edf8e6b9e", "ac524f5b860f4b73", "af6bfc4105841865", "b25dfdea45b42ece", + "b2ee46983b09686b", "b6c96aabf4daba15", "b99ef0dca48e547c", "bc89c106ed0333da", "399e08b7f60cd570", + "bd2edda7ff995e5a", "c0f36dd22b6d1df4", "c1cbe5ed9ccaf41a", "c2e62316bf302721", "c30f7e945ca5204b", + "c446b7882073d116", "c555077d0a4ca6dc", "c5556985dac877fb", "c66938fdb57ac8bd", "c7d3f2a6e0e819c7", + "437e813553f5782e", "c9147167591ac87f", "c9682c8986bdfa3f", "c9f15a774cbbb296", "c9f895250a7f6b1f", + "ca9ac59c7e4dd0dd", "ccfd7af308666817", "cde221c994e186e9", "d1c59fa1e5fd22ca", "d2c0d56090ffb617", + "d3a72db1fb71eaf6", "d58784f8ae176897", "d88381653e2c64f9", "d934528c9e7966f7", "da73ed73f0ec1dd9", + "da8381da9de5df66", "dd4f9524437dcc45", "dd6384bc82ce9677", "df5a6c2edc20af59", "e076b4232fc136e9", + "e1ada69597a5d6cd", "e1d8a4d6d6bbfb2e", "e2af4a0f5b0957d5", "e313fbfdd61fba0c", "e347453420828b08", + "e368dfa3ca97d4c7", "e3cc20cbd63d0adb", "e4435ba963a1fbef", "e5182c24f72e2747", "e660a27969605244", + "e7dad258cbc844a0", "e97d1ef509983caa", "e997a8c038464efb", "eb66b6c389ec09e4", "ed7764b9ec0265a0", + "ee8e568418c22e81", "ef22d97e0a67bed8", "f0baa883ab5f959d", "f12cb9b454600534", "f135bd1f9697ad4c", + "f166b8797656c86e", "f191a6842f342b74", "f3ea04dd3a66f76a", "f4c93c2e841f1c68", "f4d7edfeee65b0c3", + "f6528fa83345165e", "fa4172e085723211", "fc0c07879a70ce33", "fd706bf633a51444", "fd793c8cfa94f318", + "fe800048b661a783", "6cfa7cfc6f6a4a7e", +}) + +# --- 언어 판정: ~/.claude/hooks/guard_report.py의 H11과 같은 규칙(design-docs conventions/delegation-loop.md 11절) +MIN_ENGLISH = 3 +MIN_KOREAN_SHARE = 0.3 +HANGUL = re.compile(r"[가-힣]+") +FENCE = re.compile(r"^[ \t]*(`{3,}|~{3,})") +INLINE = re.compile(r"(`+)(?:(?!\1).)+?\1", re.S) +MDLINK = re.compile(r"\[[^\]\n]*\]\([^)\s]*\)") +URL = re.compile(r"(?:\b[a-z][a-z0-9+.-]*://|\bwww\.)\S+", re.I) +PATHLIKE = re.compile(r"[^\s가-힣]*[/\\][^\s가-힣]*") +FILELIKE = re.compile(r"[^\s가-힣]+\.[A-Za-z]{1,10}(?::\d+)*(?![A-Za-z])") +QUOTED = re.compile(r"\"[^\"\n]*\"|“[^”\n]*”") +TOKEN = re.compile(r"[^\s가-힣]+") +WORD = re.compile(r"^[(\[\"'“‘*_]*[A-Za-z][a-z]*(?:['’][a-z]+)?(?:-[a-z]+)*[)\]\"'”’*_.,;:!?…]*$") + +# --- 참조 +PATH_ROOTS = ("src/", "docs/", "scripts/", "compose/", "infra/", ".github/") +PLACEHOLDER = re.compile(r"[*?<>{}\[\]$…]|\.\.\.|YYYY|NNN|[가-힣]") +LINE_SUFFIX = re.compile(r"(?::\d+(?:[-,]\d+)*)+$") +# 모든 leaf에 있는 소스 세트 이름(src/test, src/main/java)은 어느 leaf의 것인지 문장이 정한다. +SOURCE_SET = re.compile(r"^src/[A-Za-z]+(?:/(?:java|resources|proto|kotlin|groovy))?/?$") +GRADLE_PATH = re.compile(r"^:[A-Za-z][\w-]*(?::[A-Za-z][\w-]*)+$") +HISTORY_QUOTE = re.compile(r"^\s*>\s*(?:\*\*)?이력") + +# --- 복사한 숫자 +COPIED_NUMBERS = [ + ("Spring Boot 버전", re.compile(r"Spring Boot \d+\.\d+\.\d+")), + ("leaf 개수", re.compile(r"\b\d+\s*개의?\s*leaf|\bleaf\s*\d+\s*개|\b\d+\s+(?:registered\s+)?lea(?:f|ves)\b", + re.I)), +] + + +@dataclass(frozen=True) +class Problem: + check: str + path: str + key: str + message: str + line: int = 0 + + def exception_line(self) -> str: + return "\t".join(part for part in (self.check, self.path, self.key) if part) + + def render(self) -> str: + where = f"{self.path}:{self.line}" if self.line else self.path + return f"[{self.check}] {where}: {self.message}" + + +def fingerprint(line: str) -> str: + return hashlib.sha256(line.encode("utf-8")).hexdigest()[:16] + + +def tracked_markdown(root: Path) -> list[str]: + """Markdown files git knows or would add: tracked plus untracked files that are not ignored.""" + result = subprocess.run( + ["git", "-C", str(root), "ls-files", "-z", "--cached", "--others", "--exclude-standard", "--", "*.md"], + capture_output=True, check=True) + names = {name for name in result.stdout.decode("utf-8").split("\0") if name} + return sorted(name for name in names if (root / name).is_file()) + + +def record_kind(path: str) -> str | None: + for prefix, kind in RECORD_KINDS: + if path.startswith(prefix): + return kind + return None + + +def is_living(path: str) -> bool: + return not path.startswith(NOT_LIVING) + + +def strip_head_block(lines: list[str]) -> list[str]: + if lines and lines[0] == HEAD_START and HEAD_END in lines[:HEAD_SEARCH_LINES]: + return lines[lines.index(HEAD_END) + 1:] + return lines + + +def strip_front_matter(lines: list[str]) -> list[str]: + if lines and lines[0].strip() == "---": + for index in range(1, len(lines)): + if lines[index].strip() == "---": + return lines[index + 1:] + return lines + + +def body_lines(text: str) -> list[str]: + return strip_front_matter(strip_head_block(text.split("\n"))) + + +def prose(text: str) -> str: + """판정에서 뺄 것(코드·명령·인용·링크·URL·경로·파일 이름)을 지운 글. H11의 prose()와 같다.""" + lines, fence = [], None + for line in text.split("\n"): + match = FENCE.match(line) + if fence: + if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence): + fence = None + continue + if match: + fence = match.group(1) + continue + if not line.lstrip().startswith(("$ ", ">")): + lines.append(line) + text = "\n".join(lines) + for pattern in (INLINE, MDLINK, URL, QUOTED, PATHLIKE, FILELIKE): + text = pattern.sub(" ", text) + return text + + +def language_counts(text: str) -> tuple[int, int]: + cleaned = prose(text) + korean = len(HANGUL.findall(cleaned)) + english = sum(1 for token in TOKEN.findall(cleaned) if WORD.match(token)) + return korean, english + + +def is_english(text: str) -> bool: + korean, english = language_counts(text) + return english >= MIN_ENGLISH and korean / (korean + english) < MIN_KOREAN_SHARE + + +def check_language(root: Path, files: list[str]) -> list[Problem]: + problems = [] + for path in files: + if not is_living(path): + continue + body = "\n".join(body_lines((root / path).read_text(encoding="utf-8"))) + if is_english(body): + korean, english = language_counts(body) + problems.append(Problem("language", path, "", + f"영어 문서다(한글 {korean}, 영어 낱말 {english}). 한국어로 쓴다")) + return problems + + +def head_block(lines: list[str]) -> tuple[list[str], int] | None: + if not lines or lines[0] != HEAD_START: + return None + window = lines[:HEAD_SEARCH_LINES] + if HEAD_END not in window: + return None + end = window.index(HEAD_END) + return lines[1:end], end + + +def backticked_paths(value: str) -> list[str]: + return re.findall(r"`([^`]+)`", value) + + +def check_head(root: Path, files: list[str]) -> list[Problem]: + problems = [] + for path in files: + kind = record_kind(path) + if kind is None: + continue + + def fail(message: str, line: int = 1) -> None: + problems.append(Problem("head", path, "", message, line)) + + lines = (root / path).read_text(encoding="utf-8").split("\n") + found = head_block(lines) + if found is None: + fail(f"맨 위에 머리 블록이 없다. 첫 줄은 `{HEAD_START}`, 블록은 `{HEAD_END}`로 닫는다") + continue + block, _ = found + label = DECISION_LABEL if kind == "결정 기록" else RECORD_LABEL.format(kind=kind) + if not block or block[0] != label: + fail(f"머리 블록 둘째 줄은 「{label}」이다", 2) + fields: dict[str, tuple[str, int]] = {} + for offset, line in enumerate(block[1:], start=3): + if not line.strip(): + continue + match = re.match(r"^- ([^:]+): (.+)$", line) + if not match: + fail(f"머리 블록의 줄은 `- 칸: 값`이다: {line!r}", offset) + continue + name, value = match.group(1).strip(), match.group(2).strip() + if name not in HEAD_FIELDS + HEAD_OPTIONAL: + fail(f"머리 블록에 없는 칸이다: {name}", offset) + elif name in fields: + fail(f"칸이 두 번 나온다: {name}", offset) + else: + fields[name] = (value, offset) + for name in HEAD_FIELDS: + if name not in fields: + fail(f"「{name}」 칸이 없다") + status, at = fields.get("상태", ("", 1)) + if "상태" in fields and status not in STATUS[kind]: + fail(f"{kind}의 상태는 {' · '.join(STATUS[kind])} 중 하나다: {status!r}", at) + written, at = fields.get("작성일", ("", 1)) + if "작성일" in fields: + try: + datetime.date.fromisoformat(written) + except ValueError: + fail(f"작성일은 YYYY-MM-DD다: {written!r}", at) + summary, at = fields.get("요약", ("", 1)) + if "요약" in fields and (not HANGUL.search(summary) or is_english(summary)): + fail("요약은 한국어 한 문장이다", at) + canonical, at = fields.get("현재 정본", ("", 1)) + if "현재 정본" in fields: + targets = backticked_paths(canonical) + if not canonical.startswith("없음") and not targets: + fail("현재 정본은 `경로`(여럿이면 쉼표) 또는 「없음 — 이유」다", at) + for target in targets: + if not (root / target).exists(): + fail(f"현재 정본 경로가 없다: {target}", at) + if status == "대체됨" and "대체됨" not in fields: + fail("상태가 대체됨이면 「대체됨」 칸에 대체한 문서를 적는다") + for name in HEAD_OPTIONAL: + if name in fields: + value, at = fields[name] + targets = backticked_paths(value) + if not targets: + fail(f"「{name}」 칸은 `경로`를 적는다", at) + for target in targets: + if not (root / target).exists(): + fail(f"「{name}」 경로가 없다: {target}", at) + return problems + + +def inline_spans(lines: list[str]) -> list[tuple[int, str]]: + """(줄 번호, 인라인 코드) — 코드 블록과 「이력」 인용 블록 밖에서만.""" + spans, fence, history = [], None, False + for number, line in enumerate(lines, start=1): + match = FENCE.match(line) + if fence: + if match and match.group(1)[0] == fence[0] and len(match.group(1)) >= len(fence): + fence = None + continue + if match: + fence = match.group(1) + continue + quoted = line.lstrip().startswith(">") + if quoted and HISTORY_QUOTE.match(line): + history = True + elif not quoted: + history = False + if history: + continue + for found in INLINE.finditer(line): + spans.append((number, found.group(0).strip("`").strip())) + return spans + + +def registry_projects(root: Path) -> set[str]: + registry = root / REGISTRY_FILE + if not registry.is_file(): + return set() + modules = json.loads(registry.read_text(encoding="utf-8")).get("modules", []) + projects: set[str] = set() + for module in modules: + parts = module["gradle_path"].split(":")[1:] + for end in range(1, len(parts) + 1): + projects.add(":" + ":".join(parts[:end])) + return projects + + +def path_candidate(token: str) -> str | None: + token = token.strip().strip("'\"()[],;") + if token.startswith("./"): + token = token[2:] + if not token.startswith(PATH_ROOTS) or PLACEHOLDER.search(token) or "://" in token: + return None + token = LINE_SUFFIX.sub("", token.split("#", 1)[0]).rstrip(".:") + return token or None + + +def resolves(root: Path, document: str, target: str) -> bool: + if (root / target).exists(): + return True + # src/main/... in a leaf document is written relative to that leaf. + folder = (root / document).parent + while folder != root and root in folder.parents: + if (folder / target).exists(): + return True + folder = folder.parent + return False + + +def ignored(root: Path, paths: set[str]) -> set[str]: + if not paths: + return set() + result = subprocess.run(["git", "-C", str(root), "check-ignore", "--no-index", "--stdin"], + input="\n".join(sorted(paths)).encode("utf-8"), capture_output=True) + return set(result.stdout.decode("utf-8").split("\n")) - {""} + + +def checked_for_drift(path: str) -> bool: + return is_living(path) and not path.startswith(DECISION_PREFIXES) and not path.startswith(HISTORY_HOLDERS) + + +def path_suffixes(root: Path) -> set[str]: + """Every trailing part of every file and folder git knows: `src/test/resources/x.sha256` written in a + manual about any leaf resolves when some leaf has it.""" + result = subprocess.run( + ["git", "-C", str(root), "ls-files", "-z", "--cached", "--others", "--exclude-standard"], + capture_output=True, check=True) + suffixes: set[str] = set() + for name in result.stdout.decode("utf-8").split("\0"): + parts = name.split("/") + for end in range(1, len(parts) + 1): + for start in range(end): + suffixes.add("/".join(parts[start:end])) + return suffixes + + +def check_reference(root: Path, files: list[str]) -> list[Problem]: + projects = registry_projects(root) + missing: list[tuple[str, int, str]] = [] + problems = [] + for path in files: + if not checked_for_drift(path): + continue + lines = body_lines((root / path).read_text(encoding="utf-8")) + offset = len((root / path).read_text(encoding="utf-8").split("\n")) - len(lines) + seen: set[str] = set() + for number, span in inline_spans(lines): + for token in span.split(): + gradle = token.strip(".,;'\"()") + if GRADLE_PATH.match(gradle): + parent = gradle.rsplit(":", 1)[0] + if projects and gradle not in projects and parent not in projects and gradle not in seen: + seen.add(gradle) + problems.append(Problem("reference", path, gradle, + f"registry에 없는 Gradle 경로다: {gradle}", number + offset)) + continue + target = path_candidate(token) + if target and SOURCE_SET.match(target): + continue + if target and target not in seen and not resolves(root, path, target): + seen.add(target) + missing.append((path, number + offset, target)) + skip = ignored(root, {target for _, _, target in missing}) + if missing: + skip |= path_suffixes(root) + for path, number, target in missing: + if target.rstrip("/") not in skip and target not in skip: + problems.append(Problem("reference", path, target, f"없는 경로다: {target}", number)) + return problems + + +def check_number(root: Path, files: list[str]) -> list[Problem]: + problems = [] + for path in files: + if not checked_for_drift(path): + continue + seen: set[str] = set() + for number, line in enumerate((root / path).read_text(encoding="utf-8").split("\n"), start=1): + for label, pattern in COPIED_NUMBERS: + for match in pattern.finditer(line): + text = match.group(0) + if text not in seen: + seen.add(text) + problems.append(Problem("number", path, text, + f"{label}를 복사했다: {text!r}. 정본을 가리킨다", number)) + return problems + + +RUNNERS = {"language": check_language, "head": check_head, "reference": check_reference, "number": check_number} + + +def read_exceptions(text: str) -> list[str]: + return [line for line in text.split("\n") if line.strip() and not line.startswith("#")] + + +def run(root: Path, only: tuple[str, ...] = CHECKS, exceptions: str | None = None, + frozen: frozenset[str] = FROZEN) -> tuple[list[str], list[str]]: + """(실패 줄, 보고 줄). 예외 목록을 적용한 뒤의 결과다.""" + if exceptions is None: + exceptions_path = root / EXCEPTIONS_FILE + exceptions = exceptions_path.read_text(encoding="utf-8") if exceptions_path.is_file() else "" + allowed = read_exceptions(exceptions) + files = tracked_markdown(root) + errors: list[str] = [] + report: list[str] = [] + for entry in allowed: + if fingerprint(entry) not in frozen: + errors.append(f"[exceptions] {EXCEPTIONS_FILE}: 기준선에 없는 예외다. 예외 목록은 늘지 않는다: {entry!r}") + allowed_set = set(allowed) + for check in only: + problems = RUNNERS[check](root, files) + hit = {problem.exception_line() for problem in problems} + unexcused = [problem for problem in problems if problem.exception_line() not in allowed_set] + stale = [entry for entry in allowed if entry.split("\t", 1)[0] == check and entry not in hit] + errors += [problem.render() for problem in unexcused] + errors += [f"[exceptions] {EXCEPTIONS_FILE}: 더는 걸리지 않는다. 이 줄을 지운다: {entry!r}" for entry in stale] + excused = len(problems) - len(unexcused) + report.append(f"{check}: 걸림 {len(problems)}, 예외 {excused}, 실패 {len(unexcused)}") + return errors, report + + +def main(argv: list[str]) -> int: + only = CHECKS + if argv[:1] == ["--only"]: + if len(argv) != 2 or argv[1] not in CHECKS: + print(f"usage: check-docs.py [--only {'|'.join(CHECKS)}]", file=sys.stderr) + return 2 + only = (argv[1],) + elif argv: + print(f"usage: check-docs.py [--only {'|'.join(CHECKS)}]", file=sys.stderr) + return 2 + errors, report = run(REPO_ROOT, only) + for line in report: + print(line) + if errors: + print(f"\nFAILED: {len(errors)}", file=sys.stderr) + for error in errors: + print(f" {error}", file=sys.stderr) + return 1 + print("\nOK") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/check-repo-layout.py b/scripts/check-repo-layout.py new file mode 100755 index 00000000..805adb87 --- /dev/null +++ b/scripts/check-repo-layout.py @@ -0,0 +1,210 @@ +#!/usr/bin/env python3 +"""저장소 루트와 src/ 최상위에 허용 목록 밖의 항목이 생기면 실패한다. + +왜: src/ 아래 계층이 아닌 폴더가 2026-07-24의 둘에서 두 달 사이 여덟으로 늘었고, 어느 커밋도 최상위 +모양을 묻지 않았다. 루트에는 개발 환경·테스트 fixture·운영 인프라가 섞인 compose 파일과 infra/ 폴더가 +쌓였다(2026-11-07 저장소 정리, design-docs repo-structure/01-backend-layout.md). 소유자는 배치 규칙을 +리뷰 기준에 두고, 이 허용 목록 검사로도 막기로 정했다(같은 날, repo-structure/README.md 3.1절). + +무엇을 보나: + +1. 저장소 루트의 추적 파일·폴더가 ROOT_ALLOWED 안에 있는가. +2. src/ 바로 아래의 추적 파일·폴더가 SRC_ALLOWED 안에 있는가. +3. registry(src/config/architecture/modules.json)의 모든 source_path가 허용된 src/ 폴더 아래에 있는가. +4. (경고만) 개발 환경·테스트 fixture 파일(compose 파일, 셸 스크립트, compose/ 아래 보조 파일)을 다른 + 추적 파일이 하나도 가리키지 않으면 이름을 출력한다. 아무도 읽지 않는 파일이 소리 없이 남는 것이 + infra/ 12개가 쌓인 방식이다. 경로를 변수로 조립하는 workflow는 이 검사가 따라가지 못하므로 경고로만 둔다. + +추적 파일만 본다(git ls-files). build 출력과 IDE 폴더는 처음부터 대상이 아니다. + +새 최상위 항목이 정말 필요하면 아래 목록과 루트 CLAUDE.md 5절 「최상위 폴더는 정해진 것만 둔다」를 같은 +변경에서 고친다. 최상위 폴더를 만들거나 옮기는 일은 파일 하나여도 큰 일이다(docs/work/README.md 2절). + +Gradle 밖에 둔다: 빌드는 저장소 배치를 판단하지 않는다(scripts/check-work-docs.py와 같은 자리). + + python3 scripts/check-repo-layout.py +""" + +from __future__ import annotations + +import json +import subprocess +import sys +from pathlib import Path, PurePosixPath + +REPO_ROOT = Path(__file__).resolve().parent.parent +REGISTRY = "src/config/architecture/modules.json" + +# 저장소 루트: 문서·스크립트·CI·개발 환경과 Gradle 루트(src)뿐이다. +ROOT_ALLOWED = { + # 폴더 + ".claude": "에이전트 세션 설정(추적되는 settings.json)", + ".github": "workflow와 공용 action", + "compose": "compose.yaml이 마운트하는 보조 파일", + "docs": "문서", + "scripts": "Gradle 밖 검사·실행 스크립트", + "src": "Gradle 루트", + # 파일 + ".gitattributes": "Git 설정", + ".gitignore": "Git 설정", + ".tool-versions": "JDK 버전 고정", + ".trivyignore.yaml": "취약점 검사 예외", + "AGENTS.md": "규칙 정본", + "CLAUDE.md": "작업 지도", + "README.md": "저장소 소개", + "compose.yaml": "개발 환경(하나뿐)", + "renovate.json": "의존성 갱신 봇 설정", + "skills-lock.json": "에이전트 스킬 고정", + "testcontainers.properties.example": "Testcontainers 로컬 설정 예", +} + +# src/ 바로 아래: 계층·조립 leaf, 들여온 제품 묶음, Gradle 루트 표준 폴더와 빌드 파일. +SRC_ALLOWED = { + # 계층과 조립 + "domain-core": "계층", + "shared-contract": "계층", + "application-core": "계층", + "application-fileserver": "계층(capability)", + "application-notification": "계층(capability)", + "application-objectstorage": "계층(capability)", + "adapter": "계층(adapter leaf 묶음)", + "composition": "조립(Clean Architecture의 Main)", + "app-bootstrap": "조립 루트", + # 들여온 제품 + "platforms": "들여온 제품(messaging, grpc, grpc-advanced)과 optional 빌드", + # Gradle 루트 표준 + "build-logic": "빌드 규칙(included build)", + "config": "빌드 전체 도구 설정(registry, checkstyle, spotbugs, 테스트 이미지)", + "gradle": "wrapper와 버전 카탈로그", + # 파일 + ".dockerignore": "이미지 빌드 context", + ".env.example": "env 계약", + ".env.local.example": "로컬 env 예", + ".gitignore": "Git 설정", + "Dockerfile": "릴리스 이미지", + "README.md": "빌드·env 안내", + "build.gradle": "루트 빌드", + "gradle.properties": "Gradle 설정", + "gradlew": "wrapper", + "gradlew.bat": "wrapper", + "settings-gradle.lockfile": "settings 잠금", + "settings.gradle": "settings", +} + +# 아무도 가리키지 않으면 경고할 파일: 개발 환경과 테스트 fixture. +FIXTURE_SUFFIXES = (".sh", ".acl", ".json", ".yaml", ".yml") +FIXTURE_PREFIXES = ("compose/", "scripts/", "src/app-bootstrap/compose-lanes/") +HISTORY_PREFIXES = ( + "docs/reviews/", + "docs/superpowers/", + "docs/evidence/", + "docs/study/", + "docs/adr/", +) + + +def tracked_files() -> list[str]: + result = subprocess.run( + ["git", "ls-files", "-z"], + cwd=REPO_ROOT, + check=True, + capture_output=True, + ) + return [path for path in result.stdout.decode("utf-8").split("\0") if path] + + +def top_level(paths: list[str], prefix: str) -> set[str]: + names = set() + for path in paths: + if not path.startswith(prefix): + continue + rest = path[len(prefix):] + names.add(rest.split("/", 1)[0]) + return names + + +def registry_violations() -> list[str]: + modules = json.loads((REPO_ROOT / REGISTRY).read_text(encoding="utf-8"))["modules"] + problems = [] + for module in modules: + source = PurePosixPath(module["source_path"]) + parts = source.parts + if len(parts) < 2 or parts[0] != "src" or parts[1] not in SRC_ALLOWED: + problems.append( + f"{REGISTRY}: {module['id']} source_path {source} is not under an allowed src/ folder" + ) + return problems + + +def is_fixture(path: str) -> bool: + if path.endswith(("README.md", ".gitignore")): + return False + name = PurePosixPath(path).name + if path.startswith(FIXTURE_PREFIXES) and name.endswith(FIXTURE_SUFFIXES): + return True + return "compose" in name and name.endswith((".yaml", ".yml")) + + +def unreferenced_fixtures(paths: list[str]) -> list[str]: + this_script = str(Path(__file__).resolve().relative_to(REPO_ROOT)) + readable = [ + p for p in paths if not p.startswith(HISTORY_PREFIXES) and p != this_script + ] + texts = {} + for path in readable: + file = REPO_ROOT / path + try: + if file.stat().st_size > 2_000_000: + continue + texts[path] = file.read_text(encoding="utf-8") + except (UnicodeDecodeError, OSError): + continue + lonely = [] + for path in sorted(p for p in paths if is_fixture(p)): + pure = PurePosixPath(path) + # The file's own path or name, or its folder when a compose file mounts the whole folder + # (./compose/redis/acl). A one-segment folder such as compose/ names too much to count. + needles = {path, pure.name} + if len(pure.parent.parts) >= 2: + needles.add(str(pure.parent)) + referenced = any( + other != path and any(needle in text for needle in needles) + for other, text in texts.items() + ) + if not referenced: + lonely.append(path) + return lonely + + +def main() -> int: + paths = tracked_files() + failures = [] + + for name in sorted(top_level(paths, "") - ROOT_ALLOWED.keys()): + failures.append(f"repository root: '{name}' is not in ROOT_ALLOWED") + for name in sorted(top_level(paths, "src/") - SRC_ALLOWED.keys()): + failures.append(f"src/: '{name}' is not in SRC_ALLOWED") + failures.extend(registry_violations()) + + for path in unreferenced_fixtures(paths): + print(f"warning: no tracked file refers to {path}") + + if failures: + for failure in failures: + print(f"FAIL: {failure}", file=sys.stderr) + print( + "check-repo-layout: a new top-level entry changes the repository's shape. If it is " + "wanted, add it to the allow list in scripts/check-repo-layout.py and to CLAUDE.md " + "section 5 in the same change.", + file=sys.stderr, + ) + return 1 + print( + f"check-repo-layout: OK — {len(top_level(paths, ''))} root entries, " + f"{len(top_level(paths, 'src/'))} src/ entries, registry paths inside allowed folders" + ) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check-review-index.py b/scripts/check-review-index.py new file mode 100755 index 00000000..184b6bae --- /dev/null +++ b/scripts/check-review-index.py @@ -0,0 +1,152 @@ +#!/usr/bin/env python3 +"""Fail when a finding written in a review's area documents is missing from that review's index. + +A review folder (`docs/reviews/-/`) holds one README and one document per area (and, +for confirmation reviews, `roundN/` documents). Each finding is a heading that starts with its ID: +`### 05-01 ...`, `#### RR-02-03 · ...`, `### RR6-01-01 · Important · ...`. Fix bundles are assigned +from the README, so a finding the README does not name is a finding nobody fixes. That happened +once: five findings were dropped while IDs were copied into the index by hand. + +This compares the two mechanically. Every finding ID in an area heading must appear in the README +(or, with --index-heading, in that README section). A range such as `RR-01-11~17` or +`06-10~06-14` counts for every ID inside it. A heading ID that still has a placeholder area +(`NN-10`) is reported too, because it cannot be assigned at all. + +When the orchestrating session writes the round's index section after two reviews are merged, the +reviewer who committed the area documents must not edit the README, so the committed tree fails +this check until that section exists. --extra-index takes the index table the reviewer puts in the +report (a file holding that table only) and counts it as part of the index, so the reviewer can show +that the table names every finding before handing it over. + + python3 scripts/check-review-index.py docs/reviews/2026-11-01-maturity-review --index-heading "12. 발견 색인" + python3 scripts/check-review-index.py docs/reviews/2026-11-03-rereview + python3 scripts/check-review-index.py docs/reviews/2026-11-03-rereview --extra-index +""" + +from __future__ import annotations + +import argparse +import re +import sys +from pathlib import Path + +# re.ASCII: Korean letters are word characters to Python's \w, so "RR6-01-07과" would not match. +FINDING_HEADING = re.compile(r"^#{2,6}\s+`?((?:RR\d*-)?(?:\d{2}|NN)-\d{2})\b", re.ASCII) +ID = r"(?:RR\d*-)?\d{2}-\d{2}" +# A list starts with a full ID and may go on with "~NN" (a range up to NN) or "·NN" (one more number +# with the same prefix): "RR-04-06~08·10·11" is 06, 07, 08, 10 and 11. "06-10~06-14" is a range too. +LIST = re.compile( + rf"`?(? dict[str, list[str]]: + findings: dict[str, list[str]] = {} + for path in sorted(review.rglob("*.md")): + if path.name == "README.md" and path.parent == review: + continue + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + match = FINDING_HEADING.match(line) + if match: + findings.setdefault(match.group(1), []).append( + f"{path.relative_to(review).as_posix()}:{number}" + ) + return findings + + +def index_text(readme: Path, heading: str | None) -> str: + lines = readme.read_text(encoding="utf-8").splitlines() + if heading is None: + return "\n".join(lines) + for start, line in enumerate(lines): + match = re.match(r"^(#+)\s+(.*)$", line) + if match and match.group(2).strip() == heading: + level = len(match.group(1)) + end = len(lines) + for later in range(start + 1, len(lines)): + other = re.match(r"^(#+)\s", lines[later]) + if other and len(other.group(1)) <= level: + end = later + break + return "\n".join(lines[start:end]) + raise SystemExit(f"{readme}: no heading '{heading}'") + + +def indexed_ids(text: str) -> set[str]: + ids = set(SINGLE.findall(text)) + for first, tail in LIST.findall(text): + prefix, number = first.rsplit("-", 1) + current = int(number) + for kind, value in STEP.findall(tail): + if "-" in value: + value_prefix, value = value.rsplit("-", 1) + if value_prefix != prefix: + ids.add(f"{value_prefix}-{value}") + continue + target = int(value) + if kind == "·": + ids.add(f"{prefix}-{target:02d}") + else: + ids.update(f"{prefix}-{n:02d}" for n in range(current, target + 1)) + current = target + return ids + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.splitlines()[0]) + parser.add_argument("review", type=Path, help="review folder, e.g. docs/reviews/2026-11-01-maturity-review") + parser.add_argument("--index-heading", help="compare against this README section only (heading text)") + parser.add_argument( + "--extra-index", + type=Path, + action="append", + default=[], + help="a file holding a round's index table that is not in the README yet; may repeat", + ) + args = parser.parse_args() + + readme = args.review / "README.md" + if not readme.is_file(): + print(f"{readme}: missing", file=sys.stderr) + return 1 + + missing_extra = [str(path) for path in args.extra_index if not path.is_file()] + if missing_extra: + print(f"--extra-index: missing {', '.join(missing_extra)}", file=sys.stderr) + return 1 + + findings = area_findings(args.review) + texts = [index_text(readme, args.index_heading)] + texts += [path.read_text(encoding="utf-8") for path in args.extra_index] + indexed = indexed_ids("\n".join(texts)) + placeholder = sorted(finding for finding in findings if "NN-" in finding) + missing = sorted(f for f in findings if f not in indexed and f not in placeholder) + duplicated = sorted(f for f, places in findings.items() if len(places) > 1) + + scope = f"section '{args.index_heading}'" if args.index_heading else "whole README" + print(f"review: {args.review}") + print(f"index: README.md, {scope}") + for path in args.extra_index: + print(f"index: + {path} (--extra-index)") + print(f"finding headings in area documents: {len(findings)}") + print(f"found in index: {len(findings) - len(missing) - len(placeholder)}") + print(f"missing from index: {len(missing)}") + for finding in missing: + print(f" {finding} ({', '.join(findings[finding])})") + if placeholder: + print(f"placeholder area (NN-): {len(placeholder)}") + for finding in placeholder: + print(f" {finding} ({', '.join(findings[finding])})") + if duplicated: + print(f"same ID in more than one heading (check they are one finding): {len(duplicated)}") + for finding in duplicated: + print(f" {finding} ({', '.join(findings[finding])})") + + return 1 if missing or placeholder else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/check-work-docs.py b/scripts/check-work-docs.py new file mode 100755 index 00000000..da225c80 --- /dev/null +++ b/scripts/check-work-docs.py @@ -0,0 +1,328 @@ +#!/usr/bin/env python3 +"""Fail when the work manual stops being readable without history or grows past its size limits. + +The work manual is the root `CLAUDE.md` (the map) plus `docs/work/`. A session that has never seen +this repository's history reads the map, `docs/work/README.md` and one playbook, and must be able +to finish the job from those alone. Two things break that, and both are mechanical: + +1. History IDs in the body. A sentence such as "fixed as in 1101/05-01" means nothing to a reader + who does not know that review. History belongs in `docs/work/evidence.md`, and the two reference + files that are indexes of history (`reference/decisions.md`, `reference/defect-patterns.md`). + The same rule covers the other files a new session reads first: the rule book `AGENTS.md` and + every `src/**/CLAUDE.md` (owner decision 2026-11-07). Module READMEs, design documents and + `docs/reviews/**` keep their IDs, because a reader can follow them from inside the repository. +2. Length. Each entry file has a line limit, and the entry path (map + README + one playbook) has a + total limit, so a session reads the whole path instead of skimming it. + +It also checks that every playbook keeps the shared nine-section skeleton, that the +"common mistakes" section stays short, and that relative links in the checked files resolve. + +This lives outside Gradle on purpose: the build does not parse documents. + + python3 scripts/check-work-docs.py + python3 scripts/check-work-docs.py --links docs README.md # relative links only, any files + python3 scripts/check-work-docs.py --history docs/manual # history IDs only, any files + +The --links form is for machines without lychee (the link checker the pull-request workflow runs). +The --history form applies the same history-ID patterns to documents outside docs/work/. +""" + +from __future__ import annotations + +import re +import sys +from pathlib import Path + +REPO_ROOT = Path(__file__).resolve().parent.parent +MAP = REPO_ROOT / "CLAUDE.md" +RULE_BOOK = REPO_ROOT / "AGENTS.md" +WORK = REPO_ROOT / "docs/work" +README = WORK / "README.md" + +PLAYBOOKS = [ + "new-feature.md", + "improve.md", + "research-design.md", + "docs-writing.md", + "operate.md", + "delegate.md", +] +REFERENCES = [ + "reference/gates.md", + "reference/review-criteria.md", + "reference/defect-patterns.md", + "reference/decisions.md", +] +EVIDENCE = "evidence.md" + +# Files that may name history, relative to docs/work/. Everything else must not. +HISTORY_ALLOWED = {EVIDENCE, "reference/decisions.md", "reference/defect-patterns.md"} + +MAP_LIMIT = 120 +README_LIMIT = 80 +PLAYBOOK_LIMIT = 150 +ENTRY_PATH_LIMIT = 350 +MISTAKES_LIMIT = 10 + +SKELETON = [ + "1. 언제 쓰나", + "2. 받아야 할 것", + "3. 크기와 사고 순서", + "4. 절차", + "5. 완료 기준", + "6. 하지 말 것", + "7. 막혔을 때", + "8. 보고 형식", + "9. 자주 하는 실수", +] + +# Each pattern names a kind of history identifier. A match is a sentence that only a reader who +# knows the past can follow. re.ASCII keeps \b and \w to ASCII: Python counts Korean letters as +# word characters, so "RR6-01-07과" would otherwise slip through. +HISTORY_PATTERNS = [ + ("review ID with a date prefix (MMDD/...)", + re.compile(r"(? str: + return path.relative_to(REPO_ROOT).as_posix() + + +def line_count(path: Path) -> int: + return len(path.read_text(encoding="utf-8").splitlines()) + + +def check_exists(errors: list[str]) -> bool: + expected = [MAP, RULE_BOOK, README, WORK / EVIDENCE] + expected += [WORK / name for name in PLAYBOOKS + REFERENCES] + missing = [rel(path) for path in expected if not path.is_file()] + for name in missing: + errors.append(f"{name}: missing") + return not missing + + +def check_limits(errors: list[str], report: list[str]) -> None: + for path, limit in [(MAP, MAP_LIMIT), (README, README_LIMIT)]: + lines = line_count(path) + report.append(f"{rel(path)}: {lines}/{limit}") + if lines > limit: + errors.append(f"{rel(path)}: {lines} lines, limit {limit}") + base = line_count(MAP) + line_count(README) + for name in PLAYBOOKS: + path = WORK / name + lines = line_count(path) + entry = base + lines + report.append(f"{rel(path)}: {lines}/{PLAYBOOK_LIMIT}, entry path {entry}/{ENTRY_PATH_LIMIT}") + if lines > PLAYBOOK_LIMIT: + errors.append(f"{rel(path)}: {lines} lines, limit {PLAYBOOK_LIMIT}") + if entry > ENTRY_PATH_LIMIT: + errors.append( + f"{rel(path)}: entry path CLAUDE.md + docs/work/README.md + this file is {entry} lines," + f" limit {ENTRY_PATH_LIMIT}" + ) + + +def outside_code_blocks(lines: list[str]) -> list[str]: + """Blank out fenced code blocks, so an example such as a report template is not a section.""" + kept: list[str] = [] + fenced = False + for line in lines: + if line.lstrip().startswith("```"): + fenced = not fenced + kept.append("") + else: + kept.append("" if fenced else line) + return kept + + +def check_skeleton(errors: list[str]) -> None: + for name in PLAYBOOKS: + path = WORK / name + lines = outside_code_blocks(path.read_text(encoding="utf-8").splitlines()) + headings = [line[3:].strip() for line in lines if line.startswith("## ")] + if headings != SKELETON: + errors.append( + f"{rel(path)}: sections must be exactly {SKELETON} in that order, found {headings}" + ) + continue + start = lines.index("## " + SKELETON[-1]) + items = [line for line in lines[start + 1:] if re.match(r"^(?:[-*]|\d+\.) ", line)] + if len(items) > MISTAKES_LIMIT: + errors.append( + f"{rel(path)}: '{SKELETON[-1]}' has {len(items)} items, limit {MISTAKES_LIMIT}" + " (move one to a reference file or delete one)" + ) + + +def module_guides() -> list[Path]: + """Every src/**/CLAUDE.md, the local rule book of a leaf or a family, outside build output.""" + skipped = {"build", ".gradle", "node_modules"} + return sorted( + path + for path in (REPO_ROOT / "src").rglob("CLAUDE.md") + if not skipped.intersection(path.relative_to(REPO_ROOT).parts) + ) + + +def history_checked_files() -> list[Path]: + files = [MAP, RULE_BOOK] + for path in sorted(WORK.rglob("*.md")): + if path.relative_to(WORK).as_posix() not in HISTORY_ALLOWED: + files.append(path) + return files + module_guides() + + +def history_match(line: str, following: str) -> tuple[str, str] | None: + """The first history ID on this line, or one that a line break splits ("review\n2026-11-01 07-10").""" + for label, pattern in HISTORY_PATTERNS: + match = pattern.search(line) + if match: + return label, match.group(0) + if not following.strip(): + return None + joined = line.rstrip() + " " + following.strip() + for label, pattern in HISTORY_PATTERNS: + for match in pattern.finditer(joined): + if match.start() < len(line.rstrip()) < match.end(): + return label, match.group(0) + return None + + +def history_hits(files: list[Path]) -> list[tuple[Path, int, str, str]]: + hits = [] + for path in files: + lines = path.read_text(encoding="utf-8").splitlines() + for number, line in enumerate(lines, start=1): + found = history_match(line, lines[number] if number < len(lines) else "") + if found: + hits.append((path, number, *found)) + return hits + + +def broken_links(files: list[Path]) -> tuple[int, list[tuple[Path, int, str]]]: + checked = 0 + broken = [] + for path in files: + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), start=1): + for target in LINK.findall(line): + if re.match(r"^[a-z][a-z0-9+.-]*:", target) or target.startswith("#"): + continue + checked += 1 + if not (path.parent / target.split("#", 1)[0]).exists(): + broken.append((path, number, target)) + return checked, broken + + +def check_history(errors: list[str], report: list[str]) -> None: + hits = history_hits(history_checked_files()) + for path, number, label, text in hits: + errors.append( + f"{rel(path)}:{number}: {label} '{text}'" + " - write the content instead, and move the ID to docs/work/evidence.md" + ) + report.append(f"history ID lines in checked files: {len(hits)}") + + +def check_links(errors: list[str], report: list[str]) -> None: + checked, broken = broken_links([MAP, RULE_BOOK] + sorted(WORK.rglob("*.md"))) + for path, number, target in broken: + errors.append(f"{rel(path)}:{number}: broken relative link '{target}'") + report.append(f"relative links checked: {checked}") + + +def markdown_files(targets: list[str]) -> list[Path]: + files: list[Path] = [] + for target in targets: + path = (Path.cwd() / target).resolve() + files += sorted(path.rglob("*.md")) if path.is_dir() else [path] + return files + + +def links_only(targets: list[str]) -> int: + files = markdown_files(targets) + checked, broken = broken_links(files) + print(f"files: {len(files)}, relative links checked: {checked}, broken: {len(broken)}") + for path, number, target in broken: + print(f" {path}:{number}: broken relative link '{target}'", file=sys.stderr) + return 1 if broken else 0 + + +def history_only(targets: list[str]) -> int: + files = markdown_files(targets) + hits = history_hits(files) + print(f"files: {len(files)}, lines with history IDs: {len(hits)}") + for path, number, label, text in hits: + print(f" {path}:{number}: {label} '{text}'", file=sys.stderr) + return 1 if hits else 0 + + +MODES = {"--links": links_only, "--history": history_only} + + +def main() -> int: + if sys.argv[1:2] and sys.argv[1] in MODES: + if len(sys.argv) < 3: + print(f"usage: check-work-docs.py {sys.argv[1]} ...", file=sys.stderr) + return 2 + return MODES[sys.argv[1]](sys.argv[2:]) + errors: list[str] = [] + report: list[str] = [] + if check_exists(errors): + check_limits(errors, report) + check_skeleton(errors) + check_history(errors, report) + check_links(errors, report) + for line in report: + print(line) + if errors: + print(f"\nFAILED: {len(errors)} problem(s)", file=sys.stderr) + for error in errors: + print(f" {error}", file=sys.stderr) + return 1 + print("\nOK") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactory.java.tmpl b/scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactory.java.tmpl index e19f4f53..42f383ed 100644 --- a/scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactory.java.tmpl +++ b/scripts/feature-scaffold/templates/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/__feature__/Uuid__Feature__IdFactory.java.tmpl @@ -8,7 +8,7 @@ import java.util.UUID; * Mints {@link __Feature__Id}s as random (version 4) UUIDs from the JDK's secure generator. * *

Random UUIDs scatter inserts across a B-tree primary key. When __Feature__ rows are written - * often, switch to a time-ordered UUIDv7 as the sample's {@code UuidWorkLogIdFactory} does; the + * often, switch to a time-ordered UUIDv7 as {@code UuidV7DurableOperationIdFactory} does; the * domain contract (canonical UUID text) does not change. */ public final class Uuid__Feature__IdFactory implements __Feature__IdFactory { diff --git a/scripts/run-compose-runtime-smoke.sh b/scripts/run-compose-runtime-smoke.sh index 770b7a97..5c07ec0d 100755 --- a/scripts/run-compose-runtime-smoke.sh +++ b/scripts/run-compose-runtime-smoke.sh @@ -13,6 +13,8 @@ # compared with the lane's expectedCapabilitiesOn and expectedPersistenceVendor; # 4. every one-shot the lane declares, each of which must exit zero — a missing or skipped # required client is a lane failure, not a lane that had nothing to check; +# 4a. no container of the lane restarted or was killed for memory — a container that died and came +# back between the checks above would otherwise leave every one of them green; # 5. sanitized evidence; # 6. teardown scoped to this project alone, on success and failure alike, after the logs are # collected rather than before. @@ -22,7 +24,7 @@ set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -CONTRACTS="${REPO_ROOT}/src/config/runtime/compose-profile-contracts.json" +CONTRACTS="${REPO_ROOT}/src/app-bootstrap/compose-lanes/compose-profile-contracts.json" EVIDENCE_ROOT="${REPO_ROOT}/src/app-bootstrap/build/evidence/runtime-smoke" RUN_ID="$(date -u +%Y%m%dT%H%M%SZ)-$$" # Compose project names accept lowercase alphanumerics, hyphens and underscores only, so the run id @@ -32,7 +34,7 @@ PROJECT_RUN_ID="$(tr '[:upper:]' '[:lower:]' <<<"${RUN_ID}")" # The lanes boot the qualification image: the application with every capability module on the # classpath (src/Dockerfile COMPOSITION, app-bootstrap qualificationBootJar). The default image is # the composition a service ships and carries none of them, so a lane that switches JPA or Kafka on -# would have nothing to switch. docker-compose.yml passes this to the build and puts it in the tag. +# would have nothing to switch. compose.yaml passes this to the build and puts it in the tag. export COMPOSITION=qualification # Every capability is on while its module is present, so each lane starts from all of them off and @@ -79,6 +81,9 @@ for tool in jq docker; do done [[ -r "${CONTRACTS}" ]] || { echo "missing ${CONTRACTS}" >&2; exit 78; } +# The lane-only TLS overlay's keypair directory (src/app-bootstrap/compose-lanes/tls.yaml). +LANE_POSTGRES_TLS="${REPO_ROOT}/src/app-bootstrap/compose-lanes/postgres/tls" + # ---- per-lane state, cleaned up by the trap --------------------------------- PROJECT="" LANE_TMP="" @@ -109,14 +114,14 @@ cleanup_lane() { fi [[ -n "${LANE_TMP}" && -d "${LANE_TMP}" ]] && rm -rf "${LANE_TMP}" # .env.lane is gone — the lane's values live in the generated overlay now — but a file left by an - # older revision of this script would still be read by the local overlay's env_file list. - rm -f "${REPO_ROOT}/src/.env.lane" "${REPO_ROOT}/infra/keycloak/secrets/graphql-smoke-client-secret" + # older revision of this script would still be read by an env_file list of an older stack. + rm -f "${REPO_ROOT}/src/.env.lane" "${REPO_ROOT}/compose/keycloak/secrets/graphql-smoke-client-secret" # The lane keypair, including the CA's private half. A certificate that outlives the run it was # made for is a credential nobody is tracking. - rm -f "${REPO_ROOT}"/infra/postgres/tls/ca.key "${REPO_ROOT}"/infra/postgres/tls/ca.crt \ - "${REPO_ROOT}"/infra/postgres/tls/ca.srl "${REPO_ROOT}"/infra/postgres/tls/server.key \ - "${REPO_ROOT}"/infra/postgres/tls/server.crt "${REPO_ROOT}"/infra/postgres/tls/server.csr \ - "${REPO_ROOT}"/infra/mailpit/tls/server.key "${REPO_ROOT}"/infra/mailpit/tls/server.crt + rm -f "${LANE_POSTGRES_TLS}"/ca.key "${LANE_POSTGRES_TLS}"/ca.crt \ + "${LANE_POSTGRES_TLS}"/ca.srl "${LANE_POSTGRES_TLS}"/server.key \ + "${LANE_POSTGRES_TLS}"/server.crt "${LANE_POSTGRES_TLS}"/server.csr \ + "${REPO_ROOT}"/compose/mailpit/tls/server.key "${REPO_ROOT}"/compose/mailpit/tls/server.crt return "${status}" } @@ -140,9 +145,8 @@ random_key() { head -c 32 /dev/urandom | base64 | tr -d '\n'; } run_lane() { local lane_json="$1" - local id profile runtime + local id runtime profile id="$(jq -r '.id' <<<"${lane_json}")" - profile="$(jq -r '.composeProfile // empty' <<<"${lane_json}")" runtime="$(jq -r '.springRuntime' <<<"${lane_json}")" PROJECT="casmoke-${id}-${PROJECT_RUN_ID}" @@ -161,10 +165,14 @@ run_lane() { file="$(jq -r --arg k "${key}" '.composeFiles[$k]' "${CONTRACTS}")" LANE_ARGS+=(-f "${REPO_ROOT}/${file}") done < <(jq -r '.files[]' <<<"${lane_json}") - [[ -n "${profile}" ]] && LANE_ARGS+=(--profile "${profile}") + # The development stack's backing services carry capability profiles and the lane-only services + # their own, so a lane enables several. The list is the lane's, never a guess from its name. + while read -r profile; do + [[ -n "${profile}" ]] && LANE_ARGS+=(--profile "${profile}") + done < <(jq -r '.composeProfiles[]' <<<"${lane_json}") # A fresh client secret per run, mode 0600, removed on teardown. The realm references it by name. - local secret_dir="${REPO_ROOT}/infra/keycloak/secrets" + local secret_dir="${REPO_ROOT}/compose/keycloak/secrets" local secret_file="${secret_dir}/graphql-smoke-client-secret" mkdir -p "${secret_dir}" local client_secret; client_secret="$(random_secret)" @@ -177,7 +185,7 @@ run_lane() { # a private key in Git. The host name matters — the prod runtime connects with sslmode=verify-full, # which checks the certificate against the name it dialled, so a certificate for anything but `db` # fails exactly as a redirected connection would. That is the check, working. - local tls_dir="${REPO_ROOT}/infra/postgres/tls" + local tls_dir="${LANE_POSTGRES_TLS}" if jq -e '.files | index("tls")' <<<"${lane_json}" >/dev/null; then mkdir -p "${tls_dir}" ( @@ -205,7 +213,7 @@ run_lane() { # Same rule as the PostgreSQL one above and for the same reason: the notification platform's # transport type has no plaintext member, so a relay without a certificate is one the platform # cannot be configured to talk to. Generated per run, removed on teardown. - local mail_tls="${REPO_ROOT}/infra/mailpit/tls" + local mail_tls="${REPO_ROOT}/compose/mailpit/tls" if jq -e '.services | index("mailpit")' <<<"${lane_json}" >/dev/null; then mkdir -p "${mail_tls}" ( @@ -232,7 +240,7 @@ run_lane() { # interpolation reads the process environment and the project .env file, never a service's # env_file. So the application got the generated password and the database got the literal # default, and no lane whose overlay did not happen to restate the value could ever authenticate. - # shared-infra-local passed only because the local overlay restates it, which made the dev lane's + # shared-infra-local passed only because the local overlay (now compose.yaml) restated it, which made the dev lane's # failure look like a dev-specific problem rather than the general one it is. export POSTGRES_DB=ca_skeleton export APP_DATASOURCE_USERNAME=ca_skeleton @@ -323,7 +331,7 @@ run_lane() { # The lane's own settings go into a generated overlay rather than into that file. # # env_file lists merge across overlays and the later file wins, so the developer's optional - # src/.env — declared by the local overlay, after the base — silently overrode the lane's values. + # src/.env — declared by the local overlay (now compose.yaml) — silently overrode the lane's values. # local-messaging started Kafka, set APP_MESSAGING_BROKER=kafka, and was refused by the dependency # validator for a broker it had supplied, because an empty value from a file nobody mentioned won # the merge. An `environment:` block beats every env_file regardless of order, so the lane's @@ -333,6 +341,10 @@ run_lane() { # Written as a function, because a handoff lane rewrites it between phases: the same project and # the same database, with the application recreated under a different activation environment. local lane_overlay="${LANE_TMP}/lane-overrides.yml" + # The application's memory limit, when the lane needs more than the development stack's 512m. + # Only the lane that boots every capability at once does (the contract's appMemoryLimit says why). + local memory_limit + memory_limit="$(jq -r '.appMemoryLimit // empty' <<<"${lane_json}")" write_lane_overlay() { local phase_override="${1:-{\}}" ( @@ -340,6 +352,10 @@ run_lane() { { echo "services:" echo " app:" + if [[ -n "${memory_limit}" ]]; then + echo " mem_limit: ${memory_limit}" + echo " memswap_limit: ${memory_limit}" + fi echo " environment:" local entry for entry in "${lane_environment[@]}"; do @@ -550,13 +566,38 @@ run_lane() { return 1 fi + # 4a. No container of the lane restarted and none was killed for memory. + # + # The application runs with `restart: unless-stopped`, so a container the kernel killed for + # exceeding its memory limit came back on its own. all-adapters did exactly that for a long time + # and failed only when the kill happened to land on a smoke request; every other run reported + # green over a container that had died and restarted under it (integration-r9, 2026-11-07). The + # checks above all ask the application a question, and a restarted application answers them, so + # the restart itself has to be the failure. The peak memory is recorded beside it, so a lane that + # is close to its limit is visible before it crosses it. + local container restarted="" + docker compose -p "${PROJECT}" "${LANE_ARGS[@]}" exec -T app cat /sys/fs/cgroup/memory.peak \ + >"${LANE_EVIDENCE}/app-memory-peak-bytes.txt" 2>/dev/null || true + while read -r container; do + [[ -z "${container}" ]] && continue + docker inspect --format '{{.Name}} restarts={{.RestartCount}} oomKilled={{.State.OOMKilled}}' \ + "${container}" >>"${LANE_EVIDENCE}/restarts.txt" + done < <(docker compose -p "${PROJECT}" "${LANE_ARGS[@]}" ps -a -q) + restarted="$(grep -v ' restarts=0 oomKilled=false$' "${LANE_EVIDENCE}/restarts.txt" || true)" + if [[ -n "${restarted}" ]]; then + echo "${id}: a container restarted or was killed for memory during the lane:" >&2 + echo "${restarted}" >&2 + return 1 + fi + # 5. the manifest ties the evidence to the exact stack that produced it jq -n \ --arg lane "${id}" --arg run "${RUN_ID}" --arg project "${PROJECT}" \ - --arg runtime "${runtime}" --arg profile "${profile}" \ + --arg runtime "${runtime}" \ + --argjson profiles "$(jq '.composeProfiles' <<<"${lane_json}")" \ --argjson services "$(jq '.services' <<<"${lane_json}")" \ '{lane:$lane, runId:$run, project:$project, springRuntime:$runtime, - composeProfile:(if $profile=="" then null else $profile end), services:$services}' \ + composeProfiles:$profiles, services:$services}' \ >"${LANE_EVIDENCE}/manifest.json" echo "== ${id}: passed" @@ -582,11 +623,22 @@ echo "running ${total} blocking lane(s), zero-skip" # script reported that all six had passed. A wrapper whose own success message is a false green is # worse than no wrapper, and nothing else here would have caught it: the count came from the # contract and the exit status from the one lane that did run. +# +# Each lane runs in a subshell with `set -e` on and its status read afterwards, never as an `if` +# condition. Bash ignores `set -e` for every command run as part of an `if` condition, functions and +# subshells included, so `if ( run_lane ... )` turned every step that relied on it into a step whose +# failure was ignored. The image build was one: a build that failed left the lane to start the +# previous run's image, and all eighteen lanes reported green on code the build had refused +# (2026-11-07). --lane mode calls run_lane directly and was not affected. RAN_LANES=0 while read -r -u 3 lane_json; do [[ -z "${lane_json}" ]] && continue RAN_LANES=$((RAN_LANES + 1)) - if ( trap cleanup_lane EXIT; run_lane "${lane_json}" ); then :; else + set +e + ( set -e; trap cleanup_lane EXIT; run_lane "${lane_json}" ) + lane_status=$? + set -e + if [[ ${lane_status} -ne 0 ]]; then FAILED_LANES+=("$(jq -r '.id' <<<"${lane_json}")") fi done 3<<<"${blocking}" diff --git a/scripts/tests/test_check_docs.py b/scripts/tests/test_check_docs.py new file mode 100644 index 00000000..64ebe46e --- /dev/null +++ b/scripts/tests/test_check_docs.py @@ -0,0 +1,255 @@ +"""scripts/check-docs.py의 시험. 고장 낸 입력에서 실패하고, 맞는 입력에서 통과하는지 본다. + + python3 -m unittest discover -s scripts/tests +""" + +from __future__ import annotations + +import importlib.util +import json +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path + +SCRIPTS = Path(__file__).resolve().parent.parent +_spec = importlib.util.spec_from_file_location("check_docs", SCRIPTS / "check-docs.py") +check_docs = importlib.util.module_from_spec(_spec) +sys.modules["check_docs"] = check_docs +_spec.loader.exec_module(check_docs) + +KOREAN = "이 문서는 한국어로 쓴 살아 있는 문서다. 코드와 같은 변경에서 고친다.\n" +ENGLISH = "This document is written in English and explains how the module works in detail.\n" + + +def head(kind: str = "설계서", status: str = "구현됨", written: str = "2026-08-11", + summary: str = "한국어로 쓴 요약 한 문장이다.", canonical: str = "`docs/live.md`", + extra: str = "", label: str | None = None) -> str: + if label is None: + label = check_docs.DECISION_LABEL if kind == "결정 기록" else check_docs.RECORD_LABEL.format(kind=kind) + lines = [check_docs.HEAD_START, label, "", f"- 상태: {status}", f"- 작성일: {written}", + f"- 요약: {summary}", f"- 현재 정본: {canonical}"] + if extra: + lines.append(extra) + lines += [check_docs.HEAD_END, ""] + return "\n".join(lines) + "\n" + + +class Repository: + """A throwaway git working tree with a registry, so the checker sees what git sees.""" + + def __init__(self) -> None: + self._directory = tempfile.TemporaryDirectory() + self.root = Path(self._directory.name) + subprocess.run(["git", "init", "-q", str(self.root)], check=True) + self.write("docs/live.md", KOREAN) + self.write(check_docs.REGISTRY_FILE, json.dumps({"modules": [ + {"id": "app", "gradle_path": ":app", "source_path": "src/app"}, + {"id": "adapter-web", "gradle_path": ":adapter:inbound:web", "source_path": "src/adapter/inbound/web"}, + ]})) + + def write(self, path: str, text: str) -> None: + target = self.root / path + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text(text, encoding="utf-8") + + def run(self, only: tuple[str, ...] = check_docs.CHECKS, exceptions: str = "", + frozen: frozenset[str] | None = None) -> list[str]: + if frozen is None: + frozen = frozenset(check_docs.fingerprint(line) for line in check_docs.read_exceptions(exceptions)) + errors, _ = check_docs.run(self.root, only, exceptions=exceptions, frozen=frozen) + return errors + + def close(self) -> None: + self._directory.cleanup() + + +class RepositoryTestCase(unittest.TestCase): + def setUp(self) -> None: + self.repo = Repository() + self.addCleanup(self.repo.close) + + def assertFailsWith(self, errors: list[str], fragment: str) -> None: + self.assertTrue(any(fragment in error for error in errors), f"no error with {fragment!r}: {errors}") + + +class LanguageTest(RepositoryTestCase): + def test_an_english_living_document_fails(self) -> None: + self.repo.write("docs/guide.md", "# Guide\n\n" + ENGLISH * 3) + self.assertFailsWith(self.repo.run(("language",)), "docs/guide.md: 영어 문서다") + + def test_a_korean_living_document_passes(self) -> None: + self.repo.write("src/app/README.md", "# 앱\n\n" + KOREAN * 3) + self.assertEqual(self.repo.run(("language",)), []) + + def test_code_commands_and_paths_do_not_make_a_korean_document_english(self) -> None: + code = "```bash\n" + "./gradlew :app:test --console=plain and many more english words here\n" * 20 + "```\n" + self.repo.write("docs/guide.md", "# 안내\n\n" + KOREAN + code + "`src/app/Foo.java`를 본다.\n") + self.assertEqual(self.repo.run(("language",)), []) + + def test_a_record_body_keeps_its_original_language(self) -> None: + self.repo.write("docs/design/2026-08-11-x-design.md", head() + "# Design\n\n" + ENGLISH * 3) + self.assertEqual(self.repo.run(("language",)), []) + + def test_an_english_decision_record_body_fails(self) -> None: + self.repo.write("docs/adr/ADR-X-001.md", head(kind="결정 기록", status="채택") + "# ADR\n\n" + ENGLISH * 3) + self.assertFailsWith(self.repo.run(("language",)), "docs/adr/ADR-X-001.md: 영어 문서다") + + +class ExceptionListTest(RepositoryTestCase): + LINE = "language\tdocs/guide.md" + + def test_a_frozen_exception_excuses_its_document(self) -> None: + self.repo.write("docs/guide.md", ENGLISH * 3) + self.assertEqual(self.repo.run(("language",), exceptions=self.LINE + "\n"), []) + + def test_adding_a_line_to_the_exception_list_fails(self) -> None: + self.repo.write("docs/guide.md", ENGLISH * 3) + errors = self.repo.run(("language",), exceptions=self.LINE + "\n", frozen=frozenset()) + self.assertFailsWith(errors, "기준선에 없는 예외다") + + def test_an_exception_that_no_longer_fails_must_be_removed(self) -> None: + self.repo.write("docs/guide.md", KOREAN * 3) + self.assertFailsWith(self.repo.run(("language",), exceptions=self.LINE + "\n"), "더는 걸리지 않는다") + + def test_an_exception_for_one_check_does_not_excuse_another(self) -> None: + self.repo.write("docs/guide.md", "`docs/gone.md`를 본다. " + KOREAN) + errors = self.repo.run(("reference",), exceptions="number\tdocs/guide.md\tdocs/gone.md\n") + self.assertFailsWith(errors, "없는 경로다: docs/gone.md") + + def test_every_line_of_the_real_exception_list_is_in_the_frozen_baseline(self) -> None: + text = (SCRIPTS.parent / check_docs.EXCEPTIONS_FILE).read_text(encoding="utf-8") + outside = [line for line in check_docs.read_exceptions(text) + if check_docs.fingerprint(line) not in check_docs.FROZEN] + self.assertEqual(outside, []) + + def test_a_new_line_in_the_real_exception_list_is_not_in_the_frozen_baseline(self) -> None: + self.assertNotIn(check_docs.fingerprint("language\tdocs/brand-new-english.md"), check_docs.FROZEN) + + +class HeadBlockTest(RepositoryTestCase): + PATH = "docs/design/2026-08-11-x-design.md" + + def errors_for(self, text: str) -> list[str]: + self.repo.write(self.PATH, text + "# Original\n\nbody\n") + return self.repo.run(("head",)) + + def test_a_complete_head_block_passes(self) -> None: + self.assertEqual(self.errors_for(head()), []) + + def test_canonical_none_with_a_reason_passes(self) -> None: + self.assertEqual(self.errors_for(head(canonical="없음 — 지운 기능이다")), []) + + def test_a_record_without_a_head_block_fails(self) -> None: + self.assertFailsWith(self.errors_for(""), "맨 위에 머리 블록이 없다") + + def test_a_status_outside_the_vocabulary_fails(self) -> None: + self.assertFailsWith(self.errors_for(head(status="Accepted")), "설계서의 상태는") + + def test_a_plan_status_on_a_decision_record_fails(self) -> None: + self.repo.write("docs/adr/ADR-X-001.md", head(kind="결정 기록", status="끝남") + "# ADR\n") + self.assertFailsWith(self.repo.run(("head",)), "결정 기록의 상태는") + + def test_a_malformed_date_fails(self) -> None: + self.assertFailsWith(self.errors_for(head(written="2026-13-01")), "작성일은 YYYY-MM-DD다") + + def test_an_english_summary_fails(self) -> None: + self.assertFailsWith(self.errors_for(head(summary="A design for the module boundary.")), "요약은 한국어") + + def test_a_canonical_path_that_does_not_exist_fails(self) -> None: + self.assertFailsWith(self.errors_for(head(canonical="`docs/missing.md`")), "현재 정본 경로가 없다") + + def test_a_canonical_value_without_a_path_fails(self) -> None: + self.assertFailsWith(self.errors_for(head(canonical="jpa 문서")), "현재 정본은") + + def test_superseded_without_its_replacement_fails(self) -> None: + self.assertFailsWith(self.errors_for(head(status="대체됨")), "「대체됨」 칸에 대체한 문서") + + def test_superseded_with_its_replacement_passes(self) -> None: + self.assertEqual(self.errors_for(head(status="대체됨", extra="- 대체됨: `docs/live.md`")), []) + + def test_a_wrong_kind_label_fails(self) -> None: + self.assertFailsWith(self.errors_for(head(label="> **기록 · 계획서** 다른 종류다.")), "머리 블록 둘째 줄은") + + def test_an_unknown_field_fails(self) -> None: + self.assertFailsWith(self.errors_for(head(extra="- 담당: 누군가")), "머리 블록에 없는 칸이다") + + def test_the_kind_follows_the_folder(self) -> None: + self.repo.write("docs/history/plans/evidence/x.md", head(kind="증거", status="보관") + "# Evidence\n") + self.assertEqual(self.repo.run(("head",)), []) + + +class ReferenceTest(RepositoryTestCase): + def errors_for(self, text: str, path: str = "docs/guide.md") -> list[str]: + self.repo.write(path, KOREAN + text) + return self.repo.run(("reference",)) + + def test_a_missing_repository_path_fails(self) -> None: + self.assertFailsWith(self.errors_for("`docs/gone.md`를 읽는다.\n"), "없는 경로다: docs/gone.md") + + def test_an_existing_path_with_a_line_number_passes(self) -> None: + self.assertEqual(self.errors_for("`docs/live.md:12`를 읽는다.\n"), []) + + def test_a_missing_path_under_the_root_compose_folder_fails(self) -> None: + self.assertFailsWith(self.errors_for("`compose/gone/README.md`를 읽는다.\n"), "없는 경로다: compose/gone/README.md") + + def test_a_path_inside_a_command_is_checked(self) -> None: + self.assertFailsWith(self.errors_for("`python3 scripts/gone.py --all`을 돌린다.\n"), "scripts/gone.py") + + def test_fenced_code_is_skipped(self) -> None: + self.assertEqual(self.errors_for("```text\n`docs/gone.md`\n```\n"), []) + + def test_a_history_quote_is_skipped(self) -> None: + self.assertEqual(self.errors_for("> 이력: `docs/gone.md`는 2026-09-25에 지웠다.\n> `src/gone/` 도.\n"), []) + + def test_a_placeholder_path_is_skipped(self) -> None: + self.assertEqual(self.errors_for("`docs/reviews/<폴더>`와 `src/**/CLAUDE.md`를 본다.\n"), []) + + def test_a_leaf_relative_source_path_resolves_through_some_leaf(self) -> None: + self.repo.write("src/app/src/test/resources/contracts/x.sha256", "x") + self.assertEqual(self.errors_for("각 leaf의 `src/test/resources/contracts/x.sha256`을 본다.\n"), []) + + def test_a_source_set_name_every_leaf_has_is_skipped(self) -> None: + self.assertEqual(self.errors_for("테스트는 각 leaf의 `src/test`와 `src/main/java/` 옆에 둔다.\n"), []) + + def test_a_gradle_path_outside_the_registry_fails(self) -> None: + self.assertFailsWith(self.errors_for("`./gradlew :sample:check`를 돌린다.\n"), "registry에 없는 Gradle 경로다: :sample:check") + + def test_a_task_of_a_registered_project_passes(self) -> None: + self.assertEqual(self.errors_for("`./gradlew :adapter:inbound:web:test`와 `:app:check`를 돌린다.\n"), []) + + def test_the_removal_table_is_not_checked(self) -> None: + self.assertEqual(self.errors_for("`src/gone/Old.java`를 지웠다.\n", path="docs/capability-status.md"), []) + + def test_a_record_is_not_checked(self) -> None: + self.repo.write("docs/design/2026-08-11-x-design.md", head() + "`docs/gone.md`\n") + self.assertEqual(self.repo.run(("reference",)), []) + + +class NumberTest(RepositoryTestCase): + def errors_for(self, text: str) -> list[str]: + self.repo.write("src/app/CLAUDE.md", KOREAN + text) + return self.repo.run(("number",)) + + def test_a_copied_spring_boot_version_fails(self) -> None: + self.assertFailsWith(self.errors_for("Runtime baseline: Spring Boot 4.0.8.\n"), "'Spring Boot 4.0.8'") + + def test_a_major_version_passes(self) -> None: + self.assertEqual(self.errors_for("Spring Boot 4 위에서 돈다.\n"), []) + + def test_a_copied_leaf_count_fails(self) -> None: + self.assertFailsWith(self.errors_for("registry는 leaf 65개를 가진다.\n"), "leaf 개수") + self.assertFailsWith(self.errors_for("declares exactly 19 leaf identities.\n"), "leaf 개수") + + def test_a_word_count_of_leaves_passes(self) -> None: + self.assertEqual(self.errors_for("leaf 하나를 고른다.\n"), []) + + +class CommandLineTest(unittest.TestCase): + def test_an_unknown_check_is_a_usage_error(self) -> None: + self.assertEqual(check_docs.main(["--only", "spelling"]), 2) + + +if __name__ == "__main__": + unittest.main() diff --git a/scripts/verify-compose-profile-contracts.sh b/scripts/verify-compose-profile-contracts.sh index c12bb386..28b86573 100755 --- a/scripts/verify-compose-profile-contracts.sh +++ b/scripts/verify-compose-profile-contracts.sh @@ -1,7 +1,7 @@ #!/usr/bin/env bash # The static half of the Compose contract: every lane renders, and renders exactly what it claims. # -# Seven things are checked, and each exists because assuming it cost something: +# Nine things are checked, and each exists because assuming it cost something: # # 1. the Compose version, because `!override` is what stops the dev overlay's tmpfs merging with # the base's and colliding with a bind mount, and it needs 2.24.4; @@ -22,12 +22,15 @@ # lanes ran Redis open and the application anonymous, and the two startup warnings that trade # prints failed the "startup is silent" check of every such lane (r3-J). Lowering that warning # would hide the same trade in production; the lane has to look like a deployment instead. +# 8. a lane's appMemoryLimit, when it has one, is a Compose memory size, because the smoke wrapper +# writes it into the application's mem_limit and a malformed one fails only at `up`. +# 9. the Keycloak realm artifact carries no key Keycloak refuses (below the lane loop). # # Static only. Nothing starts here; scripts/run-compose-runtime-smoke.sh owns that. set -euo pipefail REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)" -CONTRACTS="${REPO_ROOT}/src/config/runtime/compose-profile-contracts.json" +CONTRACTS="${REPO_ROOT}/src/app-bootstrap/compose-lanes/compose-profile-contracts.json" FAILURES=0 fail() { echo " FAIL: $*" >&2; FAILURES=$((FAILURES + 1)); } @@ -118,7 +121,6 @@ lane_count="$(jq '.lanes | length' "${CONTRACTS}")" for index in $(seq 0 $((lane_count - 1))); do lane="$(jq -c ".lanes[${index}]" "${CONTRACTS}")" id="$(jq -r '.id' <<<"${lane}")" - profile="$(jq -r '.composeProfile // empty' <<<"${lane}")" runtime="$(jq -r '.springRuntime' <<<"${lane}")" expected="$(jq -r '.services | sort | join(",")' <<<"${lane}")" @@ -130,7 +132,9 @@ for index in $(seq 0 $((lane_count - 1))); do done < <(jq -r '.files[]' <<<"${lane}") profile_args=() - [[ -n "${profile}" ]] && profile_args=(--profile "${profile}") + while read -r profile; do + [[ -n "${profile}" ]] && profile_args+=(--profile "${profile}") + done < <(jq -r '.composeProfiles[]' <<<"${lane}") # 2. exact service set # stderr goes to a file rather than into the list. It used to be merged with `2>&1`, so Compose's @@ -223,20 +227,26 @@ for index in $(seq 0 $((lane_count - 1))); do done < <(redis_authentication_problems "${lane}" "${model}") fi + # 8. the lane's own memory limit, when it sets one. + memory_limit="$(jq -r '.appMemoryLimit // empty' <<<"${lane}")" + if [[ -n "${memory_limit}" && ! "${memory_limit}" =~ ^[1-9][0-9]*[kmg]$ ]]; then + fail "${id}: appMemoryLimit '${memory_limit}' is not a Compose memory size such as 1g" + fi + [[ ${FAILURES} -eq 0 ]] && echo "${id}: ${expected} @ ${runtime}" done -# 8. the Keycloak realm artifact deserializes into Keycloak's own representation. +# 9. the Keycloak realm artifact deserializes into Keycloak's own representation. # # Keycloak rejects unknown fields rather than ignoring them, so one annotation key anywhere in the # tree fails the whole import, the container exits 1, and every lane that needs an identity provider # fails on Keycloak instead of on what it was testing. This cost two lane runs to find, once for # `_comment` on the realm and once for `_flowComment` on a client, because the second was invisible -# until the first was fixed. Rationale for that artifact lives in infra/keycloak/README.md. -realm="${REPO_ROOT}/infra/keycloak/realms/ca-skeleton-realm.json" +# until the first was fixed. Rationale for that artifact lives in compose/keycloak/README.md. +realm="${REPO_ROOT}/compose/keycloak/realms/ca-skeleton-realm.json" if [[ -f "${realm}" ]]; then if ! jq empty "${realm}" >/dev/null 2>&1; then - fail "infra/keycloak/realms/ca-skeleton-realm.json is not valid JSON" + fail "compose/keycloak/realms/ca-skeleton-realm.json is not valid JSON" else annotations="$(jq -r '[paths(scalars, objects, arrays) | .[-1] | select(type == "string") | select(startswith("_"))] | unique | join(", ")' "${realm}")" if [[ -n "${annotations}" ]]; then @@ -249,4 +259,4 @@ if [[ ${FAILURES} -gt 0 ]]; then echo "verify-compose-profile-contracts: ${FAILURES} lane(s) do not match the contract" >&2 exit 1 fi -echo "verify-compose-profile-contracts: all ${lane_count} lanes match src/config/runtime/compose-profile-contracts.json" +echo "verify-compose-profile-contracts: all ${lane_count} lanes match src/app-bootstrap/compose-lanes/compose-profile-contracts.json" diff --git a/scripts/verify-mongodb-advanced.sh b/scripts/verify-mongodb-advanced.sh index e0da8549..c30b0503 100755 --- a/scripts/verify-mongodb-advanced.sh +++ b/scripts/verify-mongodb-advanced.sh @@ -84,7 +84,7 @@ echo "=== [actual-topology] provider environments" # # The selector names the contract's class. `--tests '*Shard*'` was satisfied by the hermetic # ShardKeyAnalyzerTest, so "sharded topology" was certified by a unit test that never opened a -# connection. Which classes count is `src/config/mongodb/release-contracts.json`, and +# connection. Which classes count is `src/adapter/outbound/persistence-mongo/release/release-contracts.json`, and # MongoReleaseEvidenceVerifier checks the JUnit XML rather than the exit code. if [[ -n "${MONGODB_SHARDED_URI:-}" ]]; then # Not promoted. `mongoShardedTest` is declared in release-contracts.json under @@ -94,7 +94,7 @@ if [[ -n "${MONGODB_SHARDED_URI:-}" ]]; then # a silent skip: an operator who set it expected a qualification to run. echo "sharded topology is experimental and has no registered lane;" >&2 echo " MONGODB_SHARDED_URI was set but mongoShardedTest does not exist." >&2 - echo " See experimental_contracts in src/config/mongodb/release-contracts.json." >&2 + echo " See experimental_contracts in src/adapter/outbound/persistence-mongo/release/release-contracts.json." >&2 FAILED+=("actual-topology:sharded-not-promoted") else echo "actual-topology(sharded): no MONGODB_SHARDED_URI" diff --git a/scripts/verify-mongodb-platform.sh b/scripts/verify-mongodb-platform.sh index 2808fcf2..6543f2d8 100755 --- a/scripts/verify-mongodb-platform.sh +++ b/scripts/verify-mongodb-platform.sh @@ -155,8 +155,8 @@ mkdir -p "${MANIFEST_DIR}" echo " \"commitDirty\": $( [[ -n "$(git -C "${REPO_ROOT}" status --porcelain)" ]] && echo true || echo false )," echo " \"serverImage\": \"${MONGODB_IMAGE:-mongo:8.0.16}\"," echo " \"generatedAt\": \"$(date -u +%Y-%m-%dT%H:%M:%SZ)\"," - echo " \"contractManifest\": \"src/config/mongodb/release-contracts.json\"," - echo " \"contractManifestSha256\": \"$(sha256sum "${REPO_ROOT}/src/config/mongodb/release-contracts.json" | cut -d' ' -f1)\"" + echo " \"contractManifest\": \"src/adapter/outbound/persistence-mongo/release/release-contracts.json\"," + echo " \"contractManifestSha256\": \"$(sha256sum "${REPO_ROOT}/src/adapter/outbound/persistence-mongo/release/release-contracts.json" | cut -d' ' -f1)\"" echo "}" } > "${MANIFEST_DIR}/promotion.json" echo "promotion manifest: ${MANIFEST_DIR}/promotion.json" diff --git a/src/.env.example b/src/.env.example index 9ba52278..5b3cae28 100644 --- a/src/.env.example +++ b/src/.env.example @@ -155,8 +155,8 @@ APP_REDIS_TIMEOUT_SCRIPT=1s # reads the password from and authenticates as . With the application # reference empty and anonymous access not accepted, the application refuses to start while Redis # is on; with the advanced one empty, scripts run as the application account and startup warns. The -# Compose Redis lanes connect as the fixture accounts of infra/redis-sdk/acl/lane-fixture-accounts.acl (the -# Redis comment in src/config/runtime/compose-profile-contracts.json). +# Compose Redis lanes connect as the fixture accounts of compose/redis/acl/lane-fixture-accounts.acl (the +# Redis comment in src/app-bootstrap/compose-lanes/compose-profile-contracts.json). APP_REDIS_AUTHENTICATION_ADVANCED_CREDENTIAL_REFERENCE= APP_REDIS_AUTHENTICATION_ANONYMOUS_ACCESS_ACCEPTED=false APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE= diff --git a/src/Dockerfile b/src/Dockerfile index f7705495..20806c64 100644 --- a/src/Dockerfile +++ b/src/Dockerfile @@ -46,6 +46,11 @@ COPY gradle/ gradle/ COPY gradle.properties ./ COPY config/ ./config/ COPY --parents settings.gradle build.gradle **/build.gradle **/gradle.lockfile ./ +# The data a leaf's build script reads while Gradle configures it: the JPA leaf's readiness cards +# decide which scenarios each readiness lane requires. Since 2026-11-07 such data lives in the +# release/ folder of the leaf that owns it rather than under config/, and without this line that +# leaf fails to configure in the dependency-resolution stage below. +COPY --parents **/release/*.yaml **/release/*.json ./ # The convention plugins, whole. The glob above copies files named build.gradle and gradle.lockfile, # which picks up build-logic's own build script and misses the precompiled script plugins beside it — # so settings.gradle's `includeBuild('build-logic')` resolved against a build that declared no diff --git a/src/Dockerfile.sample b/src/Dockerfile.sample deleted file mode 100644 index 064714f5..00000000 --- a/src/Dockerfile.sample +++ /dev/null @@ -1,159 +0,0 @@ -# syntax=docker/dockerfile:1.7-labs@sha256:b99fecfe00268a8b556fad7d9c37ee25d716ae08a5d7320e6d51c4dd83246894 -# ============================================================================= -# sample-portfolio standalone demo image — twin of src/Dockerfile. -# -# Builds and runs the REFERENCE app (SamplePortfolioApplication), not the -# production composition root (CaSkeletonApplication) that src/Dockerfile builds. -# The sample is the demo-friendly entrypoint: its application.yml self-provides -# defaults for every env placeholder, so what it needs to boot is a demo profile -# and a reachable PostgreSQL (datasource + Flyway sample migrations). -# -# The profile is not baked in. The demo accounts (a published admin password) start only under an -# explicitly active `demo`, `local` or `test` profile (SampleDemoAccountsProductionGuard), and an -# image that defaulted to one would carry them into any deployment that ran it as is. Without -# SPRING_PROFILES_ACTIVE the container stops with exit code 71 and says so. -# -# Build (no build-args required — this is a disposable demo, not a release artifact): -# docker build -f src/Dockerfile.sample src/ -t ca-sample:local -# -# Run (point APP_DATASOURCE_URL at a reachable Postgres; localhost default shown): -# docker run --rm -p 8080:8080 -p 9001:9001 \ -# -e SPRING_PROFILES_ACTIVE=demo \ -# -e APP_DATASOURCE_URL=jdbc:postgresql://host.docker.internal:5432/ca_skeleton \ -# ca-sample:local -# -# The multi-stage build, --parents descriptor glob, STRICT lock verification, -# non-root user, read-only-root-fs writable mounts, and JVM container ergonomics -# are all identical to src/Dockerfile — only the bootJar target differs. -# -# Two files rather than one with a COMPOSITION=sample argument: the release image refuses to build -# without version and source metadata, and folding a zero-argument demo into it would make that -# refusal conditional. The part that must not drift — the dependency stage's COPY lines — is held -# equal by DeveloperExperienceContractTest. -# ============================================================================= - -# Demo defaults so the image builds with zero build-args. Two format constraints from the root -# build.gradle configuration guard (feature-build-release-supply-chain-contract D1/D9): -# - RELEASE_VERSION must be bare MAJOR.MINOR.PATCH — no pre-release/build suffix (build.gradle L21). -# The "-sample" marker therefore lives only on BUILD_VERSION, which is a label, not a gradle prop. -# - GIT_SHA must be 7-40 hex chars (build.gradle L35); 0000000 is the placeholder. -ARG RELEASE_VERSION=0.0.0 -ARG BUILD_VERSION=0.0.0-sample -ARG GIT_SHA=0000000 -ARG SOURCE_URL=https://example.invalid/ca-tmpl-sample - -# ---- Stage 1: builder ------------------------------------------------------- -# Uses the full JDK only in the build stage, never in the final image. -FROM eclipse-temurin:21-jdk-jammy@sha256:801b7e1a9c4befaf82bf9a2a58025ef43a7694bbc84779187ad0524d84742772 AS builder - -ARG RELEASE_VERSION -ARG GIT_SHA - -WORKDIR /build/src - -# Copy the Gradle wrapper and every module's build descriptor + dependency lockfile FIRST, -# so the expensive dependency-resolution layer is cached and only re-runs when a build.gradle -# or gradle.lockfile changes (D8). `--parents` preserves each file's directory structure, so a -# single structure-preserving glob replaces a per-module COPY list: new modules are picked up -# automatically and this stage never drifts out of sync with settings.gradle. -# (Requires the labs Dockerfile frontend — see the `# syntax` directive at the top of this file.) -COPY gradlew ./ -COPY gradle/ gradle/ -COPY gradle.properties ./ -COPY config/ ./config/ -COPY --parents settings.gradle build.gradle **/build.gradle **/gradle.lockfile ./ -# The convention plugins, whole — see src/Dockerfile. Without them settings.gradle's -# includeBuild('build-logic') has no version catalog and no plugins, and this stage failed before -# resolving anything (07-04). DeveloperExperienceContractTest holds these COPY lines equal to the -# release image's. -COPY build-logic/ ./build-logic/ - -# Resolve every module configuration in STRICT mode (no --write-locks in a demo build either). -RUN test -n "${RELEASE_VERSION}" \ - && test -n "${GIT_SHA}" \ - && ./gradlew verifyDependencyLocks --no-daemon --quiet \ - -PreleaseVersion="${RELEASE_VERSION}" -PgitRevision="${GIT_SHA}" - -# Copy full source and stage the executable sample JAR at Gradle's declared Docker output path. -COPY . . -RUN ./gradlew :sample-portfolio:stageDockerJar --no-daemon -x test \ - -PreleaseVersion="${RELEASE_VERSION}" -PgitRevision="${GIT_SHA}" - -# ---- Layer extraction ------------------------------------------------------- -# Identical to src/Dockerfile — see the long note there. Kept in sync because the header of this -# file says the builder stages are, and a demo image whose layout has drifted from the release image -# stops being a demo of the release image. Absolute paths for the same contract-test reason. -RUN java -Djarmode=tools \ - -jar /build/src/sample-portfolio/build/docker/application.jar \ - extract --layers --destination /build/src/sample-portfolio/build/docker/extracted - -# ---- Stage 2: runtime image ------------------------------------------------- -# JRE-only slim image (no full JDK in the demo image either). -FROM eclipse-temurin:21-jre-jammy@sha256:199aebeb3adcde4910695cdebfe782ada38dadb6cc8013159b58d3724451befd AS runtime - -ARG BUILD_VERSION -ARG GIT_SHA -ARG SOURCE_URL - -# OCI image labels. Unlike the release image (src/Dockerfile), the demo image does NOT hard-fail -# on missing metadata — the ARG defaults above keep it buildable with no build-args. -LABEL org.opencontainers.image.title="caskeleton-sample" \ - org.opencontainers.image.description="ca-tmpl sample-portfolio reference/demo application" \ - org.opencontainers.image.source="${SOURCE_URL}" \ - org.opencontainers.image.revision="${GIT_SHA}" \ - org.opencontainers.image.version="${BUILD_VERSION}" - -# ---- Locale / timezone ------------------------------------------------------ -ENV TZ=UTC \ - LANG=C.UTF-8 \ - LC_ALL=C.UTF-8 - -# ---- Writable HOME under read-only root fs ---------------------------------- -ENV HOME=/tmp - -# ---- JVM ergonomics --------------------------------------------------------- -# Identical to src/Dockerfile: container-aware heap, fail-fast on OOM, heap dump to a -# writable mount, and Tomcat temp redirected to /tmp for a read-only root filesystem. -ENV JAVA_TOOL_OPTIONS="\ - -XX:MaxRAMPercentage=75 \ - -XX:+UseContainerSupport \ - -XX:+ExitOnOutOfMemoryError \ - -XX:+HeapDumpOnOutOfMemoryError \ - -XX:HeapDumpPath=/var/tmp/heap \ - -Dserver.tomcat.basedir=/tmp" - -# ---- Filesystem layout (read-only root filesystem) -------------------------- -# At runtime /var/tmp/heap and /tmp MUST be writable mounts (tmpfs/emptyDir). -RUN mkdir -p /var/tmp/heap && chmod 1777 /var/tmp/heap - -# ---- Non-root user ---------------------------------------------------------- -RUN groupadd --system --gid 1000 app \ - && useradd --system --uid 1000 --gid app --no-create-home --shell /usr/sbin/nologin app - -WORKDIR /app - -# ---- Application layers ----------------------------------------------------- -# One COPY per Spring Boot layer, least- to most-frequently-changed, matching src/Dockerfile. -COPY --from=builder --chown=app:app /build/src/sample-portfolio/build/docker/extracted/dependencies/ ./ -COPY --from=builder --chown=app:app /build/src/sample-portfolio/build/docker/extracted/spring-boot-loader/ ./ -COPY --from=builder --chown=app:app /build/src/sample-portfolio/build/docker/extracted/snapshot-dependencies/ ./ -COPY --from=builder --chown=app:app /build/src/sample-portfolio/build/docker/extracted/application/ ./ - -USER app - -# ---- Ports ------------------------------------------------------------------ -# 8080 — application HTTP port -# 9001 — management / actuator port -EXPOSE 8080 9001 - -# ---- Health check ----------------------------------------------------------- -# Actuator readiness probe on the management port (9001). Ignored by Kubernetes, -# which uses its own probes — kept for docker/compose parity with src/Dockerfile. -HEALTHCHECK --interval=30s --timeout=5s --start-period=60s --retries=3 \ - CMD wget --no-verbose --tries=1 --spider \ - http://localhost:9001/actuator/health/readiness || exit 1 - -# ---- Entrypoint ------------------------------------------------------------- -# mainClass (SamplePortfolioApplication) is baked into the bootJar manifest and survives the -# extraction into the thin application.jar. -ENTRYPOINT ["java", "-jar", "application.jar"] diff --git a/src/README.md b/src/README.md index c6ba7a83..d51064ec 100644 --- a/src/README.md +++ b/src/README.md @@ -3,7 +3,7 @@ `src/` 는 Gradle 멀티모듈 루트입니다. 모듈 경계·의존 방향 규칙은 루트 [CLAUDE.md](../CLAUDE.md) 와 [AGENTS.md](../AGENTS.md), 모듈별 규칙은 각 모듈의 `CLAUDE.md` 가 SSOT 입니다. -이 문서는 [build.gradle](build.gradle) 과 [.env](.env) 의 코드 주석에서 덜어낸 **설정 항목 설명과 +이 문서는 [build.gradle](build.gradle) 과 [.env.example](.env.example)(복사해 `.env` 로 씀) 의 코드 주석에서 덜어낸 **설정 항목 설명과 결정 근거**를 모아둔 참조용 기록입니다. 두 파일에는 짧은 기능 주석과 "자세한 내용은 README 참조" 포인터만 남기고, "왜 이렇게 했나"는 여기서 풀어 설명합니다. @@ -26,11 +26,11 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 | `qualityCheck` | 모든 leaf의 SpotBugs + FindSecBugs를 실행 | | `configContractCheck` | `:app-bootstrap:verifyEnvKeys`로 환경 설정 계약을 검사 | | `qualificationCheck` | 전체 기동(system) 레인과 보조 source set Checkstyle을 실행 | -| `integrationCheck` | 선언된 strict integration lane(sample 포함)을 실행. 대부분 container runtime이 필요. 입력이 필요한 lane(Redis topology: `-Predis.topology.mode`, AWS: 보호 자격 증명 env)은 입력이 없으면 빠지고 집계가 그 이유를 출력 | -| `performanceCheck` | 선언된 strict performance lane(부하·종료·pool·자원 상한)을 실행. 실서버·container가 필요. `integration-main.yml` `performance-check`가 main·nightly에 돌림 | -| `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 workflow가 실제 실행하는 단계(`ci`·`:sample-portfolio:check`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 각 단계를 workflow가 `--dry-run` 없이 실행하는지 검사. Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-v`·`--help` 등)과, 실패해도 단계가 실패하지 않을 수 있거나(`\|\| true`, pipefail 없는 파이프, `if` 조건 등) 돌지 않을 수 있거나(조건부 `exit 0` 뒤, 요청으로만 시작하는 workflow 등) 검사가 읽지 않는(`\|\| exit 1`, `{ }` 안 등) 명령은 실행으로 세지 않는다. 자세한 목록은 `build-logic/README.md`. PR 게이트가 돌림 | +| `integrationCheck` | 선언된 strict integration lane을 실행. 대부분 container runtime이 필요. 입력이 필요한 lane(Redis topology: `-Predis.topology.mode`, AWS: 보호 자격 증명 env)은 입력이 없으면 빠지고 집계가 그 이유를 출력 | +| `performanceCheck` | 선언된 strict performance lane(부하·종료·pool·자원 상한)을 실행. 실서버·container가 필요. 상한은 매번 단언하고 끄는 속성이 없다(`-Pperformance.assertions.enabled`가 `true`가 아니면 실패, skip된 테스트가 있어도 실패). `integration-main.yml` `performance-check`가 main·nightly에 같은 명령으로 돌림 | +| `verifyStrictLaneStages` | `--dry-run` 전용. `explicitOnly`가 아닌 strict lane이 workflow가 실제 실행하는 단계(`ci`·`mainCheck`·`integrationCheck`·`performanceCheck`·`releaseCheck`) 중 하나의 계획에 있는지, 각 단계를 workflow가 `--dry-run` 없이 실행하는지 검사. Gradle이 작업을 돌리지 않는 명령(`--dry-run`·`-v`·`--help` 등)과, 실패해도 단계가 실패하지 않을 수 있거나(`\|\| true`, pipefail 없는 파이프, `if` 조건 등) 돌지 않을 수 있거나(조건부 `exit 0` 뒤, 요청으로만 시작하는 workflow, `paths` 필터로만 시작하는 workflow, `releaseCheck` 밖의 단계를 태그 push·`release`로만 시작하는 workflow 등) 검사가 읽지 않는(`\|\| exit 1`, `{ }` 안 등) 명령은 실행으로 세지 않는다. 자세한 목록은 `build-logic/README.md`. PR 게이트가 돌림 | | `ci` | PR 게이트: 모든 leaf `check`(API surface 검사 포함, 소유자 결정 20) + `architectureCheck` + `qualityCheck` | -| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + sample web 계약 + sample 전체 기동(`:sample-portfolio:systemTest`) + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) | +| `mainCheck` | main 단계: `configContractCheck` + `qualificationCheck` + `verifyPublicPathSnapshot` + 전송·메시징 qualification 레인 + 각 leaf의 `mainCheck`(문서 대조 레인 `*DocumentContractTest`, objectstorage MinIO 레인) | | `releaseCheck` | tag 전용 검사: `verifyReleaseProvenance` + `verifyPublicPathSnapshot`(`ci`를 다시 돌리지 않음) | 따라서 로컬에서 한 모듈만 수정했다면 `./gradlew :domain-core:check`처럼 focused task를 @@ -42,14 +42,14 @@ Checkstyle은 **포매터가 표현할 수 없는 것만** — 네이밍과 몇 수백 줄짜리 커스텀 YAML 파서), `verifyReadmeCommands`·`verifyDocumentedLeafCount`· `verifyRunbookReferences`·`verifyTestSourceSetRegistry`(문서 파서), `verifyConfigurationPropertiesProcessor`(`ca.spring-config` convention plugin이 대체). -근거는 `docs/superpowers/specs/2026-09-16-verification-surface-reduction-design.md`. +근거는 `docs/design/2026-09-16-verification-surface-reduction-design.md`. ### Local bootstrap -`scripts/bootstrap-local.sh [profile]`(저장소 루트)은 compile → Docker 확인 → DB 기동 대기 → +`scripts/bootstrap-local.sh`(저장소 루트)은 compile → Docker 확인 → DB 기동 대기 → app 기동(Flyway 포함) → health smoke를 순서대로 실행합니다(예전 `./gradlew bootstrap`, 리뷰 BUILD-O3-5로 build-logic 플러그인에서 스크립트로 옮김). -DB와 app lifecycle은 저장소 루트의 base/local Compose 조합이 소유하며, app startup Flyway가 +DB와 app lifecycle은 저장소 루트의 개발 compose 파일 `compose.yaml`(`db`는 `jpa` profile)이 소유하며, app startup Flyway가 끝나 public health endpoint가 준비되어야 다음 단계로 넘어갑니다. `src/.env.example`은 커밋된 env 계약이고 `src/.env`는 로컬 실행 입력입니다. `verifyEnvKeys`는 example/registry/shipped YAML을 함께 검사합니다. @@ -296,8 +296,9 @@ Kafka 없이 기동합니다. 나머지 기능은 `app-bootstrap/build.gradle` ### Compose와 런타임 스모크 -- **Docker Compose 최소 버전 `2.24.4`.** SSOT는 `src/config/runtime/compose-profile-contracts.json` - 이고, 정본 스크립트가 검증합니다. +- **Docker Compose 최소 버전 `2.24.4`.** SSOT는 `src/app-bootstrap/compose-lanes/compose-profile-contracts.json` + 이고, 정본 스크립트가 검증합니다. lane은 저장소 루트 `compose.yaml`(개발 환경)을 바탕으로 쓰고, lane에만 + 필요한 overlay·smoke client·스키마 적용은 `src/app-bootstrap/compose-lanes/`에 있습니다. - 진입점은 둘뿐이고, 그 둘만이 증거입니다. 워크플로에 명령 일부를 인라인하면 one-shot 없이 도는 레인이 초록으로 보고됩니다. @@ -305,9 +306,9 @@ Kafka 없이 기동합니다. 나머지 기능은 `app-bootstrap/build.gradle` # 정적: profile별 정확한 service set, 병합된 모델 전체, mount target 유일성 ./scripts/verify-compose-profile-contracts.sh -# 동적: 15개 blocking 레인을 zero-skip으로. create → up --wait → 필수 one-shot → -# sanitized evidence → 고유 project teardown -./scripts/run-compose-runtime-smoke.sh --matrix src/config/runtime/compose-profile-contracts.json +# 동적: 계약의 blocking 레인을 zero-skip으로. create → up --wait → 필수 one-shot → +# 컨테이너 재시작·OOM 0 확인 → sanitized evidence → 고유 project teardown +./scripts/run-compose-runtime-smoke.sh --matrix src/app-bootstrap/compose-lanes/compose-profile-contracts.json ``` `--lane `는 실패 재현용이고, 레인 하나가 초록인 것은 matrix가 통과했다는 증거가 아닙니다. @@ -317,7 +318,7 @@ Kafka 없이 기동합니다. 나머지 기능은 `app-bootstrap/build.gradle` Kafka·Redis는 위 "기능 추가 = 한 줄 + env" 표의 한 줄로 고릅니다. 모듈이 있으면 켜지고, 없으면 그 포트를 구현하는 bean이 아예 없습니다. 아래는 모듈을 고른 뒤 동작을 고르는 키입니다. -- **`APP_CACHE_REDIS_ENABLED`** — deprecated(2026-11-30 제거 예정). 읽는 곳은 `sample-portfolio`뿐이고, +- **`APP_CACHE_REDIS_ENABLED`** — deprecated(2026-11-30 제거 예정). 읽는 곳이 없고, 기본 조립에서 Redis를 켜고 끄는 것은 `APP_REDIS_ENABLED`입니다. - **`APP_CACHE_CANONICAL_DEFAULT_PROVIDER`** — canonical default semantic region 선택. `disabled`(기본) | `redis`. `redis`는 canonical Redis CACHE role binding을 함께 요구합니다. @@ -359,10 +360,7 @@ app: - 기존 `APP_OUTBOUND_HTTP_*`와 `app.outbound.http.*`는 canonical 설정이 아닙니다. 루트 `src/.env`, `app-bootstrap`의 application YAML, env-key registry에서 제거됐으며 canonical composition에 입력하면 상태와 무관하게 기동을 거부합니다. -- 다만 `sample-portfolio`의 application YAML에는 legacy facade를 시연하기 위해 15개 키가 남아 - 있습니다. 이 모듈은 fixture/reference consumer이고 production 의존성이 아니며, 그 YAML은 - `:app-bootstrap:verifyEnvKeys`가 검사하는 세 파일에 포함되지 않습니다. "제거됐다"는 문장이 저장소 전체를 - 가리킨다고 읽히지 않도록 범위를 명시합니다. +- 그 키를 시연하던 샘플 모듈의 YAML은 2026-11-07 샘플과 함께 지웠습니다. 이제 저장소 어디에도 남아 있지 않습니다. - legacy JDK facade가 필요한 fork만 canonical composition 밖에서 `OutboundHttpSettings.bindLegacy(Binder)`와 legacy configuration을 명시적으로 import합니다. timeout/retry/CB/response-size 설정은 그 migration API 내부 계약일 뿐 canonical provider @@ -535,11 +533,11 @@ migration/vendor 계약의 증거로 사용하지 않습니다. 멱등성 provid `disabled`(기본)나 `redis`로 둡니다. `postgresql`은 H2 data source에서 기동을 거부합니다. `dev` 를 호스트에서 띄우려면(`SPRING_PROFILES_ACTIVE=dev`) PostgreSQL 이 필요합니다. -`docker-compose.local.yml` 의 `db` 서비스가 루프백(`127.0.0.1:5433`)에만 게시하며, 이 주소가 +`compose.yaml` 의 `db` 서비스(`jpa` profile)가 루프백(`127.0.0.1:5433`)에만 게시하며, 이 주소가 아래 `APP_DATASOURCE_URL` 의 커밋된 기본값입니다. 저장소 루트에서 실행합니다. ```bash -docker compose -f docker-compose.yml -f docker-compose.local.yml up -d --wait db +docker compose up -d --wait db ``` 컨테이너로 띄우는 `scripts/bootstrap-local.sh` 경로는 이 호스트 포트를 쓰지 않습니다. compose 가 app diff --git a/src/adapter/inbound/graphql/CLAUDE.md b/src/adapter/inbound/graphql/CLAUDE.md index c2fa22eb..89dd89bf 100644 --- a/src/adapter/inbound/graphql/CLAUDE.md +++ b/src/adapter/inbound/graphql/CLAUDE.md @@ -73,7 +73,7 @@ platform wire-code catalogue in `GraphQlErrorCode`. - application/domain `ApiErrorCode` values remain a separate namespace and pass through with `GraphQlErrorCode.of(...)`; GraphQL must not rename product errors. Only a registered `ApiErrorCode` reaches the wire this way — a DataLoader per-key failure carries one, never a free - string (owner decision 25). + string (owner decision 2026-09-25). - new GraphQL-owned platform codes use the `GRAPHQL_` prefix. The existing unprefixed platform values are frozen legacy wire contracts and are listed explicitly by `legacyUnprefixedPlatformCodes()`. @@ -101,7 +101,7 @@ application/platform namespace split. `org.springframework.http` 을 import 하는 것은 **하나도 없다**(servlet API 는 body 상한 필터만 `compileOnly` 로 쓴다). 서버 선택은 composition root 의 결정이고, `gradle.lockfile` 이 이를 고정한다(`spring-boot-starter-web`·`spring-webmvc`·`spring-webflux`·`tomcat-embed-*` 전부 -`testCompileClasspath,testRuntimeClasspath` 만). 템플릿은 servlet 단일 스택(D4)이라 실행 +`testCompileClasspath,testRuntimeClasspath` 만). 템플릿은 servlet 단일 스택이라 실행 프로파일(`execution-profile`)·reactive 런타임 감지·blocking bridge 는 2026-09-25 에 삭제했다. - `annotationProcessor` 로 `spring-boot-configuration-processor` — `GraphQlPlatformProperties` 가 `@ConfigurationProperties` 이므로 `ca.spring-config` convention plugin이 주는 패리티 @@ -114,19 +114,21 @@ application/platform namespace split. `INBOUND_ADAPTERS_DO_NOT_DEPEND_ON_OUTBOUND_ADAPTERS`, 일반 `..adapter.inbound..` 규칙이 이 모듈을 자동 커버 — per-module 규칙 추가 불필요). - 프로덕션 feature 쿼리/뮤테이션을 스켈레톤에 두는 것 — health 표면만 (web 의 - `HealthcheckController` 와 동일 원칙). feature 스키마/컨트롤러/매퍼는 sample 모듈이 소유한다. + `HealthcheckController` 와 동일 원칙). feature 스키마/컨트롤러/매퍼는 그 기능을 가진 서비스가 소유한다. - 모듈별 `yml` — 설정은 프레임워크 `spring.graphql.*` 로 composition-root `application.yml` 에 산다. ## Error mapping (`Category → ErrorType`) 모든 client 에러는 `error/GraphQlWireErrorMapper` 하나를 거친다 — 전송 interceptor, 실행 전 pipeline(instrumentation), data fetcher resolver 세 곳이 같은 bean 을 받는다. 순서는 플랫폼 거부 -(예외가 구현한 `error/GraphQlPlatformRejection`) → `ApiErrorCarrier`(자기 `ApiErrorCode`) → 등록된 -application 매핑(`GraphQlExceptionResolver`) → `IllegalArgumentException`=`BAD_PARAMETER`. 어디에도 안 +(예외가 구현한 `error/GraphQlPlatformRejection`) → 실패 자신이 `ApiErrorCarrier`면 그 `ApiErrorCode` → 등록된 +application 매핑(`GraphQlExceptionResolver`) → 원인 사슬의 첫 carrier → `IllegalArgumentException`·인자 binder의 +`BindException`=`BAD_PARAMETER`(2026-11-07 소유자 결정). 등록 매핑이 원인 사슬의 carrier보다 먼저라, 앱이 등록한 +실패는 하위 실패를 원인으로 들어도 등록한 코드로 답한다. 실패 자신이 carrier인 타입은 등록해도 쓰이지 않는다. 어디에도 안 걸린 예외는 `INTERNAL_ERROR` 로 가려지고, 같은 executionId 로 ERROR 로그 한 줄이 남는다. client 문구는 shared-contract `ClientErrorMessages`(Category 별 한국어 표), `retryable` 은 코드의 값이다. Category → wire category/`ErrorType` 표는 mapper 의 `RENDERINGS` 하나뿐이고 [README.md](README.md)에 옮겨 둔다. -DataLoader 키 실패는 등록된 `ApiErrorCode` 만 싣는다(`GraphQlBatchLoadException`, 소유자 결정 25). +DataLoader 키 실패는 등록된 `ApiErrorCode` 만 싣는다(`GraphQlBatchLoadException`, 2026-09-25 소유자 결정). ## 향후 adopter 의 feature 기여 방법 @@ -137,7 +139,7 @@ DataLoader 키 실패는 등록된 `ApiErrorCode` 만 싣는다(`GraphQlBatchLoa - **도메인 예외 매핑**: adopter 는 자신의 `DataFetcherExceptionResolver` 를 추가하거나 `ApiErrorCarrier` 를 사용해 안정적 코드로 매핑할 수 있다. -현재 sample 에 feature GraphQL schema/controller/resolver 가 있다고 가정하지 않는다. 이 leaf 는 +템플릿에는 feature GraphQL schema/controller/resolver 가 없다. 이 leaf 는 health 스키마만 소유한다. ## 구현된 플랫폼 범위 — 등급으로 말한다 diff --git a/src/adapter/inbound/graphql/README.md b/src/adapter/inbound/graphql/README.md index 90f6f66c..ff9c7c63 100644 --- a/src/adapter/inbound/graphql/README.md +++ b/src/adapter/inbound/graphql/README.md @@ -22,8 +22,8 @@ Spring for GraphQL 은 schema-first 다. 빈 스키마로는 부팅이 실패하 스켈레톤은 **WorkLog 를 이름으로 알지 못한다.** 향후 composition root 가 이 모듈을 classpath 에 명시적으로 채택하고 feature 를 추가하면 Spring for GraphQL 이 다음 두 축으로 합성할 수 있다: -- **스키마**: `classpath:graphql/**/*.graphqls` 를 전부 병합한다. sample 모듈의 - 향후 `worklog.graphqls` 같은 feature 스키마는 스켈레톤의 `skeleton.graphqls` 와 합쳐진다. +- **스키마**: `classpath:graphql/**/*.graphqls` 를 전부 병합한다. 서비스가 더하는 + `order.graphqls` 같은 feature 스키마는 스켈레톤의 `skeleton.graphqls` 와 합쳐진다. - **resolver(핸들러)**: 컨텍스트의 모든 `@Controller` 의 `@QueryMapping`/`@MutationMapping` 메서드를 바인딩한다. 향후 feature 의 GraphQL controller 는 스켈레톤을 수정하지 않고 등록할 수 있다. @@ -48,7 +48,7 @@ Spring for GraphQL 은 schema-first 다. 빈 스키마로는 부팅이 실패하 맞는 값: local→`LOCAL`, dev→`DEV`, prod→`PRODUCTION_INTERNAL`|`PRODUCTION_PUBLIC`). production mode는 `GraphQlAuthorizationPolicy` bean도 필요하다. 나머지 `APP_GRAPHQL_*`는 기본값으로 동작한다. -`sample-portfolio` 에 feature GraphQL 스키마/controller 가 있다는 뜻은 아니며, leaf 자체는 최소 +템플릿에 feature GraphQL 스키마/controller 가 있다는 뜻은 아니며, leaf 자체는 최소 health 스키마로 독립 기동할 수 있다. ## 에러 매핑 — web `GlobalExceptionHandler` / gRPC 인터셉터의 GraphQL 형제 @@ -66,15 +66,26 @@ instrumentation, data fetcher resolver 세 곳이 같은 bean 을 받는다). 1. **플랫폼 거부** — 플랫폼 예외가 `error/GraphQlPlatformRejection`(wire code·shared `Category`· 필요하면 wire category/constraint)을 구현한다. `instanceof` 사슬로 등록하던 두 번째 목록은 없다. -2. **`ApiErrorCarrier`** — 자기 `ApiErrorCode` 로 매핑. shared-contract 의 `MappingException`· +2. **실패 자신이 `ApiErrorCarrier`** — 그 `ApiErrorCode` 로 매핑. shared-contract 의 `MappingException`· `AdapterDisabledException`·`PersistenceFailureException`(JPA 예외 포함)·`DependencyFailureException`, - application 의 멱등성 예외, DataLoader 키 실패(`GraphQlBatchLoadException`, **등록된 `ApiErrorCode` - 만** — 소유자 결정 25)가 모두 여기로 온다. -3. **등록된 application 매핑**(`GraphQlExceptionResolver`). -4. **`IllegalArgumentException`** → `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`) — web·gRPC·STOMP 와 같다. - 로그도 같은 WARN 한 줄 `request refused as BAD_PARAMETER by <예외 타입> (executionId=)` 이고, - 입력값이 들 수 있는 메시지는 남기지 않는다. -5. 나머지는 `INTERNAL_ERROR` 로 가려지고 같은 executionId 로 ERROR 로그 한 줄이 남는다. + application 의 멱등성·락 예외, DataLoader 키 실패(`GraphQlBatchLoadException`, **등록된 `ApiErrorCode` + 만** — 소유자 결정 25)가 모두 여기로 온다. 이런 타입을 `GraphQlExceptionResolver`에 등록해도 쓰이지 않는다. +3. **등록된 application 매핑**(`GraphQlExceptionResolver`). 앱이 그 실패 타입에 내린 결정이라 원인 사슬의 + carrier보다 먼저다. 앱이 등록한 실패가 하위 실패(예: `PersistenceFailureException`)를 원인으로 들어도 등록한 + 코드로 답한다. web 에서 앱의 도메인 advice 가 먼저 받는 것과 같다(소유자 결정 2026-11-07, 재리뷰 RR8-01-01). +4. **원인 사슬의 첫 carrier**(`ApiErrorCarrier.firstIn`, web·gRPC·STOMP와 같은 함수) — 등록되지 않은 예외가 + 감싼 carrier 를 그 코드로 매핑(재리뷰 RR7-01-05). +5. **`IllegalArgumentException`과 인자 binder의 `BindException`** → `BAD_PARAMETER`(`REQUEST`, `BAD_REQUEST`) — + web·gRPC·STOMP 와 같다. `BindException`은 `@Argument` 값이 파라미터 타입으로 바뀌지 않을 때 Spring 이 컨트롤러 + 전에 던진다(web 의 경로 변수 변환 실패와 같은 답, 소유자 결정 2026-11-07). 변환기가 던진 실패는 binding + result 에 남고 원인으로 실리지 않아, 변환기가 carrier 를 던져도 답은 `BAD_PARAMETER`다(인자 변환 단계는 carrier 를 + 보지 않는다, 소유자 결정 2026-11-07). 로그도 같은 WARN 한 줄 + `request refused as BAD_PARAMETER by <예외 타입> (executionId=)` 이고, 입력값이 들 수 있는 메시지 + (`BindException`은 `rejected value [...]`)는 남기지 않는다. +6. 나머지는 `INTERNAL_ERROR` 로 가려지고 같은 executionId 로 ERROR 로그 한 줄이 남는다. + +로그 줄은 어느 단계가 답하든 원인 사슬의 첫 carrier 로 정한다. 등록 매핑이 답한 실패도 그 안의 서버 쪽 carrier +(예: DB 연결 실패)는 그 carrier 의 줄(persistence 는 분류만)을 남긴다. 4xx carrier 는 남기지 않는다. - **client 문구**: shared-contract `ClientErrorMessages`(Category 별 한국어 문구 표 하나, 소유자 결정 11). 예외 메시지는 절대 나가지 않는다. @@ -292,7 +303,7 @@ trivial fetcher 는 세지 않는다. 기본 10 은 기본 page 크기 20 보다 `ObservationRegistry` 로 나가며(Actuator 가 있으면 timer 로 집계), 없으면 WARN 만 남는다. 버린 대안: 카탈로그에 등록되지 않은 list 자식 필드를 기동 때 경고 — 모든 list 필드를 adopter 가 -카탈로그에 등록해야 의미가 생겨 비용에 비해 효과가 작다. 재검토 조건: sample 에 GraphQL feature 가 +카탈로그에 등록해야 의미가 생겨 비용에 비해 효과가 작다. 재검토 조건: 템플릿에 GraphQL feature 가 들어오면 그 코드가 위 예시를 대신한다. ## 요청 deadline — 무엇이 끊기고 무엇이 안 끊기나 diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlExceptionResolver.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlExceptionResolver.java index 47d9eee1..bea2abe4 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlExceptionResolver.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlExceptionResolver.java @@ -13,6 +13,11 @@ import org.slf4j.LoggerFactory; * message. That default is the important half: a new exception type introduced anywhere in the * stack is masked automatically instead of leaking until someone notices. * + *

A registered mapping answers before a carrier in the failure's cause chain, so a failure the + * application models keeps its code when it keeps what it translated as its cause. A failure that + * is itself an {@code ApiErrorCarrier} answers with its own code before any mapping is consulted; + * registering such a type changes nothing ({@link GraphQlWireErrorMapper#map}). + * *

Partial data is untouched here. This maps one failing field; sibling fields that resolved stay * in the response. */ diff --git a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapper.java b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapper.java index cc0d86a4..3dceb849 100644 --- a/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapper.java +++ b/src/adapter/inbound/graphql/src/main/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapper.java @@ -11,9 +11,11 @@ import graphql.GraphQLError; import java.util.EnumMap; import java.util.Map; import java.util.Objects; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.graphql.execution.ErrorType; +import org.springframework.validation.BindException; /** * The one place a failure becomes something a client can see. @@ -38,11 +40,13 @@ import org.springframework.graphql.execution.ErrorType; * the detail goes to the log under that id ({@link GraphQlExceptionResolver}). * *

A carrier is logged here, with {@link ServerFailureLog}'s line — the one the web and gRPC - * adapters write — plus the execution id the client received. A server-side code therefore leaves - * its detail in the log, such as the scope digest of an {@code IDEMPOTENCY_RECOVERY_REQUIRED} - * (review 2026-11-04 RR4-03-03); a persistence failure leaves its classification only. An unmapped - * {@link IllegalArgumentException} leaves the WARN line every transport writes for it, naming its - * type and never its message (review 2026-11-05 RR6-01-06). + * adapters write — plus the execution id the client received, also when a registered mapping + * answers the failure that wraps it. A server-side code therefore leaves its detail in the log, + * such as the scope digest of an {@code IDEMPOTENCY_RECOVERY_REQUIRED} (review 2026-11-04 + * RR4-03-03); a persistence failure leaves its classification only. An unmapped {@link + * IllegalArgumentException} leaves the WARN line every transport writes for it, naming its type and + * never its message (review 2026-11-05 RR6-01-06); so does an {@code @Argument} the argument binder + * refused, whose message quotes the rejected value. */ public final class GraphQlWireErrorMapper { @@ -103,38 +107,65 @@ public final class GraphQlWireErrorMapper { /** * Maps a failure from any stage. * - *

Order: a platform rejection, then an {@link ApiErrorCarrier}, then the application's - * registered mappings, then {@link IllegalArgumentException} as {@code BAD_PARAMETER} (the same - * answer every transport gives), and finally the masked internal error. Platform rejections come - * first: an authorization denial raised from inside a resolver means the same thing to a client - * as one raised before execution. A registered mapping outranks the argument rule so an - * application that models its own {@code IllegalArgumentException} subtype keeps its code. + *

Order (owner decision 2026-11-07, re-review RR8-01-01): + * + *

    + *
  1. a platform rejection; + *
  2. a failure that is itself an {@link ApiErrorCarrier}, by its code; + *
  3. the application's registered mappings; + *
  4. the first carrier in the failure's cause chain, as on every transport (review 2026-11-06 + * RR7-01-05); + *
  5. a refused argument as {@code BAD_PARAMETER}, the same answer every transport gives; + *
  6. the masked internal error. + *
+ * + *

Platform rejections come first: an authorization denial raised from inside a resolver means + * the same thing to a client as one raised before execution. A registered mapping outranks a + * carrier in the cause chain because it is the application's decision about that failure type — a + * failure it models keeps its code when it keeps what it translated as its cause, as an + * application's own exception handler keeps it on the web transport. It does not outrank a + * failure that is itself a carrier: that failure already says its code. It outranks the argument + * rule so an application that models its own {@code IllegalArgumentException} subtype keeps its + * code. A refused argument is an {@link IllegalArgumentException} or the {@link BindException} + * Spring for GraphQL's argument binder raises when an {@code @Argument} the client sent does not + * convert to the parameter's type, as the web adapter answers a path variable that does not + * (owner decision 2026-11-07). + * + *

The binder keeps a converter's failure in the binding result, not as a cause, so a carrier a + * converter throws never answers in place of {@code BAD_PARAMETER}: the argument conversion stage + * does not read a carrier (owner decision 2026-11-07). */ public GraphQlWireError map(Throwable failure, GraphQlErrorContext context) { if (failure instanceof GraphQlPlatformRejection rejection) { return fromRejection(rejection, context); } ApiErrorCode shared = sharedCodeOf(failure); + logAnswer(failure, shared, context); if (shared != null) { - logAnswer(failure, shared, context); return fromApiError(shared, context); } return applicationMappings.resolve(failure, context); } /** - * Writes {@link ServerFailureLog}'s line for a failure answered with a shared code: a carrier's - * line at ERROR, or nothing for a client-side carrier; an unmapped {@link - * IllegalArgumentException} the WARN line naming its type, as on every transport. + * Writes {@link ServerFailureLog}'s line for a failure: the line of the first carrier in its + * cause chain at ERROR — the carrier's, not a wrapper's — or nothing for a client-side carrier, + * whichever stage answers, so a failure the application registered still leaves the server-side + * carrier it wraps in the log; an unmapped refused argument the WARN line naming its type, as on + * every transport. A binding failure's message quotes the rejected value, so it is never logged. + * Anything else is logged by the masking resolver, or not at all when a mapping answers it. + * + * @param shared the shared code the failure is answered with, or {@code null} */ private static void logAnswer( Throwable failure, ApiErrorCode shared, GraphQlErrorContext context) { String suffix = " (executionId={})"; - if (failure instanceof ApiErrorCarrier) { - ServerFailureLog.of(failure, shared) + Optional carrier = ApiErrorCarrier.firstIn(failure); + if (carrier.isPresent()) { + ServerFailureLog.of(carrier.get(), ((ApiErrorCarrier) carrier.get()).errorCode()) .ifPresent(line -> LOG.error(line.format(suffix), line.arguments(context.executionId()))); - } else if (failure instanceof IllegalArgumentException refused) { - ServerFailureLog line = ServerFailureLog.refusedArgument(refused); + } else if (shared != null && isRefusedArgument(failure)) { + ServerFailureLog line = ServerFailureLog.refused(OperationalError.BAD_PARAMETER, failure); LOG.warn(line.format(suffix), line.arguments(context.executionId())); } } @@ -191,18 +222,31 @@ public final class GraphQlWireErrorMapper { } /** - * The shared code a failure carries, or {@code null}. + * The shared code a failure is answered with, or {@code null} when a registered mapping or the + * masking answers it — stages 2, 4 and 5 of {@link #map}'s order. * - *

An {@link IllegalArgumentException} the application did not register a mapping for is {@link + *

A refused argument the application did not register a mapping for is {@link * OperationalError#BAD_PARAMETER}, as it is on the web, gRPC and STOMP transports. */ private ApiErrorCode sharedCodeOf(Throwable failure) { if (failure instanceof ApiErrorCarrier carrier) { return carrier.errorCode(); } - if (failure instanceof IllegalArgumentException && !applicationMappings.maps(failure)) { + if (applicationMappings.maps(failure)) { + return null; + } + Optional carrier = ApiErrorCarrier.firstIn(failure); + if (carrier.isPresent()) { + return ((ApiErrorCarrier) carrier.get()).errorCode(); + } + if (isRefusedArgument(failure)) { return OperationalError.BAD_PARAMETER; } return null; } + + /** An argument the request got wrong: thrown as one, or refused by the argument binder. */ + private static boolean isRefusedArgument(Throwable failure) { + return failure instanceof IllegalArgumentException || failure instanceof BindException; + } } diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java index d247b68f..bf3a6673 100644 --- a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/error/GraphQlWireErrorMapperTest.java @@ -11,9 +11,11 @@ import dev.caskeleton.adapter.inbound.graphql.dataloader.GraphQlMissingKeyExcept import dev.caskeleton.adapter.inbound.graphql.execution.GraphQlRequestCancelledException; import dev.caskeleton.application.idempotency.IdempotencyInFlightException; import dev.caskeleton.application.idempotency.IdempotencyRecoveryRequiredException; +import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; import java.sql.SQLException; +import java.time.Duration; import java.util.List; import java.util.stream.Stream; import org.junit.jupiter.api.DisplayName; @@ -21,6 +23,7 @@ import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.LoggerFactory; +import org.springframework.validation.BindException; class GraphQlWireErrorMapperTest { @@ -104,6 +107,21 @@ class GraphQlWireErrorMapperTest { .containsExactly("BAD_PARAMETER", "REQUEST"); } + @org.junit.jupiter.api.Test + void anArgumentBindingFailureIsABadParameterRequestError() { + // given + GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking(); + BindException failure = new BindException(new Object(), "order"); + + // when + GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test()); + + // then + assertThat(error.extensions()) + .extracting(extensions -> extensions.get("code"), extensions -> extensions.get("category")) + .containsExactly("BAD_PARAMETER", "REQUEST"); + } + @org.junit.jupiter.api.Test void anOversizedRequestIsPayloadTooLarge() { // given @@ -231,8 +249,150 @@ class GraphQlWireErrorMapperTest { null); } + @org.junit.jupiter.api.Test + void aLockAcquisitionTimeoutKeepsItsRetryableCode() { + // given + GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking(); + RuntimeException failure = + new LockAcquisitionTimeoutException("orders/42", Duration.ofSeconds(3)); + + // when + GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test()); + + // then + assertThat(error.extensions()) + .extracting(extensions -> extensions.get("code"), extensions -> extensions.get("retryable")) + .containsExactly("LOCK_ACQUISITION_TIMEOUT", true); + } + + @org.junit.jupiter.api.Test + void aCarrierWrappedInAnotherExceptionKeepsItsOwnCode() { + // given + GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking(); + RuntimeException failure = + new IllegalStateException("use case failed", persistenceFailureWithASqlCause()); + + // when + GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test()); + + // then + assertThat(error.extensions()) + .extracting(extensions -> extensions.get("code"), extensions -> extensions.get("category")) + .containsExactly("DB_UNAVAILABLE", "DEPENDENCY"); + } + + @org.junit.jupiter.api.Test + void aWrappedPersistenceFailureIsLoggedByItsClassificationWithoutTheWrapperOrTheSqlCause() { + // given + GraphQlWireErrorMapper mapper = GraphQlWireErrorMapper.masking(); + RuntimeException failure = + new IllegalStateException("use case failed", persistenceFailureWithASqlCause()); + + // when + List logged = + loggedWhile(() -> mapper.map(failure, GraphQlErrorContext.of("exec-9"))); + + // then + assertThat(logged) + .singleElement() + .extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getThrowableProxy) + .containsExactly( + "persistence failure classified as DB_UNAVAILABLE (category=TRANSIENT_DEPENDENCY," + + " retryable=true) (executionId=exec-9)", + null); + } + + @org.junit.jupiter.api.Test + void aRegisteredFailureThatKeepsACarrierAsItsCauseIsAnsweredWithItsRegisteredCode() { + // given + GraphQlWireErrorMapper mapper = new GraphQlWireErrorMapper(orderUnavailableRegistered()); + RuntimeException failure = new OrderUnavailableException(persistenceFailureWithASqlCause()); + + // when + GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test()); + + // then + assertThat(error.extensions()) + .extracting(extensions -> extensions.get("code"), extensions -> extensions.get("category")) + .containsExactly("ORDER_UNAVAILABLE", "BUSINESS"); + } + + @org.junit.jupiter.api.Test + void aRegisteredFailureThatKeepsACarrierAsItsCauseStillLeavesTheCarriersServerLine() { + // given + GraphQlWireErrorMapper mapper = new GraphQlWireErrorMapper(orderUnavailableRegistered()); + RuntimeException failure = new OrderUnavailableException(persistenceFailureWithASqlCause()); + + // when + List logged = + loggedWhile(() -> mapper.map(failure, GraphQlErrorContext.of("exec-9"))); + + // then + assertThat(logged) + .singleElement() + .extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getThrowableProxy) + .containsExactly( + "persistence failure classified as DB_UNAVAILABLE (category=TRANSIENT_DEPENDENCY," + + " retryable=true) (executionId=exec-9)", + null); + } + + @org.junit.jupiter.api.Test + void aCarrierTheApplicationAlsoRegisteredIsAnsweredWithItsOwnCode() { + // given + GraphQlWireErrorMapper mapper = + new GraphQlWireErrorMapper( + GraphQlExceptionResolver.builder() + .map( + LockAcquisitionTimeoutException.class, + GraphQlErrorCode.of("ORDER_BUSY"), + GraphQlErrorCategory.BUSINESS, + "주문을 처리하는 중입니다") + .build()); + RuntimeException failure = + new LockAcquisitionTimeoutException("orders/42", Duration.ofSeconds(3)); + + // when + GraphQlWireError error = mapper.map(failure, GraphQlErrorContext.test()); + + // then + assertThat(error.extensions()) + .extracting(extensions -> extensions.get("code"), extensions -> extensions.get("retryable")) + .containsExactly("LOCK_ACQUISITION_TIMEOUT", true); + } + + private static GraphQlExceptionResolver orderUnavailableRegistered() { + return GraphQlExceptionResolver.builder() + .map( + OrderUnavailableException.class, + GraphQlErrorCode.of("ORDER_UNAVAILABLE"), + GraphQlErrorCategory.BUSINESS, + "주문을 지금 처리할 수 없습니다") + .build(); + } + + private static PersistenceFailureException persistenceFailureWithASqlCause() { + return new PersistenceFailureException( + OperationalError.DB_UNAVAILABLE, + "08006", + new SQLException("jdbc:postgresql://db.internal/customer?password=secret", "08006")); + } + + /** A failure the application models and registers; it keeps what it translated as its cause. */ + private static final class OrderUnavailableException extends RuntimeException { + private static final long serialVersionUID = 1L; + + OrderUnavailableException(Throwable cause) { + super("order unavailable", cause); + } + } + + /** + * Every line this package writes while {@code action} runs: the mapper's own and the masking + * resolver's, so a failure that should have been classified but was masked shows up too. + */ private static List loggedWhile(Runnable action) { - Logger logger = (Logger) LoggerFactory.getLogger(GraphQlWireErrorMapper.class); + Logger logger = (Logger) LoggerFactory.getLogger(GraphQlWireErrorMapper.class.getPackageName()); ListAppender appender = new ListAppender<>(); appender.start(); logger.addAppender(appender); diff --git a/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlArgumentBindingFailureTest.java b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlArgumentBindingFailureTest.java new file mode 100644 index 00000000..a738d769 --- /dev/null +++ b/src/adapter/inbound/graphql/src/test/java/dev/caskeleton/adapter/inbound/graphql/runtime/GraphQlArgumentBindingFailureTest.java @@ -0,0 +1,166 @@ +package dev.caskeleton.adapter.inbound.graphql.runtime; + +import static org.assertj.core.api.Assertions.assertThat; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; +import dev.caskeleton.adapter.inbound.graphql.error.GraphQlWireErrorMapper; +import dev.caskeleton.shared.error.OperationalError; +import dev.caskeleton.shared.error.PersistenceFailureException; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.context.annotation.AnnotationConfigApplicationContext; +import org.springframework.core.io.ByteArrayResource; +import org.springframework.graphql.ResponseError; +import org.springframework.graphql.data.method.annotation.Argument; +import org.springframework.graphql.data.method.annotation.QueryMapping; +import org.springframework.graphql.data.method.annotation.support.AnnotatedControllerConfigurer; +import org.springframework.graphql.execution.DefaultExecutionGraphQlService; +import org.springframework.graphql.execution.GraphQlSource; +import org.springframework.graphql.test.tester.ExecutionGraphQlServiceTester; +import org.springframework.stereotype.Controller; + +/** + * A controller {@code @Argument} the client sent that does not convert to the parameter's type. + * Spring for GraphQL's argument binder refuses it with a {@code BindException} before the + * controller runs; the message of that exception quotes the rejected value. Driven through a real + * {@link AnnotatedControllerConfigurer} with this module's resolver, so the failure the mapper sees + * is the one Spring raises. + */ +class GraphQlArgumentBindingFailureTest { + + private static final String SCHEMA = + "type Query { order(id: ID!): String invoice(number: String!): String }"; + + private static final String QUERY = "{ order(id: \"alice@example.com\") }"; + + @Test + void anArgumentThatDoesNotConvertIsABadParameterRequestError() { + // when + List errors = errorsOf(QUERY); + + // then + assertThat(errors) + .singleElement() + .extracting( + error -> error.getExtensions().get("code"), + error -> error.getExtensions().get("category")) + .containsExactly("BAD_PARAMETER", "REQUEST"); + } + + @Test + void anArgumentThatDoesNotConvertIsLoggedAtWarnByItsTypeWithoutTheValue() { + // when + List logged = loggedWhile(() -> errorsOf(QUERY)); + + // then + assertThat(logged) + .singleElement() + .extracting( + ILoggingEvent::getLevel, + event -> + event.getFormattedMessage().replaceAll("executionId=[^)]*", "executionId="), + ILoggingEvent::getThrowableProxy) + .containsExactly( + Level.WARN, + "request refused as BAD_PARAMETER by org.springframework.validation.BindException" + + " (executionId=)", + null); + } + + @Test + @DisplayName("변환기가 carrier 를 던져도 인자 변환 실패는 BAD_PARAMETER 다(인자 변환 단계는 carrier 를 보지 않는다)") + void anArgumentWhoseConverterThrowsACarrierIsStillABadParameterRequestError() { + // when + List errors = errorsOf("{ invoice(number: \"INV-1\") }"); + + // then + assertThat(errors) + .singleElement() + .extracting( + error -> error.getExtensions().get("code"), + error -> error.getExtensions().get("category")) + .containsExactly("BAD_PARAMETER", "REQUEST"); + } + + private static List errorsOf(String document) { + AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(); + context.registerBean(OrderController.class); + context.refresh(); + AnnotatedControllerConfigurer controllers = new AnnotatedControllerConfigurer(); + controllers.setApplicationContext(context); + controllers.afterPropertiesSet(); + GraphQlSource source = + GraphQlSource.schemaResourceBuilder() + .schemaResources(new ByteArrayResource(SCHEMA.getBytes(StandardCharsets.UTF_8))) + .configureRuntimeWiring(controllers) + .exceptionResolvers( + List.of(new GraphQlDataFetcherExceptionResolver(GraphQlWireErrorMapper.masking()))) + .build(); + List errors = new ArrayList<>(); + try { + ExecutionGraphQlServiceTester.create(new DefaultExecutionGraphQlService(source)) + .document(document) + .execute() + .errors() + .satisfy(errors::addAll); + } finally { + context.close(); + } + return errors; + } + + /** Every WARN or ERROR line this module writes while {@code action} runs. */ + private static List loggedWhile(Runnable action) { + Logger logger = (Logger) LoggerFactory.getLogger("dev.caskeleton.adapter.inbound.graphql"); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + action.run(); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + return appender.list.stream() + .filter(event -> event.getLevel().isGreaterOrEqual(Level.WARN)) + .toList(); + } + + /** A feature controller whose argument is an id type the client's value does not fit. */ + @Controller + static class OrderController { + + @QueryMapping + String order(@Argument UUID id) { + return id.toString(); + } + + @QueryMapping + String invoice(@Argument InvoiceNumber number) { + return "unreachable: the number never converts"; + } + } + + /** An argument type whose conversion fails with a server-side carrier, as a lookup could. */ + public static final class InvoiceNumber { + + private InvoiceNumber() {} + + /** The conversion the binder finds; a lookup that fails with a carrier for any number. */ + public static InvoiceNumber valueOf(String value) { + if (!value.isEmpty()) { + throw new PersistenceFailureException( + OperationalError.DB_UNAVAILABLE, "invoice lookup failed for " + value, null); + } + return new InvoiceNumber(); + } + } +} diff --git a/src/adapter/inbound/grpc/CLAUDE.md b/src/adapter/inbound/grpc/CLAUDE.md index 4f431f17..5c4dff1a 100644 --- a/src/adapter/inbound/grpc/CLAUDE.md +++ b/src/adapter/inbound/grpc/CLAUDE.md @@ -90,7 +90,7 @@ credential path and a separately qualified non-loopback bind. ## Feature 기여 방법 -현재 저장소에는 production feature RPC나 sample gRPC service가 없다. 향후 feature를 도입할 +현재 저장소에는 feature RPC가 없다. 향후 feature를 도입할 때는 `.proto`/generated stub/`BindableService`를 해당 feature가 소유하고, 서비스 빈과 정확히 한 개의 caller-supplied `GrpcAuthenticationPolicy` 빈을 함께 제공한다. 정책이 없거나 여러 개면 listener 시작이 실패한다. 정책은 `Optional authenticate(Metadata)`이고, 돌려준 diff --git a/src/adapter/inbound/grpc/README.md b/src/adapter/inbound/grpc/README.md index f2e93588..47bd49d8 100644 --- a/src/adapter/inbound/grpc/README.md +++ b/src/adapter/inbound/grpc/README.md @@ -146,7 +146,12 @@ handler throw, listener callback throw, `responseObserver.onError(...)`, raw - **`IllegalArgumentException`** 은 `BAD_PARAMETER`(`INVALID_ARGUMENT`) — 모든 전송이 같다. - **`ApiErrorCode` 추출**: feature 예외는 `ApiErrorCarrier`(이 모듈이 제공하는 전송-중립 hook)를 구현해 자신의 `ApiErrorCode` 를 노출한다. shared-contract 의 `PersistenceFailureException` / - `DependencyFailureException`(outbound 어댑터에서 올라온 분류된 실패)도 직접 인식한다. + `DependencyFailureException`(outbound 어댑터에서 올라온 분류된 실패)도 직접 인식한다. carrier 는 원인 + 사슬의 첫 것을 shared-contract `ApiErrorCarrier.firstIn` 으로 찾는다. web·GraphQL·STOMP 도 같은 함수다. +- **raw status 를 던지든 `onError` 로 넘기든 같은 판정**: 던진 raw status 는 그 예외 자체가 원인 자리에 와서 + `close` 에 닿는다. 그래서 인터셉터는 status 예외를 벗긴 뒤의 실패 하나로 carrier·`IllegalArgumentException` + 판정과 로그를 모두 한다. `Status.INVALID_ARGUMENT.withCause(iae).asRuntimeException()` 은 던져도 넘겨도 + `BAD_PARAMETER`·WARN 한 줄이다(재리뷰 RR7-01-03 전에는 던지면 `INTERNAL_ERROR`·ERROR 에 메시지까지 남았다). - **leak 방지**: 인식된 코드는 안정적 `code` 문자열만 status description/trailer 로 노출하고, raw 예외 메시지(SQLState/업스트림 세부를 담을 수 있음)는 절대 클라이언트에 내보내지 않는다. 인식되지 않은 예외와 raw gRPC status/description은 원래 status를 신뢰하지 않고 `Status.INTERNAL` + diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/ApiErrorException.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/ApiErrorException.java index e808c723..cb926654 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/ApiErrorException.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/ApiErrorException.java @@ -6,7 +6,7 @@ import dev.caskeleton.shared.error.ApiErrorCode; /** * Adapter-level throwable a feature gRPC service throws after mapping a domain exception to a * stable {@link ApiErrorCode} (typically a feature code such as {@code - * PortfolioErrorCode.WORKLOG_NOT_FOUND} or a skeleton {@code OperationalError}). It implements the + * OrderErrorCode.ORDER_NOT_FOUND} or a skeleton {@code OperationalError}). It implements the * shared-contract {@link ApiErrorCarrier} hook so the {@link GrpcExceptionHandlingInterceptor} * translates it to the matching gRPC {@code Status} plus {@code code} / {@code category} trailers * through the same single carrier branch that handles the shared-contract infra exceptions. diff --git a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptor.java b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptor.java index 7f6e18ab..a707b4b5 100644 --- a/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptor.java +++ b/src/adapter/inbound/grpc/src/main/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptor.java @@ -13,6 +13,7 @@ import io.grpc.ServerInterceptor; import io.grpc.Status; import io.grpc.StatusException; import io.grpc.StatusRuntimeException; +import java.util.Optional; import java.util.concurrent.atomic.AtomicBoolean; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -28,7 +29,8 @@ import org.slf4j.LoggerFactory; * ApiErrorCarrier} hook — implemented by a feature throwable (the gRPC {@link ApiErrorException} * carrying a mapped domain code) and by the shared-contract {@code PersistenceFailureException} / * {@code DependencyFailureException}, so a single {@code instanceof ApiErrorCarrier} branch covers - * them all. An {@link IllegalArgumentException} maps to {@link OperationalError#BAD_PARAMETER} + * them all, found with {@link ApiErrorCarrier#firstIn} anywhere in the cause chain as on every + * transport. An {@link IllegalArgumentException} maps to {@link OperationalError#BAD_PARAMETER} * ({@code INVALID_ARGUMENT}), as on every other transport. Any other unrecognised exception or raw * gRPC status maps to {@link Status#INTERNAL} with {@link OperationalError#INTERNAL_ERROR}. The * client sees the stable code, category and retryability in the trailers and the shared category @@ -128,20 +130,23 @@ public class GrpcExceptionHandlingInterceptor implements ServerInterceptor { } String method = delegate.getMethodDescriptor().getFullMethodName(); - Throwable carrier = carrierOf(status.getCause()); + // A thrown raw status arrives wrapped in itself (closeWithError); one passed to onError + // does not. Judging the failure behind it answers both the same way (RR7-01-03). + Throwable failure = failureBehind(status.getCause()); + Optional carrier = ApiErrorCarrier.firstIn(failure); ApiErrorCode code; - if (carrier != null) { - code = ((ApiErrorCarrier) carrier).errorCode(); - ServerFailureLog.of(carrier, code) + if (carrier.isPresent()) { + code = ((ApiErrorCarrier) carrier.get()).errorCode(); + ServerFailureLog.of(carrier.get(), code) .ifPresent(line -> log.error(line.format(" (method={})"), line.arguments(method))); - } else if (status.getCause() instanceof IllegalArgumentException refused) { + } else if (failure instanceof IllegalArgumentException refused) { code = OperationalError.BAD_PARAMETER; ServerFailureLog line = ServerFailureLog.refusedArgument(refused); log.warn(line.format(" (method={})"), line.arguments(method)); } else { code = OperationalError.INTERNAL_ERROR; if (!delegate.isCancelled()) { - logUnrecognised(method, status); + logUnrecognised(method, status, failure); } } super.close(statusMapper.statusFor(code), statusMapper.trailersFor(code)); @@ -153,43 +158,32 @@ public class GrpcExceptionHandlingInterceptor implements ServerInterceptor { call.close(Status.fromThrowable(exception).withCause(exception), new Metadata()); } - private static void logUnrecognised(String method, Status status) { - // The cause, when there is one, is the last argument and so the logged exception; the raw + private static void logUnrecognised(String method, Status status, Throwable failure) { + // The failure, when there is one, is the last argument and so the logged exception; the raw // description is never logged. log.error( "unhandled failure on {} answered as {} (status={})", method, OperationalError.INTERNAL_ERROR.code(), status.getCode(), - failureBehind(status.getCause())); + failure); } /** - * The exception to attach for an unrecognised failure. A thrown raw status reaches {@code close} - * as the status's own cause ({@link #closeWithError}), and its message is {@code "CODE: - * description"} — the description that may echo input. So a raw status is never attached: only - * the first cause behind it that is not one, if any (review 2026-11-05 RR6-01-05). + * The failure a status was closed for, which is what the interceptor judges and attaches. A + * thrown raw status reaches {@code close} as the status's own cause ({@link #closeWithError}), + * and its message is {@code "CODE: description"} — the description that may echo input. So a raw + * status is never the failure: the first cause behind it that is not one is, if any (review + * 2026-11-05 RR6-01-05). A raw status passed to {@code onError} reaches {@code close} with its + * own cause already, so both ways of ending a call with the same status are judged alike (review + * 2026-11-06 RR7-01-03). */ private static Throwable failureBehind(Throwable cause) { Throwable current = cause; - while (current instanceof StatusRuntimeException || current instanceof StatusException) { + while ((current instanceof StatusRuntimeException || current instanceof StatusException) + && !(current instanceof ApiErrorCarrier)) { current = current.getCause(); } return current; } - - /** The first {@link ApiErrorCarrier} in the cause chain, or {@code null}. */ - private static Throwable carrierOf(Throwable throwable) { - Throwable current = throwable; - while (current != null) { - if (current instanceof ApiErrorCarrier) { - return current; - } - if (current.getCause() == current) { - break; - } - current = current.getCause(); - } - return null; - } } diff --git a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptorTest.java b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptorTest.java index 2df5c86c..eee506a2 100644 --- a/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptorTest.java +++ b/src/adapter/inbound/grpc/src/test/java/dev/caskeleton/adapter/inbound/grpc/GrpcExceptionHandlingInterceptorTest.java @@ -16,10 +16,13 @@ import io.grpc.MethodDescriptor; import io.grpc.ServerCall; import io.grpc.ServerCallHandler; import io.grpc.Status; +import io.grpc.stub.ServerCalls; import java.sql.SQLException; import java.util.List; import java.util.concurrent.atomic.AtomicBoolean; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; import org.slf4j.LoggerFactory; /** @@ -327,6 +330,100 @@ class GrpcExceptionHandlingInterceptorTest { null); } + @ParameterizedTest + @EnumSource(Ending.class) + void aRawStatusAroundAnIllegalArgumentIsABadParameterHoweverTheServiceEndsTheCall(Ending ending) { + // given + RuntimeException rawStatus = + Status.INVALID_ARGUMENT + .withCause(new IllegalArgumentException("unknown recipient alice@example.com")) + .asRuntimeException(); + + // when + CapturingServerCall call = endUnaryCall(ending, rawStatus); + + // then + assertThat(call) + .extracting( + captured -> captured.status.getCode(), + captured -> captured.trailers.get(GrpcStatusMapper.CODE_KEY)) + .containsExactly(Status.Code.INVALID_ARGUMENT, "BAD_PARAMETER"); + } + + @ParameterizedTest + @EnumSource(Ending.class) + void aRawStatusAroundAnIllegalArgumentIsLoggedAtWarnByItsTypeHoweverTheServiceEndsTheCall( + Ending ending) { + // given + RuntimeException rawStatus = + Status.INVALID_ARGUMENT + .withCause(new IllegalArgumentException("unknown recipient alice@example.com")) + .asRuntimeException(); + + // when + List logged = loggedWhile(() -> endUnaryCall(ending, rawStatus)); + + // then + assertThat(logged) + .singleElement() + .extracting( + ILoggingEvent::getLevel, + ILoggingEvent::getFormattedMessage, + ILoggingEvent::getThrowableProxy) + .containsExactly( + Level.WARN, + "request refused as BAD_PARAMETER by java.lang.IllegalArgumentException" + + " (method=test.Fixture/Call)", + null); + } + + @Test + void aCarrierWrappedInAnotherExceptionIsAnsweredWithItsOwnCode() { + // given + IllegalStateException wrapper = + new IllegalStateException( + "use case failed", + new PersistenceFailureException( + OperationalError.DB_UNAVAILABLE, + "08006", + new SQLException("jdbc:postgresql://db.internal/customer", "08006"))); + + // when + CapturingServerCall call = closeAfterThrowing(wrapper); + + // then + assertThat(call) + .extracting( + captured -> captured.status.getCode(), + captured -> captured.trailers.get(GrpcStatusMapper.CODE_KEY)) + .containsExactly(Status.Code.UNAVAILABLE, "DB_UNAVAILABLE"); + } + + /** The two ways grpc-java lets a unary service end its call with a failure. */ + enum Ending { + THROWN, + PASSED_TO_ON_ERROR; + + ServerCallHandler serviceFailingWith(RuntimeException failure) { + return ServerCalls.asyncUnaryCall( + (request, responseObserver) -> { + if (this == THROWN) { + throw failure; + } + responseObserver.onError(failure); + }); + } + } + + private CapturingServerCall endUnaryCall(Ending ending, RuntimeException failure) { + CapturingServerCall call = new CapturingServerCall(); + ServerCall.Listener listener = + interceptor.interceptCall(call, new Metadata(), ending.serviceFailingWith(failure)); + listener.onMessage("request"); + listener.onHalfClose(); + return call; + } + private static List loggedWhile(Runnable action) { Logger logger = (Logger) LoggerFactory.getLogger(GrpcExceptionHandlingInterceptor.class); ListAppender appender = new ListAppender<>(); diff --git a/src/adapter/inbound/web-advanced/CLAUDE.md b/src/adapter/inbound/web-advanced/CLAUDE.md index 538dfff0..18d3212d 100644 --- a/src/adapter/inbound/web-advanced/CLAUDE.md +++ b/src/adapter/inbound/web-advanced/CLAUDE.md @@ -21,11 +21,11 @@ service adds and the settings are in [README.md](README.md). ## Rules -- Not in any default composition. `app-bootstrap` and `sample-portfolio` main must not depend on it; +- Not in any default composition. `app-bootstrap` main은 이 leaf에 의존하지 않는다; `app-bootstrap` takes it `testRuntimeOnly` so the whole-repository ArchUnit import reads it. - It depends on `adapter:inbound:web` (the `core` vocabulary), never the reverse. - No component-scannable stereotype. A consuming application may scan the adapter packages - (`sample-portfolio` scans `dev.caskeleton.adapter.inbound.web`), so a + (서비스가 `dev.caskeleton.adapter.inbound.web`을 scan할 수 있다), so a `@Configuration`/`@Component` here would be created whatever its switch says. Switched wiring is `@AutoConfiguration` + an imports line; imported helpers carry no stereotype (`MvcStreamingSupportConfiguration`). diff --git a/src/adapter/inbound/web-advanced/README.md b/src/adapter/inbound/web-advanced/README.md index 56e396a5..e7d8efac 100644 --- a/src/adapter/inbound/web-advanced/README.md +++ b/src/adapter/inbound/web-advanced/README.md @@ -3,7 +3,7 @@ **라이브러리 API — 서비스의 어댑터 leaf에서 `implementation`으로 받아 직접 호출; 기본 조립에 없음.** `adapter:inbound:web` 에 있던 코드 중 servlet 운영 경로가 닿지 않는 것만 모은 opt-in leaf 다. -`app-bootstrap`·`sample-portfolio` 는 이 leaf 에 의존하지 않는다. 패키지 루트는 +`app-bootstrap` 은 이 leaf 에 의존하지 않는다. 패키지 루트는 `dev.caskeleton.adapter.inbound.web.advanced` (web 과 겹치는 패키지 없음). ## 추가할 한 줄 diff --git a/src/adapter/inbound/web/CLAUDE.md b/src/adapter/inbound/web/CLAUDE.md index fb4dfe4b..35c66ca8 100644 --- a/src/adapter/inbound/web/CLAUDE.md +++ b/src/adapter/inbound/web/CLAUDE.md @@ -28,7 +28,7 @@ health and rate-limit beans; `WebSecurityAutoConfiguration` imports the JWT chai with its own posture excludes only that root; `WebMethodSecurityAutoConfiguration` imports method security and the permission port and stays when the chain is replaced; nobody scans this leaf), and the types -`app-bootstrap`, `sample-portfolio`, `web-fileserver` and `composition:fileserver-platform` name — +`app-bootstrap`, `web-fileserver` and `composition:fileserver-platform` name — plus their transitive references. Library code that no production path reaches (streaming, virtual threads, patch, codecs, OpenAPI 3.2, URI/method policy, versioning, operation, budget, contract, security-context bridge, `JsonIdempotentResponseCodec`, route inventory) lives in the opt-in leaf @@ -42,8 +42,8 @@ ArchUnit `WEB-ARCH-ADV`). - `:domain-core` - `:shared-contract` - `:adapter:outbound:support` — `StrictSettingsBinder` only. `app.security` (`SecuritySettings`, the - authentication mode included) is bound by the one strict binder every module uses (review - 2026-11-01 07-10); the ArchUnit inbound/outbound rules allow that class and nothing else from the + authentication mode included) is bound by the one strict binder every module uses (since + 2026-11-01); the ArchUnit inbound/outbound rules allow that class and nothing else from the leaf. - Spring Web/Security/Validation dependencies. @@ -76,8 +76,7 @@ also drives the runtime patterns reference implementations must follow. `Optional` wrappers on request records. - **B3 — Mapper-internal failures.** Map record canonical-constructor `IllegalArgumentException`, MapStruct generated NPE, ACL normalization - failures, etc. by throwing `MappingException` (sample implementation in - `sample-portfolio`); the global handler routes it to `MAPPING_FAILED` (HTTP 400), + failures, etc. by throwing `MappingException`; the global handler routes it to `MAPPING_FAILED` (HTTP 400), never to `BAD_PARAMETER` or `INTERNAL_ERROR`. Plain `IllegalArgumentException` remains `BAD_PARAMETER` for non-mapper callers. - **B4 — Validation layering.** Class-level Bean Validation constraints belong @@ -111,16 +110,13 @@ Domain `@RestControllerAdvice` in a consuming module must be annotated `@Order(Ordered.HIGHEST_PRECEDENCE)` (or otherwise ordered ahead of this module's base `GlobalExceptionHandler`), because the base handler's catch-all `@ExceptionHandler(Exception.class)` would otherwise resolve domain exceptions -to `INTERNAL_ERROR`. See `sample-portfolio`'s `DomainExceptionHandler` for the -pattern. +to `INTERNAL_ERROR`. The base operational handler (`error/GlobalExceptionHandler`), the error-code contract (`dev.caskeleton.shared.error.ApiErrorCode` + `OperationalError`), the `error/ErrorResponseFactory`, and the `envelope/EnvelopeBodyAdvice` now live in production modules (`adapter:inbound:web` / `shared-contract`), so the running application -provides them without depending on `sample-portfolio`. Domain-specific exception -handlers and error codes live in the consuming module (see sample's -`DomainExceptionHandler` / `PortfolioErrorCode`). +provides them. 기능 전용 예외 handler와 오류 코드는 그 기능을 가진 모듈에 둔다(`docs/manual/06-errors.md`). ## Schema / serialization contract @@ -133,14 +129,14 @@ live in `app-bootstrap` (`application.yml` `spring.jackson.serialization.*` / `spring.jackson.generator.*`); ArchUnit + effective-config tests live in `app-bootstrap` (`JacksonSerializationPolicyTest`, `no_bigdecimal_double_constructor`). -- **S1 — Date / time / timezone (D2).** `WRITE_DATES_AS_TIMESTAMPS=false` is +- **S1 — Date / time / timezone.** `WRITE_DATES_AS_TIMESTAMPS=false` is pinned, so `java.time` values serialize as ISO-8601 strings via `JavaTimeModule` (`OffsetDateTime` → `"...Z"`, `LocalDate` → `"YYYY-MM-DD"`), never a numeric epoch or `[y,m,d,...]` array. Server timezone is **UTC**: emit instants as `OffsetDateTime`/`Instant` with a `Z` offset. Use `LocalDate` only for date-only calendar fields. Do **not** put timezone-less `LocalDateTime` on a response DTO — it serializes without an offset and breaks the contract. -- **S2 — Money / BigDecimal (D3).** Default scale 2, rounding `HALF_UP` unless +- **S2 — Money / BigDecimal.** Default scale 2, rounding `HALF_UP` unless the domain documents otherwise (KRW/JPY = scale 0 with a schema note). `WRITE_BIGDECIMAL_AS_PLAIN=true` is pinned so values never serialize in scientific notation. Pick **one** JSON representation per API and state it in @@ -151,17 +147,17 @@ live in `app-bootstrap` (`application.yml` `spring.jackson.serialization.*` / - **S3 — `new BigDecimal(double)` is banned.** The `double`/`float` constructors capture binary floating-point error (`new BigDecimal(0.1)` ≠ `0.1`). Build from a `String` (`new BigDecimal("0.1")`) or `BigDecimal.valueOf(double)`. Enforced - by the `no_bigdecimal_double_constructor` ArchUnit rule (D3 / SBMS-C3). + by the `no_bigdecimal_double_constructor` ArchUnit rule. - **S4 — Enum / null·empty·missing.** Request-side unknown enum → `VALIDATION_FAILED` (B1 `read-unknown-enum-values-as-null=false`); legacy values map through an explicit adapter, never a silent fallback. The absent / explicit-null / value distinction is owned by the inbound web mapper (Controller DTO → Command), expressed with `Patch` (B2); `domain-core` and `application-core` receive the already-resolved 3-state, never a wire type. -- **S5 — Out of this branch's scope.** OpenAPI drift enforcement (D5) is owned by +- **S5 — Out of this branch's scope.** OpenAPI drift enforcement is owned by the verification suite / api-contract-baseline; removed-field-reuse ban tooling - (D6, `x-removed-fields` vs markdown catalog) is `needs-confirmation`; Avro - Schema Registry for outbox/event (D7) and response field rename/versioning + (`x-removed-fields` vs markdown catalog) is `needs-confirmation`; Avro + Schema Registry for outbox/event and response field rename/versioning (`feature-api-compatibility-deprecation-contract`) are separate branches. ## Business rule validation contract @@ -188,7 +184,7 @@ above and is enforced by ArchUnit + contract tests (not new runtime mechanism). the type immutable, so no application-service or persistence path can hand out an invariant-violating instance. A DB constraint is a backstop, never the only check (Forbidden: "DB constraint as only invariant"). -- **C3 / C7 / D9 — Persistence integrity maps to an operational error, leak-free.** A +- **C3 / C7 — Persistence integrity maps to an operational error, leak-free.** A unique/FK/check/serialization failure maps to `DATA_INTEGRITY` / `CONFLICT` with a **client-safe message only**. The raw SQL, constraint/index name, SQLState code, exception class, and stack frame must never reach `error.message` or diff --git a/src/adapter/inbound/web/README.md b/src/adapter/inbound/web/README.md index 7b2336ca..134acd95 100644 --- a/src/adapter/inbound/web/README.md +++ b/src/adapter/inbound/web/README.md @@ -115,6 +115,10 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML 코드의 일반 `client_safe_message` 만 담고, 원시 예외 텍스트·`Authorization` 헤더·issuer·audience 는 절대 포함하지 않는다. 로그 라인엔 code/category/요청 path 만 기록하고 bearer token 은 절대 로깅하지 않는다(leak 테스트가 강제하는 계약). 전체 로그 마스킹 필터는 별도 log-management 영역에서 다룬다. +- **로그 레벨.** 4xx(토큰 누락·만료·서명·issuer·audience·kid 실패, 권한 부족)는 호출자 쪽 실패라 WARN이다. + 5xx(`AUTH_JWKS_UNAVAILABLE` 503, `INTERNAL_AUTH_MISCONFIGURATION` 500)는 서버 쪽 고장이라 ERROR다. 다른 + 경로가 5xx를 ERROR로 남기는 규칙(shared-contract `ServerFailureLog`)과 같다. 레벨은 오류 코드 레지스트리의 + 칸이 아니라 이 코드가 정한다(설계 메모 `docs/design/2026-11-06-error-code-log-level-design.md`). - **WWW-Authenticate(RFC 9110 §15.5.2).** 401 응답은 반드시 WWW-Authenticate 헤더를 갖되, `error_description` 으로 issuer/token 세부가 새지 않도록 최소한으로 유지한다. @@ -139,7 +143,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML `WebSecurityAutoConfiguration`(JWT/session 체인)이 아니라 이 auto-configuration이 들여온다. - 이유: 인증 방식(체인)을 바꾸는 애플리케이션은 `WebSecurityAutoConfiguration`만 뺀다. 둘이 한 root에 있을 때는 체인을 빼면 advisor도 같이 빠져서, 그 애플리케이션의 `@RequiresPermission`이 아무 경고 없이 - 주석이 됐다(샘플이 그랬다 — 익명 삭제 가능). 이제 체인을 바꿔도 권한 검사는 남는다. + 주석이 됐다(지운 샘플 모듈이 그랬다 — 익명 삭제 가능). 이제 체인을 바꿔도 권한 검사는 남는다. - 메서드 보안까지 끄려면 이 클래스를 따로 exclude 해야 한다. 그 결정은 exclude 목록에 이름으로 드러난다. ### MethodSecurityConfig @@ -204,9 +208,18 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML supported-method 같은 bounded 구조 메타데이터로 `details`에 둔다. collection/map index와 key는 field path에서 제거한다. - `ApiErrorCarrier`(shared `MappingException`·`AdapterDisabledException`·`PersistenceFailureException`· - `DependencyFailureException`, application 멱등성 예외, adopter 예외)는 `handleCarrier` 분기 + `DependencyFailureException`, application 멱등성·분산 락 예외, adopter 예외)는 `handleCarrier` 분기 하나로 매핑한다. 5xx 는 원인과 함께 로그를 남기고(persistence 는 분류만), retryable 코드는 `RetryAfterAdvisor`로 `Retry-After`를 붙인다. +- carrier 를 다른 예외로 감싸 던져도 같다. `handleUnknown`(그 밖의 예외)과 `handleIllegalArgument` 는 + 원인 사슬의 첫 carrier(`ApiErrorCarrier.firstIn`)를 찾아 `handleCarrier` 로 넘긴다. 감싼 + persistence 실패도 500 `INTERNAL_ERROR` 와 SQL 원인 대신 그 분류 코드와 분류 한 줄로 남는다. GraphQL·gRPC·STOMP + 도 같은 함수를 쓴다(소유자 결정 2026-11-06, 재리뷰 RR7-01-05). +- 인자 변환 단계는 원인의 carrier 를 보지 않는다. 경로 변수·쿼리 파라미터가 바뀌지 않은 + `MethodArgumentTypeMismatchException` 은 `BAD_PARAMETER`, 읽지 못한 본문의 `HttpMessageNotReadableException` 은 + `VALIDATION_FAILED` 다. 사용자 `Converter` 나 Jackson creator 가 carrier 를 던져 그 원인에 있어도 같다. 요청 + 형식 오류이고 그 코드는 전송이 정한다(소유자 결정 2026-11-07, 재리뷰 README 19.4절 ④). STOMP 도 같은 실패를 + 거부로 남긴다. 단언은 `TransportErrorHandlingTest`. - 개별 override 가 없는 Spring MVC 예외(필수 파라미터·헤더·part 누락, binding 실패 등)는 `handleExceptionInternal` override 가 상태 코드 → 코드로 바꿔 같은 Envelope 로 보낸다. 503(Spring 의 async 요청 시간 초과)은 `INTERNAL_ERROR` 가 아니라 `REQUEST_TIMEOUT`(503, retryable) 이다(리뷰 02-08). @@ -216,8 +229,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML - **등록은 한 곳이다.** `WebMvcPlatformAutoConfiguration` 의 `@ConditionalOnMissingBean` bean 하나뿐이다. `app.web.mvc.enabled=false` 면 이 핸들러·요청 id 필터·JSON 본문 상한·중복 키 거부가 함께 빠지고, 서비스가 셋을 직접 준다. 같은 타입 bean 을 주면 그것만 쓰인다(리뷰 02-10, `WebMvcPlatformAutoConfigurationTest`). -- `adapter-web` 에 위치하는 이유: 실행 앱이 어떤 sample 모듈에도 의존하지 않고 envelope 형식 에러 응답을 - 제공하도록. +- `adapter-web` 에 위치하는 이유: 실행 앱이 기능 모듈 없이도 envelope 형식 에러 응답을 제공하도록. - **`spanErrorRecorder`.** 프로덕션 코드를 특정 트레이서 라이브러리에 결합하지 않고 span 에러를 기록하기 위한 이음새. 기본값 `SpanErrorRecorder.NOOP`. `@Autowired` 생성자가 `ObjectProvider` 로 self-default 하므로 전체 컨텍스트 / `@WebMvcTest` 슬라이스 / 순수 단위 테스트 @@ -244,6 +256,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML | `IdempotencyCompletionUnknownException` | `IDEMPOTENCY_COMPLETION_UNKNOWN` | 503 (retryable=true) | action 이 돈 뒤 결과 기록(complete) 중 저장소가 응답하지 않음. 결과 불명 — 같은 키로 재전송, 새 키 금지(`docs/web/http-contract.md` §2, 재리뷰 RR-02-03). carrier 분기 | | `IdempotencyRecoveryRequiredException` | `IDEMPOTENCY_RECOVERY_REQUIRED` | 500 (retryable=false) | 이전 시도의 외부 효과 여부를 판단할 수 없음. carrier 분기 | | `IdempotencyInFlightException` | `IDEMPOTENT_IN_FLIGHT` | 409 (retryable=true, `Retry-After: 2`) | 같은 scope 의 다른 시도가 아직 처리 중(executor 는 기다리지 않는다). 클라이언트 행동: 결과 불명. 같은 `Idempotency-Key`로 `Retry-After` 뒤 재전송. 새 키 금지(`docs/web/http-contract.md` §2). 진단정보(scope digest)는 클라이언트 미도달 | +| `LockAcquisitionTimeoutException` | `LOCK_ACQUISITION_TIMEOUT` | 409 (retryable=true, `Retry-After: 1`) | 분산 락을 `waitTime` 안에 못 잡음. 경합은 일시적이라 잠시 뒤 같은 요청을 다시 보낸다. carrier 분기(전에는 carrier 가 아니라 500 `INTERNAL_ERROR`, 재리뷰 RR7-01-04) | | `IdempotencyRequestMismatchException` | `IDEMPOTENT_REQUEST_MISMATCH` | 422 (retryable=false) | D8: `Idempotency-Key` 를 다른 본문으로 재사용. 다시 보내지 않는다(`docs/web/http-contract.md` §2). fingerprint/scope 노출 금지 | | `PersistenceFailureException` (JPA `JpaPersistenceException` 포함) | `ex.errorCode()` (사전분류 `DB_*`) | 코드 결정 | adapter-persistence translator 가 SQLState→`DB_*` 로 이미 분류, JPA 예외는 `FailureCategory`→`DB_*`. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**(SQLState/제약명 담음, 서버 로그 전용) | | `DependencyFailureException` | `ex.errorCode()` (사전분류 `DEPENDENCY_*`) | 코드 결정 | adapter-outbound `OutboundHttpErrorMapper` 가 upstream 실패를 분류. 클라이언트 메시지는 category 문구, **절대 `ex.getMessage()` 아님**. retryable + `retry_after_seconds` 있으면 `RetryAfterAdvisor` 로 `Retry-After` 부착 | @@ -278,7 +291,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML - **이미 직렬화된 `byte[]` 본문은 감싸지 않는다.** 그 본문을 쓰는 converter 는 받은 값을 그대로 복사하므로 envelope 객체를 받으면 500 으로 끝난다. springdoc 이 OpenAPI 문서를 `byte[]` 로 돌려주어, 감싸던 시절에는 실행 중인 앱의 `/api/v3/api-docs` 가 항상 500 이었다(리뷰 09-04). `String` 반환은 감싸되 JSON 문자열로 - 직렬화해 넘긴다(리뷰 02-06). 단언은 `EnvelopeBodyAdviceTest`, 샘플 전체 조합의 `SampleApiDocsSystemTest`. + 직렬화해 넘긴다(리뷰 02-06). 단언은 `EnvelopeBodyAdviceTest`. - **`String` 반환도 JSON 클라이언트에게는 Envelope 다.** `String` 은 `StringHttpMessageConverter` 가 Jackson 보다 먼저 고른다. 예전에는 그 컨버터에 `Envelope` 객체를 넘겨 `Accept: application/json` 이면 `ClassCastException` 500, `*/*` 면 200 text 였다(리뷰 02-06). 지금은 String 컨버터가 JSON 을 쓰게 될 때 @@ -287,8 +300,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML 용도를 막고, 규칙을 돌리지 않는 서비스에는 함정이 그대로 남는다. - **4xx·5xx 본문은 감싸지 않는다.** `success` 는 클라이언트가 가르는 판별자라, 오류 status 본문을 `success:true` 로 감싸면 성공으로 읽힌다. Boot `/error` 의 map 이 그렇게 나갔다(재리뷰 RR-02-02). -- 위치: sample 모듈이 아니라 adapter-web. 실행 앱은 adapter-web 에 의존하지만 sample-portfolio 에는 의존하지 - 않으므로, 응답 래핑이 실제로 동작하려면 여기 있어야 한다. +- 위치: adapter-web. 실행 앱이 늘 싣는 leaf 라, 응답 래핑이 실제로 동작하려면 여기 있어야 한다. ### EnvelopeErrorController - 컨트롤러에 닿기 전에 생긴 오류(보안 방화벽의 `RequestRejectedException`, 필터의 `sendError`, 필터가 @@ -297,12 +309,19 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML `success:true` 로 감쌌으며 `path` 는 요청 경로 원문이었다(재리뷰 RR-02-02). 이 컨트롤러가 그 자리를 대신해 status 를 `GlobalExceptionHandler` 와 같은 표(`HttpStatusErrorCodes`)로 코드에 매핑하고 실패 Envelope 를 `EnvelopeResponseWriter` 로 쓴다. 요청에서 가져온 값은 싣지 않는다. +- 필터가 던진 예외는 `GlobalExceptionHandler` 를 지나지 않으니 `ServerFailureLog` 의 줄(persistence 는 분류만)도 + 없다. 대신 컨테이너가 `/error` 로 넘기기 전에 그 예외를 원인 사슬째 ERROR 로 남긴다. Tomcat 은 logger + `org.apache.catalina.core.ContainerBase.[…].[dispatcherServlet]` 에 `Servlet.service() for servlet + [dispatcherServlet] … threw exception` 과 스택을 쓰고, persistence 실패의 SQL 원인(값·제약 이름·접속 문자열)도 + `Caused by:` 로 그대로 실린다. 필터에서 저장소나 외부 의존을 부르면 실패를 필터에서 잡아 `EnvelopeResponseWriter` + 로 답하고, 로그 줄은 `ServerFailureLog.of` 로 정한다. 단언은 실제 Tomcat 의 `FilterFailureContainerLogIT` + (systemTest, 2026-11-07). Jetty 는 확인하지 않았다. - `WebMvcPlatformAutoConfiguration` 이 `ErrorMvcAutoConfiguration` 보다 먼저 `ErrorController` 가 없을 때만 등록한다. 어댑터가 자기 `ErrorController` 를 두면 물러난다. - `SecurityConfig` 는 오류 **디스패치**만 허용한다(`DispatcherType.ERROR`). 예전에는 `/error` 가 공개 경로가 아니라서 익명 요청의 400 이 401 로 바뀌었다. `/error` 를 직접 부른 요청은 여전히 인증이 필요하다. 단언은 실제 Tomcat 의 `TomcatWebContractIT`(공유 `WebContractAssertions`)와 `JwtChainErrorDispatchIT`. -- 앱이 보안 체인을 직접 정의하면(예: sample 의 데모 체인) 같은 한 줄 +- 앱이 보안 체인을 직접 정의하면(예: 데모용 체인) 같은 한 줄 (`dispatcherTypeMatchers(DispatcherType.ERROR).permitAll()`)을 그 체인에도 둬야 원래 status 가 나간다. ### CacheControlFilter @@ -453,7 +472,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML ### JacksonNullableConfig - `JsonNullableModule` 을 Spring 관리 `ObjectMapper` 에 등록. 없으면 PATCH 요청 DTO 의 `JsonNullable`(B2)를 Jackson 이 역직렬화하지 못해 absent / explicit-null 구분이 조용히 붕괴된다. -- 스켈레톤 전역 web 관심사(공유 `Patch` 타입과 짝)라 도메인 샘플 모듈이 아니라 adapter-web 에 위치. +- 스켈레톤 전역 web 관심사(공유 `Patch` 타입과 짝)라 기능 모듈이 아니라 adapter-web 에 위치. ### IdempotencyKeyHeader - KEYED 엔드포인트가 헤더를 키로 바꾸는 유일한 지점(리뷰 02-12). 문법: 보이는 ASCII(`0x21`–`0x7E`) @@ -487,7 +506,7 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML ### MdcCorrelationIdPortAdapter - `WebMvcRequestIdFilter`가 무해화하고 MDC `correlation_id`에 넣은 값을 application-core의 `CorrelationIdPort`로 투영한다. -- absent/blank는 `Optional.empty()`로 반환한다. application/sample 계층은 SLF4J/MDC를 직접 +- absent/blank는 `Optional.empty()`로 반환한다. application 계층은 SLF4J/MDC를 직접 참조하지 않고 event-id fallback 정책만 소유한다. ### HeaderSanitizer @@ -517,6 +536,10 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML (web-advanced `ADMISSION_REFUSED` = 1초). - `IDEMPOTENT_IN_FLIGHT` 는 2초: 기본 processing lease(30s)보다 짧아 첫 시도가 끝날 수 있는 동안 같은 키로 다시 묻게 한다. 근거와 클라이언트 행동은 `docs/web/http-contract.md` §2. +- 표는 레지스트리의 `retry_after_seconds` 가 있는 행마다 한 줄이다(`LOCK_ACQUISITION_TIMEOUT` 1초, DB·outbox·job + 코드 포함). `OperationalErrorRegistryContractTest`(app-bootstrap document-contract)가 `OperationalError` 마다 표와 + 레지스트리를 대조한다. 전에는 대조가 없어 7개가 빠진 채였다(advisor 단위 테스트는 값을 코드마다 손으로 옮겨 + 적었고, enum·레지스트리 대조 테스트는 category·status·retryable 만 봤다). --- @@ -562,11 +585,10 @@ commit-aware response wrapper 계약을 구현한다. 또한 이 모듈은 HTML - web leaf에는 별도 DB replay 엔진을 두지 않는다. 같은 요청 의미를 web/application 두 계층이 서로 다른 fingerprint로 판정하면 동일 key의 의미가 endpoint마다 달라지기 때문이다. - 헤더 → 키 변환은 `IdempotencyKeyHeader` 하나로 한다(위 settings / config / http 절). -- production 예시는 sample의 poster image publication 경로다. controller는 key를 받기만 하고, - `PublishPosterImageUseCase`가 application `IdempotencyExecutor`를 사용한다. +- controller는 key를 받기만 하고, 유스케이스가 application `IdempotencyExecutor`를 쓴다. 템플릿에는 이 + 경로를 HTTP부터 끝까지 이은 업무 기능 예가 없다(`docs/manual/05-idempotency.md`). - response-loss system fixture도 동일한 application executor를 사용해, 연결이 끊긴 뒤 같은 key 재시도에서 첫 committed 결과가 복구되고 side effect가 한 번만 실행되는지 검증한다. ### JsonIdempotentResponseCodec -- `adapter:inbound:web-advanced` 로 옮겼다(운영 경로 호출자 0). sample 은 자기 codec - (`PosterImagePublicationReservationCodec`)을 쓰고, response-loss fixture 는 fixture 안의 익명 codec 을 쓴다. +- `adapter:inbound:web-advanced` 로 옮겼다(운영 경로 호출자 0). response-loss fixture 는 fixture 안의 익명 codec 을 쓴다. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java index 79068f66..7893d1ba 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/auth/AuthErrorResponseWriter.java @@ -8,6 +8,7 @@ import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.slf4j.event.Level; import org.springframework.http.HttpHeaders; import tools.jackson.databind.ObjectMapper; @@ -28,13 +29,16 @@ class AuthErrorResponseWriter { void write(HttpServletRequest request, HttpServletResponse response, OperationalError code) throws IOException { - // Log only safe metadata — never the token or the raw failure message. - log.warn( - "security failure: code={} category={} method={} path={}", - code.code(), - code.category(), - request.getMethod(), - request.getRequestURI()); + // Log only safe metadata — never the token or the raw failure message. A 5xx is the server's + // own failure (the key service is down, the decoder is misconfigured) and is an ERROR, as a 5xx + // is on every other path (ServerFailureLog); a 4xx is the caller's and stays a WARN. + log.atLevel(code.httpStatus() >= 500 ? Level.ERROR : Level.WARN) + .log( + "security failure: code={} category={} method={} path={}", + code.code(), + code.category(), + request.getMethod(), + request.getRequestURI()); // A 401 response carries a minimal WWW-Authenticate header (no issuer / token detail). if (code.httpStatus() == 401) { diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeErrorDetails.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeErrorDetails.java index 763ee618..e8d498c3 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeErrorDetails.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/ClientSafeErrorDetails.java @@ -3,7 +3,7 @@ package dev.caskeleton.adapter.inbound.web.error; /** * An {@link dev.caskeleton.shared.error.ApiErrorCarrier} that has bounded, client-safe structure to * put in {@code error.details} — a JSON pointer the client sent, field names from a server - * allowlist. {@link GlobalExceptionHandler#handleCarrier(Exception)} copies it to the wire. + * allowlist. {@link GlobalExceptionHandler#handleCarrier(Throwable)} copies it to the wire. * *

Never the exception message, a server value, or anything the caller may not read: what this * returns is published verbatim. diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java index 6331f7fa..22563880 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandler.java @@ -18,6 +18,7 @@ import java.util.ArrayList; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; +import java.util.Optional; import java.util.Set; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -86,12 +87,14 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { /** * An {@link IllegalArgumentException} is read as "the request was wrong" and answered 400, with * {@link ServerFailureLog#refusedArgument}'s WARN line — the exception type, never the message, - * which may echo request input. The GraphQL, gRPC and STOMP adapters write the same line. + * which may echo request input. The GraphQL, gRPC and STOMP adapters write the same line. A + * carrier in its cause chain answers instead, as on every transport. */ @ExceptionHandler(IllegalArgumentException.class) public ResponseEntity> handleIllegalArgument(IllegalArgumentException ex) { - if (ex instanceof ApiErrorCarrier) { - return handleCarrier(ex); + Optional carrier = ApiErrorCarrier.firstIn(ex); + if (carrier.isPresent()) { + return handleCarrier(carrier.get()); } ServerFailureLog line = ServerFailureLog.refusedArgument(ex); log.warn(line.format(""), line.arguments()); @@ -105,6 +108,12 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { return ErrorResponseFactory.envelope(OperationalError.VALIDATION_FAILED, violations); } + /** + * A path variable, query parameter or header that does not convert to its parameter's type is + * {@code BAD_PARAMETER}, whatever the conversion threw: a carrier a user {@code Converter} threw + * is not searched for, because the argument conversion stage answers a malformed request with the + * transport's own code (owner decision 2026-11-07). STOMP logs the same failure as a refusal. + */ @ExceptionHandler(MethodArgumentTypeMismatchException.class) public ResponseEntity> handleTypeMismatch(MethodArgumentTypeMismatchException ex) { Class requiredType = ex.getRequiredType(); @@ -155,9 +164,11 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { /** * Maps every {@link ApiErrorCarrier} — the shared-contract carriers ({@code MappingException}, * {@code AdapterDisabledException}, {@code PersistenceFailureException}, {@code - * DependencyFailureException}), the application's idempotency failures and any adopter carrier — - * through its own {@link ApiErrorCode}. One branch, so the web adapter answers a carrier exactly - * as the GraphQL, gRPC and STOMP adapters do. + * DependencyFailureException}), the application's idempotency and lock failures and any adopter + * carrier — through its own {@link ApiErrorCode}. One branch, so the web adapter answers a + * carrier exactly as the GraphQL, gRPC and STOMP adapters do. A carrier wrapped in another + * exception is found in the cause chain ({@link ApiErrorCarrier#firstIn}) and answers the same + * way (review 2026-11-06 RR7-01-05). * *

What reaches the log is {@link ServerFailureLog}'s line, the one the GraphQL and gRPC * adapters write too: a persistence carrier by its classification only (its cause can hold SQL @@ -166,9 +177,10 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { * incident. The span gets the same failure, a persistence one again reduced to its * classification. A retryable code with a registered delay also carries {@code Retry-After}. * - * @param failure a throwable that implements {@link ApiErrorCarrier} + * @param failure a throwable that implements {@link ApiErrorCarrier} — the carrier itself, not a + * wrapper around it, so its type decides what reaches the log */ - public ResponseEntity> handleCarrier(Exception failure) { + public ResponseEntity> handleCarrier(Throwable failure) { ApiErrorCode code = ((ApiErrorCarrier) failure).errorCode(); ServerFailureLog.of(failure, code) .ifPresent( @@ -194,8 +206,9 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { @ExceptionHandler(Exception.class) public ResponseEntity> handleUnknown(Exception ex, WebRequest req) { - if (ex instanceof ApiErrorCarrier) { - return handleCarrier(ex); + Optional carrier = ApiErrorCarrier.firstIn(ex); + if (carrier.isPresent()) { + return handleCarrier(carrier.get()); } log.error("unhandled exception on {}", req.getDescription(false), ex); spanErrorRecorder.recordException(ex, OperationalError.INTERNAL_ERROR.code()); @@ -217,6 +230,11 @@ public class GlobalExceptionHandler extends ResponseEntityExceptionHandler { HttpStatusCode.valueOf(OperationalError.VALIDATION_FAILED.httpStatus())); } + /** + * An unreadable body is {@code VALIDATION_FAILED}, or {@code PAYLOAD_TOO_LARGE} when the body + * ceiling cut the read. A carrier a Jackson creator threw is not searched for, for the same + * reason as {@link #handleTypeMismatch}. + */ @Override protected ResponseEntity handleHttpMessageNotReadable( HttpMessageNotReadableException ex, diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebSecurityAutoConfiguration.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebSecurityAutoConfiguration.java index 34decefd..9c9ff482 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebSecurityAutoConfiguration.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/mvc/autoconfigure/WebSecurityAutoConfiguration.java @@ -17,13 +17,13 @@ import org.springframework.core.Ordered; * envelope entry point and access-denied handler, CORS and their settings. * *

Separate from {@link WebAdapterAutoConfiguration} so an application that brings its own - * posture — the demo sample, a contract fixture — excludes exactly this class and still gets the - * error envelope, filters, health endpoint and rate limiting from the web root. Excluding it does - * not switch off {@code @RequiresPermission}: that is {@link WebMethodSecurityAutoConfiguration}, - * which an application keeps while it replaces the chain. Before this root was split from the web - * root, the only way to drop the security chain was to drop the whole root and component-scan the - * leaf back in minus two classes, and every new controller in the leaf then arrived in that scan - * whether it was meant to or not. + * posture — a demo, a contract fixture — excludes exactly this class and still gets the error + * envelope, filters, health endpoint and rate limiting from the web root. Excluding it does not + * switch off {@code @RequiresPermission}: that is {@link WebMethodSecurityAutoConfiguration}, which + * an application keeps while it replaces the chain. Before this root was split from the web root, + * the only way to drop the security chain was to drop the whole root and component-scan the leaf + * back in minus two classes, and every new controller in the leaf then arrived in that scan whether + * it was meant to or not. * *

First among auto-configurations for the same reason as the web root: the filter chain and the * JWT decoder have to exist before Spring Boot's own security auto-configurations decide whether to diff --git a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java index 8fcae639..cdc4aed4 100644 --- a/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java +++ b/src/adapter/inbound/web/src/main/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisor.java @@ -11,29 +11,36 @@ import java.util.OptionalInt; */ public final class RetryAfterAdvisor { - /** Per-code {@code Retry-After} values (seconds). */ + /** + * Per-code {@code Retry-After} values (seconds): the registry's {@code retry_after_seconds} + * column, every row that has one. {@code OperationalErrorRegistryContractTest} (app-bootstrap, + * document-contract) fails when a code here and its registry row differ. + */ private static final Map RETRY_AFTER_SECONDS = - Map.of( - "RATE_LIMIT_EXCEEDED", - 1, + Map.ofEntries( + Map.entry("RATE_LIMIT_EXCEEDED", 1), // The application's value, which the processing-lease check also reads: the resend // arrives while the first attempt can still finish. docs/web/http-contract.md §2. - "IDEMPOTENT_IN_FLIGHT", - Math.toIntExact(IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER.toSeconds()), - "AUTH_KID_UNKNOWN", - 5, - "AUTH_JWKS_UNAVAILABLE", - 30, - "DEPENDENCY_TIMEOUT", - 2, - "DEPENDENCY_CONNECT_FAILED", - 2, - "DEPENDENCY_DNS_FAILED", - 5, - "DEPENDENCY_5XX_SERVER", - 2, - "DEPENDENCY_CIRCUIT_OPEN", - 10); + Map.entry( + "IDEMPOTENT_IN_FLIGHT", + Math.toIntExact(IdempotencyExecutor.IN_FLIGHT_RETRY_AFTER.toSeconds())), + Map.entry("AUTH_KID_UNKNOWN", 5), + Map.entry("AUTH_JWKS_UNAVAILABLE", 30), + Map.entry("DEPENDENCY_TIMEOUT", 2), + Map.entry("DEPENDENCY_CONNECT_FAILED", 2), + Map.entry("DEPENDENCY_DNS_FAILED", 5), + Map.entry("DEPENDENCY_5XX_SERVER", 2), + Map.entry("DEPENDENCY_CIRCUIT_OPEN", 10), + Map.entry("LOCK_ACQUISITION_TIMEOUT", 1), + Map.entry("DB_UNAVAILABLE", 5), + Map.entry("DB_SERIALIZATION_FAILURE", 1), + Map.entry("DB_DEADLOCK", 1), + Map.entry("DB_IDLE_IN_TX_TIMEOUT", 2), + // Never on an HTTP response today (an async failure's 500 is a placeholder), kept so the + // table and the registry stay one-to-one. + Map.entry("OUTBOX_PUBLISH_FAILED", 30), + Map.entry("JOB_EXECUTOR_REJECTED", 5), + Map.entry("JOB_TIMEOUT", 10)); private RetryAfterAdvisor() {} diff --git a/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/FilterFailureContainerLogIT.java b/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/FilterFailureContainerLogIT.java new file mode 100644 index 00000000..898802ce --- /dev/null +++ b/src/adapter/inbound/web/src/systemTest/java/dev/caskeleton/adapter/inbound/web/testkit/mvc/FilterFailureContainerLogIT.java @@ -0,0 +1,145 @@ +package dev.caskeleton.adapter.inbound.web.testkit.mvc; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.classic.spi.IThrowableProxy; +import ch.qos.logback.core.read.ListAppender; +import dev.caskeleton.shared.error.OperationalError; +import dev.caskeleton.shared.error.PersistenceFailureException; +import dev.caskeleton.webtestkit.ContractFixtureApplication; +import jakarta.servlet.Filter; +import java.net.URI; +import java.net.http.HttpClient; +import java.net.http.HttpRequest; +import java.net.http.HttpResponse; +import java.sql.SQLException; +import java.time.Duration; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.slf4j.LoggerFactory; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.web.server.LocalServerPort; +import org.springframework.boot.web.servlet.FilterRegistrationBean; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.core.Ordered; +import org.springframework.test.context.ActiveProfiles; + +/** + * What the server log gets when a servlet filter throws, over a real Tomcat. + * + *

A filter runs before the MVC handler, so its exception never reaches {@code + * GlobalExceptionHandler} and never gets {@code ServerFailureLog}'s line, which keeps a persistence + * failure to its classification. The container logs the exception itself, causes and all, before it + * forwards to {@code /error}. A real container rather than MockMvc, because the line under test is + * the container's. + */ +@SpringBootTest( + classes = { + ContractFixtureApplication.class, + FilterFailureContainerLogIT.ThrowingFilterConfig.class + }, + webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@ActiveProfiles("web-contract") +class FilterFailureContainerLogIT { + + private static final String FAILING_PATH = "/filter-failure"; + + /** The SQL detail a persistence failure's cause can hold; it must be visible to the test only. */ + private static final String SQL_DETAIL = "jdbc:postgresql://db.internal/customer?password=secret"; + + private final HttpClient client = + HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(5)).build(); + + @LocalServerPort private int port; + + @Test + @DisplayName( + "필터가 던진 예외는 GlobalExceptionHandler 를 거치지 않고, 컨테이너가 원인 사슬째(persistence 원인의 SQL 문구까지) ERROR 한 줄로 남긴다") + void aFailureThrownByAFilterIsLoggedByTheContainerWithItsWholeCauseChain() throws Exception { + // when + List logged = warningsAndErrorsWhileRequesting(FAILING_PATH); + + // then + assertThat(logged) + .extracting( + event -> event.getLoggerName().startsWith("org.apache.catalina.core.ContainerBase"), + ILoggingEvent::getLevel, + event -> causeMessages(event.getThrowableProxy()).contains(SQL_DETAIL)) + .as("every WARN or ERROR line: %s", describe(logged)) + .containsExactly(tuple(true, Level.ERROR, true)); + } + + /** Every WARN or ERROR line written anywhere while one request for {@code path} is answered. */ + private List warningsAndErrorsWhileRequesting(String path) throws Exception { + Logger root = (Logger) LoggerFactory.getLogger(org.slf4j.Logger.ROOT_LOGGER_NAME); + ListAppender appender = new ListAppender<>(); + appender.start(); + root.addAppender(appender); + try { + client.send( + HttpRequest.newBuilder(URI.create("http://localhost:" + port + path)) + .header("Accept", "application/json") + .GET() + .build(), + HttpResponse.BodyHandlers.discarding()); + } finally { + root.detachAppender(appender); + appender.stop(); + } + return appender.list.stream() + .filter(event -> event.getLevel().isGreaterOrEqual(Level.WARN)) + .toList(); + } + + /** The messages of a logged exception and all its causes. */ + private static List causeMessages(IThrowableProxy throwable) { + List messages = new ArrayList<>(); + for (IThrowableProxy current = throwable; current != null; current = current.getCause()) { + messages.add(current.getMessage()); + } + return messages; + } + + private static List describe(List logged) { + return logged.stream() + .map( + event -> + event.getLevel() + + " " + + event.getLoggerName() + + ": " + + event.getFormattedMessage() + + " " + + causeMessages(event.getThrowableProxy())) + .toList(); + } + + /** A filter in front of every handler that fails the way a filter calling a store can. */ + @Configuration(proxyBeanMethods = false) + static class ThrowingFilterConfig { + + @Bean + FilterRegistrationBean throwingFilter() { + Filter filter = + (request, response, chain) -> { + throw new IllegalStateException( + "filter failed", + new PersistenceFailureException( + OperationalError.DB_UNAVAILABLE, + "08006", + new SQLException(SQL_DETAIL, "08006"))); + }; + FilterRegistrationBean registration = new FilterRegistrationBean<>(filter); + registration.addUrlPatterns(FAILING_PATH); + registration.setOrder(Ordered.HIGHEST_PRECEDENCE); + return registration; + } + } +} diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java index 3ad25ca3..d580043b 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/auth/EnvelopeAuthenticationEntryPointTest.java @@ -2,17 +2,23 @@ package dev.caskeleton.adapter.inbound.web.auth; import static org.assertj.core.api.Assertions.assertThat; +import ch.qos.logback.classic.Logger; +import ch.qos.logback.classic.spi.ILoggingEvent; +import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; +import java.io.IOException; import java.util.List; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.slf4j.LoggerFactory; import org.springframework.boot.test.system.CapturedOutput; import org.springframework.boot.test.system.OutputCaptureExtension; import org.springframework.http.HttpHeaders; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.security.authentication.InsufficientAuthenticationException; +import org.springframework.security.core.AuthenticationException; import org.springframework.security.oauth2.core.OAuth2Error; import org.springframework.security.oauth2.core.OAuth2ErrorCodes; import org.springframework.security.oauth2.jwt.BadJwtException; @@ -106,6 +112,86 @@ class EnvelopeAuthenticationEntryPointTest { .isEqualTo("AUTH_JWKS_UNAVAILABLE"); } + @Test + void aKeyServiceOutageIsLoggedAtError() throws Exception { + // given + AuthenticationException outage = + new InvalidBearerTokenException( + "invalid", + new JwtDecoderConfig.AuthenticationKeyServiceUnavailableException( + new IOException("connect timed out"))); + + // when + List lines = writerLinesFor(outage); + + // then + assertThat(lines) + .singleElement() + .extracting(event -> event.getLevel().toString(), ILoggingEvent::getFormattedMessage) + .containsExactly( + "ERROR", + "security failure: code=AUTH_JWKS_UNAVAILABLE category=TRANSIENT_DEPENDENCY" + + " method=GET path=/v1/things"); + } + + @Test + void aDecoderMisconfigurationIsLoggedAtError() throws Exception { + // given + AuthenticationException misconfiguration = + new InvalidBearerTokenException( + "invalid", + new JwtDecoderConfig.AuthenticationDecoderMisconfigurationException( + new IllegalStateException("issuer metadata does not match"))); + + // when + List lines = writerLinesFor(misconfiguration); + + // then + assertThat(lines) + .singleElement() + .extracting(event -> event.getLevel().toString(), ILoggingEvent::getFormattedMessage) + .containsExactly( + "ERROR", + "security failure: code=INTERNAL_AUTH_MISCONFIGURATION category=INTERNAL" + + " method=GET path=/v1/things"); + } + + @Test + void aRejectedSignatureStaysAtWarn() throws Exception { + // given + AuthenticationException rejected = + new InvalidBearerTokenException( + "invalid", new BadJwtException("Signed JWT rejected: Invalid signature")); + + // when + List lines = writerLinesFor(rejected); + + // then + assertThat(lines) + .singleElement() + .extracting(event -> event.getLevel().toString(), ILoggingEvent::getFormattedMessage) + .containsExactly( + "WARN", + "security failure: code=AUTH_TOKEN_INVALID_SIGNATURE category=AUTH" + + " method=GET path=/v1/things"); + } + + /** The lines the security writer logs while the entry point answers {@code failure}. */ + private List writerLinesFor(AuthenticationException failure) throws Exception { + Logger logger = (Logger) LoggerFactory.getLogger(AuthErrorResponseWriter.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + entryPoint.commence( + new MockHttpServletRequest("GET", "/v1/things"), new MockHttpServletResponse(), failure); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + return appender.list; + } + @Test void tokenValueNeverLeaksIntoResponseBodyOrLogs(CapturedOutput output) throws Exception { // §테스트 계약: a JWT value must never appear in the response or the log output. diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java index dd525914..faf2ac72 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/GlobalExceptionHandlerTest.java @@ -10,6 +10,7 @@ import ch.qos.logback.core.read.ListAppender; import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedException; import dev.caskeleton.adapter.inbound.web.http.ApiHeaders; import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; +import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; import dev.caskeleton.shared.error.AdapterDisabledException; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; @@ -26,6 +27,7 @@ import jakarta.validation.constraints.Pattern; import jakarta.validation.metadata.ConstraintDescriptor; import java.lang.reflect.Method; import java.sql.SQLException; +import java.time.Duration; import java.util.List; import java.util.Map; import java.util.Set; @@ -697,6 +699,105 @@ class GlobalExceptionHandlerTest { .isNull(); } + @Test + void aLockAcquisitionTimeoutIsAnsweredWithItsRetryableConflictAndTheRegisteredRetryAfter() { + // when + ResponseEntity> response = + handler.handleUnknown( + new LockAcquisitionTimeoutException("orders/42", Duration.ofSeconds(3)), + new ServletWebRequest(new MockHttpServletRequest("POST", "/orders/42"))); + + // then + assertThat(response) + .extracting( + answer -> answer.getStatusCode().value(), + answer -> answer.getBody().error().code(), + answer -> answer.getBody().error().retryable(), + answer -> answer.getHeaders().getFirst(ApiHeaders.RETRY_AFTER)) + .containsExactly(409, "LOCK_ACQUISITION_TIMEOUT", true, "1"); + } + + @Test + void aCarrierWrappedInAnotherExceptionIsAnsweredWithItsOwnCode() { + // given + IllegalStateException wrapper = + new IllegalStateException("use case failed", persistenceFailureWithASqlCause()); + + // when + ResponseEntity> response = + handler.handleUnknown( + wrapper, new ServletWebRequest(new MockHttpServletRequest("POST", "/work-logs"))); + + // then + assertThat(response) + .extracting( + answer -> answer.getStatusCode().value(), answer -> answer.getBody().error().code()) + .containsExactly(503, "DB_UNAVAILABLE"); + } + + @Test + void aWrappedPersistenceFailureIsLoggedByItsClassificationWithoutTheWrapperOrTheSqlCause() { + // given + IllegalStateException wrapper = + new IllegalStateException("use case failed", persistenceFailureWithASqlCause()); + + // when + List logged = + loggedWhile( + () -> + handler.handleUnknown( + wrapper, + new ServletWebRequest(new MockHttpServletRequest("POST", "/work-logs")))); + + // then + assertThat(logged) + .singleElement() + .extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getThrowableProxy) + .containsExactly( + "persistence failure classified as DB_UNAVAILABLE (category=TRANSIENT_DEPENDENCY," + + " retryable=true)", + null); + } + + @Test + void anIllegalArgumentAroundACarrierIsAnsweredWithTheCarriersCode() { + // given + IllegalArgumentException wrapper = + new IllegalArgumentException("bad request", persistenceFailureWithASqlCause()); + + // when + ResponseEntity> response = handler.handleIllegalArgument(wrapper); + + // then + assertThat(response) + .extracting( + answer -> answer.getStatusCode().value(), answer -> answer.getBody().error().code()) + .containsExactly(503, "DB_UNAVAILABLE"); + } + + private static PersistenceFailureException persistenceFailureWithASqlCause() { + return new PersistenceFailureException( + OperationalError.DB_UNAVAILABLE, + "persistence failure classified from SQLState=08006", + new SQLException("jdbc:postgresql://db.internal/customer?password=secret", "08006")); + } + + /** Every line the handler writes while {@code action} runs. */ + private static List loggedWhile(Runnable action) { + ch.qos.logback.classic.Logger logger = + (ch.qos.logback.classic.Logger) LoggerFactory.getLogger(GlobalExceptionHandler.class); + ListAppender appender = new ListAppender<>(); + appender.start(); + logger.addAppender(appender); + try { + action.run(); + } finally { + logger.detachAppender(appender); + appender.stop(); + } + return appender.list; + } + private static MethodParameter validationProbeParameter() { try { Method method = diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java index 571a2323..85e9c0b7 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/error/TransportErrorHandlingTest.java @@ -12,6 +12,8 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers. import dev.caskeleton.adapter.inbound.web.conditional.PreconditionFailedException; import dev.caskeleton.adapter.inbound.web.envelope.EnvelopeBodyAdvice; import dev.caskeleton.adapter.inbound.web.pagination.PageValidationException; +import dev.caskeleton.shared.error.OperationalError; +import dev.caskeleton.shared.error.PersistenceFailureException; import dev.caskeleton.shared.tracing.SpanErrorRecorder; import jakarta.validation.constraints.Max; import java.util.List; @@ -24,6 +26,7 @@ import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import org.springframework.web.HttpMediaTypeNotAcceptableException; import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestHeader; @@ -150,9 +153,47 @@ class TransportErrorHandlingTest { .andExpect(jsonPath("$.error.details[0].rejectedValue").doesNotExist()); } + @Test + @DisplayName("경로 변수 변환기가 던진 carrier 는 원인에 있어도 보지 않는다: 400 BAD_PARAMETER(인자 변환 단계)") + void aPathVariableWhoseConverterThrowsACarrierIsStillABadParameter() throws Exception { + // when + var result = mvc.perform(get("/t/invoices/INV-1")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("BAD_PARAMETER")); + } + + @Test + @DisplayName("본문 생성자가 던진 carrier 는 원인에 있어도 보지 않는다: 400 VALIDATION_FAILED(인자 변환 단계)") + void aBodyWhoseCreatorThrowsACarrierIsStillValidationFailed() throws Exception { + // when + var result = + mvc.perform( + post("/t/signup") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"email\": \"alice@example.com\"}")); + + // then + result + .andExpect(status().isBadRequest()) + .andExpect(jsonPath("$.error.code").value("VALIDATION_FAILED")); + } + @RestController static class Probe { + @GetMapping("/t/invoices/{number}") + Map invoice(@PathVariable("number") InvoiceNumber number) { + return Map.of("ok", "unreachable: the number never converts"); + } + + @PostMapping(value = "/t/signup", consumes = MediaType.APPLICATION_JSON_VALUE) + Map signup(@RequestBody Signup signup) { + return Map.of("ok", "unreachable: the body never reads"); + } + @GetMapping("/t/async-timeout") Map asyncTimeout() { throw new AsyncRequestTimeoutException(); @@ -203,4 +244,29 @@ class TransportErrorHandlingTest { throw new PageValidationException("size", "SIZE_EXCEEDS_MAX", "size must be <= 100"); } } + + /** A path-variable type whose conversion fails with a server-side carrier, as a lookup could. */ + public static final class InvoiceNumber { + + private InvoiceNumber() {} + + /** The conversion Spring finds; a lookup that fails with a carrier for any number. */ + public static InvoiceNumber valueOf(String value) { + if (!value.isEmpty()) { + throw new PersistenceFailureException( + OperationalError.DB_UNAVAILABLE, "invoice lookup failed for " + value, null); + } + return new InvoiceNumber(); + } + } + + /** A request body whose creator fails with a server-side carrier for any address. */ + record Signup(String email) { + Signup { + if (!email.isEmpty()) { + throw new PersistenceFailureException( + OperationalError.DB_UNAVAILABLE, "signup lookup failed", null); + } + } + } } diff --git a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisorTest.java b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisorTest.java index d08c8f10..791eed54 100644 --- a/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisorTest.java +++ b/src/adapter/inbound/web/src/test/java/dev/caskeleton/adapter/inbound/web/observability/RetryAfterAdvisorTest.java @@ -5,6 +5,8 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.shared.error.OperationalError; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; class RetryAfterAdvisorTest { @@ -96,4 +98,28 @@ class RetryAfterAdvisorTest { assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.DEPENDENCY_CIRCUIT_OPEN)) .hasValue(10); } + + // docs/registries/error-codes.yaml LOCK_ACQUISITION_TIMEOUT row: retry_after_seconds 1. + @Test + void lockAcquisitionTimeoutHasRetryAfter1s() { + assertThat(RetryAfterAdvisor.retryAfterSeconds(OperationalError.LOCK_ACQUISITION_TIMEOUT)) + .hasValue(1); + } + + // docs/registries/error-codes.yaml retry_after_seconds of the database, outbox and job rows. + // RetryAfterAdvisor's table once left these out; the registry contract test (app-bootstrap + // OperationalErrorRegistryContractTest) now compares every code. + @ParameterizedTest + @CsvSource({ + "DB_UNAVAILABLE, 5", + "DB_SERIALIZATION_FAILURE, 1", + "DB_DEADLOCK, 1", + "DB_IDLE_IN_TX_TIMEOUT, 2", + "OUTBOX_PUBLISH_FAILED, 30", + "JOB_EXECUTOR_REJECTED, 5", + "JOB_TIMEOUT, 10" + }) + void aRetryableCodeWithARegisteredDelayHasThatRetryAfter(OperationalError code, int seconds) { + assertThat(RetryAfterAdvisor.retryAfterSeconds(code)).hasValue(seconds); + } } diff --git a/src/adapter/inbound/websocket/CLAUDE.md b/src/adapter/inbound/websocket/CLAUDE.md index 3b4163e6..4b54b060 100644 --- a/src/adapter/inbound/websocket/CLAUDE.md +++ b/src/adapter/inbound/websocket/CLAUDE.md @@ -98,8 +98,9 @@ WebSocket is a **build-composition opt-in**, not a dormant feature inside the de - Client `SEND` to `/topic/**` and other destinations is rejected. - Every client-visible processing failure becomes an ERROR frame with an empty payload and the fixed `message` `WEBSOCKET_REQUEST_REJECTED`. Its `error-code` header is the carried - `ApiErrorCode` when an `ApiErrorCarrier` is in the cause chain, `BAD_PARAMETER` for an - `IllegalArgumentException`, and `WEBSOCKET_REQUEST_REJECTED` otherwise. + `ApiErrorCode` of the first `ApiErrorCarrier` in the cause chain (even behind an + `IllegalArgumentException`), `BAD_PARAMETER` for an `IllegalArgumentException`, and + `WEBSOCKET_REQUEST_REJECTED` otherwise. ## Event projection contract @@ -110,7 +111,7 @@ envelope contains only `type`, bounded string `fields`, and `occurredAt`. The br own bounded executor, so the simple broker's fan-out to subscribers never runs on the thread that published the domain event; a full broker queue drops the event (best-effort, R1). -No current `sample-portfolio` feature publishes a WebSocket event or contributes a projector. +템플릿에는 WebSocket 이벤트를 발행하거나 projector를 기여하는 기능이 없다. ## Evidence and limits diff --git a/src/adapter/inbound/websocket/README.md b/src/adapter/inbound/websocket/README.md index 2d60e86f..8bb1bf11 100644 --- a/src/adapter/inbound/websocket/README.md +++ b/src/adapter/inbound/websocket/README.md @@ -32,14 +32,30 @@ 클라이언트가 물러났다가(가능하면 다른 노드로) 다시 붙게 한다. - handler 메서드가 돌기 전의 처리 실패(inbound interceptor의 거부 등)는 빈 본문의 ERROR 프레임이 되고 `message` 헤더는 고정값 `WEBSOCKET_REQUEST_REJECTED`다. `error-code` 헤더는 원인 사슬에 - `ApiErrorCarrier`가 있으면 그 코드, `IllegalArgumentException`이면 `BAD_PARAMETER`, 나머지는 - `WEBSOCKET_REQUEST_REJECTED`다. + `ApiErrorCarrier`가 있으면 첫 carrier의 코드(`IllegalArgumentException` 뒤에 있어도), + `IllegalArgumentException`이면 `BAD_PARAMETER`, 나머지는 `WEBSOCKET_REQUEST_REJECTED`다. - `@MessageMapping` 메서드의 실패는 inbound 채널 executor에서 끝나서 프레임이 나가지 않는다. 서버 로그는 `StompHandlerFailureLog`가 web·GraphQL·gRPC와 같은 줄로 남긴다(`ServerFailureLog`): persistence 실패는 - 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. `IllegalArgumentException`은 + 분류만, 5xx carrier는 예외와 함께, 4xx carrier는 남기지 않는다. 다른 예외로 감싼 carrier도 원인 사슬의 + 첫 carrier로 같은 줄을 남긴다(재리뷰 RR7-01-05). `IllegalArgumentException`은 `BAD_PARAMETER`로 보고 WARN 한 줄(`request refused as BAD_PARAMETER by <예외 타입>`)만 남긴다. 메시지는 - 입력값이 들 수 있어 남기지 않는다. 그 밖의 예외는 예외와 함께 ERROR. 전에는 Spring이 예외 전체 - (persistence 실패의 SQL 원인 포함)를 ERROR로 남겼다. + 입력값이 들 수 있어 남기지 않는다. +- handler가 돌기 전에 Spring이 클라이언트 메시지를 거부한 실패도 같은 모양 WARN 한 줄로 남긴다. 코드는 web이 + 같은 실패에 답하는 코드다(재리뷰 RR7-01-06): + - 읽지 못한 payload(`MessageConversionException`, 받은 메시지가 실린 것): `VALIDATION_FAILED` + - 비었거나 검증에 걸린 payload(`MethodArgumentNotValidException`): `VALIDATION_FAILED` + - `@DestinationVariable`·`@Header` 값이 파라미터 타입으로 바뀌지 않음(`ConversionFailedException`): `BAD_PARAMETER` + + 이 예외들의 메시지는 받은 JSON 조각이나 값을 담는다. 그래서 타입만 남긴다. 응답을 JSON으로 쓰지 못한 + `MessageConversionException`은 받은 메시지가 실리지 않는다. 서버 탓이라 ERROR로 남는다. + + 이 거부는 원인 사슬의 carrier보다 먼저 판정한다. payload creator나 destination 변수 타입의 변환이 carrier를 + 던져도(조회하다 DB 실패 등) 인자를 거부한 것이라 같은 WARN 한 줄이다. web이 읽지 못한 본문과 바뀌지 않는 경로 + 변수에 원인과 상관없이 `VALIDATION_FAILED`·`BAD_PARAMETER`로 답하는 것과 같다. 인자 변환 단계는 carrier를 보지 + 않는다(소유자 결정 2026-11-07, 재리뷰 README 19.4절 ④). +- 그 밖의 예외는 예외와 함께 ERROR. 전에는 Spring이 예외 전체(persistence 실패의 SQL 원인 포함)를 ERROR로 남겼다. + 필수 header·destination 변수가 없을 때의 `MessageHandlingException`도 ERROR다. 메시지에 입력값이 없고, Spring이 + 같은 타입으로 서버 실패도 감싸서 타입만으로는 클라이언트 탓을 가를 수 없다(결정 색인 기본값 2026-11-07). - `LiveEventProjector` bean이 정확히 하나 있는 `@DomainEvent` 타입만 broadcast한다. 도메인 객체를 그대로 직렬화하지 않고, projector가 만든 bounded `Map`만 보낸다. diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandler.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandler.java index 7b957598..017bb745 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandler.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandler.java @@ -2,6 +2,7 @@ package dev.caskeleton.adapter.inbound.websocket.stomp; import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.OperationalError; +import java.util.Optional; import org.springframework.messaging.Message; import org.springframework.messaging.simp.stomp.StompCommand; import org.springframework.messaging.simp.stomp.StompHeaderAccessor; @@ -14,9 +15,10 @@ import org.springframework.web.socket.messaging.StompSubProtocolErrorHandler; *

The frame's {@code message} header is fixed, so no exception text can reach the client. Its * {@code error-code} header is the stable code every other transport would send for the same * failure: an {@link ApiErrorCarrier} anywhere in the cause chain (Spring wraps a failure raised - * while the frame is processed in a {@code MessagingException}) reports its own code, an {@link - * IllegalArgumentException} reports {@code BAD_PARAMETER}, and everything else stays {@link - * #SAFE_ERROR_CODE}. + * while the frame is processed in a {@code MessagingException}) reports its own code — the first + * one, found as every transport finds it ({@link ApiErrorCarrier#firstIn}), even behind an {@link + * IllegalArgumentException} — then an {@link IllegalArgumentException} reports {@code + * BAD_PARAMETER}, and everything else stays {@link #SAFE_ERROR_CODE}. * *

What reaches it is what fails before a handler method runs — an inbound interceptor's refusal, * on the thread that received the frame. A {@code @MessageMapping} method runs on the inbound @@ -42,13 +44,14 @@ final class SafeStompSubProtocolErrorHandler extends StompSubProtocolErrorHandle } private static String errorCodeOf(Throwable failure) { + Optional carrier = ApiErrorCarrier.firstIn(failure); + if (carrier.isPresent()) { + return ((ApiErrorCarrier) carrier.get()).errorCode().code(); + } int depth = 0; for (Throwable cause = failure; cause != null && depth++ < MAX_CAUSE_DEPTH; cause = cause.getCause()) { - if (cause instanceof ApiErrorCarrier carrier) { - return carrier.errorCode().code(); - } if (cause instanceof IllegalArgumentException) { return OperationalError.BAD_PARAMETER.code(); } diff --git a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLog.java b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLog.java index 7ae5ff66..18f8f6c9 100644 --- a/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLog.java +++ b/src/adapter/inbound/websocket/src/main/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLog.java @@ -1,10 +1,19 @@ package dev.caskeleton.adapter.inbound.websocket.stomp; import dev.caskeleton.shared.error.ApiErrorCarrier; +import dev.caskeleton.shared.error.ApiErrorCode; +import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.ServerFailureLog; +import java.util.Optional; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.core.convert.ConversionFailedException; +import org.springframework.core.convert.TypeDescriptor; +import org.springframework.messaging.converter.MessageConversionException; +import org.springframework.messaging.handler.annotation.DestinationVariable; +import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.MessageExceptionHandler; +import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException; import org.springframework.web.bind.annotation.ControllerAdvice; /** @@ -15,14 +24,30 @@ import org.springframework.web.bind.annotation.ControllerAdvice; * SafeStompSubProtocolErrorHandler}, which only sees what fails before a handler runs (an * interceptor's refusal). Without a handler for it, Spring's method handler logs the whole * exception and stops: a persistence failure's SQL cause — values, constraint names, credentials — - * went to the log, and a client-side refusal was logged as an error. With this advice a carrier - * gets {@link ServerFailureLog}'s line (a persistence failure its classification only, a - * client-side code nothing); an {@link IllegalArgumentException} is the {@code BAD_PARAMETER} every - * transport makes of it and gets the WARN line naming its type, never its message, which may echo - * input (review 2026-11-05 RR6-01-06); anything else is logged with its exception, as before. The - * request id is on MDC ({@link WebSocketCorrelationInterceptor}). The client is answered as before: - * a handler method that throws sends no frame. A feature's own {@code @MessageExceptionHandler} - * still takes precedence over this one. + * went to the log, and a client-side refusal was logged as an error. With this advice a carrier — + * the failure itself or the first one in its cause chain, as on every transport (review 2026-11-06 + * RR7-01-05) — gets {@link ServerFailureLog}'s line (a persistence failure its classification only, + * a client-side code nothing); an {@link IllegalArgumentException} is the {@code BAD_PARAMETER} + * every transport makes of it and gets the WARN line naming its type, never its message, which may + * echo input (review 2026-11-05 RR6-01-06); anything else is logged with its exception, as before. + * The request id is on MDC ({@link WebSocketCorrelationInterceptor}). The client is answered as + * before: a handler method that throws sends no frame. A feature's own + * {@code @MessageExceptionHandler} still takes precedence over this one. + * + *

Spring's own refusals of a message the client got wrong are client failures too, and get the + * same WARN line under the code the web adapter answers the same failure with (review 2026-11-06 + * RR7-01-06): a payload the converter could not read ({@code VALIDATION_FAILED}, like an unreadable + * HTTP body), a payload that failed validation or was empty ({@code VALIDATION_FAILED}), and a + * destination variable or header that does not convert to its parameter's type ({@code + * BAD_PARAMETER}, like a path variable). Their messages quote the input, so they are not logged. A + * reply the converter could not write is the server's failure: Spring raises the same {@link + * MessageConversionException} for it, but without a failed message, and it stays an error. + * + *

Those refusals are judged before the cause chain is searched for a carrier. A converter that + * throws a carrier — a payload creator or a destination-variable type that looks something up — + * still made a refusal of the argument, as the web adapter answers an unreadable body or a path + * variable that does not convert whatever their cause: the argument conversion stage does not read + * a carrier (owner decision 2026-11-07). */ @ControllerAdvice class StompHandlerFailureLog { @@ -31,8 +56,15 @@ class StompHandlerFailureLog { @MessageExceptionHandler void logFailure(Exception failure) { - if (failure instanceof ApiErrorCarrier carrier) { - ServerFailureLog.of(failure, carrier.errorCode()) + Optional refusal = clientRefusalOf(failure); + if (refusal.isPresent()) { + ServerFailureLog line = ServerFailureLog.refused(refusal.get(), failure); + log.warn(line.format(""), line.arguments()); + return; + } + Optional carrier = ApiErrorCarrier.firstIn(failure); + if (carrier.isPresent()) { + ServerFailureLog.of(carrier.get(), ((ApiErrorCarrier) carrier.get()).errorCode()) .ifPresent(line -> log.error(line.format(""), line.arguments())); return; } @@ -43,4 +75,25 @@ class StompHandlerFailureLog { } log.error("unhandled failure in a STOMP message handler", failure); } + + /** The client-side code of a message Spring refused before the handler ran, if it is one. */ + private static Optional clientRefusalOf(Exception failure) { + if (failure instanceof MessageConversionException conversion + && conversion.getFailedMessage() != null) { + return Optional.of(OperationalError.VALIDATION_FAILED); + } + if (failure instanceof MethodArgumentNotValidException) { + return Optional.of(OperationalError.VALIDATION_FAILED); + } + if (failure instanceof ConversionFailedException conversion + && isBoundFromTheMessage(conversion.getTargetType())) { + return Optional.of(OperationalError.BAD_PARAMETER); + } + return Optional.empty(); + } + + /** Whether a conversion was into a handler parameter the client's destination or header fills. */ + private static boolean isBoundFromTheMessage(TypeDescriptor target) { + return target.hasAnnotation(DestinationVariable.class) || target.hasAnnotation(Header.class); + } } diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandlerTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandlerTest.java index 702f7bad..2c180d1c 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandlerTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/SafeStompSubProtocolErrorHandlerTest.java @@ -46,6 +46,23 @@ class SafeStompSubProtocolErrorHandlerTest { .containsExactly("MAPPING_FAILED", SafeStompSubProtocolErrorHandler.SAFE_ERROR_CODE); } + @Test + void anIllegalArgumentAroundACarrierReportsTheCarriersCode() { + // given + Throwable failure = + new MessagingException( + "SECRET_SENTINEL", + new IllegalArgumentException( + "SECRET_SENTINEL", new MappingException("SECRET_SENTINEL mapping detail"))); + + // when + Message result = handler.handleClientMessageProcessingError(null, failure); + + // then + assertThat(StompHeaderAccessor.wrap(result).getFirstNativeHeader("error-code")) + .isEqualTo("MAPPING_FAILED"); + } + @Test void anIllegalArgumentReportsBadParameter() { // when diff --git a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLogTest.java b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLogTest.java index fbe0a153..6f747789 100644 --- a/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLogTest.java +++ b/src/adapter/inbound/websocket/src/test/java/dev/caskeleton/adapter/inbound/websocket/stomp/StompHandlerFailureLogTest.java @@ -10,14 +10,31 @@ import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.ApiErrorCode; import dev.caskeleton.shared.error.OperationalError; import dev.caskeleton.shared.error.PersistenceFailureException; +import java.nio.charset.StandardCharsets; import java.sql.SQLException; import java.util.HashMap; import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.stream.Stream; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; import org.slf4j.LoggerFactory; import org.springframework.context.support.StaticApplicationContext; import org.springframework.messaging.Message; +import org.springframework.messaging.converter.ByteArrayMessageConverter; +import org.springframework.messaging.converter.CompositeMessageConverter; +import org.springframework.messaging.converter.JacksonJsonMessageConverter; +import org.springframework.messaging.converter.MessageConversionException; +import org.springframework.messaging.converter.MessageConverter; +import org.springframework.messaging.converter.StringMessageConverter; +import org.springframework.messaging.handler.annotation.DestinationVariable; +import org.springframework.messaging.handler.annotation.Header; import org.springframework.messaging.handler.annotation.MessageMapping; +import org.springframework.messaging.handler.annotation.Payload; import org.springframework.messaging.simp.SimpMessageHeaderAccessor; import org.springframework.messaging.simp.SimpMessageType; import org.springframework.messaging.simp.SimpMessagingTemplate; @@ -114,25 +131,156 @@ class StompHandlerFailureLogTest { IllegalStateException.class.getName()); } + /** Messages a client gets wrong before the handler method runs: Spring refuses the argument. */ + static Stream clientArgumentRefusals() { + return Stream.of( + Arguments.of( + "/app/greeting", + "{\"name\": \"alice@example.com".getBytes(StandardCharsets.UTF_8), + Map.of(), + "VALIDATION_FAILED", + "org.springframework.messaging.converter.MessageConversionException"), + Arguments.of( + "/app/greeting", + new byte[0], + Map.of(), + "VALIDATION_FAILED", + "org.springframework.messaging.handler.annotation.support" + + ".MethodArgumentNotValidException"), + Arguments.of( + "/app/orders/alice@example.com", + new byte[0], + Map.of(), + "BAD_PARAMETER", + "org.springframework.core.convert.ConversionFailedException"), + Arguments.of( + "/app/count", + new byte[0], + Map.of("count", "alice@example.com"), + "BAD_PARAMETER", + "org.springframework.core.convert.ConversionFailedException")); + } + + @ParameterizedTest + @MethodSource("clientArgumentRefusals") + @DisplayName("읽을 수 없거나 검증에 걸린 payload, 변환할 수 없는 destination 변수·header는 WARN 한 줄(타입만)로 남는다") + void aClientArgumentRefusalIsLoggedAtWarnByItsTypeWithoutItsMessage( + String destination, + byte[] payload, + Map headers, + String code, + String failureType) { + // when + List logged = loggedWhileHandling(destination, payload, headers); + + // then + assertThat(logged) + .singleElement() + .extracting( + ILoggingEvent::getLevel, + ILoggingEvent::getFormattedMessage, + ILoggingEvent::getThrowableProxy) + .containsExactly(Level.WARN, "request refused as " + code + " by " + failureType, null); + } + + /** Arguments whose conversion threw a server-side carrier: the converter, not the use case. */ + static Stream conversionRefusalsAroundACarrier() { + return Stream.of( + Arguments.of( + "/app/signup", + "{\"email\": \"alice@example.com\"}".getBytes(StandardCharsets.UTF_8), + "VALIDATION_FAILED", + "org.springframework.messaging.converter.MessageConversionException"), + Arguments.of( + "/app/invoices/INV-1", + new byte[0], + "BAD_PARAMETER", + "org.springframework.core.convert.ConversionFailedException")); + } + + @ParameterizedTest + @MethodSource("conversionRefusalsAroundACarrier") + @DisplayName("변환기가 던진 carrier 를 원인으로 든 인자 변환 실패도 거부로 WARN 한 줄이다(인자 변환 단계는 carrier 를 보지 않는다)") + void aConversionRefusalAroundACarrierIsStillLoggedAsARefusal( + String destination, byte[] payload, String code, String failureType) { + // when + List logged = loggedWhileHandling(destination, payload, Map.of()); + + // then + assertThat(logged) + .singleElement() + .extracting( + ILoggingEvent::getLevel, + ILoggingEvent::getFormattedMessage, + ILoggingEvent::getThrowableProxy) + .containsExactly(Level.WARN, "request refused as " + code + " by " + failureType, null); + } + + @Test + void aReplyTheConverterCannotWriteIsLoggedAtErrorWithTheFailure() { + // when + List logged = loggedWhileHandling("/app/unwritable-reply"); + + // then + assertThat(logged) + .singleElement() + .extracting( + ILoggingEvent::getLevel, + ILoggingEvent::getFormattedMessage, + event -> event.getThrowableProxy().getClassName()) + .containsExactly( + Level.ERROR, + "unhandled failure in a STOMP message handler", + MessageConversionException.class.getName()); + } + + @Test + void aWrappedPersistenceFailureIsLoggedByItsClassificationWithoutTheWrapperOrTheSqlCause() { + // when + List logged = loggedWhileHandling("/app/wrapped-persistence"); + + // then + assertThat(logged) + .singleElement() + .extracting(ILoggingEvent::getFormattedMessage, ILoggingEvent::getThrowableProxy) + .containsExactly( + "persistence failure classified as DB_UNAVAILABLE (category=TRANSIENT_DEPENDENCY," + + " retryable=true)", + null); + } + /** * Every ERROR or WARN line written anywhere while one message to {@code destination} is handled. */ private static List loggedWhileHandling(String destination) { + return loggedWhileHandling(destination, new byte[0], Map.of()); + } + + /** + * Every ERROR or WARN line written anywhere while one message to {@code destination}, carrying + * {@code payload} and {@code headers}, is handled. + */ + private static List loggedWhileHandling( + String destination, byte[] payload, Map headers) { StaticApplicationContext context = new StaticApplicationContext(); context.registerSingleton("failingController", FailingController.class); context.registerSingleton("stompHandlerFailureLog", StompHandlerFailureLog.class); context.refresh(); // The handler @EnableWebSocketMessageBroker wires; it is the one that reads @ControllerAdvice. + // The converters @EnableWebSocketMessageBroker gives the handler and the broker template. + SimpMessagingTemplate brokerTemplate = + new SimpMessagingTemplate(new ExecutorSubscribableChannel()); + brokerTemplate.setMessageConverter(brokerMessageConverter()); WebSocketAnnotationMethodMessageHandler handler = new WebSocketAnnotationMethodMessageHandler( - new ExecutorSubscribableChannel(), - new ExecutorSubscribableChannel(), - new SimpMessagingTemplate(new ExecutorSubscribableChannel())); + new ExecutorSubscribableChannel(), new ExecutorSubscribableChannel(), brokerTemplate); + handler.setMessageConverter(brokerMessageConverter()); handler.setDestinationPrefixes(List.of("/app")); handler.setApplicationContext(context); handler.afterPropertiesSet(); Message message = - MessageBuilder.withPayload(new byte[0]) + MessageBuilder.withPayload(payload) + .copyHeaders(headers) .setHeader(SimpMessageHeaderAccessor.MESSAGE_TYPE_HEADER, SimpMessageType.MESSAGE) .setHeader(SimpMessageHeaderAccessor.DESTINATION_HEADER, destination) .setHeader(SimpMessageHeaderAccessor.SESSION_ID_HEADER, "session-1") @@ -155,6 +303,14 @@ class StompHandlerFailureLogTest { .toList(); } + private static MessageConverter brokerMessageConverter() { + return new CompositeMessageConverter( + List.of( + new StringMessageConverter(), + new ByteArrayMessageConverter(), + new JacksonJsonMessageConverter())); + } + /** A feature's STOMP controller whose use case fails in each of the ways that matter. */ @Controller static class FailingController { @@ -188,6 +344,71 @@ class StompHandlerFailureLogTest { void unrecognised() { throw new IllegalStateException("boom"); } + + @MessageMapping("/greeting") + void greeting(@Payload Greeting greeting) {} + + @MessageMapping("/orders/{id}") + void order(@DestinationVariable UUID id) {} + + @MessageMapping("/count") + void count(@Header("count") int count) {} + + @MessageMapping("/signup") + void signup(@Payload Signup signup) {} + + @MessageMapping("/invoices/{number}") + void invoice(@DestinationVariable InvoiceNumber number) {} + + @MessageMapping("/unwritable-reply") + UnwritableReply unwritableReply() { + return new UnwritableReply(); + } + + @MessageMapping("/wrapped-persistence") + void wrappedPersistence() { + throw new IllegalStateException( + "use case failed", + new PersistenceFailureException( + OperationalError.DB_UNAVAILABLE, + "08006", + new SQLException("jdbc:postgresql://db.internal/customer?password=secret", "08006"))); + } + } + + /** A payload a client sends as JSON. */ + record Greeting(String name) {} + + /** A payload whose creator fails with a server-side carrier for any address. */ + record Signup(String email) { + Signup { + if (!email.isEmpty()) { + throw new PersistenceFailureException( + OperationalError.DB_UNAVAILABLE, "signup lookup failed", null); + } + } + } + + /** A destination-variable type whose conversion fails with a server-side carrier. */ + public static final class InvoiceNumber { + + private InvoiceNumber() {} + + /** The conversion Spring finds; a lookup that fails with a carrier for any number. */ + public static InvoiceNumber valueOf(String value) { + if (!value.isEmpty()) { + throw new PersistenceFailureException( + OperationalError.DB_UNAVAILABLE, "invoice lookup failed for " + value, null); + } + return new InvoiceNumber(); + } + } + + /** A reply the JSON converter cannot write: its only property is itself. */ + static final class UnwritableReply { + public UnwritableReply getSelf() { + return this; + } } /** A use-case failure carrying a shared code. */ diff --git a/src/adapter/outbound/cache-redis/CLAUDE.md b/src/adapter/outbound/cache-redis/CLAUDE.md index d3927556..79842ed2 100644 --- a/src/adapter/outbound/cache-redis/CLAUDE.md +++ b/src/adapter/outbound/cache-redis/CLAUDE.md @@ -53,9 +53,9 @@ nothing of the SDK (`RedisRuntimePackageBoundaryTest` in the runtime holds that in `META-INF/spring.factories` as the runtime's `RedisCorrectnessRequirement`. The typed SDK described in -`docs/superpowers/specs/2026-08-07-redis-wrapper-typed-api-design.md` remains an optional library +`docs/design/2026-08-07-redis-wrapper-typed-api-design.md` remains an optional library rather than part of the shipped semantic Redis adapter. Delivery status and adaptation history are -in `docs/superpowers/plans/2026-08-07-redis-wrapper-typed-api-status.md`. +in `docs/history/plans/2026-08-07-redis-wrapper-typed-api-status.md`. - `sdk.api..` is the public contract. It must never import Spring, Lettuce, Micrometer, or any SDK implementation package; Reactor is confined to `sdk.api.reactive`. @@ -130,12 +130,12 @@ be silently skipped when selected. Two real-server lanes. `redisContainerContractTest` (integration category, in `integrationCheck` only — not in this leaf's `mainCheck` too, which ran it twice per push to main) starts its own Redis with Testcontainers — the `redis` image of -`config/testing/container-images.properties`, loading `infra/redis-sdk/acl/lane-fixture-accounts.acl` — and +`config/testing/container-images.properties`, loading `compose/redis/acl/lane-fixture-accounts.acl` — and runs `LiveRedisCacheRegionContractTest`, `LiveRedisDistributedLeaseContractTest` and `LiveRedisIdempotencyStoreContractTest` (the `application-core` port contracts the in-memory fakes also pass), `LiveRedisSemanticPortsTest` and `LiveRedisSemanticScriptAclProbeTest`; a skip fails it -(review 2026-11-01 05-16). The idempotency contract was on the explicit-only topology lane alone -until review 2026-11-03 RR-04-05, so the Lua state machine's stale-handle, renew-refusal and +(since 2026-11-01). The idempotency contract was on the explicit-only topology lane alone +until 2026-11-03, so the Lua state machine's stale-handle, renew-refusal and retry cases reached a real server in no gate. `RedisTestContainer` starts the server only when that lane names the ACL file. @@ -183,19 +183,19 @@ that reads a cache entry cannot execute a script. The cache's conditional writes run on the same account but on a lane of their own, `CacheScriptLane.CACHE_SCRIPT` (`app.capabilities.cache.maximum-script-connections`, contributed by `RedisCacheConfig` as a `RedisLaneContribution`). Do not move them back to `SCRIPT`: that lane is the -idempotency, rate-limit and lease budget, and a cache under load must not take it (review 2026-11-03 -README §4, RR-04-02). Each lane's wait, refusals and reconnects are meters of `redis-runtime` +idempotency, rate-limit and lease budget, and a cache under load must not take it (decided +2026-11-03). Each lane's wait, refusals and reconnects are meters of `redis-runtime` (`RedisLaneMetrics`, `redis.lane.*`, tag `lane`), so whether the cache stays off `SCRIPT` is a query, not an assumption. The `DEGRADED` health order ships with `redis-runtime`, which reports the -status (`config/module-defaults/redis-runtime.yml`, RR-04-10). +status (`config/module-defaults/redis-runtime.yml`). A Cluster transaction runs on one node, so the SDK's `RedisTransactionRunner` derives a routing key from the watched keys (or an explicit `RedisSlotTag`) and borrows `RedisSdkLane.TRANSACTION`, which is pinned to its key's owner, on the node that owns that slot. Routed leases are never pooled: a pooled connection is pinned to the previous caller's node. -Settings binding is a recorded exception to capability criterion 4 (one prefix, `StrictSettingsBinder`, -review finding 05-18): `app.redis.*` is bound by `redis-runtime` with setters and `validate()`, +Settings binding is a recorded exception to capability criterion 4 (one prefix, `StrictSettingsBinder`; +decided 2026-11-03): `app.redis.*` is bound by `redis-runtime` with setters and `validate()`, because that leaf has no project dependencies and cannot reach `StrictSettingsBinder` (support); `app.capabilities.*` (cache, lease, rate-limit provider) is bound strictly by this leaf under the shared capability-selector root; `app.rate-limit.*` is the HTTP boundary's switch that this leaf only diff --git a/src/adapter/outbound/cache-redis/README.md b/src/adapter/outbound/cache-redis/README.md index 7761b8d6..515dc06e 100644 --- a/src/adapter/outbound/cache-redis/README.md +++ b/src/adapter/outbound/cache-redis/README.md @@ -277,16 +277,32 @@ revision) come from app-bootstrap `IdempotencySettings`. This leaf reads only `k `renew` has its own program rather than the generic transition. Renewal keeps the record in `EXECUTING`, and the transition answers "already in the target state" before it reads the revision (that answer exists for a retry whose first reply was lost), so a renewal sent through it was always -`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. For a start that answer is given only to -the handle the start was applied from — the record one revision past it — because the executor runs -the action on it: another handle of the same attempt (one from before a takeover, or the current one -a replayed claim returned) used to be told the start was applied and ran the action a second time; -it is now `NOT_OWNER` or `NOT_CLAIMED`, as in the PostgreSQL store (round6 RR6-02-01). The renew program checks owner, +`ALREADY_RENEWED_SAME_OPERATION` and never moved the lease. That answer is given only to the handle +the transition was applied from — the record one revision past it, with `lastKind` (written by the +claim, renew and transition programs) naming that transition. Another handle of the same +attempt (one from before a takeover, or the current one a replayed claim returned) used to be told a +start was applied and ran the action a second time (round6 RR6-02-01), and to be told a completion +or failure that followed a takeover was its own (owner decision 2026-11-06); it is now `NOT_OWNER` +or `NOT_CLAIMED`/`NOT_IN_PROGRESS`, as in the PostgreSQL store. Without the kind, a start through the +handle a renewal was applied from was confirmed too — renewal leaves the record `EXECUTING` one +revision past that handle (round8 RR8-04-02); it is `NOT_OWNER`. A failure from the handle that +applied one, asking for the other disposition, is `OPERATION_CONFLICT` (it fell through to +`NOT_OWNER`); the record keeps no retention, so another retention is confirmed (owner decision +2026-11-07). The renew program checks owner, operation, revision and state, then extends `leaseUntil` from Redis `TIME` and bumps the revision. A lost renewal reply is recognised by what the renewal recorded — the revision it started from and the lease it asked for: the same lease is `ALREADY_RENEWED_SAME_OPERATION` with the current handle, a different lease is `OPERATION_CONFLICT`. +Every program compares the operation a call names with the one the record was claimed under, right +after the owner token: another operation is `OPERATION_CONFLICT` and changes nothing. The PostgreSQL +store and the in-memory fake used to apply it; they now answer the same (owner decision 2026-11-06, +`IdempotencyStoreContract`). The release program also checks the handle's revision, as the +transition does: owner token and operation alone let the handle from before the same attempt took +its claim over release the claim it holds now. A release deletes the record, so a release that finds +no record — its own retry, an expired record, one never claimed — is `ABSENT`; it used to be +confirmed as `ALREADY_RELEASED_SAME_OPERATION`, which the store cannot know. + A lease that runs out is taken over only from a claim that never started or an attempt marked retryable — by whoever claims next, the holder's own attempt included: the claim program checks for a takeover before it replays a same-owner claim, so an attempt whose start was refused takes its diff --git a/src/adapter/outbound/cache-redis/build.gradle b/src/adapter/outbound/cache-redis/build.gradle index f9909060..d0f217cb 100644 --- a/src/adapter/outbound/cache-redis/build.gradle +++ b/src/adapter/outbound/cache-redis/build.gradle @@ -69,14 +69,15 @@ redisTopologyLane { // needs coordinates of a topology someone else started — so until this lane existed the Redis // adapters' port contracts reached a real server in no stage, and the fake and the adapter could hide // the same defect (05-02, 05-03). The image is config/testing/container-images.properties' `redis`, -// and the ACL file is infra/redis-sdk's own, so the accounts and their rights are the standalone +// and the ACL file is the one the development stack and the redis-sdk topologies share +// (compose/redis/acl), so the accounts and their rights are the standalone // topology's. Integration category, so integrationCheck runs it — integration-main.yml's // `integration-check` job, on every push to main and nightly. It is deliberately not in this leaf's // mainCheck as well: `main-check` and `integration-check` are two jobs of the same workflow run, so a // lane in both started a second Redis container and ran every live contract twice per push without // covering anything the first run did not (found while fixing review 2026-11-03). Sentinel, cluster // and TLS remain the topology lane's. -def redisAclDirectory = rootProject.projectDir.parentFile.toPath().resolve('infra/redis-sdk/acl').toFile() +def redisAclDirectory = rootProject.projectDir.parentFile.toPath().resolve('compose/redis/acl').toFile() strictTestLanes { lane('redisContainerContractTest') { integration() diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java index d68e6b8a..d92ddc04 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/IdempotencyScripts.java @@ -62,7 +62,7 @@ public final class IdempotencyScripts { redis.call('HSET', KEYS[1], 'state', 'CLAIMED', 'owner', ARGV[1], 'attempt', 1, 'rev', 1, 'op', ARGV[2], 'fp', ARGV[3], 'codec', ARGV[4], 'policy', ARGV[5], - 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease) + 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease, 'lastKind', 'CLAIM') redis.call('PEXPIRE', KEYS[1], leaseMillis + afterLease) return {'ACQUIRED', 1, 1, ARGV[1], '', tostring(nowMillis + leaseMillis)} end @@ -91,7 +91,8 @@ public final class IdempotencyScripts { -- record it holds would hand back a claim that cannot start (round6 RR6-02-01). redis.call('HSET', KEYS[1], 'state', 'CLAIMED', 'owner', ARGV[1], 'attempt', attempt + 1, 'rev', rev + 1, - 'op', ARGV[2], 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease) + 'op', ARGV[2], 'leaseUntil', nowMillis + leaseMillis, 'afterLease', afterLease, + 'lastKind', 'CLAIM') redis.call('PEXPIRE', KEYS[1], leaseMillis + afterLease) return {'TAKEN_OVER', attempt + 1, rev + 1, ARGV[1], '', tostring(nowMillis + leaseMillis)} @@ -123,6 +124,21 @@ public final class IdempotencyScripts { * execution that had just begun; the PostgreSQL store refused it (re-review 2026-11-04 README 15, * {@code IdempotencyStoreContract}). Completion and failure read no lease: the holder's late * result is recorded (owner decision 2026-11-04). + * + *

A transition already applied is answered {@code ALREADY} only to the handle it was applied + * from. A completion or failure used to be reported back to any handle of its operation, so the + * same attempt's handle from before a takeover was told the completion that followed it was its + * own (owner decision 2026-11-06). + * + *

"Applied from this handle" is the record one revision past it and {@code lastKind} + * naming this transition. Every program that moves the revision writes {@code lastKind} (claim, + * renew and this one; release deletes the record). The revision alone confirmed a start through + * the handle a renewal was applied from: renewal leaves the record {@code EXECUTING}, the start's + * target, one revision past that handle (round8 RR8-04-02). A failure from the handle that + * applied one, asking for the other disposition, is {@code OPERATION_CONFLICT}: the same + * transition with other arguments, which used to fall through to {@code NOT_OWNER} (owner + * decision 2026-11-07). Its retention is not compared — the record does not keep it, and a resend + * with another retention is confirmed. */ private static final String TRANSITION = """ @@ -140,26 +156,31 @@ public final class IdempotencyScripts { if op ~= ARGV[3] then return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''} end - if state == ARGV[5] then - -- Already in the target state, under the same owner and the same operation: a retry whose - -- first reply was lost, not a second transition. This is checked BEFORE the revision check - -- below, deliberately. The caller's handle necessarily carries the pre-transition revision - -- — they never received the reply that would have replaced it — so that check first would - -- turn every lost reply into NOT_OWNER and make the idempotent call non-idempotent. + if rev == tonumber(ARGV[2]) + 1 and redis.call('HGET', KEYS[1], 'lastKind') == ARGV[9] then + -- This transition, applied from this handle, under the same owner and the same operation: + -- a retry whose first reply was lost, not a second transition. This is checked BEFORE the + -- revision check below, deliberately. The caller's handle necessarily carries the + -- pre-transition revision — they never received the reply that would have replaced it — so + -- that check first would turn every lost reply into NOT_OWNER and make the idempotent call + -- non-idempotent. -- - -- A start is the one transition whose ALREADY runs the action, so for a start the owner and - -- operation are not proof enough: the same attempt also holds a handle from before a - -- takeover, and the current handle a replayed claim returned after the start. Either one + -- The owner and operation are not proof enough: the same attempt also holds a handle from + -- before a takeover, and the current handle a replayed claim returned. Either one -- presenting a start the record already shows was answered ALREADY, and the executor ran the - -- action a second time (round6 RR6-02-01). A start is confirmed only to the handle it was - -- applied from — the record one revision past it — and any other falls through to the - -- revision check: NOT_OWNER for a stale handle, WRONG_STATE for the current one. The - -- PostgreSQL store answers the same: its start replay digest covers the handle's attempt - -- and revision. A completion or failure already applied is still reported back to any - -- handle of its operation: nothing runs on that answer. - if ARGV[4] ~= 'CLAIMED' or rev == tonumber(ARGV[2]) + 1 then + -- action a second time (round6 RR6-02-01); either one presenting a completion or failure + -- applied after the takeover was told it was its own. A transition is confirmed only to + -- the handle it was applied from — the record one revision past it, moved there by this + -- kind of transition — and any other falls through to the revision check: NOT_OWNER for a + -- stale handle, WRONG_STATE for the current one (owner decision 2026-11-06). The kind is + -- what tells a start from the renewal that followed it (round8 RR8-04-02). The PostgreSQL + -- store answers the same: it reads a recorded transition as a replay only for the handle + -- one revision behind the row and only for the kind the row records. + if state == ARGV[5] then return {'ALREADY', attempt, rev, owner, redis.call('HGET', KEYS[1], 'resp') or '', ''} end + -- The same transition with another target: a failure asking for the other disposition + -- than the one recorded. The same id with other arguments (owner decision 2026-11-07). + return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''} end if rev ~= tonumber(ARGV[2]) then -- Stale handle: somebody moved the record on after this owner read it, and the target @@ -177,7 +198,7 @@ public final class IdempotencyScripts { return {'LEASE_EXPIRED', attempt, rev, owner, '', ''} end end - redis.call('HSET', KEYS[1], 'state', ARGV[5], 'rev', rev + 1) + redis.call('HSET', KEYS[1], 'state', ARGV[5], 'rev', rev + 1, 'lastKind', ARGV[9]) if ARGV[6] ~= '' then redis.call('HSET', KEYS[1], 'resp', ARGV[6]) end @@ -257,7 +278,7 @@ public final class IdempotencyScripts { end redis.call('HSET', KEYS[1], 'leaseUntil', nowMillis + tonumber(ARGV[4]), 'rev', rev + 1, - 'renewedFromRev', ARGV[2], 'renewedLease', ARGV[4]) + 'renewedFromRev', ARGV[2], 'renewedLease', ARGV[4], 'lastKind', 'RENEW') local keep = tonumber(ARGV[4]) + tonumber(redis.call('HGET', KEYS[1], 'afterLease') or '0') local ttl = redis.call('PTTL', KEYS[1]) @@ -267,7 +288,15 @@ public final class IdempotencyScripts { return {'APPLIED', attempt, rev + 1, owner, '', ''} """; - /** Release before execution: only from CLAIMED, and only by the owner that holds it. */ + /** + * Release before execution: only from CLAIMED, and only by the owner that holds it at the + * revision its handle carries. + * + *

The release deletes the record, so a retry finds nothing and is {@code ABSENT}, as is a + * release whose record expired. The revision is checked as in {@link #TRANSITION}: the owner + * token and operation alone let the handle from before the same attempt took its claim over + * release the claim it holds now ({@code IdempotencyStoreContract}). + */ private static final String RELEASE = """ local state = redis.call('HGET', KEYS[1], 'state') @@ -284,6 +313,9 @@ public final class IdempotencyScripts { if op ~= ARGV[3] then return {'OPERATION_CONFLICT', attempt, rev, owner, '', ''} end + if rev ~= tonumber(ARGV[2]) then + return {'NOT_OWNER', attempt, rev, owner, '', ''} + end if state ~= 'CLAIMED' then return {'WRONG_STATE', attempt, rev, owner, state, ''} end diff --git a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java index 7329ae62..edb8f3c7 100644 --- a/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java +++ b/src/adapter/outbound/cache-redis/src/main/java/dev/caskeleton/adapter/outbound/cache/redis/idempotency/RedisIdempotencyStoreAdapter.java @@ -169,7 +169,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort return transition( ownerHandle, operationId, - new Transition("CLAIMED", "EXECUTING", "", "", ""), + new Transition("START", "CLAIMED", "EXECUTING", "", "", ""), Map.of( ScriptStatus.APPLIED, IdempotencyStartOutcome.STARTED, ScriptStatus.ALREADY, IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION, @@ -230,6 +230,7 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort session.commands(), keys.recordKey(ownerHandle.scope()), new Transition( + "COMPLETE", "EXECUTING", "COMPLETED", response.payload(), @@ -270,8 +271,13 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort // EFFECT_UNKNOWN_ABANDONED does not, because retrying an unknown effect is how it happens // twice. boolean retryable = disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE; + // One kind for both dispositions: a resend from the handle that applied the failure, asking for + // the other one, is the same transition with other arguments — OPERATION_CONFLICT, not a stale + // owner (owner decision 2026-11-07). The retention is not sent for comparison; the record does + // not keep it. Transition transition = new Transition( + "FAIL", "EXECUTING", retryable ? "FAILED_RETRYABLE" : "ABANDONED", "", @@ -320,7 +326,10 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort operationId.value()))); return switch (reply.status()) { case APPLIED -> IdempotencyReleaseOutcome.RELEASED_BEFORE_EXECUTION; - case ABSENT -> IdempotencyReleaseOutcome.ALREADY_RELEASED_SAME_OPERATION; + // The release deletes the record, so nothing tells this release's retry from a record + // that expired or was never there. It was confirmed as the release already applied; + // the PostgreSQL store answers a missing record ABSENT (IdempotencyStoreContract). + case ABSENT -> IdempotencyReleaseOutcome.ABSENT; case NOT_OWNER -> IdempotencyReleaseOutcome.NOT_OWNER; case OPERATION_CONFLICT -> IdempotencyReleaseOutcome.OPERATION_CONFLICT; case WRONG_STATE -> IdempotencyReleaseOutcome.EXECUTION_ALREADY_STARTED; @@ -422,6 +431,8 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort /** * One owner+revision compare-and-set, as the transition program takes it. * + * @param kind which transition, recorded so a resend is confirmed only as the transition the + * record last took ({@code START}, {@code COMPLETE}, {@code FAIL}) * @param fromState the state the record must be in * @param toState the state it moves to * @param payload the response to store, empty for none @@ -429,7 +440,12 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort * @param ttlMillis a new record TTL, empty to keep the current one */ private record Transition( - String fromState, String toState, String payload, String leaseMillis, String ttlMillis) { + String kind, + String fromState, + String toState, + String payload, + String leaseMillis, + String ttlMillis) { List arguments(IdempotencyOwner ownerHandle, OperationId operationId) { return List.of( @@ -440,7 +456,8 @@ public final class RedisIdempotencyStoreAdapter implements IdempotencyStorePort toState, payload, leaseMillis, - ttlMillis); + ttlMillis, + kind); } } diff --git a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java index 65ef2da7..43287b02 100644 --- a/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java +++ b/src/adapter/outbound/cache-redis/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/RedisTestContainer.java @@ -12,7 +12,7 @@ import org.testcontainers.utility.MountableFile; * One Redis server for the container lane ({@code redisContainerContractTest}), so the live * contracts run against a real server without an external topology (review 2026-11-01 05-16). * - *

The server is the standalone topology of {@code infra/redis-sdk}: the image is the {@code + *

The server is the standalone topology of {@code redis-sdk/compose}: the image is the {@code * redis} entry of {@code config/testing/container-images.properties} (handed to every test JVM as * {@code ca.test.image.redis}), and the ACL file is the one that topology loads, so the default * user is off and the application and advanced accounts carry the same rights they carry there. A diff --git a/src/adapter/outbound/fileserver/CLAUDE.md b/src/adapter/outbound/fileserver/CLAUDE.md index 996be8b8..2f89dd43 100644 --- a/src/adapter/outbound/fileserver/CLAUDE.md +++ b/src/adapter/outbound/fileserver/CLAUDE.md @@ -30,7 +30,7 @@ verification, identifiers, audit, metrics). Design rationale lives in [README.md ## Forbidden -- Inbound adapters, persistence, `app-bootstrap`, `sample-portfolio` (ArchUnit +- Inbound adapters, persistence, `app-bootstrap` (ArchUnit `OUTBOUND_ADAPTERS_*` family rules). - Leaking filesystem, stream, framework, or provider types across the application ports. - Advertising a platform feature as implemented unless `docs/fileserver/support-matrix.md` lists it. diff --git a/src/adapter/outbound/fileserver/README.md b/src/adapter/outbound/fileserver/README.md index 5e71124d..dca317a9 100644 --- a/src/adapter/outbound/fileserver/README.md +++ b/src/adapter/outbound/fileserver/README.md @@ -10,7 +10,7 @@ verification reads that registry. Module rules live in [CLAUDE.md](CLAUDE.md). Transport, security, configuration and operations contracts live in `docs/fileserver/`. For the repository-level choice between this Fileserver platform and Object Storage, see -[`docs/storage-capability-boundary.md`](../../../docs/storage-capability-boundary.md). +[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md). ## Activation diff --git a/infra/fileserver/nfs/compose.yml b/src/adapter/outbound/fileserver/compose/nfs/compose.yml similarity index 88% rename from infra/fileserver/nfs/compose.yml rename to src/adapter/outbound/fileserver/compose/nfs/compose.yml index e029819c..b34eba6f 100644 --- a/infra/fileserver/nfs/compose.yml +++ b/src/adapter/outbound/fileserver/compose/nfs/compose.yml @@ -7,11 +7,11 @@ # # Opt in with FILESERVER_NFS_TESTS=true; the default test run does not start this. # -# docker compose -f infra/fileserver/nfs/compose.yml up -d +# docker compose -f src/adapter/outbound/fileserver/compose/nfs/compose.yml up -d # FILESERVER_NFS_TESTS=true ./gradlew :adapter:outbound:fileserver:test # # To exercise the ambiguity paths: -# docker compose -f infra/fileserver/nfs/compose.yml restart nfs-server # stale handles +# docker compose -f src/adapter/outbound/fileserver/compose/nfs/compose.yml restart nfs-server # stale handles # docker network disconnect fileserver-nfs # lost responses services: @@ -49,7 +49,7 @@ services: mount -t nfs4 -o hard,timeo=50,retrans=2 nfs-server:/ /mnt/fileserver && tail -f /dev/null" volumes: - - ../../..:/workspace:ro + - ../../../../../..:/workspace:ro networks: - fileserver-nfs diff --git a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/testkit/NfsAmbiguityIntegrationTest.java b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/testkit/NfsAmbiguityIntegrationTest.java index 31f303c6..5ccc7844 100644 --- a/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/testkit/NfsAmbiguityIntegrationTest.java +++ b/src/adapter/outbound/fileserver/src/test/java/dev/caskeleton/adapter/outbound/fileserver/testkit/NfsAmbiguityIntegrationTest.java @@ -14,7 +14,7 @@ import org.junit.jupiter.api.condition.EnabledIfEnvironmentVariable; * *

These scenarios cannot be reproduced on a local filesystem, so they are gated rather than * quietly skipped: a green default run must never be mistaken for network-filesystem certification. - * The environment is defined in {@code infra/fileserver/nfs/compose.yml}. + * The environment is defined in {@code src/adapter/outbound/fileserver/compose/nfs/compose.yml}. */ @EnabledIfEnvironmentVariable(named = NfsTestEnvironment.ENABLE_FLAG, matches = "true") class NfsAmbiguityIntegrationTest { diff --git a/src/adapter/outbound/httpclient/CLAUDE.md b/src/adapter/outbound/httpclient/CLAUDE.md index 9b819b9a..2a9a3149 100644 --- a/src/adapter/outbound/httpclient/CLAUDE.md +++ b/src/adapter/outbound/httpclient/CLAUDE.md @@ -13,7 +13,7 @@ Package root: `dev.caskeleton.adapter.outbound.httpclient`. ## Design authority The implementation follows -`httpclient-superpowers-package/docs/superpowers/specs/2026-08-08-httpclient-platform-design.md`. +`docs/design/2026-08-08-httpclient-platform-design.md`. The design assumes 19 separate Gradle modules; this repository's fail-closed registry outranks that layout, so those modules are **packages** here. The mapping, and every other deliberate substitution, is recorded in `docs/httpclient/repository-adaptation.md`. Read it before @@ -24,7 +24,7 @@ moving a type between packages. - Own the public call surfaces: H1 typed service clients (default), H2 generic exchange, H3 dynamic target. H4 native engine access stays internal to `apache`, `jdk`, and `http3`. - Blocking only: calls run on the caller's (virtual) thread through `RestClient`. The reactive stack - (`WebClient`, Reactor Netty) was removed by decision 9 (2026-09-25); do not add it back. + (`WebClient`, Reactor Netty) was removed by the 2026-09-25 owner decision; do not add it back. - Own Named Client Profiles, runtime generations, transport SPI, deadlines, evidence-based retry, resilience, authentication, TLS, SSRF defence, streaming lifecycle, and observability. - Adapt external HTTP calls behind application/domain ports. @@ -81,12 +81,13 @@ Default lane: `./gradlew :adapter:outbound:httpclient:test`. Additional lanes, a | `jmh` | per-call overhead benchmarks | A selected lane never skips silently: the fault lane throws without Docker, the contract lane throws -on an empty or unknown transport selection, and the performance lane prints which machine-dependent -bounds were not asserted. +on an empty or unknown transport selection, and the performance lane asserts every bound in every +run — the strict-lane convention fails it when the build sets `performance.assertions.enabled` to +anything but `true` or when one of its tests is skipped. The transport port (`BlockingTransportProvider`) has one abstract contract in the test fixtures, `testkit/BlockingTransportProviderContract`. The engines pass it over a real socket (`StableTransportProviderContractTest`, the contract lane, once per selected transport) and the scripted fake the gateway tests stand on passes it in the default lane (`ScriptedTransportContractTest`). A new transport, or a change to `ScriptedTransport`, inherits the -same class rather than a copy (AGENTS.md rule 6; review 2026-11-01 05-16). +same class rather than a copy (AGENTS.md rule 6). diff --git a/src/adapter/outbound/httpclient/README.md b/src/adapter/outbound/httpclient/README.md index 9ae38727..a0d50646 100644 --- a/src/adapter/outbound/httpclient/README.md +++ b/src/adapter/outbound/httpclient/README.md @@ -5,7 +5,7 @@ HTTP. It is not a wrapper around `RestClient` — it owns the target, the connec time budget, the evidence of what actually executed, retry safety, authentication, TLS, SSRF defence, and observability. -Design: `httpclient-superpowers-package/docs/superpowers/specs/2026-08-08-httpclient-platform-design.md` +Design: `docs/design/2026-08-08-httpclient-platform-design.md` Adaptation to this repository: `docs/httpclient/repository-adaptation.md` ## Choosing a surface @@ -111,8 +111,9 @@ cd src ``` No lane skips silently. The fault lane fails without Docker, the contract lane fails on an empty or -unknown transport selection, and the performance lane reports which machine-dependent bounds it did -not assert. +unknown transport selection, and the performance lane asserts every bound in every run (it fails +when the build sets `performance.assertions.enabled` to anything but `true`, or when a test is +skipped). ## Further reading diff --git a/src/adapter/outbound/httpclient/build.gradle b/src/adapter/outbound/httpclient/build.gradle index 40108ed1..2673999a 100644 --- a/src/adapter/outbound/httpclient/build.gradle +++ b/src/adapter/outbound/httpclient/build.gradle @@ -7,7 +7,7 @@ plugins { // Shared test code as a Gradle test-fixtures variant — ADR-BUILD-001. // Outbound HTTP Client Platform leaf — see -// docs/superpowers/specs/2026-08-08-httpclient-platform-design.md (design package) and +// docs/design/2026-08-08-httpclient-platform-design.md (design package) and // docs/httpclient/repository-adaptation.md (how the design's 19 library modules map here). // // The design models the platform as 19 separate Gradle modules. This repository's fail-closed @@ -138,8 +138,9 @@ dependencies { } // Which transports the contract suites cover and whether the HTTP/3 opt-in runs: the same two -// properties for every Test task of this leaf, declared once (review 2026-11-01 O-10a). Values a -// single lane needs (the performance assertions, the httpbin image) stay in that lane. +// properties for every Test task of this leaf, declared once (review 2026-11-01 O-10a). A value a +// single lane needs (the httpbin image) stays in that lane. The performance lane's bounds have no +// switch here: the strict-lane convention asserts them in every run. tasks.withType(Test).configureEach { systemProperty 'httpclient.contract.transports', providers.gradleProperty('httpclient.contract.transports').orElse('apache,jdk').get() @@ -193,8 +194,6 @@ strictTestLanes { performance() sourceSet = 'httpClientPerformanceTest' description = 'Certifies pool, streaming, retry, and rotation resource bounds (design §28.8).' - systemProperty 'performance.assertions.enabled', - providers.gradleProperty('performance.assertions.enabled').orElse('false').get() } lane('httpClientFailureInjectionTest') { integration() diff --git a/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/LargeBodyResourceTest.java b/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/LargeBodyResourceTest.java index 2c2837da..68f54585 100644 --- a/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/LargeBodyResourceTest.java +++ b/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/LargeBodyResourceTest.java @@ -52,11 +52,18 @@ class LargeBodyResourceTest { } } long peakIncrease = usedHeap() - before; + // The measured value, so a passing run is a recorded number and not only a green line. + System.out.println( + "[httpclient-performance] streaming download heap increase " + + peakIncrease + + " bytes, bound " + + payloadBytes / 2 + + " bytes"); assertThat(consumed).isEqualTo(payloadBytes); - PerformanceAssertions.machineDependent( - "streaming download heap increase stays well below the payload size", - () -> assertThat(peakIncrease).isLessThan((long) payloadBytes / 2)); + assertThat(peakIncrease) + .as("streaming download heap increase stays well below the payload size") + .isLessThan((long) payloadBytes / 2); } } } diff --git a/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PerformanceAssertions.java b/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PerformanceAssertions.java index ca812905..924e9b10 100644 --- a/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PerformanceAssertions.java +++ b/src/adapter/outbound/httpclient/src/httpClientPerformanceTest/java/dev/caskeleton/adapter/outbound/httpclient/performance/PerformanceAssertions.java @@ -3,32 +3,19 @@ package dev.caskeleton.adapter.outbound.httpclient.performance; import static org.assertj.core.api.Assertions.assertThat; /** - * Separates deterministic bounds from machine-dependent ones (design §28.8, §37). + * Structural bounds — retry budget arithmetic, a refresh collapsing to one request, drain + * completing — that hold on any machine (design §28.8, §37). * - *

Structural bounds — retry budget arithmetic, streaming not buffering the whole payload, drain - * completing — always run. Latency and absolute memory numbers depend on the host, so they are - * asserted only when the certification flag is set; when it is off the lane still executes and - * still reports, rather than becoming a silent pass. + *

The machine-dependent bound (the streaming heap increase) is asserted in place, in every run. + * It used to sit behind {@code performance.assertions.enabled}, which defaulted to {@code false} in + * this leaf, so a lane run by hand reported success with the bound compared to nothing. A + * performance lane now asserts all of its bounds; the strict-lane convention rejects a build that + * tries to turn them off. */ final class PerformanceAssertions { private PerformanceAssertions() {} - static boolean certificationEnabled() { - return Boolean.parseBoolean(System.getProperty("performance.assertions.enabled", "false")); - } - - static void machineDependent(String description, Runnable assertion) { - if (certificationEnabled()) { - assertion.run(); - return; - } - System.out.println( - "[httpclient-performance] skipped machine-dependent bound (enable with " - + "-Pperformance.assertions.enabled=true): " - + description); - } - static void structural(String description, boolean condition) { assertThat(condition).describedAs(description).isTrue(); } diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java index 6b28ad8f..943f3a5d 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/jdk/DeadlineAwareJdkRequestFactory.java @@ -22,6 +22,11 @@ import org.springframework.http.client.JdkClientHttpRequestFactory; * timeout, remaining deadline)} from {@link AttemptDeadline}. The factory only holds references; * the client and the write executor are shared. * + *

That timer is the only thing that ends a JDK attempt at its deadline, and it keeps whole + * milliseconds. {@link AttemptDeadline#bound(Duration)} rounds the remaining time up for that + * reason: truncated, the timer fired just before the deadline and the attempt was reported as a + * response timeout rather than the deadline. + * *

A streaming download cannot use that request. Its body is handed to the caller and may run for * minutes, but Spring's timer only stops when the body stream is closed, so every JDK download * longer than the response-header timeout was cut mid-body (review 2026-11-03 RR-04-03). Inside a diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistry.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistry.java index 8078fc62..6b566576 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistry.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistry.java @@ -169,6 +169,11 @@ public final class ClientRuntimeRegistry implements AutoCloseable { * the executor reports termination from inside the worker before that thread exits, so under load * the thread could still be listed when close returned. Joining the thread is what makes "no * thread left" true when this returns. + * + *

An interrupt does not cut the wait short; the flag is restored once the wait is over. A + * closing thread that was already interrupted used to give up at the first wait and return + * normally with the drain thread still running — the one failure path that said nothing (review + * 2026-11-06 RR7-02-01). */ private void stopDrainThread() { ScheduledExecutorService scheduler = drainScheduler.getAndSet(null); @@ -177,23 +182,38 @@ public final class ClientRuntimeRegistry implements AutoCloseable { } scheduler.shutdownNow(); long deadline = System.nanoTime() + TimeUnit.MILLISECONDS.toNanos(SHUTDOWN_AWAIT_MILLIS); + boolean interrupted = false; try { - if (!scheduler.awaitTermination(SHUTDOWN_AWAIT_MILLIS, TimeUnit.MILLISECONDS)) { - throw new IllegalStateException("http client drain scheduler did not terminate"); - } - for (Thread thread : drainThreads) { - long remaining = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); - thread.join(Math.max(1L, remaining)); - if (thread.isAlive()) { - throw new IllegalStateException("http client drain thread did not exit"); + while (true) { + try { + awaitDrainThreadExit(scheduler, deadline); + return; + } catch (InterruptedException interruptedWait) { + interrupted = true; } } - drainThreads.clear(); - } catch (InterruptedException interrupted) { - Thread.currentThread().interrupt(); + } finally { + if (interrupted) { + Thread.currentThread().interrupt(); + } } } + private void awaitDrainThreadExit(ScheduledExecutorService scheduler, long deadline) + throws InterruptedException { + if (!scheduler.awaitTermination(deadline - System.nanoTime(), TimeUnit.NANOSECONDS)) { + throw new IllegalStateException("http client drain scheduler did not terminate"); + } + for (Thread thread : drainThreads) { + long remaining = TimeUnit.NANOSECONDS.toMillis(deadline - System.nanoTime()); + thread.join(Math.max(1L, remaining)); + if (thread.isAlive()) { + throw new IllegalStateException("http client drain thread did not exit"); + } + } + drainThreads.clear(); + } + private AtomicReference holder(ClientProfileName name) { AtomicReference holder = runtimes.get(name); if (holder == null) { diff --git a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java index 36d072bb..b2ac3dfa 100644 --- a/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java +++ b/src/adapter/outbound/httpclient/src/main/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadline.java @@ -1,6 +1,7 @@ package dev.caskeleton.adapter.outbound.httpclient.transport; import java.time.Duration; +import java.time.temporal.ChronoUnit; import java.util.ArrayList; import java.util.List; import java.util.Objects; @@ -83,14 +84,30 @@ public final class AttemptDeadline { return Optional.ofNullable(CURRENT.get()).map(Scope::remaining); } - /** A stage timeout no longer than the current attempt's remaining time. */ + /** + * A stage timeout cut down to the current attempt's remaining time when that is shorter. + * + *

A cut-down value is rounded up to the next whole millisecond, so an engine timer armed from + * it never ends before the deadline. Engines keep their timeouts in milliseconds — Spring's JDK + * request arms its timer with {@code Duration.toMillis()} — and the truncated remainder made that + * timer fire just before the deadline. The executor names the deadline by asking the scope after + * the engine gave up, so such an attempt was reported as a response timeout on a healthy upstream + * and the circuit breaker counted the caller's own deadline against it. Ending under a + * millisecond late costs nothing: by then the scope reports itself expired. + */ public static Duration bound(Duration stageTimeout) { Objects.requireNonNull(stageTimeout, "stage timeout"); return remaining() .filter(remaining -> remaining.compareTo(stageTimeout) < 0) + .map(AttemptDeadline::toWholeMillisecondsUp) .orElse(stageTimeout); } + private static Duration toWholeMillisecondsUp(Duration duration) { + Duration truncated = duration.truncatedTo(ChronoUnit.MILLIS); + return truncated.equals(duration) ? duration : truncated.plusMillis(1); + } + /** * Registers how to abort the exchange the current attempt is about to start. * diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistryTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistryTest.java index 8b3a2501..6c5c29d6 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistryTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/profile/ClientRuntimeRegistryTest.java @@ -7,7 +7,10 @@ import dev.caskeleton.adapter.outbound.httpclient.testkit.ClientProfiles; import java.time.Duration; import java.util.Map; import java.util.Set; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; class ClientRuntimeRegistryTest { @@ -83,6 +86,56 @@ class ClientRuntimeRegistryTest { assertThat(liveDrainThreads()).isEmpty(); } + @Test + @DisplayName("interrupt된 스레드에서 닫아도 drain 스레드가 끝난 뒤에 돌아오고 interrupt 상태는 남긴다") + void closingFromAnInterruptedThreadStillWaitsForTheDrainThread() throws InterruptedException { + // given: the drain thread is busy closing the old generation, and ignores the interrupt + // shutdownNow sends it, when the registry closes + CountDownLatch drainStarted = new CountDownLatch(1); + ClientRuntime busy = + new ClientRuntime( + ClientProfiles.builder("payment").build(), + new RuntimeGeneration(1), + () -> { + drainStarted.countDown(); + sleepIgnoringInterrupts(Duration.ofMillis(500)); + }); + ClientRuntimeRegistry registry = new ClientRuntimeRegistry(Map.of(busy.name(), busy)); + ClientRuntimeLease lease = registry.acquire(busy.name()); + registry.swap(busy.name(), running(2), Duration.ofMillis(1)); + assertThat(drainStarted.await(5, TimeUnit.SECONDS)).isTrue(); + + // when + Thread.currentThread().interrupt(); + boolean stillInterrupted; + try { + registry.close(); + } finally { + stillInterrupted = Thread.interrupted(); + } + + // then + Set left = liveDrainThreads(); + lease.close(); + assertThat(left).isEmpty(); + assertThat(stillInterrupted).isTrue(); + } + + private static void sleepIgnoringInterrupts(Duration duration) { + long end = System.nanoTime() + duration.toNanos(); + boolean interrupted = false; + for (long left = duration.toNanos(); left > 0; left = end - System.nanoTime()) { + try { + Thread.sleep(Duration.ofNanos(left)); + } catch (InterruptedException ignored) { + interrupted = true; + } + } + if (interrupted) { + Thread.currentThread().interrupt(); + } + } + private static Set liveDrainThreads() { return Thread.getAllStackTraces().keySet().stream() .filter(Thread::isAlive) diff --git a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java index 388bb2c6..fa2cfc77 100644 --- a/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java +++ b/src/adapter/outbound/httpclient/src/test/java/dev/caskeleton/adapter/outbound/httpclient/transport/AttemptDeadlineTest.java @@ -6,6 +6,7 @@ import java.time.Duration; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; +import java.util.concurrent.locks.LockSupport; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -41,6 +42,31 @@ class AttemptDeadlineTest { } } + @Test + @DisplayName("bound 값을 밀리초로 잘라 건 엔진 timer도 attempt deadline보다 먼저 끝나지 않는다") + void anEngineTimerArmedInWholeMillisecondsDoesNotEndBeforeTheDeadline() { + // Spring's JDK request arms its timer with Duration.toMillis(). A remaining time with a + // sub-millisecond part lost it there, the engine gave up just before the deadline, and the + // executor, asking the scope a moment later, reported a response timeout instead. + try (AttemptDeadline.Scope scope = + AttemptDeadline.open(Duration.ofMillis(20).plusNanos(900_000))) { + // given + Duration bounded = AttemptDeadline.bound(Duration.ofSeconds(2)); + long armedAt = System.nanoTime(); + long firesAt = armedAt + TimeUnit.MILLISECONDS.toNanos(bounded.toMillis()); + + // when + while (System.nanoTime() - firesAt < 0) { + LockSupport.parkNanos(firesAt - System.nanoTime()); + } + + // then + assertThat(scope.expired()) + .as("deadline passed when a whole-millisecond timer from bound() = %s fired", bounded) + .isTrue(); + } + } + @Test @DisplayName("deadline이 지나면 등록된 중단 동작을 실행하고 scope는 만료로 보고한다") void theRegisteredAbortRunsWhenTheDeadlinePasses() throws Exception { diff --git a/src/adapter/outbound/identifier/CLAUDE.md b/src/adapter/outbound/identifier/CLAUDE.md index 85a1c08c..bd2ac640 100644 --- a/src/adapter/outbound/identifier/CLAUDE.md +++ b/src/adapter/outbound/identifier/CLAUDE.md @@ -19,9 +19,9 @@ build choices) live in [README.md](README.md). (HMAC-SHA-256 of the UTF-8 principal, lowercase hex). - `UuidV7DurableOperationIdFactory` — `DurableOperationIdFactory` implementation (UUIDv7 via `uuid-creator`). The operation id is also the submission event's id, and the messaging platform's - message id accepts only UUIDv7 (review 2026-11-01 06-06). Wired by `composition:durable-operation`. + message id accepts only UUIDv7. Wired by `composition:durable-operation`. - The leaf name says "identifier"; general-purpose clock and random sources are not here. - The name is kept because Gradle paths and consumers use it (README, review 05-21). + The name is kept because Gradle paths and consumers use it (README). - Wiring is `composition/service-runtime` (`PseudonymizationConfig`), not this leaf. ## Allowed @@ -29,21 +29,20 @@ build choices) live in [README.md](README.md). Declared in [build.gradle](build.gradle); the registry entry is the SSOT. - `:application-core` — the ports both classes implement. -- `:shared-contract`, for `HmacSha256` only (review 2026-11-01 01-11). The pseudonym is the hex HMAC +- `:shared-contract`, for `HmacSha256` only. The pseudonym is the hex HMAC of the principal; `HmacUserPrincipalPseudonymizerVectorTest` pins it to a vector computed outside the JVM, because logs written before and after a release are joined on it. - `:domain-core` — a feature's server-assigned id adapter implements its domain `*IdFactory` port here (registry edge `adapter:outbound:identifier -> domain-core`; `docs/manual/02-new-feature.md`). - `com.github.f4b6a3:uuid-creator` (`libs.uuid.creator`) — UUIDv7 for - `UuidV7DurableOperationIdFactory`, the generator the sample's id adapters use. + `UuidV7DurableOperationIdFactory`. ## Forbidden - Persistence or web technology (JPA/Hibernate/Spring Data/Spring Web) — ArchUnit `identifier_adapter_does_not_depend_on_other_adapters_or_bootstrap`; `.claude/hooks/ca_import_gate.py` G4 가 쓰기 시점에 차단. -- inbound adapters, persistence adapters, other outbound leaves, `app-bootstrap`, - `sample-portfolio`. +- inbound adapters, persistence adapters, other outbound leaves, `app-bootstrap`. - External IO (HTTP / messaging / cache / DB) — that belongs in `adapter-outbound`. ## Test diff --git a/src/adapter/outbound/identifier/README.md b/src/adapter/outbound/identifier/README.md index f740eb57..95acbb3d 100644 --- a/src/adapter/outbound/identifier/README.md +++ b/src/adapter/outbound/identifier/README.md @@ -11,7 +11,7 @@ leaf 이름은 `identifier`지만 범용 식별자 생성기·clock·random 소스는 여기 없다. 식별자 생성은 durable operation id(UUIDv7) 하나뿐이고(아래), 기능이 서버에서 id를 정하면 그 기능의 domain `*IdFactory` 구현도 여기 둔다(`:domain-core` 의존이 그 때문이다). 예전 문서가 범용 생성기 계획을 현재 내용처럼 적었다. 이름은 바꾸지 않았다: Gradle 경로·registry id·소비자 -(`composition:service-runtime`, `app-bootstrap`, `sample-portfolio`)의 의존 선언이 모두 이 이름을 +(`composition:service-runtime`, `app-bootstrap`)의 의존 선언이 모두 이 이름을 쓰고, 바꿔서 얻는 것은 이름 하나뿐이다. 외부 연동이 없는 crypto 능력을 새로 둘 곳이 필요하면 이 leaf에 둔다. 그때 이 절을 고친다. @@ -34,7 +34,7 @@ leaf에 둔다. 그때 이 절을 고친다. ## UuidV7DurableOperationIdFactory `DurableOperationIdFactory`(application-core) 구현. `UuidCreator.getTimeOrderedEpochPlus1()`로 UUIDv7을 -만든다(샘플 id adapter와 같은 방식). operation id는 제출 이벤트의 event id가 되고, messaging platform +만든다. operation id는 제출 이벤트의 event id가 되고, messaging platform `MessageId`는 UUIDv7만 받는다. 예전에는 web controller가 `UUID.randomUUID()`(v4)로 만들어 모든 제출 이벤트가 발행 시점에 거부되어 DEAD가 됐다(리뷰 2026-11-01 06-06, Kafka relay lane이 발견). `composition:durable-operation`이 bean으로 조립한다. diff --git a/src/adapter/outbound/identifier/build.gradle b/src/adapter/outbound/identifier/build.gradle index 577351c6..d037ecb0 100644 --- a/src/adapter/outbound/identifier/build.gradle +++ b/src/adapter/outbound/identifier/build.gradle @@ -12,6 +12,6 @@ dependencies { // A feature's server-assigned id adapter implements its domain `*IdFactory` port here // (registry edge `adapter:outbound:identifier -> domain-core`); docs/manual/02-new-feature.md. implementation project(':domain-core') - // UUIDv7 ids (UuidV7DurableOperationIdFactory), the generator the sample's id adapters use. + // UUIDv7 ids (UuidV7DurableOperationIdFactory). implementation libs.uuid.creator } diff --git a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactory.java b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactory.java index 7e317892..472cbb94 100644 --- a/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactory.java +++ b/src/adapter/outbound/identifier/src/main/java/dev/caskeleton/adapter/outbound/identifier/UuidV7DurableOperationIdFactory.java @@ -5,9 +5,9 @@ import dev.caskeleton.application.operation.DurableOperationId; import dev.caskeleton.application.operation.DurableOperationIdFactory; /** - * {@link DurableOperationIdFactory} minting time-ordered UUIDv7 ids, the same mechanism ({@code - * UuidCreator.getTimeOrderedEpochPlus1()}) the sample's identifier adapters use. The id is also the - * submission event's id, and the messaging platform's message id accepts only UUIDv7. + * {@link DurableOperationIdFactory} minting time-ordered UUIDv7 ids ({@code + * UuidCreator.getTimeOrderedEpochPlus1()}). The id is also the submission event's id, and the + * messaging platform's message id accepts only UUIDv7. */ public final class UuidV7DurableOperationIdFactory implements DurableOperationIdFactory { diff --git a/src/adapter/outbound/messaging-kafka/CLAUDE.md b/src/adapter/outbound/messaging-kafka/CLAUDE.md index 293b83c7..060cd2b3 100644 --- a/src/adapter/outbound/messaging-kafka/CLAUDE.md +++ b/src/adapter/outbound/messaging-kafka/CLAUDE.md @@ -7,7 +7,7 @@ `messaging:messaging-spring-boot-starter-kafka` (the vendored platform and its Kafka transport) and ships the module defaults in `config/module-defaults/messaging.yml`. - Boundaries: add no code here. A publish rule belongs to the bridge (`adapter:outbound:messaging`), - a Kafka rule to the vendored product (`src/messaging/CLAUDE.md`); a class here would be a third + a Kafka rule to the vendored product (`src/platforms/messaging/CLAUDE.md`); a class here would be a third place. Allowed edges come only from the registry entry. - Tests: activation tests (`./gradlew :adapter:outbound:messaging-kafka:test`) and the real-Kafka lane `messagingKafkaRelayIntegrationTest` (relay → bridge → broker record bytes; `:integrationCheck`). diff --git a/src/adapter/outbound/messaging/CLAUDE.md b/src/adapter/outbound/messaging/CLAUDE.md index 6cdb166a..d7d4f08d 100644 --- a/src/adapter/outbound/messaging/CLAUDE.md +++ b/src/adapter/outbound/messaging/CLAUDE.md @@ -38,8 +38,8 @@ Package root: `dev.caskeleton.adapter.outbound.messaging`. may not carry this module. The R1 contract/binding compilers and JSON Schema envelope encoder were removed on 2026-09-25 (see `docs/capability-status.md`). - No JSON Schema engine (NetworkNT) on the main classpath. The evidence manifest schema check and the - capability card check (`config/messaging`) are this leaf's tests (`evidence/`); snakeyaml is - test-only (owner decision 29). + capability card check (`release/`) are this leaf's tests (`evidence/`); snakeyaml is + test-only (owner decision 2026-09-25). - Do not hide use-case sequencing or business routing policy in broker adapters. - `OutboxMessagePublishAdapter` is delegate-only and emits no dependency log. The confirmed FAILED/DEAD transition owns the one canonical ERROR. diff --git a/src/adapter/outbound/messaging/README.md b/src/adapter/outbound/messaging/README.md index 10323d26..433775e0 100644 --- a/src/adapter/outbound/messaging/README.md +++ b/src/adapter/outbound/messaging/README.md @@ -107,7 +107,7 @@ payload/envelope/exception-derived field는 받거나 렌더링하지 않는다. 있다. integration event 계약 검증은 루트 `verifyMessagingContracts`(`src/build.gradle`)가 한다. application-core· -shared-contract·sample-portfolio의 qualification lane 셋을 묶은 task다. 이 leaf는 그 검증에 관여하지 않는다. +shared-contract의 qualification lane 둘을 묶은 task다. 이 leaf는 그 검증에 관여하지 않는다. canonical path는 platform `PublishResult`의 confirmation/transmission evidence를 application `OutboxPublishOutcome`으로 명시적으로 변환하고, 실패 code를 `OutboxPublishAttempt`에 함께 싣는다. diff --git a/src/adapter/outbound/messaging/build.gradle b/src/adapter/outbound/messaging/build.gradle index e768936c..6267abee 100644 --- a/src/adapter/outbound/messaging/build.gradle +++ b/src/adapter/outbound/messaging/build.gradle @@ -19,7 +19,7 @@ dependencies { // Test-only: MessagingEvidenceSchemaValidatorTest holds the common evidence schema to Draft 2020-12. testImplementation libs.json.schema.validator // Test-only (owner decision 29): MessagingCapabilityRegistryContractTest reads the capability - // cards in config/messaging/*.yaml. The rules below keep snakeyaml out of every main + // cards in release/*.yaml. The rules below keep snakeyaml out of every main // configuration; only the `test*` ones may resolve it. testImplementation 'org.yaml:snakeyaml' } @@ -57,8 +57,8 @@ configurations.configureEach { configuration -> } } -// The card check reads the whole config/messaging tree (cards, profiles, the evidence schema). +// The card check reads the whole release tree (cards, profiles, the evidence schema). tasks.named('test') { - inputs.dir(rootProject.file('config/messaging')) + inputs.dir(file('release')) .withPathSensitivity(PathSensitivity.RELATIVE) } diff --git a/src/config/messaging/evidence/build-evidence-manifest-v1.schema.json b/src/adapter/outbound/messaging/release/evidence/build-evidence-manifest-v1.schema.json similarity index 100% rename from src/config/messaging/evidence/build-evidence-manifest-v1.schema.json rename to src/adapter/outbound/messaging/release/evidence/build-evidence-manifest-v1.schema.json diff --git a/src/config/messaging/profile-compatibility.yaml b/src/adapter/outbound/messaging/release/profile-compatibility.yaml similarity index 100% rename from src/config/messaging/profile-compatibility.yaml rename to src/adapter/outbound/messaging/release/profile-compatibility.yaml diff --git a/src/config/messaging/readiness-cards.yaml b/src/adapter/outbound/messaging/release/readiness-cards.yaml similarity index 100% rename from src/config/messaging/readiness-cards.yaml rename to src/adapter/outbound/messaging/release/readiness-cards.yaml diff --git a/src/config/messaging/release-profile-assertions.yaml b/src/adapter/outbound/messaging/release/release-profile-assertions.yaml similarity index 100% rename from src/config/messaging/release-profile-assertions.yaml rename to src/adapter/outbound/messaging/release/release-profile-assertions.yaml diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingCapabilityRegistryContractTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingCapabilityRegistryContractTest.java index 97b5c182..f26caaff 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingCapabilityRegistryContractTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingCapabilityRegistryContractTest.java @@ -23,8 +23,9 @@ import tools.jackson.core.type.TypeReference; import tools.jackson.databind.json.JsonMapper; /** - * The messaging capability cards under {@code config/messaging} (readiness cards, compatibility and - * release profiles, the common evidence manifest schema) stay closed and fail-safe. + * The messaging capability cards under {@code adapter/outbound/messaging/release} (readiness cards, + * compatibility and release profiles, the common evidence manifest schema) stay closed and + * fail-safe. * *

Owner decision 29: the card check lives in this leaf's tests, and snakeyaml is on this leaf's * test classpath only — main stays YAML-free (build.gradle). The files it reads are declared as @@ -350,7 +351,8 @@ class MessagingCapabilityRegistryContractTest { } private static Path requiredConfig(String relativePath) { - Path path = repositorySrcRoot().resolve("config/messaging").resolve(relativePath); + Path path = + repositorySrcRoot().resolve("adapter/outbound/messaging/release").resolve(relativePath); assertThat(path).as("required Messaging configuration %s", path).isRegularFile(); return path; } diff --git a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingEvidenceSchemaValidatorTest.java b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingEvidenceSchemaValidatorTest.java index 168e76ff..4855926f 100644 --- a/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingEvidenceSchemaValidatorTest.java +++ b/src/adapter/outbound/messaging/src/test/java/dev/caskeleton/adapter/outbound/messaging/evidence/MessagingEvidenceSchemaValidatorTest.java @@ -11,13 +11,13 @@ import java.util.List; import org.junit.jupiter.api.Test; /** - * The common build-evidence manifest schema (config/messaging/evidence) is valid Draft 2020-12 and - * accepts the manifest shape the R2 evidence producers are specified to write. + * The common build-evidence manifest schema (release/evidence) is valid Draft 2020-12 and accepts + * the manifest shape the R2 evidence producers are specified to write. */ class MessagingEvidenceSchemaValidatorTest { private static final Path COMMON_SCHEMA = - Path.of("../../../config/messaging/evidence/build-evidence-manifest-v1.schema.json"); + Path.of("release/evidence/build-evidence-manifest-v1.schema.json"); private static final String SHA256 = "sha256:" + "0".repeat(64); private static final String VALID_MANIFEST = """ diff --git a/src/adapter/outbound/notification/build.gradle b/src/adapter/outbound/notification/build.gradle index 0d21c40b..b252150f 100644 --- a/src/adapter/outbound/notification/build.gradle +++ b/src/adapter/outbound/notification/build.gradle @@ -10,7 +10,7 @@ dependencies { implementation project(':application-notification') implementation project(':shared-contract') implementation project(':adapter:outbound:support') - // UUIDv7 for notification ids: the generator the sample's identifier adapters already use. + // UUIDv7 for notification ids: the generator adapter:outbound:identifier already uses. implementation libs.uuid.creator implementation 'org.springframework.boot:spring-boot-autoconfigure' diff --git a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java index 5ae5747c..24afb2bd 100644 --- a/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java +++ b/src/adapter/outbound/notification/src/main/java/dev/caskeleton/adapter/outbound/notification/platform/dispatch/UuidV7Generator.java @@ -7,8 +7,8 @@ import java.util.Objects; import java.util.UUID; /** - * RFC 9562 UUIDv7, minted by uuid-creator — the same generator the sample's identifier adapters use - * (review S1-lead-2), rather than a second hand-written bit layout. + * RFC 9562 UUIDv7, minted by uuid-creator — the same generator the identifier adapter uses (review + * S1-lead-2), rather than a second hand-written bit layout. * *

Time-ordered rather than random because these identifiers are primary keys: a random UUID * scatters inserts across the whole index, and a notification table takes the highest insert rate diff --git a/src/adapter/outbound/objectstorage/CLAUDE.md b/src/adapter/outbound/objectstorage/CLAUDE.md index 973d3a8f..f7306d2f 100644 --- a/src/adapter/outbound/objectstorage/CLAUDE.md +++ b/src/adapter/outbound/objectstorage/CLAUDE.md @@ -36,8 +36,7 @@ readiness live in [README.md](README.md) and ## Forbidden -- Inbound adapters, sibling outbound adapters, persistence, app-bootstrap, or sample-portfolio - dependencies. +- Inbound adapters, sibling outbound adapters, persistence, or app-bootstrap dependencies. - Provider keys, paths, locators, SDK types, Spring types, or control-record types leaking into application-core. - A default provider/destination/namespace, local-dev in production, or startup mutation when the diff --git a/src/adapter/outbound/objectstorage/README.md b/src/adapter/outbound/objectstorage/README.md index 97d73e0b..0e85a8ba 100644 --- a/src/adapter/outbound/objectstorage/README.md +++ b/src/adapter/outbound/objectstorage/README.md @@ -7,11 +7,11 @@ records behind the application boundary. The allowed production dependencies are owned by `src/config/architecture/modules.json`. Module rules live in [CLAUDE.md](CLAUDE.md), the full design -in `docs/superpowers/specs/2026-07-28-objectstorage-production-capability-design.md`, and exact +in `docs/design/2026-07-28-objectstorage-production-capability-design.md`, and exact evidence claims in `docs/registries/object-storage-readiness.yaml`. For when to use this capability rather than the HTTP Fileserver platform, see -[`docs/storage-capability-boundary.md`](../../../docs/storage-capability-boundary.md). +[`docs/storage-capability-boundary.md`](../../../../docs/storage-capability-boundary.md). ## Current readiness @@ -120,7 +120,7 @@ release the `status`, `excludedProfiles` and `limitations` beside it were measur `-PobjectStorageMinioImage=/@sha256:`. A value that does not end in the evidence digest is refused: a different build is a new measurement, made by re-running the lanes and rewriting the evidence file (image and findings together). -- The local compose runtime (`docker-compose.infra.yml`, `LOCAL_MINIO_IMAGE`) uses the same digest. +- The local compose runtime (`compose.yaml`, and the compose lanes' smoke client in `src/app-bootstrap/compose-lanes/lane-services.yaml`; `LOCAL_MINIO_IMAGE`) uses the same digest. `ComposeMinioImageMatchesEvidenceTest` (leaf `test`) fails when the compose default and the evidence disagree; change both together. - The contract lane also runs `MinioS3ManagedObjectProviderContractTest`: the S3 adapter itself under diff --git a/src/adapter/outbound/objectstorage/build.gradle b/src/adapter/outbound/objectstorage/build.gradle index ee772b62..15612ce7 100644 --- a/src/adapter/outbound/objectstorage/build.gradle +++ b/src/adapter/outbound/objectstorage/build.gradle @@ -96,16 +96,21 @@ dependencies { def objectStorageReadinessRegistry = rootProject.projectDir.parentFile.toPath() .resolve('docs/registries/object-storage-readiness.yaml').toFile() // The local compose MinIO must be the image the evidence measured (review 05-09); -// ComposeMinioImageMatchesEvidenceTest compares the two. -def localComposeFile = rootProject.projectDir.parentFile.toPath() - .resolve('docker-compose.infra.yml').toFile() +// ComposeMinioImageMatchesEvidenceTest compares the two. The development stack runs the server and +// the compose lanes' smoke client runs the same image; YAML anchors do not cross files, so each file +// carries its own default and both are compared. +def repositoryRootForCompose = rootProject.projectDir.parentFile.toPath() +def localComposeFiles = [ + repositoryRootForCompose.resolve('compose.yaml').toFile(), + repositoryRootForCompose.resolve('src/app-bootstrap/compose-lanes/lane-services.yaml').toFile(), +] tasks.named('test') { inputs.file(objectStorageReadinessRegistry) .withPathSensitivity(PathSensitivity.RELATIVE) systemProperty 'objectstorage.readiness.registry', objectStorageReadinessRegistry.absolutePath - inputs.file(localComposeFile) + inputs.files(localComposeFiles) .withPathSensitivity(PathSensitivity.RELATIVE) - systemProperty 'objectstorage.compose.file', localComposeFile.absolutePath + systemProperty 'objectstorage.compose.files', localComposeFiles*.absolutePath.join(File.pathSeparator) } // A mirror of the measured MinIO digest, for when the origin registry stops serving it (review diff --git a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/ComposeMinioImageMatchesEvidenceTest.java b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/ComposeMinioImageMatchesEvidenceTest.java index 91f91394..13cf4384 100644 --- a/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/ComposeMinioImageMatchesEvidenceTest.java +++ b/src/adapter/outbound/objectstorage/src/test/java/dev/caskeleton/adapter/outbound/objectstorage/qualification/ComposeMinioImageMatchesEvidenceTest.java @@ -2,9 +2,11 @@ package dev.caskeleton.adapter.outbound.objectstorage.qualification; import static org.assertj.core.api.Assertions.assertThat; +import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; +import java.util.List; import java.util.Optional; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -13,12 +15,14 @@ import org.junit.jupiter.api.Test; /** * The local compose MinIO is the image the lanes measured. Compose cannot read the evidence JSON, - * so this is the one check that keeps the two references from drifting apart again (review 05-09: - * four copies, two of them disagreeing). The build declares the compose file as this task's input. + * so this is the one check that keeps the references from drifting apart again (review 05-09: four + * copies, two of them disagreeing). Two Compose files carry the default — the development stack's + * server and the compose lanes' smoke client, because a YAML anchor does not cross files — and the + * build declares both as this task's input. */ class ComposeMinioImageMatchesEvidenceTest { - static final String COMPOSE_FILE_PROPERTY = "objectstorage.compose.file"; + static final String COMPOSE_FILES_PROPERTY = "objectstorage.compose.files"; private static final Pattern LOCAL_MINIO_DEFAULT = Pattern.compile( "x-local-minio-image:\\s*&local-minio-image\\s*\"\\$\\{LOCAL_MINIO_IMAGE:-([^}]+)}\""); @@ -27,14 +31,21 @@ class ComposeMinioImageMatchesEvidenceTest { @DisplayName("compose의 기본 MinIO 이미지는 evidence가 측정한 이미지와 같은 digest다") void theComposeDefaultMinioImageIsTheMeasuredEvidenceImage() throws IOException { // given - String compose = Files.readString(Path.of(System.getProperty(COMPOSE_FILE_PROPERTY))); - Matcher defaultImage = LOCAL_MINIO_DEFAULT.matcher(compose); + List composeFiles = + Pattern.compile(Pattern.quote(File.pathSeparator)) + .splitAsStream(System.getProperty(COMPOSE_FILES_PROPERTY)) + .map(Path::of) + .toList(); // when String measured = MinioQualificationImage.load(Optional.empty()).minio(); // then - assertThat(defaultImage.find()).as("x-local-minio-image default in the compose file").isTrue(); - assertThat(defaultImage.group(1)).isEqualTo(measured); + assertThat(composeFiles).hasSize(2); + for (Path composeFile : composeFiles) { + Matcher defaultImage = LOCAL_MINIO_DEFAULT.matcher(Files.readString(composeFile)); + assertThat(defaultImage.find()).as("x-local-minio-image default in %s", composeFile).isTrue(); + assertThat(defaultImage.group(1)).as("%s", composeFile).isEqualTo(measured); + } } } diff --git a/src/adapter/outbound/persistence-fileserver/CLAUDE.md b/src/adapter/outbound/persistence-fileserver/CLAUDE.md index 21a15ad1..1df1b76c 100644 --- a/src/adapter/outbound/persistence-fileserver/CLAUDE.md +++ b/src/adapter/outbound/persistence-fileserver/CLAUDE.md @@ -12,7 +12,7 @@ store adapters that implement `application-fileserver` ports. Root `AGENTS.md` a classes that register them as beans. `persistence-notification` follows the same rule (`platform.entity`, `platform.repository`, adapters -in `platform`), so the two capability leaves read the same way (review 04-16). +in `platform`), so the two capability leaves read the same way. ## Rules @@ -23,7 +23,7 @@ in `platform`), so the two capability leaves read the same way (review 04-16). extend `AssignedIdEntity` (`Persistable`). Without it `save` merges — a SELECT before every insert, and a second insert under an existing id overwrites the row instead of failing on the primary key. A new `@Version` column may stay primitive `long`; newness comes from - `Persistable`, not from the version (review 04-17). + `Persistable`, not from the version. - **No policy here.** Retry budgets, lease lengths and other decisions belong to `application-fileserver` and arrive as port arguments. A claim token or other fence travels in the port type (`CleanupItem.claimToken`), never in a field of the adapter. @@ -55,13 +55,13 @@ in `platform`), so the two capability leaves read the same way (review 04-16). - Port contracts live in `application-fileserver` testFixtures (`*PortContract`, and `FileQuotaLedgerContract` for the three quota ports, which share one table). The in-memory fakes and the PostgreSQL tests both extend them; every port this leaf implements has one - (`docs/testing/TESTING_STRATEGY.md` 9.3). The PostgreSQL side of the seven added in review - 2026-11-03 RR-01-04 is tagged `jpa-contract` and runs in persistence-jpa's + (`docs/testing/TESTING_STRATEGY.md` 9.3). The PostgreSQL side of the seven added on + 2026-11-03 is tagged `jpa-contract` and runs in persistence-jpa's `jpaPlatformContractTest` lane on `FileserverPostgreSqlStack`, whose clock a case moves. - The real-PostgreSQL tests are still in `persistence-jpa`'s `postgresqlIntegrationTest` source set, which owns the container and Flyway wiring, and the JPA readiness card - (`config/jpa/readiness-cards.yaml`, checked by `JpaReadinessRegistryTest`) names them as that - leaf's tasks — moving them means moving the card's tasks and selectors with them (review 04-04): + (`persistence-jpa/release/readiness-cards.yaml`, checked by `JpaReadinessRegistryTest`) names them as that + leaf's tasks — moving them means moving the card's tasks and selectors with them: `postgresqlFileserverMigrationIntegrationTest`, `postgresqlFileserverMetadataIntegrationTest`, `postgresqlFileserverReclamationIntegrationTest` (`./gradlew :adapter:outbound:persistence-jpa: --console=plain`). diff --git a/src/adapter/outbound/persistence-fileserver/build.gradle b/src/adapter/outbound/persistence-fileserver/build.gradle index 4f3fc89f..4ec73236 100644 --- a/src/adapter/outbound/persistence-fileserver/build.gradle +++ b/src/adapter/outbound/persistence-fileserver/build.gradle @@ -46,6 +46,6 @@ apiSurface { adopterBaseline = rootProject.file('../docs/architecture/persistence-fileserver-adopter-api-surface.txt') adopterSources = fileTree(rootProject.projectDir) { include '*/**/src/main/java/**/*.java' - exclude '**/build/**', 'adapter/outbound/persistence-fileserver/**', 'build-logic/**', 'optional-platforms/**' + exclude '**/build/**', 'adapter/outbound/persistence-fileserver/**', 'build-logic/**', 'platforms/optional-build/**' } } diff --git a/src/adapter/outbound/persistence-jpa/CLAUDE.md b/src/adapter/outbound/persistence-jpa/CLAUDE.md index e8caf319..bf3622e6 100644 --- a/src/adapter/outbound/persistence-jpa/CLAUDE.md +++ b/src/adapter/outbound/persistence-jpa/CLAUDE.md @@ -20,7 +20,7 @@ adapters implement application/domain ports directly and must not depend on this ## JPA relational persistence platform -The platform in `docs/superpowers/specs/2026-08-11-jpa-persistence-platform-design.md` is +The platform in `docs/design/2026-08-11-jpa-persistence-platform-design.md` is implemented here. The design models it as 18 Stable library modules; this repository's fail-closed registry outranks that layout, so those modules are **packages** in this leaf and `docs/jpa/repository-adaptation.md` records the mapping. Read it before moving a type between @@ -100,8 +100,9 @@ not grow by wiring accident. - Flyway holds its PostgreSQL migration lock for the session, never in an open transaction, or a `CREATE INDEX CONCURRENTLY` migration waits for Flyway forever: `spring.flyway.postgresql.transactional-lock: false` in the module defaults, and every Flyway built in code starts from - `FlywaySchemaPolicy.configure()` (`JpaProductionArchitectureTest` refuses `Flyway.configure()`; - `docs/jpa/migration-guide.md` "Who may change the schema"). + `FlywaySchemaPolicy.configure()` (`JpaProductionArchitectureTest` refuses `Flyway.configure()` and + constructing a Flyway configuration directly — `new FluentConfiguration()`, `new + ClassicConfiguration()`, a subclass; `docs/jpa/migration-guide.md` "Who may change the schema"). - Metric tags, exception messages, and logs carry no SQL parameters, entity ids, tenant ids, or PII. - Contracts run against real PostgreSQL. H2 never satisfies one. @@ -191,8 +192,8 @@ module. The `fileserver` package is the current case: every `Jpa*` adapter there `@ConditionalOnProperty(prefix = "app.fileserver-platform", name = "enabled", havingValue = "true")`. Without the gate a composition root that merely includes this module builds those beans, and each of -them needs collaborators only the Fileserver configuration supplies — which is how `sample-portfolio` -came to fail on a Fileserver collaborator it has no use for. A store for a capability nobody enabled +them needs collaborators only the Fileserver configuration supplies. 지운 샘플 모듈이 쓰지도 않는 +Fileserver 협력 객체 때문에 기동에 실패한 일이 그 예다. A store for a capability nobody enabled should not exist. ## Allowed @@ -217,8 +218,8 @@ should not exist. [application-core/CLAUDE.md](../../../application-core/CLAUDE.md)). - **DB drivers** (`org.postgresql..`, `org.h2..`) or **`org.flywaydb.database.postgresql..`** — those are vendor-specific and belong only in this module's matching vendor package (`.postgresql`, - `.h2`); NoSQL-specific dependencies belong only in their own future modules - (persistence-multi-db-extensibility D3). This is enforced by ArchUnit + `.h2`); NoSQL-specific dependencies belong only in their own future modules. + This is enforced by ArchUnit `PERSISTENCE_RDBMS_STAYS_VENDOR_NEUTRAL` and `PERSISTENCE_RDBMS_STAYS_NEUTRAL_OF_H2` in `CleanArchitectureTest`. - NoSQL adapter code. MongoDB/Redis/DynamoDB adapters are sibling modules, not children of this module. @@ -235,19 +236,19 @@ should not exist. | `inRead` | `REQUIRED` | `READ_COMMITTED` (pool) | `true` | `app.persistence-jpa.transaction.read-timeout` (30 s) | | `inNew` | `REQUIRES_NEW` | `READ_COMMITTED` (pool) | `false` | 30 s, fixed | -Isolation is pinned on the pool, not on the templates (review 09-05): the templates use +Isolation is pinned on the pool, not on the templates: the templates use `ISOLATION_DEFAULT`, the module defaults set `spring.datasource.hikari.transaction-isolation: TRANSACTION_READ_COMMITTED` (applied once per physical connection), and `HikariPoolConstraintValidator` refuses to boot with any other level. Naming the level per template made Spring call `getTransactionIsolation()` at every begin, which pgjdbc answers with a `SHOW TRANSACTION ISOLATION LEVEL` round trip. -Every mode is time-bounded (review 04-10). Spring hands the remaining time to each statement, so a +Every mode is time-bounded (since 2026-11-01). Spring hands the remaining time to each statement, so a slow query or lock wait is cancelled by the server (`57014` → `DB_QUERY_CANCELED`), and a deadline that passed before the next statement gets the same code: Spring's `TransactionTimedOutException` on the JDBC path, and on the JPA path (`JpaTransactionManager`, production) Hibernate's own `TransactionException`, which has no SQLState and is classified because `SpringTransaction` knows -its deadline passed (`translateAfterDeadline`, review RR-03-03). A business exception thrown after +its deadline passed (`translateAfterDeadline`). A business exception thrown after the deadline is passed on unchanged. Pre-built templates are immutable after construction so concurrent callers cannot @@ -261,7 +262,7 @@ When an actual ambient transaction exists it MUST throw committed. A commit failure propagates the transaction exception and no success value is returned to the caller. -### `inNew` pool-sizing constraint (D12 of feature-application-port-usecase-contract) +### `inNew` pool-sizing constraint (feature-application-port-usecase-contract) `REQUIRES_NEW` acquires a NEW physical JDBC connection while pinning the outer transaction's connection. Provision the pool to satisfy: @@ -273,7 +274,7 @@ hikari.maximumPoolSize >= (concurrent_threads × (1 + max_inNew_depth)) + 1 Loop-per-record `inNew` calls are forbidden (pool exhaustion + deadlock risk). Batch records inside ONE `inNew`, or move the loop outside the transaction. -## Persistence failure translation contract (feature-persistence-failure-baseline D1) +## Persistence failure translation contract (feature-persistence-failure-baseline) A raw Spring `DataAccessException` (and the JPA exception / SQLState / constraint name inside it) must never reach the presentation layer. The @@ -305,7 +306,7 @@ framework-neutral `shared.error.PersistenceFailureException` carrying one of the | `23513` | `DB_CHECK_VIOLATION` | H2 (`.h2` package) — H2 reports CHECK as 23513, not the standard 23514 the core table maps | | `HYT00` | `DB_QUERY_CANCELED` | H2 — H2 collapses statement and lock timeout into one state | -The PostgreSQL rows are not a second table (review 04-06). `PostgreSqlSqlStateErrorMapping` derives +The PostgreSQL rows are not a second table: before 2026-11-01 a hand-kept second table had already drifted. `PostgreSqlSqlStateErrorMapping` derives them from `PostgreSqlFailureClassifier` (SQLState → `FailureCategory`) and `FailureCategory.operationalError()` (category → code) — the same classification the library `PostgreSqlExceptionTranslator` uses — leaving out the standard rows above, categories with no @@ -314,7 +315,7 @@ state, add it to `PostgreSqlState` and the classifier; `SqlStateClassificationPa the two paths disagree on any state. **No SQLState, classified by type:** a lost `@Version` race (`OptimisticLockingFailureException`, -JPA `OptimisticLockException`) → `DB_OPTIMISTIC_CONFLICT` (409, review 04-05); an expired Spring +JPA `OptimisticLockException`) → `DB_OPTIMISTIC_CONFLICT` (409); an expired Spring transaction deadline (`TransactionTimedOutException`) → `DB_QUERY_CANCELED`; any other persistence failure (JPA, Spring data-access or Spring transaction exception) of a transaction `SpringTransaction` began, once its deadline has passed → `DB_QUERY_CANCELED`. @@ -336,16 +337,16 @@ PostgreSQL `57P01`, `57P02`) or a transport break with no SQLState becomes ## Persistence auditing contract (feature-persistence-auditing-contract) -Audit metadata (`created_at` / `updated_at` / `created_by` / `updated_by`, D3) is an -infrastructure concern that must never reach `domain-core` (D2). It lives only on the +Audit metadata (`created_at` / `updated_at` / `created_by` / `updated_by`) is an +infrastructure concern that must never reach `domain-core`. It lives only on the `audit/AuditableEntity` `@MappedSuperclass`; a domain aggregate persistence entity opts in -by extending it (D6 — e.g. the sample `WorkLogEntity`). The domain aggregate itself carries +by extending it (생성 명령이 만드는 서비스 persistence leaf의 엔티티가 그렇게 한다). The domain aggregate itself carries zero audit fields, enforced by ArchUnit `domain_is_pure` (no `jakarta.persistence..`) plus `domain_entities_do_not_carry_audit_fields` (no `createdAt`/`updatedAt`/`createdBy`/`updatedBy` fields under `..domain..`). -- **Capture = Manual explicit-set (D1 current default).** The repository adapter - constructor-injects `Clock` (D4) and `AuditContextPort` (D5) and stamps audit on `save`: +- **Capture = Manual explicit-set (current default).** The repository adapter + constructor-injects `Clock` and `AuditContextPort` and stamps audit on `save`: INSERT (null version) → `initializeAudit(now, actor)`; UPDATE (non-null version) → carry the persisted `created_*` forward + `applyModification(now, actor)`. `created_*` is `updatable = false`. @@ -353,17 +354,17 @@ fields under `..domain..`). seam and falls back to `"system"` when no principal is bound (scheduler / Flyway / anonymous). The actor's value semantics are owned by feature-authentication-authorization-contract (UNSUPPORTED here); the type is fixed to `String`. -- **Excluded (D6).** Infra/immutable entities such as `IdempotencyRecordEntity` (own +- **Excluded.** Infra/immutable entities such as `IdempotencyRecordEntity` (own `created_at`, no `updated_at`) do NOT extend `AuditableEntity`. `version`/optimistic-lock is owned by feature-persistence-failure-baseline / feature-transaction-concurrency-contract, not by this audit base. -- **Growth path (D1, deferred).** There is no second auditing implementation in the tree. If +- **Growth path (deferred).** There is no second auditing implementation in the tree. If manual stamping becomes too error-prone, migrate the canonical `AuditableEntity` contract atomically to Spring Data listeners while preserving its `created_*`/`updated_*` schema, actor bound, `Clock`, and `AuditContextPort` semantics. Bulk/native `@Query` UPDATEs bypass listeners too, so they must continue to stamp audit columns explicitly. -## MapStruct generated mapper exemption (D9 of feature-architecture-enforcement-rules) +## MapStruct generated mapper exemption (feature-architecture-enforcement-rules) If MapStruct is introduced for persistence mappers, the generated mapper class will be annotated with `javax.annotation.processing.Generated`. Architecture rules that diff --git a/src/adapter/outbound/persistence-jpa/README.md b/src/adapter/outbound/persistence-jpa/README.md index e3334e9b..5f07bbd6 100644 --- a/src/adapter/outbound/persistence-jpa/README.md +++ b/src/adapter/outbound/persistence-jpa/README.md @@ -50,8 +50,7 @@ durable operation HTTP 엔드포인트(`POST /operations`·`GET`·`DELETE /opera append 포트(`APP_OUTBOX_ENABLED=true`)가 모두 있을 때만 켜진다. submit·cancel에는 `operation-submit` 역할(`operation:submit`, `operation:cancel`)이 필요하다. -애플리케이션이 제공해야 하는 bean: `Clock`, `DomainContextPropagator`(app-bootstrap과 -sample-portfolio가 제공). +애플리케이션이 제공해야 하는 bean: `Clock`, `DomainContextPropagator`(app-bootstrap이 제공). **필요한 env 키** (`src/.env.example`, 레지스트리 `docs/registries/env-keys.yaml`) @@ -173,10 +172,10 @@ Spring Boot 메인 클래스는 `dev.caskeleton.bootstrap` 에 있어서, `@Auto 소유한 모듈에 둬서 와이어링을 그 자리에 유지한다. ### 왜 이름이 `JpaConfig` 가 아닌가 -sample 모듈에 이미 `...sample.portfolio.adapter.persistence.config.JpaConfig` 가 있다. IDE 의 -"Run main class" 가 테스트 스코프 sample 모듈을 클래스패스에 올리면, simple name `JpaConfig` 를 +서비스가 자기 설정 클래스에 `JpaConfig` 라는 이름을 쓰기 쉽다. 그러면 simple name `JpaConfig` 를 공유하는 두 `@Configuration` 이 기본 빈 이름 `jpaConfig` 에서 충돌한다 -(`ConflictingBeanDefinitionException`). 다른 simple name 으로 이를 피한다. +(`ConflictingBeanDefinitionException`). 다른 simple name 으로 이를 피한다. 처음 충돌한 곳은 지운 +샘플 모듈의 `JpaConfig` 였다. ## failure — 퍼시스턴스 실패 변환 SPI @@ -390,7 +389,7 @@ cadence 측정 필요). retention 한 값은 reaper-local 이라 `@Value` 로 ## JPA production capability candidate -`src/config/jpa/readiness-cards.yaml`이 capability와 독립 schema stream의 +`src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml`이 capability와 독립 schema stream의 machine-readable SSOT다(개수는 registry가 소유한다). `selected` base card와 `implemented-candidate` reliability card를 구분하며, 실제 PostgreSQL 테스트 통과만으로 immutable 운영 evidence가 필요한 R2를 주장하지 않는다. @@ -405,8 +404,9 @@ Flyway의 PostgreSQL 마이그레이션 잠금은 트랜잭션이 아니라 세 열어 두고, `CREATE INDEX CONCURRENTLY`·`REINDEX … CONCURRENTLY`는 그 트랜잭션이 끝나기를 기다려 배포가 끝나지 않는다(재리뷰 round6 RR6-03-01). Spring Boot의 Flyway는 `config/module-defaults/persistence-jpa.yml`의 `spring.flyway.postgresql.transactional-lock: false`로, 템플릿이 직접 만드는 Flyway는 -`FlywaySchemaPolicy.configure()`로 받는다. 운영 코드가 `Flyway.configure()`를 직접 부르면 -`JpaProductionArchitectureTest`가 거부한다. 배포 마이그레이션 도구에도 같은 값을 넣는다 +`FlywaySchemaPolicy.configure()`로 받는다. 운영 코드가 `Flyway.configure()`를 직접 부르거나 Flyway 설정 객체를 +직접 만들면(`new FluentConfiguration()`, `new ClassicConfiguration()`, 그 하위 클래스) `JpaProductionArchitectureTest`가 +거부한다. 배포 마이그레이션 도구에도 같은 값을 넣는다 (`docs/jpa/migration-guide.md` "Who may change the schema", lane `postgresqlConcurrentIndexMigrationIntegrationTest`). 적용된 versioned migration은 수정하지 않는다. Flyway가 기동할 때마다 checksum을 검사하므로 @@ -437,10 +437,25 @@ RR6-02-01). raw client key는 저장하지 않고 versioned HMAC scope digest만 Redis store·in-memory fake와 같은 계약(`IdempotencyStoreContract`)을 실 PostgreSQL에서 통과한다 (`PostgreSqlIdempotencyStoreContractTest`, `jpaPlatformContractTest`). 그 계약에 맞춰 두 가지를 -정했다(review 2026-11-01 01-05). 이전 revision의 핸들은 owner 튜플이 다르므로 `NOT_OWNER`다 -(`OPERATION_CONFLICT`는 같은 operation id가 다른 인자로 이미 적용된 경우만). 시작은 핸들 말고 인자가 없어서, -이미 기록된 시작과 digest가 다르면 다른 핸들이다 — 넘겨받기 전 핸들은 `NOT_OWNER`, 재생받은 현재 핸들은 -`NOT_CLAIMED`(라운드6 RR6-02-01, 전에는 `OPERATION_CONFLICT`). renew는 `EXECUTING`의 +정했다(review 2026-11-01 01-05). 이전 revision의 핸들은 owner 튜플이 다르므로 `NOT_OWNER`다. +`OPERATION_CONFLICT`는 둘이다. 하나는 owner token이 같은데 호출이 claim과 다른 operation id를 댄 경우로, 다섯 +전이(start·renew·complete·fail·release) 모두 거절하고 행을 바꾸지 않는다. 같은 token·다른 operation의 inspect도 +상태와 상관없이(완료된 행도) `OPERATION_CONFLICT`다(2026-11-06 소유자 결정 — 전에는 CAS가 핸들의 claim +operation만 보고 호출의 id는 `last_transition_operation_id`에 적기만 해서 적용했다). 다른 하나는 같은 operation +id가 다른 인자로 이미 적용된 경우다. 이미 기록된 전이는 그 전이를 적용한 핸들(owner identity가 같고 행보다 +revision이 하나 낮은 핸들)에게만 재생으로 읽는다(2026-11-06 소유자 결정). 그 핸들이면 digest가 같을 때 "이미 +처리됨", 다를 때 `OPERATION_CONFLICT`다. 다른 핸들은 재생이 아니라 owner 검사로 간다. 그래서 같은 operation id를 +쓴 다른 attempt의 늦은 complete와, 같은 attempt가 넘겨받기 전 핸들로 다시 보낸 complete·markFailed·renew·release는 +`NOT_OWNER`다(전에는 complete를 owner token만 보고 `ALREADY_COMPLETED_SAME_RESULT`로 확인했고, 나머지는 digest가 +달라 `OPERATION_CONFLICT`였다). renew가 돌려준 핸들로 다시 renew하면 한 번 더 renew된다(전에는 앞 renew의 digest와 +달라 `OPERATION_CONFLICT`였다). 시작은 핸들 말고 인자가 없어서, 넘겨받기 전 핸들은 `NOT_OWNER`, 재생받은 현재 +핸들은 `NOT_CLAIMED`다(라운드6 RR6-02-01, 전에는 `OPERATION_CONFLICT`). release한 핸들로 시작하면 행이 남아 있어 +`NOT_OWNER`다. 행을 지우는 Redis·fake는 `ABSENT`이고 계약은 둘 다 받는다. 실패는 disposition마다 전이 종류가 +둘(`FAIL_RETRYABLE`·`FAIL_ABANDONED`)이라, 적용한 핸들이 다른 disposition으로 다시 보내면 종류가 달라 재생으로 +읽히지 않고 `NOT_OWNER`였다. 두 종류를 모두 실패의 재생으로 읽어, 다른 disposition은 digest가 달라 +`OPERATION_CONFLICT`다. fail digest에는 retention을 넣지 않는다 — complete의 replay TTL처럼 결과를 얼마나 +보관하나일 뿐이라, retention만 다른 재전송은 "이미 처리됨"이고 처음 retention이 남는다(전에는 +`OPERATION_CONFLICT`, 2026-11-07 소유자 결정). renew는 `EXECUTING`의 lease만 늘리고, 시작 전 `CLAIMED`는 `NOT_IN_PROGRESS`다. ### outbox V2 (삭제됨) @@ -573,7 +588,7 @@ holder 가 락을 잡을 수 있다. 아래)이 아래 가드를 등록한다. 전부 `adapter:outbound:support`의 `StartupFailures`로 실패하므로 exit 코드(78/70/71)와 구조화 로그 필드(`startup.phase`/`error.code`/`error.category`)는 옮기기 전과 같다. `migrationStartupRunner`는 `@ConditionalOnMissingBean(FlywayMigrationStrategy)`라, 자기 전략을 둔 -애플리케이션(sample-portfolio의 두 번째 마이그레이션 스트림)에는 끼어들지 않는다. +애플리케이션(예: 두 번째 마이그레이션 스트림을 돌리는 서비스)에는 끼어들지 않는다. ### FlywayProdSafetyValidator - **`prod` 프로파일에서 Flyway 안전장치가 꺼지지 못하도록 런타임에서 강제한다.** Flyway 옵션은 diff --git a/src/adapter/outbound/persistence-jpa/build.gradle b/src/adapter/outbound/persistence-jpa/build.gradle index 2061a83f..2484ee71 100644 --- a/src/adapter/outbound/persistence-jpa/build.gradle +++ b/src/adapter/outbound/persistence-jpa/build.gradle @@ -11,7 +11,7 @@ plugins { // implementations, and the vendor-neutral SPI interfaces (OutboxClaimRepository / // SqlStateErrorMapping). The PostgreSQL driver, flyway-database-postgresql dialect, and vendor // Flyway migrations live only under the .postgresql subpackage (ArchUnit keeps the base neutral). -// The JPA relational persistence platform (docs/superpowers/specs/2026-08-11-jpa-persistence- +// The JPA relational persistence platform (docs/design/2026-08-11-jpa-persistence- // platform-design.md) models itself as 18 Stable library modules. This repository's fail-closed // module registry outranks that layout, so those modules are packages here and // JpaModuleBoundaryTest enforces the design's module dependency table. The full mapping is in @@ -117,7 +117,7 @@ dependencies { postgresqlIntegrationTestImplementation testFixtures(project(':application-fileserver')) // The notification capability's persistence moved out the same way, and its real-PostgreSQL // qualifications stay here for the same reason: this lane owns the container, the Flyway wiring - // and the readiness cards that name those tests (config/jpa/readiness-cards.yaml). Test scope + // and the readiness cards that name those tests (release/readiness-cards.yaml). Test scope // only. postgresqlIntegrationTestImplementation project(':adapter:outbound:persistence-notification') postgresqlIntegrationTestImplementation project(':application-notification') @@ -171,7 +171,7 @@ dependencies { // Real-PostgreSQL lanes. A readiness lane runs one named class (the security lane also names the // runtime-role namespace-denial method), a platform lane selects a tag, and the pool lane has a -// source set of its own. release.yml (jpa-release-gate) and config/jpa/*.{json,yaml} name these tasks. +// source set of its own. release.yml (jpa-release-gate) and release/*.{json,yaml} name these tasks. def jpaEvidenceImage = providers.gradleProperty('jpaPostgreSqlEvidenceImage').orElse(testContainerImages['postgres-16']).get() def jpaMatrixVersions = providers.gradleProperty('jpa.matrix.versions').orElse('16').get() def readinessLanes = [ @@ -205,12 +205,12 @@ def platformLanes = [ jpaPlatformQueryPlanTest: ['jpa-queryplan', 'Asserts query plan structure and planner estimate error (design §33).'], jpaPlatformSecurityTest : ['jpa-security', 'Verifies runtime role privileges and search_path safety (design §36).'], ] -// Every scenario a readiness card cites (config/jpa/readiness-cards.yaml `evidence.scenarios`) is a +// Every scenario a readiness card cites (release/readiness-cards.yaml `evidence.scenarios`) is a // required test of the lane that runs its class, and a readiness lane rejects skips. That is what the // deleted JPA evidence manifest used to establish from JUnit XML after the fact; JpaReadinessRegistryTest // checks the cards themselves. def readinessScenarios = new groovy.json.JsonSlurper() - .parse(rootProject.file('config/jpa/readiness-cards.yaml')) + .parse(file('release/readiness-cards.yaml')) .cards.values() .findAll { it.state != 'not-implemented' } .collectMany { card -> (card.evidence?.scenarios ?: []).collect { it.selector } } @@ -265,13 +265,29 @@ strictTestLanes { } } +// The recovery of a failed concurrent index migration (re-review 2026-11-03 round 7, RR7-03-03) is +// SQL the migration runbook gives an operator; the lane reads it out of the runbook the same way. +tasks.named('postgresqlConcurrentIndexMigrationIntegrationTest', Test) { + def migrationFailedRunbook = new File(rootProject.projectDir.parentFile, 'docs/runbooks/migration-failed.md') + inputs.file(migrationFailedRunbook).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('migrationFailedRunbook') + systemProperty 'migration.failed.runbook', migrationFailedRunbook.absolutePath +} + +// The lock-timeout runbook gives an operator SQL to find who holds a lock; the lock lane reads it out +// of the runbook the same way, so the query an operator runs is the one that ran against PostgreSQL. +tasks.named('postgresqlDistributedLockIntegrationTest', Test) { + def lockTimeoutRunbook = new File(rootProject.projectDir.parentFile, 'docs/runbooks/lock-acquisition-timeout.md') + inputs.file(lockTimeoutRunbook).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('lockTimeoutRunbook') + systemProperty 'lock.acquisition-timeout.runbook', lockTimeoutRunbook.absolutePath +} + tasks.named('postgresqlSecurityBaselineIntegrationTest') { // Cross-leaf task edge: see the handoff. verifyCleanArchitectureDependencies inspects // configurations, not the task graph, so this edge is invisible to it. dependsOn ':adapter:inbound:web:jpaPersistenceRedactionContractTest' } -// Which JPA lanes block a release is declared by config/jpa/release-registry.json (jpaReleaseQualification below). +// Which JPA lanes block a release is declared by release/release-registry.json (jpaReleaseQualification below). // This leaf declares the lanes and how each runs; it does not own release orchestration. // The unit lane reads three files that are not Java sources: the release registry and its two @@ -282,9 +298,9 @@ tasks.named('postgresqlSecurityBaselineIntegrationTest') { // up-to-date after a registry demotion or a workflow edit — so the drift checks that exist to catch // exactly those edits never run on them. tasks.named('test') { - inputs.file(rootProject.file('config/jpa/release-registry.json')) + inputs.file(file('release/release-registry.json')) // JpaReadinessRegistryTest: the readiness cards, the lanes they name and the scenarios they cite. - inputs.file(rootProject.file('config/jpa/readiness-cards.yaml')) + inputs.file(file('release/readiness-cards.yaml')) inputs.dir(file('src/postgresqlIntegrationTest/java')).withPropertyName('readinessScenarioSources') inputs.file(new File(rootProject.projectDir.parentFile, 'docs/jpa/support-matrix.md')) inputs.file(new File(rootProject.projectDir.parentFile, 'docs/jpa/repository-adaptation.md')) @@ -300,7 +316,7 @@ tasks.named('test') { inputs.dir(file('../persistence-fileserver/src/main/resources/db/migration')) .withPropertyName('fileserverMigrations') // ...and the messaging platform's tree, whose inbox range the consume side applies here. - inputs.dir(file('../../../messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration')) + inputs.dir(file('../../../platforms/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration')) .withPropertyName('messagingMigrations') } @@ -335,20 +351,20 @@ apiSurface { include '*/**/src/main/java/**/*.java' exclude '**/build/**', 'adapter/outbound/persistence-jpa/**', 'adapter/outbound/persistence-fileserver/**', 'adapter/outbound/persistence-notification/**', - 'build-logic/**', 'optional-platforms/**' + 'build-logic/**', 'platforms/optional-build/**' } } -// The release registry (config/jpa/release-registry.json) names the blocking release gates; this +// The release registry (release/release-registry.json) names the blocking release gates; this // aggregate runs exactly those. It replaced the build-tools `ca.jpa-qualification` plugin (review // 2026-09-24 BUILD-O3-2): a gate that names a task that does not exist fails when the task graph is // built, which is the whole of what `verifyJpaReleaseGateTasks` used to check. tasks.register('jpaReleaseQualification') { group = 'verification' - description = 'Runs exactly the blocking JPA release gates declared by config/jpa/release-registry.json.' + description = 'Runs exactly the blocking JPA release gates declared by release/release-registry.json.' dependsOn(new groovy.json.JsonSlurper() - .parse(rootProject.file('config/jpa/release-registry.json')) + .parse(file('release/release-registry.json')) .gates.findAll { it.blocking }.collect { it.task }) } diff --git a/src/config/jpa/readiness-cards.yaml b/src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml similarity index 100% rename from src/config/jpa/readiness-cards.yaml rename to src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml diff --git a/src/config/jpa/release-registry.json b/src/adapter/outbound/persistence-jpa/release/release-registry.json similarity index 100% rename from src/config/jpa/release-registry.json rename to src/adapter/outbound/persistence-jpa/release/release-registry.json diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java index b26c8b41..a40f9cd4 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/config/PersistenceJpaConfig.java @@ -8,7 +8,7 @@ import org.springframework.data.jpa.repository.config.EnableJpaRepositories; * Registers this module's always-installed JPA entities and Spring Data repositories. * *

The explicit scans are required because the Boot main class lives in another package; the - * simple name avoids {@code JpaConfig} to dodge a bean-name collision with the sample module. See + * simple name avoids {@code JpaConfig}, a name a service's own configuration is likely to take. See * README "config". * *

The package list is enumerated rather than given as the persistence root. {@code diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java index 3bb75bd4..d0aea51b 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/IdempotencyDigestPolicy.java @@ -14,8 +14,12 @@ import java.util.Objects; *

It omitted several. {@code transition|operationId|ownerToken|attempt|stateRevision} covers who * and when, and nothing about what: a {@code FAIL} recorded with a retryable disposition and one * recorded as abandoned produced identical digests, as did two completions carrying different - * responses or different retention. A replay comparing digests concluded "same transition" for two - * transitions whose whole difference was the part that mattered. + * responses. A replay comparing digests concluded "same transition" for two transitions whose whole + * difference was the part that mattered. + * + *

How long a result is kept is not part of what a failure decided: a failure's retention is left + * out, so a resend with another retention is the failure already recorded (owner decision + * 2026-11-07 — it was a conflict here and confirmed by the Redis store). * *

Length-framed, because every component is variable-width text and at least one — the owner * token — is not this platform's to constrain. Joining with a delimiter means two different @@ -37,7 +41,7 @@ final class IdempotencyDigestPolicy { * @param attempt the owner's attempt number * @param stateRevision the record revision the transition was applied to * @param semanticArguments every further input that changes what the transition means — - * disposition, retention, response digest, codec identity — in a fixed order + * disposition, response digest, replay TTL, codec identity — in a fixed order */ static String of( String transition, diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java index 54a99f0b..52e748f4 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/idempotency/postgresql/PostgreSqlIdempotencyStore.java @@ -27,6 +27,7 @@ import java.time.Instant; import java.util.HexFormat; import java.util.Objects; import java.util.Optional; +import java.util.Set; import org.springframework.jdbc.core.JdbcOperations; /** @@ -62,6 +63,9 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { private static final Duration MAXIMUM_PROCESSING_LEASE = Duration.ofHours(1); private static final Duration MAXIMUM_RETENTION = Duration.ofDays(30); + /** The two kinds a failure is recorded under, one per disposition. */ + private static final Set FAILURE_KINDS = Set.of("FAIL_RETRYABLE", "FAIL_ABANDONED"); + private static final String ACTIVE_CAPABILITY_SQL = """ select count(*) @@ -183,6 +187,9 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (row == null) { return startResult(IdempotencyStartOutcome.ABSENT, null); } + if (namesAnotherOperation(row, owner, operationId)) { + return startResult(IdempotencyStartOutcome.OPERATION_CONFLICT, null); + } String startDigest = transitionDigest("START", operationId, owner); // A start carries no argument but the handle, so a recorded start with another digest was // applied from another handle of the same operation — one from before a takeover by the same @@ -190,7 +197,8 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { // handle, which the classification below names as the Redis store does (NOT_OWNER, // NOT_CLAIMED); it used to be OPERATION_CONFLICT (round6 RR6-02-01). It never reaches the // update: a recorded start leaves the row EXECUTING until a later transition replaces it. - if (replayVerdict(row, "START", operationId, startDigest) == ReplayVerdict.SAME_ARGUMENTS) { + if (replayVerdict(row, owner, Set.of("START"), operationId, startDigest) + == ReplayVerdict.SAME_ARGUMENTS) { return startResult(IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION, owner(row)); } IdempotencyStartOutcome mismatch = classifyStartMismatch(row, owner); @@ -220,12 +228,15 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (row == null) { return renewResult(IdempotencyRenewOutcome.ABSENT, null); } + if (namesAnotherOperation(row, owner, operationId)) { + return renewResult(IdempotencyRenewOutcome.OPERATION_CONFLICT, null); + } // The lease TTL is part of what a renewal decided, so it is part of the digest. Without it, a // retry asking for a different lease was confirmed as the renewal already applied, and the // caller went on believing it held the record for longer than the row says it does. String renewDigest = transitionDigest("RENEW", operationId, owner, Long.toString(processingLeaseTtl.toMillis())); - switch (replayVerdict(row, "RENEW", operationId, renewDigest)) { + switch (replayVerdict(row, owner, Set.of("RENEW"), operationId, renewDigest)) { case SAME_ARGUMENTS -> { return renewResult(IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION, owner(row)); } @@ -267,10 +278,18 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyCompleteOutcome.ABSENT; } + if (namesAnotherOperation(row, owner, operationId)) { + return IdempotencyCompleteOutcome.OPERATION_CONFLICT; + } String responseDigest = sha256(response.payload()); + // A completion is reported back only to the handle it was applied from. The operation id alone + // confirmed the late completion of another attempt that carried the same id, and the owner + // token alone confirmed it to the same attempt's handle from before a takeover; the Redis + // store refuses both as NOT_OWNER (IdempotencyStoreContract, owner decision 2026-11-06). if (row.state() == IdempotencyState.COMPLETED && "COMPLETE".equals(row.lastTransitionKind()) - && operationId.value().equals(row.lastTransitionOperationId())) { + && operationId.value().equals(row.lastTransitionOperationId()) + && appliedFrom(row, owner)) { return responseDigest.equals(row.responseDigest()) ? IdempotencyCompleteOutcome.ALREADY_COMPLETED_SAME_RESULT : IdempotencyCompleteOutcome.RESPONSE_CONFLICT; @@ -315,18 +334,20 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyFailOutcome.ABSENT; } + if (namesAnotherOperation(row, owner, operationId)) { + return IdempotencyFailOutcome.OPERATION_CONFLICT; + } String transitionKind = disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE ? "FAIL_RETRYABLE" : "FAIL_ABANDONED"; - String failDigest = - transitionDigest( - transitionKind, - operationId, - owner, - disposition.name(), - Long.toString(retention.toMillis())); - switch (replayVerdict(row, transitionKind, operationId, failDigest)) { + // The disposition is what a failure decided, so it is in the digest, and a failure of either + // kind recorded from this handle is this failure resent: with the other disposition it is a + // conflict, not a stale owner (owner decision 2026-11-07 — it fell through to NOT_OWNER). The + // retention is not: like a completion's replay TTL it is how long the result is kept, so a + // resend with another one is confirmed and the row keeps the first (it was OPERATION_CONFLICT). + String failDigest = transitionDigest(transitionKind, operationId, owner, disposition.name()); + switch (replayVerdict(row, owner, FAILURE_KINDS, operationId, failDigest)) { case SAME_ARGUMENTS -> { return IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION; } @@ -372,8 +393,11 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyReleaseOutcome.ABSENT; } + if (namesAnotherOperation(row, owner, operationId)) { + return IdempotencyReleaseOutcome.OPERATION_CONFLICT; + } String releaseDigest = transitionDigest("RELEASE", operationId, owner); - switch (replayVerdict(row, "RELEASE", operationId, releaseDigest)) { + switch (replayVerdict(row, owner, Set.of("RELEASE"), operationId, releaseDigest)) { case SAME_ARGUMENTS -> { return IdempotencyReleaseOutcome.ALREADY_RELEASED_SAME_OPERATION; } @@ -411,6 +435,11 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FINGERPRINT_MISMATCH); } boolean sameAttempt = sameClaimAttempt(row, request.claimAttempt()); + // The owner token under another operation is refused in every state, a completed record + // included, as the Redis store refuses it; the response used to be replayed to it here. + if (row.ownerToken().equals(request.claimAttempt().ownerToken()) && !sameAttempt) { + return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.OPERATION_CONFLICT); + } if (row.state() == IdempotencyState.COMPLETED && row.responsePayload() != null) { return new IdempotencyInspection( IdempotencyInspectionOutcome.COMPLETED_REPLAY, @@ -425,9 +454,6 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { if (sameAttempt && row.state() == IdempotencyState.EXECUTING) { return inspectionWithOwner(IdempotencyInspectionOutcome.EXECUTING_SAME_OPERATION, row); } - if (row.ownerToken().equals(request.claimAttempt().ownerToken()) && !sameAttempt) { - return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.OPERATION_CONFLICT); - } // Somebody else's execution whose lease ran out is reported as a claim would answer it. The // database's clock decides, as it does for the claim; the read takes no lock, so a lease that // ends between the row and the clock is reported as ended, which is what a claim would see. @@ -452,9 +478,25 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return new IdempotencyClaimOutcome.TakenOverClaimed(owner(reset), reset.processingLeaseUntil()); } + /** + * Whether the holder of the record names an operation other than the one it was claimed under. + * + *

Every transition names the claim's operation, and a holder naming another one is refused + * before anything else is read: nothing changes, as in the Redis store and the in-memory fake. It + * used to be applied — the owner tuple took the claim's operation from the handle, and the named + * one was only written to {@code last_transition_operation_id} (owner decision 2026-11-06, {@code + * IdempotencyStoreContract}). Another owner token is still {@code NOT_OWNER}. + */ + private static boolean namesAnotherOperation( + IdempotencyRecordRow row, IdempotencyOwner owner, OperationId operationId) { + return row.ownerToken().equals(owner.ownerToken()) + && !row.claimOperationId().equals(operationId.value()); + } + // A handle at an older revision is a stale owner tuple, so it is NOT_OWNER — what the Redis store - // and the in-memory fake answer (IdempotencyStoreContract). OPERATION_CONFLICT keeps its one - // meaning: the same operation id already applied this transition with different arguments. + // and the in-memory fake answer (IdempotencyStoreContract). OPERATION_CONFLICT means the holder + // named another operation than the claim's (namesAnotherOperation), or the same operation id + // already applied this transition with different arguments. private IdempotencyStartOutcome classifyStartMismatch( IdempotencyRecordRow row, IdempotencyOwner owner) { if (!sameOwnerIdentity(row, owner)) { @@ -554,6 +596,15 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { return sameOwnerIdentity(row, owner) && row.stateRevision() == owner.stateRevision(); } + /** + * Whether the row's last transition was applied from this handle: the same owner identity, one + * revision behind the row, as every transition advances the revision by one. Only that handle may + * be told a recorded transition was its own (owner decision 2026-11-06). + */ + private static boolean appliedFrom(IdempotencyRecordRow row, IdempotencyOwner owner) { + return sameOwnerIdentity(row, owner) && row.stateRevision() == owner.stateRevision() + 1; + } + /** * Whether the recorded transition is this call again, and whether it carried these arguments. * @@ -568,14 +619,30 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { * the owner handle it presented the first time, so the revision, the owner and every semantic * argument reproduce the stored digest exactly; anything else is a different transition wearing * the same operation id, and belongs in a conflict rather than in a confirmation. + * + *

That holds only for the handle the transition was applied from. Any other handle recomputes + * a different digest from its own attempt and revision, and was answered {@code + * OPERATION_CONFLICT}: the holder's second renewal through the handle its first one returned, and + * the same attempt's handle from before a takeover resending a failure or a release that followed + * it. Neither is a replay — the first is a new transition, the second a stale owner — so both go + * on to the ownership checks, as in the Redis store (owner decision 2026-11-06). + * + *

{@code transitionKinds} is every kind the call's transition is recorded under. A failure has + * two, one per disposition, and a resend from the applying handle with the other disposition used + * to find the other kind and go on to the ownership checks as a stale owner; it is the same + * failure with another argument, so a conflict (owner decision 2026-11-07). */ private static ReplayVerdict replayVerdict( IdempotencyRecordRow row, - String transitionKind, + IdempotencyOwner owner, + Set transitionKinds, OperationId operationId, String expectedDigest) { - if (!transitionKind.equals(row.lastTransitionKind()) - || !operationId.value().equals(row.lastTransitionOperationId())) { + // A claim leaves no transition recorded, and an immutable set refuses a null lookup. + if (row.lastTransitionKind() == null + || !transitionKinds.contains(row.lastTransitionKind()) + || !operationId.value().equals(row.lastTransitionOperationId()) + || !appliedFrom(row, owner)) { return ReplayVerdict.NOT_A_REPLAY; } return expectedDigest.equals(row.lastTransitionResultDigest()) @@ -648,7 +715,7 @@ public final class PostgreSqlIdempotencyStore implements IdempotencyStorePort { * when, and nothing about what. A {@code FAIL} recorded as retryable and one recorded as * abandoned produced the same digest, and so did two completions carrying different responses. * - * @param semanticArguments disposition, retention, response digest, codec identity — whatever + * @param semanticArguments disposition, response digest, replay TTL, codec identity — whatever * this particular transition also decided */ private static String transitionDigest( diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywaySchemaPolicy.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywaySchemaPolicy.java index 1ac9fbaf..272cb06e 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywaySchemaPolicy.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/migration/FlywaySchemaPolicy.java @@ -109,8 +109,11 @@ public final class FlywaySchemaPolicy { * spring.flyway.postgresql.transactional-lock}); a deployment's migration tool has to be given it * ({@code docs/jpa/migration-guide.md}, "Who may change the schema"). * - *

Callers chain their own settings onto the result. Calling {@link Flyway#configure()} - * directly in production code is refused by {@code JpaProductionArchitectureTest}. + *

Callers chain their own settings onto the result. Production code that builds a Flyway any + * other way — calling {@link Flyway#configure()}, or constructing a Flyway configuration itself + * ({@code new FluentConfiguration()}, {@code new ClassicConfiguration()}, a subclass of either) — + * is refused by {@code JpaProductionArchitectureTest}; {@code new Flyway(...)} over this method's + * result is allowed (re-review 2026-11-03 round 7, RR7-03-06). */ public static FluentConfiguration configure() { return sessionLevelLock(Flyway.configure()); diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java index 3a933778..e23e34ca 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/outbox/jpa/JpaOutboxStore.java @@ -125,7 +125,7 @@ public class JpaOutboxStore * and increments the committed counter instead (review RR-03-01). * *

Statements rather than one {@code INSERT … ON CONFLICT DO UPDATE … RETURNING} like {@code - * JpaLiveEventReplay}'s position allocator: the sample appends events on the H2 developer run + * JpaLiveEventReplay}'s position allocator: a service appends events on the H2 developer run * ({@code bootRunH2}), and H2 accepts {@code ON CONFLICT DO NOTHING} but not {@code DO UPDATE}. * The common case — the counter exists — is still one {@code UPDATE} and one read. */ diff --git a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java index 64816cff..d77279fd 100644 --- a/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java +++ b/src/adapter/outbound/persistence-jpa/src/main/java/dev/caskeleton/adapter/outbound/persistence/startup/JpaStartupAutoConfiguration.java @@ -60,7 +60,7 @@ class JpaStartupAutoConfiguration { * Runs Flyway during refresh, before readiness, and turns a failure into exit 70. * *

The bean name is what Flyway auto-configuration looks up. An application that supplies its - * own strategy — the sample runs a second migration stream — keeps it. + * own strategy — to run a second migration stream, say — keeps it. */ @Bean @ConditionalOnMissingBean(FlywayMigrationStrategy.class) diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlConcurrentIndexMigrationIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlConcurrentIndexMigrationIntegrationTest.java index ef691bd0..50874d12 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlConcurrentIndexMigrationIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlConcurrentIndexMigrationIntegrationTest.java @@ -9,11 +9,15 @@ import java.io.IOException; import java.nio.file.Files; import java.nio.file.Path; import java.sql.Connection; +import java.sql.DriverManager; import java.sql.PreparedStatement; +import java.sql.ResultSet; import java.sql.SQLException; +import java.sql.Statement; import java.time.Duration; import java.util.List; import java.util.Locale; +import java.util.Map; import java.util.UUID; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; @@ -24,6 +28,8 @@ import java.util.concurrent.TimeoutException; import javax.sql.DataSource; import org.junit.jupiter.api.AfterAll; import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; import org.junit.jupiter.api.io.TempDir; import org.junit.jupiter.params.ParameterizedTest; import org.junit.jupiter.params.provider.ValueSource; @@ -53,6 +59,18 @@ import org.springframework.jdbc.datasource.DelegatingDataSource; * way every Flyway this template constructs itself does ({@link FlywaySchemaPolicy#configure()}). A * deploy still waiting after {@link #FINISHES_WITHIN} is cancelled, which leaves the invalid index * an interrupted build leaves in production too. + * + *

Five more cases pin what happens when such a deploy fails (re-review 2026-11-03 round 7, + * RR7-03-03 and RR7-03-04; round 8, RR8-03-01). A concurrent build next to another statement is + * refused before any of it runs when nothing configures the file, and is left half applied when + * {@code executeInTransaction=false} does: Flyway commits each statement on its own. A concurrent + * statement alone that fails leaves an invalid index and a failed history row, and the deploy after + * it is refused until the row is gone. The recovery cases run the SQL of {@code + * docs/runbooks/migration-failed.md} ("Recover a failed concurrent index migration"), read out of + * the runbook itself, for each statement the runbook covers, and deploy again: a unique build that + * fails on a duplicate, and a rebuild and a drop cancelled while they wait for an open transaction. + * The drop leaves invalid the very index it was dropping, so the runbook leaves that index for the + * deploy again to drop: dropped by hand first, the same statement fails with {@code 42704}. */ class PostgreSqlConcurrentIndexMigrationIntegrationTest { @@ -64,6 +82,29 @@ class PostgreSqlConcurrentIndexMigrationIntegrationTest { INSERT INTO probe SELECT g, 'note ' || g FROM generate_series(1, 1000) AS g; """; + /** A second row with row 1's note, so that a unique index on the note cannot be built. */ + private static final String DUPLICATE_NOTE = + "INSERT INTO probe (id, note) VALUES (2001, 'note 1');\n"; + + private static final String UNIQUE_NOTE_INDEX = + "CREATE UNIQUE INDEX CONCURRENTLY ix_probe_note_u ON probe (note)"; + + /** A concurrent build after another statement, the file the guide says not to write. */ + private static final String MIXED = + "INSERT INTO probe (id, note) VALUES (3001, 'partial');\n" + UNIQUE_NOTE_INDEX + ";\n"; + + private static final String FLYWAY_REFUSES_A_MIXED_MIGRATION = + "Detected both transactional and non-transactional statements"; + + /** A read of the table, which a {@code DROP INDEX CONCURRENTLY} waits for while it is open. */ + private static final String A_READ = "SELECT count(*) FROM probe"; + + /** A write to the table, which a {@code REINDEX ... CONCURRENTLY} waits for while it is open. */ + private static final String A_WRITE = "UPDATE probe SET note = note WHERE id = 1"; + + /** The system property naming {@code docs/runbooks/migration-failed.md} for this lane. */ + private static final String MIGRATION_FAILED_RUNBOOK = "migration.failed.runbook"; + private static PostgreSqlReadinessSupport postgres; @BeforeAll @@ -126,6 +167,210 @@ class PostgreSqlConcurrentIndexMigrationIntegrationTest { } } + @Test + @DisplayName("설정 파일 없이 동시 인덱스 문장과 다른 문장을 섞은 마이그레이션은 Flyway가 아무것도 실행하기 전에 거부한다") + void aMixedMigrationWithoutConfigurationIsRefusedBeforeAnyOfItRuns(@TempDir Path stream) + throws Exception { + try (HikariDataSource database = postgres.createDatabase(databaseName())) { + // given + Files.writeString(stream.resolve("V1__probe.sql"), FIRST_RELEASE + DUPLICATE_NOTE); + migrateTheWayTheTemplateDoes(database, stream); + Files.writeString(stream.resolve("V2__mixed.sql"), MIXED); + + // when + Throwable thrown = catchThrowable(() -> migrateTheWayTheTemplateDoes(database, stream)); + + // then + assertThat( + List.of( + String.valueOf(thrown).contains(FLYWAY_REFUSES_A_MIXED_MIGRATION), + aftermath(database))) + .containsExactly( + true, "row 3001 0, indexes [ix_probe_id true, probe_pkey true], history [1 true]"); + } + } + + @Test + @DisplayName( + "executeInTransaction=false를 붙여 섞은 마이그레이션은 앞 문장을 커밋한 채 동시 빌드에서 실패해 부분 적용, 무효 인덱스, 실패 이력을 남긴다") + void aMixedMigrationMarkedOutsideATransactionIsLeftHalfApplied(@TempDir Path stream) + throws Exception { + try (HikariDataSource database = postgres.createDatabase(databaseName())) { + // given + Files.writeString(stream.resolve("V1__probe.sql"), FIRST_RELEASE + DUPLICATE_NOTE); + migrateTheWayTheTemplateDoes(database, stream); + Files.writeString(stream.resolve("V2__mixed.sql"), MIXED); + Files.writeString(stream.resolve("V2__mixed.sql.conf"), "executeInTransaction=false\n"); + + // when + Throwable thrown = catchThrowable(() -> migrateTheWayTheTemplateDoes(database, stream)); + + // then + assertThat(List.of(thrown != null, aftermath(database))) + .containsExactly( + true, + "row 3001 1, indexes [ix_probe_id true, ix_probe_note_u false, probe_pkey true]," + + " history [1 true, 2 false]"); + } + } + + @Test + @DisplayName( + "중복 값으로 실패한 unique 동시 인덱스 빌드는 runbook 절차(빌드 확인, 원인 정리, 무효 인덱스 삭제, 그 버전의 실패 이력 행 삭제) 뒤 다시 배포하면 적용된다") + void aFailedConcurrentIndexMigrationIsRecoveredByTheRunbookProcedure(@TempDir Path stream) + throws Exception { + RunbookSql runbook = RunbookSql.fromSystemProperty(MIGRATION_FAILED_RUNBOOK); + try (HikariDataSource database = postgres.createDatabase(databaseName())) { + // given + Files.writeString(stream.resolve("V1__probe.sql"), FIRST_RELEASE + DUPLICATE_NOTE); + migrateTheWayTheTemplateDoes(database, stream); + String checksumOfV1 = checksumOf(database, "1"); + writeConcurrentMigration(stream, UNIQUE_NOTE_INDEX); + Throwable failed = catchThrowable(() -> migrateTheWayTheTemplateDoes(database, stream)); + String afterFailure = aftermath(database); + JdbcTemplate jdbc = new JdbcTemplate(database); + + // when + List> buildsRunning = + jdbc.queryForList(runbook.block("failed-concurrent-index-builds")); + jdbc.execute("DELETE FROM probe WHERE id = 2001"); + jdbc.execute( + runbook.block( + "failed-concurrent-index-drop", Map.of("invalid_index", "ix_probe_note_u"))); + jdbc.execute( + runbook.block( + "failed-concurrent-index-history-row", + Map.of("owned_history_table", "flyway_schema_history", "version", "2"))); + Throwable again = catchThrowable(() -> migrateTheWayTheTemplateDoes(database, stream)); + + // then + assertThat( + List.of( + failed != null, + afterFailure, + buildsRunning.size(), + String.valueOf(again), + aftermath(database), + checksumOf(database, "1"))) + .containsExactly( + true, + "row 3001 0, indexes [ix_probe_id true, ix_probe_note_u false, probe_pkey true]," + + " history [1 true, 2 false]", + 0, + "null", + "row 3001 0, indexes [ix_probe_id true, ix_probe_note_u true, probe_pkey true]," + + " history [1 true, 2 true]", + checksumOfV1); + } + } + + @Test + @DisplayName( + "열린 트랜잭션을 기다리다 취소된 REINDEX CONCURRENTLY는 runbook 절차(빌드 확인, 원인 정리, 남은 _ccnew 무효 인덱스 삭제, 그 버전의 실패 이력 행 삭제) 뒤 다시 배포하면 적용된다") + void aFailedConcurrentRebuildIsRecoveredByTheRunbookProcedure(@TempDir Path stream) + throws Exception { + RunbookSql runbook = RunbookSql.fromSystemProperty(MIGRATION_FAILED_RUNBOOK); + String name = databaseName(); + try (HikariDataSource database = postgres.createDatabase(name)) { + // given + Files.writeString(stream.resolve("V1__probe.sql"), FIRST_RELEASE); + migrateTheWayTheTemplateDoes(database, stream); + String checksumOfV1 = checksumOf(database, "1"); + writeConcurrentMigration(stream, "REINDEX INDEX CONCURRENTLY ix_probe_id"); + Throwable failed; + String afterFailure; + List> buildsRunning; + JdbcTemplate jdbc = new JdbcTemplate(database); + try (Connection writer = openTransactionOn(database, A_WRITE)) { + failed = cancelledOnceItWaits(name, () -> migrateTheWayTheTemplateDoes(database, stream)); + afterFailure = aftermath(database); + + // when + buildsRunning = jdbc.queryForList(runbook.block("failed-concurrent-index-builds")); + writer.rollback(); + } + jdbc.execute( + runbook.block( + "failed-concurrent-index-drop", Map.of("invalid_index", "ix_probe_id_ccnew"))); + jdbc.execute( + runbook.block( + "failed-concurrent-index-history-row", + Map.of("owned_history_table", "flyway_schema_history", "version", "2"))); + Throwable again = catchThrowable(() -> migrateTheWayTheTemplateDoes(database, stream)); + + // then + assertThat( + List.of( + failed != null, + afterFailure, + buildsRunning.size(), + String.valueOf(again), + aftermath(database), + checksumOf(database, "1"))) + .containsExactly( + true, + "row 3001 0, indexes [ix_probe_id true, ix_probe_id_ccnew false, probe_pkey true]," + + " history [1 true, 2 false]", + 0, + "null", + "row 3001 0, indexes [ix_probe_id true, probe_pkey true], history [1 true, 2 true]", + checksumOfV1); + } + } + + @Test + @DisplayName( + "열린 트랜잭션을 기다리다 취소된 DROP INDEX CONCURRENTLY는 runbook 절차대로 빌드 확인, 원인 정리, 그 버전의 실패 이력 행 삭제만 하고 남은 무효 인덱스는 두면 다시 배포한 같은 문장이 그 인덱스를 지우고 적용된다") + void aFailedConcurrentDropIsRecoveredByTheRunbookProcedure(@TempDir Path stream) + throws Exception { + RunbookSql runbook = RunbookSql.fromSystemProperty(MIGRATION_FAILED_RUNBOOK); + String name = databaseName(); + try (HikariDataSource database = postgres.createDatabase(name)) { + // given + Files.writeString(stream.resolve("V1__probe.sql"), FIRST_RELEASE); + migrateTheWayTheTemplateDoes(database, stream); + String checksumOfV1 = checksumOf(database, "1"); + writeConcurrentMigration(stream, "DROP INDEX CONCURRENTLY ix_probe_id"); + Throwable failed; + String afterFailure; + List> buildsRunning; + JdbcTemplate jdbc = new JdbcTemplate(database); + try (Connection reader = openTransactionOn(database, A_READ)) { + failed = cancelledOnceItWaits(name, () -> migrateTheWayTheTemplateDoes(database, stream)); + afterFailure = aftermath(database); + + // when + buildsRunning = jdbc.queryForList(runbook.block("failed-concurrent-index-builds")); + reader.rollback(); + } + int deleted = + jdbc.update( + runbook.block( + "failed-concurrent-index-history-row", + Map.of("owned_history_table", "flyway_schema_history", "version", "2"))); + Throwable again = catchThrowable(() -> migrateTheWayTheTemplateDoes(database, stream)); + + // then + assertThat( + List.of( + failed != null, + afterFailure, + buildsRunning.size(), + deleted, + String.valueOf(again), + aftermath(database), + checksumOf(database, "1"))) + .containsExactly( + true, + "row 3001 0, indexes [ix_probe_id false, probe_pkey true], history [1 true, 2 false]", + 0, + 1, + "null", + "row 3001 0, indexes [probe_pkey true], history [1 true, 2 true]", + checksumOfV1); + } + } + /** V2: the one concurrent statement, with the companion configuration the guide asks for. */ private static void writeConcurrentMigration(Path stream, String statement) throws IOException { Files.writeString(stream.resolve("V2__concurrent_index.sql"), statement + ";\n"); @@ -207,6 +452,60 @@ class PostgreSqlConcurrentIndexMigrationIntegrationTest { } } + /** + * A connection to the database with a transaction open on the table: {@code statement} has run in + * it and holds its lock until the caller ends the transaction, as a report or an operator's + * {@code BEGIN} would. Opened outside the test's pool, which the deploy needs. + */ + private static Connection openTransactionOn(HikariDataSource database, String statement) + throws SQLException { + Connection holder = + DriverManager.getConnection( + database.getJdbcUrl(), database.getUsername(), database.getPassword()); + holder.setAutoCommit(false); + try (Statement holding = holder.createStatement()) { + holding.execute(statement); + } + return holder; + } + + /** + * Runs the deploy until its statement waits for a lock in the database, cancels that wait as an + * operator ending a stuck deploy would, and returns how the deploy failed. + */ + private static Throwable cancelledOnceItWaits(String databaseName, Runnable migration) + throws Exception { + ExecutorService deployer = Executors.newSingleThreadExecutor(); + try { + Future deploy = deployer.submit(migration); + long deadline = System.nanoTime() + FINISHES_WITHIN.toNanos(); + while (!aStatementWaitsForALock(databaseName)) { + if (deploy.isDone() || System.nanoTime() > deadline) { + throw new IllegalStateException("the deploy never waited for a lock"); + } + Thread.sleep(50); + } + cancelLockWaits(databaseName); + return catchThrowable(() -> deploy.get(FINISHES_WITHIN.toMillis(), TimeUnit.MILLISECONDS)); + } finally { + deployer.shutdownNow(); + } + } + + private static boolean aStatementWaitsForALock(String databaseName) throws SQLException { + try (Connection admin = postgres.connection(); + PreparedStatement waiting = + admin.prepareStatement( + "SELECT count(*) FROM pg_stat_activity" + + " WHERE datname = ? AND wait_event_type = 'Lock'" + + " AND pid <> pg_backend_pid()")) { + waiting.setString(1, databaseName); + try (ResultSet count = waiting.executeQuery()) { + return count.next() && count.getInt(1) > 0; + } + } + } + /** The version the history ends on and whether every index on the table is usable. */ private static String state(DataSource database) { JdbcTemplate jdbc = new JdbcTemplate(database); @@ -222,6 +521,37 @@ class PostgreSqlConcurrentIndexMigrationIntegrationTest { return "version " + version + ", indexes valid " + valid; } + /** + * What a deploy left behind: whether the row the mixed V2 inserts first is there, every index on + * the table with whether it is valid, and every history row with whether it succeeded. + */ + private static String aftermath(DataSource database) { + JdbcTemplate jdbc = new JdbcTemplate(database); + Integer row = jdbc.queryForObject("SELECT count(*) FROM probe WHERE id = 3001", Integer.class); + List indexes = + jdbc.queryForList( + "SELECT c.relname || ' ' || i.indisvalid FROM pg_index i" + + " JOIN pg_class c ON c.oid = i.indexrelid" + + " WHERE i.indrelid = 'probe'::regclass ORDER BY c.relname COLLATE \"C\"", + String.class); + List history = + jdbc.queryForList( + "SELECT coalesce(version, '-') || ' ' || success FROM flyway_schema_history" + + " ORDER BY installed_rank", + String.class); + return "row 3001 " + row + ", indexes " + indexes + ", history " + history; + } + + /** The checksum the history holds for a successful version. */ + private static String checksumOf(DataSource database, String version) { + return String.valueOf( + new JdbcTemplate(database) + .queryForObject( + "SELECT checksum FROM flyway_schema_history WHERE version = ? AND success", + Integer.class, + version)); + } + private static String databaseName() { return "concurrent_" + UUID.randomUUID().toString().replace("-", "").toLowerCase(Locale.ROOT); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java index 07b6d24c..1449be98 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlDistributedLockIntegrationTest.java @@ -8,8 +8,12 @@ import dev.caskeleton.application.lock.DistributedLock; import dev.caskeleton.application.lock.DistributedLockPort; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; import dev.caskeleton.application.lock.testkit.DistributedLockContract; +import java.nio.charset.StandardCharsets; import java.time.Duration; import java.util.ConcurrentModificationException; +import java.util.List; +import java.util.Map; +import java.util.UUID; import javax.sql.DataSource; import org.flywaydb.core.Flyway; import org.junit.jupiter.api.AfterAll; @@ -19,11 +23,18 @@ import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.springframework.integration.jdbc.lock.DefaultLockRepository; import org.springframework.integration.jdbc.lock.JdbcLockRegistry; +import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.jdbc.datasource.DataSourceTransactionManager; -/** Real PostgreSQL contract for the Spring Integration JDBC distributed-lock adapter. */ +/** + * Real PostgreSQL contract for the Spring Integration JDBC distributed-lock adapter, and the SQL + * the lock-timeout runbook gives an operator to find a lock's holder, read out of the runbook + * itself. + */ class PostgreSqlDistributedLockIntegrationTest { + private static final String LOCK_TIMEOUT_RUNBOOK = "lock.acquisition-timeout.runbook"; + private static PostgreSqlReadinessSupport postgres; private static DataSource dataSource; @@ -120,6 +131,65 @@ class PostgreSqlDistributedLockIntegrationTest { } } + @Test + void theRunbookListsAHeldLockWithTheInstanceHoldingIt() throws Exception { + // given + RunbookSql runbook = RunbookSql.fromSystemProperty(LOCK_TIMEOUT_RUNBOOK); + Duration ttl = Duration.ofSeconds(30); + String holder = UUID.randomUUID().toString(); + DefaultLockRepository repository = repository(dataSource, holder); + String key = "orders/runbook-holders-" + System.nanoTime(); + DistributedLock held = adapter(repository, ttl).tryAcquire(key, Duration.ofSeconds(1), ttl); + try { + // when + List> rows = + new JdbcTemplate(dataSource).queryForList(runbook.block("lock-holders")); + + // then + assertThat(rows) + .filteredOn(row -> holder.equals(row.get("client_id"))) + .extracting(row -> row.get("lock_key")) + .containsExactly(nameBasedUuidOf(key)); + } finally { + held.close(); + repository.stop(); + } + } + + @Test + void theRunbookFindsTheInstanceHoldingTheLockOfAKeyItIsGiven() throws Exception { + // given + RunbookSql runbook = RunbookSql.fromSystemProperty(LOCK_TIMEOUT_RUNBOOK); + Duration ttl = Duration.ofSeconds(30); + String holder = UUID.randomUUID().toString(); + DefaultLockRepository holderRepository = repository(dataSource, holder); + DefaultLockRepository neighbourRepository = repository(dataSource); + String key = "orders/runbook-key-" + System.nanoTime(); + DistributedLock held = + adapter(holderRepository, ttl).tryAcquire(key, Duration.ofSeconds(1), ttl); + DistributedLock neighbour = + adapter(neighbourRepository, ttl).tryAcquire(key + "/next", Duration.ofSeconds(1), ttl); + try { + // when + List> rows = + new JdbcTemplate(dataSource) + .queryForList(runbook.block("lock-holder-of-key", Map.of("lock_key", key))); + + // then + assertThat(rows).extracting(row -> row.get("client_id")).containsExactly(holder); + } finally { + held.close(); + neighbour.close(); + holderRepository.stop(); + neighbourRepository.stop(); + } + } + + /** What Spring Integration stores as {@code LOCK_KEY} for a key that is not itself a UUID. */ + private static String nameBasedUuidOf(String key) { + return UUID.nameUUIDFromBytes(key.getBytes(StandardCharsets.UTF_8)).toString(); + } + private static DistributedLock acquireWithin( LockRegistryDistributedLock adapter, String key, Duration leaseTtl, Duration bound) throws InterruptedException { @@ -143,7 +213,11 @@ class PostgreSqlDistributedLockIntegrationTest { } private static DefaultLockRepository repository(DataSource dataSource) { - DefaultLockRepository repository = new DefaultLockRepository(dataSource); + return repository(dataSource, UUID.randomUUID().toString()); + } + + private static DefaultLockRepository repository(DataSource dataSource, String clientId) { + DefaultLockRepository repository = new DefaultLockRepository(dataSource, clientId); repository.setCheckDatabaseOnStart(false); repository.setTransactionManager(new DataSourceTransactionManager(dataSource)); repository.afterPropertiesSet(); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java index c231797e..7285703c 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlIdempotencyIntegrationTest.java @@ -91,8 +91,7 @@ class PostgreSqlIdempotencyIntegrationTest { ignored -> { IdempotencyOwner owner = ((IdempotencyClaimOutcome.Acquired) store.claim(request)).owner(); - owner = - store.markExecutionStarted(owner, new OperationId("start-1")).owner().orElseThrow(); + owner = store.markExecutionStarted(owner, owner.claimOperationId()).owner().orElseThrow(); jdbc.update( "insert into idempotency_business_probe(scope_hash, mutation_count) values (?, 1)", SCOPE.digest()); @@ -102,7 +101,7 @@ class PostgreSqlIdempotencyIntegrationTest { owner, new StoredResponse("{\"workLogId\":\"42\"}"), Duration.ofHours(24), - new OperationId("complete-1"))) + owner.claimOperationId())) .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); }); @@ -157,7 +156,7 @@ class PostgreSqlIdempotencyIntegrationTest { transactions .execute( ignored -> - store.markExecutionStarted(staleOwner, new OperationId("stale-start"))) + store.markExecutionStarted(staleOwner, staleOwner.claimOperationId())) .outcome()) .isEqualTo(IdempotencyStartOutcome.NOT_OWNER); } @@ -173,7 +172,7 @@ class PostgreSqlIdempotencyIntegrationTest { store.claim(request(original, Duration.ofMillis(25)))) .owner(); return store - .markExecutionStarted(owner, new OperationId("start-executing")) + .markExecutionStarted(owner, owner.claimOperationId()) .owner() .orElseThrow(); }); @@ -217,7 +216,7 @@ class PostgreSqlIdempotencyIntegrationTest { ((IdempotencyClaimOutcome.Acquired) store.claim(firstRequest)).owner(); owner = store - .markExecutionStarted(owner, new OperationId("start-first")) + .markExecutionStarted(owner, owner.claimOperationId()) .owner() .orElseThrow(); jdbc.update( @@ -229,7 +228,7 @@ class PostgreSqlIdempotencyIntegrationTest { owner, new StoredResponse("done"), Duration.ofHours(1), - new OperationId("complete-first"))) + owner.claimOperationId())) .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); firstHasCompletedInsideTransaction.countDown(); await(allowFirstCommit); @@ -284,7 +283,7 @@ class PostgreSqlIdempotencyIntegrationTest { ((IdempotencyClaimOutcome.Acquired) store.claim(firstRequest)).owner(); IdempotencyOwner executing = store - .markExecutionStarted(owner, new OperationId("start-slow")) + .markExecutionStarted(owner, owner.claimOperationId()) .owner() .orElseThrow(); firstStarted.countDown(); @@ -293,7 +292,7 @@ class PostgreSqlIdempotencyIntegrationTest { executing, new StoredResponse("slow-but-done"), Duration.ofHours(1), - new OperationId("complete-slow")); + executing.claimOperationId()); }); return null; }); @@ -346,7 +345,7 @@ class PostgreSqlIdempotencyIntegrationTest { ((IdempotencyClaimOutcome.Acquired) store.claim(firstRequest)).owner(); IdempotencyOwner executing = store - .markExecutionStarted(owner, new OperationId("start-fails")) + .markExecutionStarted(owner, owner.claimOperationId()) .owner() .orElseThrow(); firstStarted.countDown(); @@ -357,7 +356,7 @@ class PostgreSqlIdempotencyIntegrationTest { executing, IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED, Duration.ofHours(1), - new OperationId("fail-unknown")); + executing.claimOperationId()); throw new IllegalStateException("the action failed"); }); return null; @@ -383,7 +382,7 @@ class PostgreSqlIdempotencyIntegrationTest { @Test void aRetriedFailureWithTheSameArgumentsIsConfirmedRatherThanAppliedTwice() { - IdempotencyOwner executing = claimAndStart("claim-fail-replay", "start-fail-replay"); + IdempotencyOwner executing = claimAndStart("claim-fail-replay"); IdempotencyFailOutcome first = transactions.execute( @@ -392,7 +391,7 @@ class PostgreSqlIdempotencyIntegrationTest { executing, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), - new OperationId("fail-1"))); + executing.claimOperationId())); IdempotencyFailOutcome retry = transactions.execute( ignored -> @@ -400,15 +399,15 @@ class PostgreSqlIdempotencyIntegrationTest { executing, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), - new OperationId("fail-1"))); + executing.claimOperationId())); assertThat(first).isEqualTo(IdempotencyFailOutcome.MARKED_RETRYABLE); assertThat(retry).isEqualTo(IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION); } @Test - void aFailureRepeatedUnderOneOperationIdWithDifferentRetentionIsAConflict() { - IdempotencyOwner executing = claimAndStart("claim-fail-conflict", "start-fail-conflict"); + void aFailureRepeatedUnderOneOperationIdWithDifferentRetentionIsConfirmedAndKeepsItsRetention() { + IdempotencyOwner executing = claimAndStart("claim-fail-conflict"); transactions.execute( ignored -> @@ -416,7 +415,7 @@ class PostgreSqlIdempotencyIntegrationTest { executing, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), - new OperationId("fail-2"))); + executing.claimOperationId())); IdempotencyFailOutcome different = transactions.execute( ignored -> @@ -424,13 +423,14 @@ class PostgreSqlIdempotencyIntegrationTest { executing, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(9), - new OperationId("fail-2"))); + executing.claimOperationId())); + // The retention is how long the failure is kept, not what it decided, so it is not compared: + // the resend is the failure already recorded, and the row keeps the first retention (owner + // decision 2026-11-07 — this store answered OPERATION_CONFLICT, the Redis store confirmed it). assertThat(different) - .as( - "the recorded failure kept the record for an hour; reporting this call as the one" - + " already applied would tell the caller it got nine") - .isEqualTo(IdempotencyFailOutcome.OPERATION_CONFLICT); + .as("the resend asked for nine hours; the row still keeps the failure for one") + .isEqualTo(IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION); assertThat( jdbc.queryForObject( "select extract(epoch from (expires_at - updated_at))::bigint " @@ -443,25 +443,25 @@ class PostgreSqlIdempotencyIntegrationTest { @Test void aRenewalRepeatedUnderOneOperationIdWithADifferentLeaseIsAConflict() { // Started first: only an executing operation's lease is renewed (IdempotencyStoreContract). - IdempotencyOwner executing = claimAndStart("claim-renew-conflict", "start-renew-conflict"); + IdempotencyOwner executing = claimAndStart("claim-renew-conflict"); IdempotencyRenewOutcome first = transactions .execute( ignored -> - store.renew(executing, Duration.ofSeconds(30), new OperationId("renew-1"))) + store.renew(executing, Duration.ofSeconds(30), executing.claimOperationId())) .outcome(); IdempotencyRenewOutcome same = transactions .execute( ignored -> - store.renew(executing, Duration.ofSeconds(30), new OperationId("renew-1"))) + store.renew(executing, Duration.ofSeconds(30), executing.claimOperationId())) .outcome(); IdempotencyRenewOutcome different = transactions .execute( ignored -> - store.renew(executing, Duration.ofMinutes(45), new OperationId("renew-1"))) + store.renew(executing, Duration.ofMinutes(45), executing.claimOperationId())) .outcome(); assertThat(first).isEqualTo(IdempotencyRenewOutcome.RENEWED); @@ -488,10 +488,12 @@ class PostgreSqlIdempotencyIntegrationTest { .owner()); } - private static IdempotencyOwner claimAndStart(String claimOperation, String startOperation) { + // Every transition names the operation its record was claimed under; these tests gave each + // transition an id of its own, which the store now refuses (owner decision 2026-11-06). + private static IdempotencyOwner claimAndStart(String claimOperation) { IdempotencyOwner claimed = claim(claimOperation); return transactions - .execute(ignored -> store.markExecutionStarted(claimed, new OperationId(startOperation))) + .execute(ignored -> store.markExecutionStarted(claimed, claimed.claimOperationId())) .owner() .orElseThrow(); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java index c0a730d7..2f3b0e53 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlMigrationLockWaitIntegrationTest.java @@ -53,6 +53,13 @@ import org.springframework.jdbc.core.JdbcTemplate; * LockWaitMigrationInspectorTest}, which pins Flyway's own patterns in the pull request's {@code * ci} (round 6, RR6-03-03). * + *

Two more cases pin what the documents say about the edges of that list (round 7, RR7-03-02 and + * RR7-03-05): Flyway runs {@code REINDEX INDEX|TABLE ... CONCURRENTLY} in the transaction, where + * PostgreSQL refuses it, but {@code REINDEX SCHEMA|DATABASE ... CONCURRENTLY} outside one on its + * own; and a {@code VACUUM FULL} or {@code REINDEX SCHEMA} that a {@code .sql.conf} keeps in the + * transaction ({@code executeInTransaction=true}) is refused by PostgreSQL at deploy, and by the + * inspector before it. + * *

The migrations run under the template's Flyway settings ({@code FlywaySchemaPolicy}), whose * PostgreSQL lock is held for the session rather than in an open transaction (RR6-03-01): the bound * is shown under the lock the deploy actually takes. @@ -231,15 +238,26 @@ class PostgreSqlMigrationLockWaitIntegrationTest { } } - @Test + @ParameterizedTest + @CsvSource( + delimiter = '|', + value = { + "REINDEX TABLE CONCURRENTLY probe | refused 25001", + "REINDEX INDEX CONCURRENTLY probe_pkey | refused 25001", + "REINDEX (CONCURRENTLY) TABLE probe | refused 25001", + "REINDEX SCHEMA CONCURRENTLY public | applied", + "REINDEX DATABASE CONCURRENTLY | applied" + }) @DisplayName( - "Flyway는 REINDEX TABLE CONCURRENTLY를 트랜잭션 안에서 돌려 PostgreSQL이 거부하므로 executeInTransaction=false가 필요하다") - void flywayRunsReindexConcurrentlyInATransactionWherePostgresqlRefusesIt(@TempDir Path stream) - throws Exception { - try (HikariDataSource database = postgres.createDatabase(databaseName())) { + "Flyway는 REINDEX INDEX·TABLE … CONCURRENTLY를 트랜잭션 안에서 돌려 PostgreSQL이 거부하고, REINDEX SCHEMA·DATABASE … CONCURRENTLY는 스스로 트랜잭션 밖에서 돌린다") + void flywayRunsOnlyReindexIndexOrTableConcurrentlyInATransactionWherePostgresqlRefusesIt( + String statement, String expected, @TempDir Path stream) throws Exception { + String name = databaseName(); + try (HikariDataSource database = postgres.createDatabase(name)) { // given new JdbcTemplate(database).execute("CREATE TABLE probe (id INT PRIMARY KEY)"); - Files.writeString(stream.resolve("V1__reindex.sql"), "REINDEX TABLE CONCURRENTLY probe;\n"); + Files.writeString( + stream.resolve("V1__reindex.sql"), statement.replace("", name) + ";\n"); Flyway flyway = FlywaySchemaPolicy.configure() .dataSource(database) @@ -250,9 +268,47 @@ class PostgreSqlMigrationLockWaitIntegrationTest { // when Throwable thrown = catchThrowable(flyway::migrate); + String outcome = + thrown == null ? "applied" : "refused " + new Attempt(thrown, Duration.ZERO).sqlState(); // then - assertThat(new Attempt(thrown, Duration.ZERO).sqlState()).isEqualTo(ACTIVE_SQL_TRANSACTION); + assertThat(outcome).as("%s (%s)", statement, thrown).isEqualTo(expected); + } + } + + @ParameterizedTest + @ValueSource(strings = {"VACUUM FULL probe", "REINDEX SCHEMA public"}) + @DisplayName( + "executeInTransaction=true로 트랜잭션 안에 둔 VACUUM FULL·REINDEX SCHEMA는 PostgreSQL이 배포 때 거부하고 검사기도 거부한다") + void aLockingStatementAConfigurationKeepsInATransactionIsRefusedByPostgresqlAndTheInspector( + String statement, @TempDir Path stream) throws Exception { + try (HikariDataSource database = postgres.createDatabase(databaseName())) { + // given + new JdbcTemplate(database).execute("CREATE TABLE probe (id INT PRIMARY KEY)"); + Path script = + Files.writeString( + stream.resolve("V1__probe.sql"), + "SET LOCAL lock_timeout = '5s';\n" + statement + ";\n"); + Files.writeString(stream.resolve("V1__probe.sql.conf"), "executeInTransaction=true\n"); + Flyway flyway = + FlywaySchemaPolicy.configure() + .dataSource(database) + .locations("filesystem:" + stream.toAbsolutePath()) + .baselineOnMigrate(true) + .baselineVersion("0") + .load(); + + // when + Throwable thrown = catchThrowable(flyway::migrate); + List named = new LockWaitMigrationInspector().unboundedLockingStatements(script); + + // then + assertThat( + List.of( + String.valueOf(new Attempt(thrown, Duration.ZERO).sqlState()), + named.toString().contains("cannot run in a transaction"))) + .as("%s: Flyway %s, inspector %s", statement, thrown, named) + .containsExactly(ACTIVE_SQL_TRANSACTION, true); } } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java index d5b7f9f9..bcf1ace4 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxDispositionRunbookIntegrationTest.java @@ -41,13 +41,13 @@ class PostgreSqlOutboxDispositionRunbookIntegrationTest { private static final Duration IN_FLIGHT_TIMEOUT = Duration.ofMinutes(5); private static PostgreSqlReadinessSupport postgres; - private static OutboxRunbookSql deadLetterRunbook; - private static OutboxRunbookSql publishFailedRunbook; + private static RunbookSql deadLetterRunbook; + private static RunbookSql publishFailedRunbook; @BeforeAll static void setup() throws IOException { - deadLetterRunbook = OutboxRunbookSql.fromSystemProperty("outbox.runbook"); - publishFailedRunbook = OutboxRunbookSql.fromSystemProperty("outbox.publish-failed.runbook"); + deadLetterRunbook = RunbookSql.fromSystemProperty("outbox.runbook"); + publishFailedRunbook = RunbookSql.fromSystemProperty("outbox.publish-failed.runbook"); postgres = PostgreSqlReadinessSupport.start(); } diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java index 09a8381c..94f7a156 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/PostgreSqlOutboxOrderKeyRunbookIntegrationTest.java @@ -47,13 +47,13 @@ class PostgreSqlOutboxOrderKeyRunbookIntegrationTest { private static final Instant OCCURRED = Instant.parse("2026-11-01T00:00:00Z"); private static PostgreSqlReadinessSupport postgres; - private static OutboxRunbookSql runbook; + private static RunbookSql runbook; private static String duplicateCheck; private static String removePublishedDuplicates; @BeforeAll static void setup() throws IOException { - runbook = OutboxRunbookSql.fromSystemProperty("outbox.runbook"); + runbook = RunbookSql.fromSystemProperty("outbox.runbook"); duplicateCheck = runbook.block("v21-duplicate-order-keys"); removePublishedDuplicates = runbook.block("v21-remove-published-duplicates"); postgres = PostgreSqlReadinessSupport.start(); diff --git a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/RunbookSql.java similarity index 78% rename from src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java rename to src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/RunbookSql.java index 395ffcc9..ba1855cd 100644 --- a/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/OutboxRunbookSql.java +++ b/src/adapter/outbound/persistence-jpa/src/postgresqlIntegrationTest/java/dev/caskeleton/adapter/outbound/persistence/readiness/RunbookSql.java @@ -7,18 +7,21 @@ import java.nio.file.Path; import java.util.Map; /** - * The SQL an outbox runbook gives an operator, read out of the runbook itself. + * The SQL a runbook gives an operator, read out of the runbook itself. Every lane that runs a + * runbook's SQL reads it through this one class: so far the outbox runbooks and the migration + * runbook's recovery of a failed concurrent index migration (re-review 2026-11-03 round 8, + * RR8-03-03: the class kept an outbox name after the migration runbook began to use it). * *

A runbook block is marked {@code } and followed by a {@code sql} * fence. The lanes that run these blocks against real PostgreSQL read them from the document rather * than keep a copy, so editing a block in the runbook is what the lane tests: a copy would pass * while the document an operator follows is wrong. */ -final class OutboxRunbookSql { +final class RunbookSql { private final String runbook; - private OutboxRunbookSql(String runbook) { + private RunbookSql(String runbook) { this.runbook = runbook; } @@ -29,13 +32,13 @@ final class OutboxRunbookSql { * @return the runbook's SQL blocks * @throws IOException when the file cannot be read */ - static OutboxRunbookSql fromSystemProperty(String property) throws IOException { + static RunbookSql fromSystemProperty(String property) throws IOException { String path = System.getProperty(property); if (path == null || path.isBlank()) { throw new IllegalStateException( "system property " + property + " must name the runbook this lane runs"); } - return new OutboxRunbookSql(Files.readString(Path.of(path), StandardCharsets.UTF_8)); + return new RunbookSql(Files.readString(Path.of(path), StandardCharsets.UTF_8)); } /** @@ -48,7 +51,7 @@ final class OutboxRunbookSql { String marker = ""; int at = runbook.indexOf(marker); if (at < 0) { - throw new IllegalStateException("the outbox runbook has no SQL block marked " + id); + throw new IllegalStateException("the runbook has no SQL block marked " + id); } int open = runbook.indexOf("```sql\n", at); int close = runbook.indexOf("\n```", open + 1); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java index 57e0d4a6..fad7c2cd 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/CandidateAdapterCompositionTest.java @@ -10,12 +10,11 @@ import org.springframework.stereotype.Repository; * A candidate implementation nobody selected must not be composed. * *

{@code CaSkeletonApplication} excludes {@code dev.caskeleton.adapter.outbound.persistence..*} - * from its component scan, but {@code SamplePortfolioApplication} scans all of {@code - * dev.caskeleton}. So a {@code @Repository} on a PostgreSQL-only adapter becomes a bean there — - * including under H2, which has no migration tree at all, and in a database that never applied the - * optional stream the adapter reads. The bean exists and its tables do not: the failure surfaces as - * vendor-specific SQL against a missing relation, or as a boot failure under {@code - * ddl-auto=validate}. + * from its component scan, but a service application may scan all of {@code dev.caskeleton}. So a + * {@code @Repository} on a PostgreSQL-only adapter becomes a bean there — including under H2, which + * has no migration tree at all, and in a database that never applied the optional stream the + * adapter reads. The bean exists and its tables do not: the failure surfaces as vendor-specific SQL + * against a missing relation, or as a boot failure under {@code ddl-auto=validate}. */ class CandidateAdapterCompositionTest { diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java index 83cd9ab0..018843b1 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/migration/MigrationTrees.java @@ -40,7 +40,7 @@ final class MigrationTrees { Path.of("../persistence-notification/src/main/resources/db/migration"), Path.of("../persistence-fileserver/src/main/resources/db/migration"), Path.of( - "../../../messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration")); + "../../../platforms/messaging/messaging-reliability-jdbc-postgresql/src/main/resources/db/migration")); private MigrationTrees() {} diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaReadinessRegistryTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaReadinessRegistryTest.java index abb795df..b9451b34 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaReadinessRegistryTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/JpaReadinessRegistryTest.java @@ -20,7 +20,8 @@ import tools.jackson.databind.JsonNode; import tools.jackson.databind.json.JsonMapper; /** - * The JPA readiness cards ({@code src/config/jpa/readiness-cards.yaml}) against the lanes and tests + * The JPA readiness cards ({@code + * src/adapter/outbound/persistence-jpa/release/readiness-cards.yaml}) against the lanes and tests * they name. * *

This replaced the build-tools {@code ca.jpa-qualification}/{@code ca.jpa-evidence} plugins @@ -33,8 +34,8 @@ import tools.jackson.databind.json.JsonMapper; class JpaReadinessRegistryTest { private static final Path SOURCE_ROOT = Path.of("../../..").toAbsolutePath().normalize(); - private static final Path REGISTRY = SOURCE_ROOT.resolve("config/jpa/readiness-cards.yaml"); private static final Path LEAF = SOURCE_ROOT.resolve("adapter/outbound/persistence-jpa"); + private static final Path REGISTRY = LEAF.resolve("release/readiness-cards.yaml"); private static final String LEAF_PATH = ":adapter:outbound:persistence-jpa:"; private static final Set STATES = Set.of("selected", "implemented-candidate", "not-implemented"); diff --git a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java index 4cc49c68..8f2cf4ad 100644 --- a/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java +++ b/src/adapter/outbound/persistence-jpa/src/test/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspectorTest.java @@ -381,6 +381,29 @@ class LockWaitMigrationInspectorTest { assertThat(unbounded).isEmpty(); } + @ParameterizedTest + @ValueSource( + strings = { + "SET LOCAL lock_timeout = '5s';\nVACUUM FULL outbox_event;", + "SET LOCAL lock_timeout = '5s';\nREINDEX SCHEMA public;" + }) + @DisplayName("executeInTransaction=true 설정이 있어도 트랜잭션 안에서 돌 수 없는 잠금 문장은 마이그레이션에 두지 말라는 이유로 거부된다") + void aLockingStatementThatCannotRunInATransactionIsRefusedWhateverTheConfigurationSays( + String sql, @TempDir Path stream) throws IOException { + // given + Path script = Files.writeString(stream.resolve("V99__change.sql"), sql); + Files.writeString(stream.resolve("V99__change.sql.conf"), "executeInTransaction=true\n"); + + // when + List unbounded = inspector.unboundedLockingStatements(script); + + // then + assertThat(unbounded) + .singleElement(STRING) + .contains("cannot run in a transaction") + .contains("executeInTransaction=true"); + } + /** Every static {@link Pattern} the class declares, by field name. */ private static Map staticPatterns(Class type) throws IllegalAccessException { Map patterns = new TreeMap<>(); diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java index b5615b69..f1a0f843 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/ConcurrentIndexMigrationInspector.java @@ -10,19 +10,37 @@ import java.util.regex.Pattern; * *

PostgreSQL refuses {@code CREATE INDEX CONCURRENTLY}, {@code DROP INDEX CONCURRENTLY} and * {@code REINDEX ... CONCURRENTLY} inside a transaction block. Flyway 11 runs a script outside its - * transaction on its own when it holds {@code CREATE} or {@code DROP INDEX CONCURRENTLY}, but not - * {@code REINDEX ... CONCURRENTLY}: that one Flyway runs in the transaction, and PostgreSQL refuses - * it at deploy. So {@link #validate} wants {@code executeInTransaction=false} beside every - * concurrent statement, whether Flyway would detect it or not. Next to any other statement, one - * Flyway runs outside a transaction makes Flyway refuse the whole script before it runs any of it - * (its default {@code mixed=false}); {@link #requireIsolatedStatement} wants the statement alone so - * that a failed build is recovered by dropping one invalid index. + * transaction on its own when it holds {@code CREATE} or {@code DROP INDEX CONCURRENTLY}, or {@code + * REINDEX SCHEMA|DATABASE} with or without {@code CONCURRENTLY}. It runs {@code REINDEX INDEX|TABLE + * ... CONCURRENTLY} — the option-list form {@code REINDEX (CONCURRENTLY) TABLE} included — in the + * transaction, and PostgreSQL refuses it at deploy ({@code + * postgresqlMigrationLockWaitIntegrationTest} shows the five forms; re-review 2026-11-03 round 7, + * RR7-03-02). So {@link #validate} wants {@code executeInTransaction=false} beside every concurrent + * statement, whether Flyway would detect it or not. + * + *

{@link #requireIsolatedStatement} wants the statement alone in its migration. Next to another + * statement it is refused by Flyway before any of the script runs when nothing configures the file + * (Flyway's default {@code mixed=false}); with the {@code executeInTransaction=false} that {@link + * #validate} asks for, Flyway runs and commits each statement on its own, and a failed build leaves + * the statements before it applied (round 7, RR7-03-04). Alone, a failed statement leaves an + * invalid index and its version's failed history row, which Flyway refuses the next deploy over + * until the row is gone: {@code docs/runbooks/migration-failed.md} ("Recover a failed concurrent + * index migration") deletes that one row, after dropping the index a failed build or rebuild left. + * A failed {@code DROP INDEX CONCURRENTLY} leaves invalid the index it was dropping, and the deploy + * after the row is gone drops it ({@code postgresqlConcurrentIndexMigrationIntegrationTest} runs + * all three; round 7, RR7-03-03; round 8, RR8-03-01). * *

Outside a transaction, {@code CREATE INDEX CONCURRENTLY} and {@code REINDEX ... CONCURRENTLY} * still wait for every transaction older than themselves. They finish because the template's Flyway * holds its PostgreSQL lock for the session ({@code FlywaySchemaPolicy.configure()}): under * Flyway's default the lock's own open transaction is one of those, and the deploy never ends * (re-review 2026-11-03 round 6, RR6-03-01 and RR6-03-05). + * + *

The gRPC ledger's lane uses it too. It lives in the optional build, which cannot depend on + * this testkit, so {@code grpc-operation-ledger-jpa} compiles this file and {@link + * MigrationResource} from here into its integration-test sources at build time (its {@code + * build.gradle}, {@code sharedMigrationFileSources}; round 7, RR7-03-01). Hence the rule for both + * files: the JDK only, nothing else from this testkit. */ public final class ConcurrentIndexMigrationInspector { @@ -53,8 +71,8 @@ public final class ConcurrentIndexMigrationInspector { throw new IllegalStateException( migration.name() + " must set executeInTransaction=false: PostgreSQL refuses a concurrent index" - + " statement inside a transaction block, and Flyway runs REINDEX ... CONCURRENTLY in" - + " one unless the migration says otherwise"); + + " statement inside a transaction block, and Flyway runs REINDEX INDEX|TABLE ..." + + " CONCURRENTLY in one unless the migration says otherwise"); } /** Whether the script contains a statement PostgreSQL forbids inside a transaction. */ @@ -68,9 +86,12 @@ public final class ConcurrentIndexMigrationInspector { /** * Fails when a concurrent-index migration also contains other statements. * - *

A concurrent index build can fail and leave an invalid index behind. Recovering from that is - * a single {@code DROP INDEX} when the migration did nothing else, and a manual reconstruction of - * partial state when it did. + *

A concurrent index statement can fail and leave an invalid index and its version's failed + * history row behind. When the migration did nothing else, recovering is the runbook's few + * statements: drop the index a failed build left, delete that one failed row, deploy again + * ({@code docs/runbooks/migration-failed.md}, "Recover a failed concurrent index migration"). + * When it did more, Flyway ran the file outside a transaction and has committed the statements + * before the failed one, and that partial state has to be reconstructed by hand. */ public void requireIsolatedStatement(MigrationResource migration) { Objects.requireNonNull(migration, "migration"); @@ -88,9 +109,11 @@ public final class ConcurrentIndexMigrationInspector { if (statements > 1L) { throw new IllegalStateException( migration.name() - + " mixes a concurrent index statement with other statements; a failed concurrent" - + " build must be recoverable by dropping one invalid index, which requires the" - + " migration to contain nothing else"); + + " mixes a concurrent index statement with other statements; outside a" + + " transaction Flyway commits each of them on its own, so a failed build leaves the" + + " others applied. Alone, a failed statement is recovered by deleting its version's" + + " failed history row (docs/runbooks/migration-failed.md, \"Recover a failed" + + " concurrent index migration\")"); } } } diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java index 19a4bca5..3752c1fd 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/LockWaitMigrationInspector.java @@ -61,7 +61,9 @@ import java.util.regex.Pattern; * that holds any other statement is refused at deploy; with {@code mixed=true} it runs, unbounded. * A locking statement that cannot run in a transaction itself ({@code VACUUM FULL}, a * non-concurrent {@code REINDEX SCHEMA}) can never be bounded and is refused with the advice to - * keep it out of migrations (re-review 2026-11-03 round 4, RR4-02-01). The check assumes Flyway's + * keep it out of migrations (re-review 2026-11-03 round 4, RR4-02-01) — whatever the {@code + * .sql.conf} says: {@code executeInTransaction=true} keeps the {@code SET LOCAL} in force, but only + * for PostgreSQL to refuse the statement at deploy (round 7, RR7-03-05). The check assumes Flyway's * defaults, as the template runs it: {@code executeInTransaction=true} and {@code mixed=false} for * the whole run. */ @@ -147,11 +149,11 @@ public final class LockWaitMigrationInspector { * The statements Flyway runs outside a transaction on PostgreSQL 12 and later, as Flyway 11's * {@code PostgreSQLParser#detectCanExecuteInTransaction} lists them: the statement's leading * words outside parentheses, lower case and one space apart, match one of these in full. {@code - * ALTER TYPE ... ADD VALUE} is on Flyway's list only below PostgreSQL 12. {@code REINDEX TABLE - * CONCURRENTLY} is not on it: Flyway runs it in the transaction and PostgreSQL refuses it there. - * {@code LockWaitMigrationInspectorTest} pins Flyway's own patterns, read from {@code - * PostgreSQLParser}, so a Flyway upgrade that adds a statement or changes one fails the pull - * request's {@code ci} until this copy follows. {@code + * ALTER TYPE ... ADD VALUE} is on Flyway's list only below PostgreSQL 12. {@code REINDEX + * INDEX|TABLE CONCURRENTLY} is not on it: Flyway runs it in the transaction and PostgreSQL + * refuses it there. {@code LockWaitMigrationInspectorTest} pins Flyway's own patterns, read from + * {@code PostgreSQLParser}, so a Flyway upgrade that adds a statement or changes one fails the + * pull request's {@code ci} until this copy follows. {@code * postgresqlMigrationLockWaitIntegrationTest} compares this copy with Flyway on real PostgreSQL * for the statements it lists, and only those (re-review 2026-11-03 round 6, RR6-03-03). */ @@ -254,14 +256,15 @@ public final class LockWaitMigrationInspector { for (Pattern pattern : LOCKING) { Matcher statement = pattern.matcher(text); while (statement.find()) { + boolean cannotRunInATransaction = within(statement.start(), outside); Map.Entry setting = bounds.lowerEntry(statement.start()); - boolean bounded = setting != null && setting.getValue(); + boolean bounded = !cannotRunInATransaction && setting != null && setting.getValue(); if (!bounded && !createdEarlier(statement, createdAt)) { String named = statement.group().trim(); found.add( new Located( statement.start(), - inTransaction + inTransaction && !cannotRunInATransaction ? named : named + " (" + whyUnbounded(statement.start(), outside, configured) + ")")); } @@ -274,14 +277,17 @@ public final class LockWaitMigrationInspector { } /** - * Why a locking statement at {@code at} has no bound in a script that runs outside a transaction. + * Why a locking statement at {@code at} has no bound: it cannot run in a transaction itself, or + * the script runs outside one. */ private static String whyUnbounded(int at, List outside, Configured configured) { - for (Statement statement : outside) { - if (statement.start() <= at && at < statement.end()) { - return "cannot run in a transaction, so no SET LOCAL can bound its wait: keep it out of" - + " migrations and run it by hand as an operations step, outside deploys"; - } + if (within(at, outside)) { + return "cannot run in a transaction, so no SET LOCAL can bound its wait" + + (configured == Configured.IN_A_TRANSACTION + ? " (executeInTransaction=true only makes PostgreSQL refuse it at deploy)" + : "") + + ": keep it out of migrations and run it by hand as an operations step, outside" + + " deploys"; } if (configured == Configured.OUTSIDE_A_TRANSACTION) { return "executeInTransaction=false: SET LOCAL does nothing outside a transaction; move it to" @@ -294,6 +300,16 @@ public final class LockWaitMigrationInspector { + " in a migration of its own"; } + /** Whether the position {@code at} is inside one of the statements Flyway runs outside one. */ + private static boolean within(int at, List outside) { + for (Statement statement : outside) { + if (statement.start() <= at && at < statement.end()) { + return true; + } + } + return false; + } + /** * The statements Flyway runs outside a transaction, found the way Flyway finds them: each * statement's words outside parentheses, up to {@link #FLYWAY_DETECTION_WORDS} words in all, diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java index 614452af..6251b391 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/migration/MigrationResource.java @@ -5,6 +5,9 @@ import java.util.Objects; /** * One migration script as the inspector sees it (design §32). * + *

The gRPC ledger's lane in the optional build compiles this file with {@link + * ConcurrentIndexMigrationInspector} (see there), so it keeps to the JDK only. + * * @param name the versioned script name, e.g. {@code V42__order_index.sql} * @param sql the script body */ diff --git a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/release/JpaReleaseManifest.java b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/release/JpaReleaseManifest.java index e113da59..cba4d2dc 100644 --- a/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/release/JpaReleaseManifest.java +++ b/src/adapter/outbound/persistence-jpa/src/testFixtures/java/dev/caskeleton/adapter/outbound/persistence/testkit/release/JpaReleaseManifest.java @@ -43,7 +43,8 @@ public record JpaReleaseManifest( String providerBaseline) { /** Where the registry lives, relative to the repository's {@code src} directory. */ - public static final String REGISTRY_PATH = "config/jpa/release-registry.json"; + public static final String REGISTRY_PATH = + "adapter/outbound/persistence-jpa/release/release-registry.json"; /** * The registry, located by walking up from the working directory. diff --git a/src/adapter/outbound/persistence-mongo/CLAUDE.md b/src/adapter/outbound/persistence-mongo/CLAUDE.md index 03320813..3936e48c 100644 --- a/src/adapter/outbound/persistence-mongo/CLAUDE.md +++ b/src/adapter/outbound/persistence-mongo/CLAUDE.md @@ -50,8 +50,8 @@ design package's assumed module layout onto this leaf lives in ## Allowed - Two project dependencies. `shared-contract` for the `Sha256` and `HmacSha256` helpers (tenant - observable key, admin command digest, credential fingerprint, keyset cursor tag — review - 2026-11-01 01-11; `MongoDigestOutputTest` pins the outputs). `application-core`, for + observable key, admin command digest, credential fingerprint, keyset cursor tag; + `MongoDigestOutputTest` pins the outputs). `application-core`, for `SecretSourcePort` only. The registry entry's `allowed_dependencies` is `["application-core", "shared-contract"]`, matching what the build actually uses; the bridge in `MongoProfileClientSettingsAutoConfiguration` resolves a typed profile's `uri-secret` @@ -64,15 +64,14 @@ design package's assumed module layout onto this leaf lives in carry it. The leaf is imperative only: the reactive twin (`reactive/**`, reactive transactions/sessions), the change-stream consumer and the change-stream-to-messaging bridge were removed on 2026-09-25 (see `docs/capability-status.md`), so the leaf carries neither the reactive - starter nor the reactive-streams driver (`MongoReactiveDriverAbsenceTest`). `sample-portfolio` - does not carry it. + starter nor the reactive-streams driver (`MongoReactiveDriverAbsenceTest`). - External includes the (sync) Mongo starter, spring-boot-autoconfigure, spring-boot-health, micrometer-core, slf4j-api, and the configuration processor. Jackson annotations are compile-only because Boot Health carries Jackson annotations while runtime JSON serialization remains application-owned. Versions come from the shared Spring Boot BOM; never pin the driver directly. - Test-only: ArchUnit, Testcontainers (`mongodb`, `toxiproxy`). ## Forbidden -- Inbound adapters, sibling outbound adapters, `app-bootstrap`, `sample-portfolio` (ArchUnit +- Inbound adapters, sibling outbound adapters, `app-bootstrap` (ArchUnit `OUTBOUND_ADAPTERS_*` family rules). - Shipping placeholder `Example*` document, repository, record, or adapter types in production. - Adding idempotency/outbox/lock on Mongo without a separately approved contract. @@ -110,7 +109,7 @@ The architecture rule catalogue (`…mongo.architecture`) is in the **testkit** production: it is ArchUnit input, and shipping it put rule text on every consumer's runtime classpath. Release gating is testkit-only for the same reason and is one implementation, not two: `…mongo.testkit.release` reads the JUnit XML a lane wrote and is what -`scripts/verify-mongodb-platform.sh` and `src/config/mongodb/release-contracts.json` drive. A second +`scripts/verify-mongodb-platform.sh` and `src/adapter/outbound/persistence-mongo/release/release-contracts.json` drive. A second pair on the production classpath — a hand-built set of category names and a gate that checked it — had no caller outside its own test and no source of truth behind the categories; it is gone rather than moved. diff --git a/src/adapter/outbound/persistence-mongo/README.md b/src/adapter/outbound/persistence-mongo/README.md index b2e8303a..105f6310 100644 --- a/src/adapter/outbound/persistence-mongo/README.md +++ b/src/adapter/outbound/persistence-mongo/README.md @@ -5,7 +5,7 @@ document/repository/mapper와 application 또는 domain port 구현을 추가할 수 있는 구성 경계와 플랫폼 정책을 제공한다. -설계 원본은 `mongodb-superpowers-package/docs/superpowers/specs/`이고, 이 저장소로 어떻게 +설계 원본은 `docs/design/`이고, 이 저장소로 어떻게 매핑했는지는 [docs/mongodb/repository-adaptation.md](../../../../docs/mongodb/repository-adaptation.md)가 단일 기록이다. diff --git a/src/adapter/outbound/persistence-mongo/build.gradle b/src/adapter/outbound/persistence-mongo/build.gradle index e32912e3..c894cb2a 100644 --- a/src/adapter/outbound/persistence-mongo/build.gradle +++ b/src/adapter/outbound/persistence-mongo/build.gradle @@ -8,7 +8,7 @@ plugins { // Shared test code as a Gradle test-fixtures variant — ADR-BUILD-001. Applied here rather than // from the root, the way the GraphQL leaf does: only a leaf that has shared test code needs it. // MongoDB Document Persistence Platform leaf — see -// docs/superpowers/specs/2026-08-11-mongodb-document-persistence-platform-design.md (design package) +// docs/design/2026-08-11-mongodb-document-persistence-platform-design.md (design package) // and docs/mongodb/repository-adaptation.md (how the design's 19 stable + 12 advanced library // modules map here). // @@ -239,9 +239,8 @@ strictTestLanes { providers.gradleProperty('mongoCompatibilityImage').orElse(testContainerImages['mongo-7']).get() systemProperty 'mongodb.toxiproxy.image', providers.gradleProperty('mongoToxiproxyImage').orElse(testContainerImages['toxiproxy']).get() - // Assertions on by default: a performance gate without bounds is only a report. - systemProperty 'performance.assertions.enabled', - providers.gradleProperty('performance.assertions.enabled').orElse('true').get() + // No assertions switch: the strict-lane convention asserts a performance lane's bounds in + // every run, because a performance gate without bounds is only a report. } } @@ -258,7 +257,7 @@ tasks.named('check') { strictTestLanes { lane('mongoDocumentContractTest') { tag = 'document-contract' - description = 'Holds the Mongo lane tags to config/mongodb/release-contracts.json.' + description = 'Holds the Mongo lane tags to release/release-contracts.json.' rejectSkipped = true mainStage() } diff --git a/src/config/mongodb/release-contracts.json b/src/adapter/outbound/persistence-mongo/release/release-contracts.json similarity index 100% rename from src/config/mongodb/release-contracts.json rename to src/adapter/outbound/persistence-mongo/release/release-contracts.json diff --git a/src/adapter/outbound/persistence-mongo/src/mongoPerformanceTest/java/dev/caskeleton/adapter/outbound/mongo/performance/MongoResourceBudgetLaneTest.java b/src/adapter/outbound/persistence-mongo/src/mongoPerformanceTest/java/dev/caskeleton/adapter/outbound/mongo/performance/MongoResourceBudgetLaneTest.java index 969d1690..15441d34 100644 --- a/src/adapter/outbound/persistence-mongo/src/mongoPerformanceTest/java/dev/caskeleton/adapter/outbound/mongo/performance/MongoResourceBudgetLaneTest.java +++ b/src/adapter/outbound/persistence-mongo/src/mongoPerformanceTest/java/dev/caskeleton/adapter/outbound/mongo/performance/MongoResourceBudgetLaneTest.java @@ -27,16 +27,16 @@ import org.junit.jupiter.api.Test; * it is the same on an idle machine and a busy one, and it is what actually predicts the query * falling over as the collection grows. * - *

Timing bounds are asserted only when {@code -Pperformance.assertions.enabled=true}, for the - * same reason. The ratio bound is always asserted. + *

The timing bounds are asserted too, in every run, but the gate's bounds are generous for the + * same reason: they catch a query that falls over, not one that was slower than last time. They + * used to sit behind {@code performance.assertions.enabled}, which the build defaulted to on and + * this class to off, so a run outside Gradle skipped them; the strict-lane convention now asserts a + * performance lane's bounds in every run. */ class MongoResourceBudgetLaneTest { private static final int DOCUMENT_COUNT = 5_000; - private static final boolean TIMING_ASSERTIONS = - Boolean.parseBoolean(System.getProperty("performance.assertions.enabled", "false")); - private static MongoSingleReplicaSetContainer container; private static MongoClient client; @@ -75,18 +75,16 @@ class MongoResourceBudgetLaneTest { @Test void anIndexedQueryStaysInsideTheResourceBudget() { MongoResourceBudgetReport report = measure(new Document("status", "PENDING"), "ix_status"); + // The measured values, so a passing run is a recorded number and not only a green line. + System.out.println("[mongo-performance] indexed query " + report.asArtifact()); assertThat(report.documentsReturned()).isEqualTo(DOCUMENT_COUNT / 50); assertThat(report.examinedToReturnedRatio()) .as("an index seek examines about what it returns") .isLessThanOrEqualTo(MongoPerformanceGate.standard().maximumExaminedToReturnedRatio()); assertThat(MongoPerformanceGate.standard().violations(report)) - .filteredOn(violation -> violation.startsWith("examined/returned")) + .as("an indexed query stays inside every bound of the standard gate") .isEmpty(); - - if (TIMING_ASSERTIONS) { - assertThat(MongoPerformanceGate.standard().passes(report)).isTrue(); - } } @Test diff --git a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoTestLaneContractTest.java b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoTestLaneContractTest.java index d9854111..595b211b 100644 --- a/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoTestLaneContractTest.java +++ b/src/adapter/outbound/persistence-mongo/src/test/java/dev/caskeleton/adapter/outbound/mongo/architecture/MongoTestLaneContractTest.java @@ -30,8 +30,7 @@ import tools.jackson.databind.json.JsonMapper; class MongoTestLaneContractTest { private static final Path INTEGRATION_SOURCES = Path.of("src/mongoIntegrationTest/java"); - private static final Path RELEASE_CONTRACTS = - Path.of("../../../config/mongodb/release-contracts.json"); + private static final Path RELEASE_CONTRACTS = Path.of("release/release-contracts.json"); private static final Set DOCKER_LANE_TAGS = Set.of( "mongodb-replicaset", diff --git a/src/adapter/outbound/persistence-notification/CLAUDE.md b/src/adapter/outbound/persistence-notification/CLAUDE.md index 0939743d..156c57c2 100644 --- a/src/adapter/outbound/persistence-notification/CLAUDE.md +++ b/src/adapter/outbound/persistence-notification/CLAUDE.md @@ -6,7 +6,7 @@ `src/config/architecture/modules.json`. - Focused test: `./gradlew :adapter:outbound:persistence-notification:test --console=plain`. - Package root: `dev.caskeleton.adapter.outbound.persistence.notification`. The package rule is - the one `persistence-fileserver` uses, so both capability leaves read the same way (review 04-16): + the one `persistence-fileserver` uses, so both capability leaves read the same way: - `platform.entity` — JPA rows only. - `platform.repository` — Spring Data interfaces and the SQL text they run (`RecipientClaimSql`). - `platform` — the store adapters (`Jpa*`, `Jdbc*`, the inbox's `JpaNotificationInbox` and its @@ -17,7 +17,7 @@ package; an entity never leaves the leaf (the ports carry records). Visibility no longer says so, so a rule does: `JpaArchitectureRules.entitiesAreUsedOnlyInsideTheirLeaf`, run over the production graph by `JpaProductionArchitectureTest` (app-bootstrap `architectureTest`) for this leaf and - `persistence-fileserver` (review RR-03-09). + `persistence-fileserver`. ## Where the tests are @@ -37,7 +37,7 @@ without a contract (the serving-state read model, consent, inbox), and why, are ## Rules - **Every write joins the caller's transaction.** A store write starts with - `CallerTransaction.require("")`; the use case owns the transaction (owner decision 33). + `CallerTransaction.require("")`; the use case owns the transaction (owner decision 2026-09-25). - **Migrations** live in `src/main/resources/db/migration/jpa/notification-platform` and run as their own Flyway stream (`NotificationSchemaStream`, history table `flyway_jpa_notification_history`). An applied file is never edited: add the next `V__`, pin diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisTopologyEndpoint.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisTopologyEndpoint.java index 00307b0f..7a387951 100644 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisTopologyEndpoint.java +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/RedisTopologyEndpoint.java @@ -165,7 +165,7 @@ public record RedisTopologyEndpoint( * *

Deliberately credential-free, and that is not an oversight. A sentinel is a different * process with its own ACL: it does not load the data nodes' {@code aclfile}, so the accounts in - * {@code infra/redis-sdk/acl} do not exist there and presenting one gets {@code WRONGPASS}. The + * {@code compose/redis/acl} do not exist there and presenting one gets {@code WRONGPASS}. The * {@code sentinel auth-user} / {@code auth-pass} directives in the lane are about how the * sentinel authenticates to the monitored primary, which is a different direction * entirely. Securing the sentinels themselves would mean giving them their own ACL file, and the diff --git a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java index b27a92ab..bd44bf14 100644 --- a/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java +++ b/src/adapter/outbound/redis-runtime/src/testFixtures/java/dev/caskeleton/adapter/outbound/cache/redis/runtime/command/InMemorySemanticRedisCommands.java @@ -204,6 +204,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand setField(rendered, "fp", fingerprint); setField(rendered, "leaseUntil", Long.toString(nowMillis + leaseTtl)); setField(rendered, "afterLease", afterLease); + setField(rendered, "lastKind", "CLAIM"); expireHashAfter(rendered, leaseTtl + Long.parseLong(afterLease)); return reply("ACQUIRED", 1, 1, ownerToken, "", Long.toString(nowMillis + leaseTtl)); } @@ -238,6 +239,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand setField(rendered, "op", operationId); setField(rendered, "leaseUntil", Long.toString(nowMillis + leaseTtl)); setField(rendered, "afterLease", afterLease); + setField(rendered, "lastKind", "CLAIM"); expireHashAfter(rendered, leaseTtl + Long.parseLong(afterLease)); return reply( "TAKEN_OVER", attempt + 1, rev + 1, ownerToken, "", Long.toString(nowMillis + leaseTtl)); @@ -265,6 +267,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand String payload = text(arguments.get(5)); String leaseUntil = text(arguments.get(6)); String recordTtl = text(arguments.get(7)); + String kind = text(arguments.get(8)); String state = field(rendered, "state"); if (state == null) { return reply("ABSENT", 0, 0, "", "", ""); @@ -280,10 +283,16 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); } // ALREADY before the revision check, matching the program: a lost reply leaves the caller - // holding the pre-transition revision. A start is confirmed only to the handle it was applied - // from — the record one revision past it — because its ALREADY runs the action (round6 - // RR6-02-01); any other handle falls through to NOT_OWNER or WRONG_STATE. - if (state.equals(toState) && (!"CLAIMED".equals(fromState) || rev == expectedRev + 1)) { + // holding the pre-transition revision. A transition is confirmed only to the handle it was + // applied from — the record one revision past it, moved there by this kind of transition + // (round6 RR6-02-01 for a start, owner decision 2026-11-06 for a completion or failure, round8 + // RR8-04-02 for a start after a renewal); any other handle falls through to NOT_OWNER or + // WRONG_STATE. The same kind with another target is a failure asking for the other disposition: + // OPERATION_CONFLICT (owner decision 2026-11-07). + if (rev == expectedRev + 1 && kind.equals(field(rendered, "lastKind"))) { + if (!state.equals(toState)) { + return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); + } String stored = field(rendered, "resp"); return reply("ALREADY", attempt, rev, owner, stored == null ? "" : stored, ""); } @@ -299,6 +308,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand } setField(rendered, "state", toState); setField(rendered, "rev", Long.toString(rev + 1)); + setField(rendered, "lastKind", kind); if (!payload.isEmpty()) { setField(rendered, "resp", payload); } @@ -353,6 +363,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand setField(rendered, "rev", Long.toString(rev + 1)); setField(rendered, "renewedFromRev", handleRevision); setField(rendered, "renewedLease", leaseMillis); + setField(rendered, "lastKind", "RENEW"); // As the program: the key's TTL is stretched, never shortened, to the new lease plus the margin // the claim recorded behind it. String afterLease = field(rendered, "afterLease"); @@ -366,6 +377,7 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand private List idempotencyRelease(String rendered, List arguments) { String ownerToken = text(arguments.get(0)); + long expectedRev = Long.parseLong(text(arguments.get(1))); String operationId = text(arguments.get(2)); String state = field(rendered, "state"); if (state == null) { @@ -380,6 +392,9 @@ public final class InMemorySemanticRedisCommands implements SemanticRedisCommand if (!operationId.equals(field(rendered, "op"))) { return reply("OPERATION_CONFLICT", attempt, rev, owner, "", ""); } + if (rev != expectedRev) { + return reply("NOT_OWNER", attempt, rev, owner, "", ""); + } if (!"CLAIMED".equals(state)) { return reply("WRONG_STATE", attempt, rev, owner, state, ""); } diff --git a/src/adapter/outbound/redis-sdk/README.md b/src/adapter/outbound/redis-sdk/README.md index b591af57..cf641d16 100644 --- a/src/adapter/outbound/redis-sdk/README.md +++ b/src/adapter/outbound/redis-sdk/README.md @@ -47,7 +47,7 @@ service contributes them to the runtime as beans, one per lane it uses, through — and builds `LettuceRedisCommandGateway.over(lease.driver())` over a borrowed lease. The last bean matters only with an admin account: under `prod`, `SecretSourceValidator` refuses a secret that holds -a lane fixture password (`fixture-admin` is in `infra/redis-sdk/acl`), but it learns which variables +a lane fixture password (`fixture-admin` is in `compose/redis/acl`), but it learns which variables are secrets from the registry, from `secret://` references in the environment and from `RequiredProductionSecrets` beans — not from a reference held in code. Without the bean the admin account could run in production on the public lane password (review 2026-11-04 RR3-04-03). The SDK @@ -107,5 +107,5 @@ The SDK reads none itself. It runs on `redis-runtime`, whose rows in Contract tests run the operations against this leaf's own in-memory gateway (`InMemoryRedisCommandGateway`, test sources); the topology endpoint helper comes from `testFixtures(project(':adapter:outbound:redis-runtime'))`. The real-server lane is -`redisTopologyTest` (see `infra/redis-sdk/README.md`); this leaf declares `standalone`, `sentinel` +`redisTopologyTest` (see [compose/README.md](compose/README.md)); this leaf declares `standalone`, `sentinel` and `cluster` in `build.gradle`. `tls` is qualified by `redis-runtime`. diff --git a/infra/redis-sdk/README.md b/src/adapter/outbound/redis-sdk/compose/README.md similarity index 93% rename from infra/redis-sdk/README.md rename to src/adapter/outbound/redis-sdk/compose/README.md index 832c5860..291b8572 100644 --- a/infra/redis-sdk/README.md +++ b/src/adapter/outbound/redis-sdk/compose/README.md @@ -25,9 +25,9 @@ in the repository is a private key in the repository, however the file is named day, so a stale lane fails visibly instead of drifting. ```bash -REDIS_VERSION=7.4 docker compose -f infra/redis-sdk/tls/compose.yml up -d --wait +REDIS_VERSION=7.4 docker compose -f src/adapter/outbound/redis-sdk/compose/tls/compose.yml up -d --wait # The client needs the generated CA; copy it out of the volume first. -docker compose -f infra/redis-sdk/tls/compose.yml cp redis:/tls/ca.crt /tmp/redis-lane-ca.pem +docker compose -f src/adapter/outbound/redis-sdk/compose/tls/compose.yml cp redis:/tls/ca.crt /tmp/redis-lane-ca.pem cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest \ -Predis.topology.host=127.0.0.1 -Predis.topology.port=6390 \ -Predis.topology.mode=tls -Predis.topology.trust-material=/tmp/redis-lane-ca.pem @@ -73,12 +73,12 @@ rest of the topology is discovered. ```bash # Standalone -REDIS_VERSION=7.4 docker compose -f infra/redis-sdk/standalone/compose.yml up -d --wait +REDIS_VERSION=7.4 docker compose -f src/adapter/outbound/redis-sdk/compose/standalone/compose.yml up -d --wait cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest :adapter:outbound:redis-sdk:redisTopologyTest :adapter:outbound:cache-redis:redisTopologyTest \ -Predis.topology.host=localhost -Predis.topology.port=6379 -Predis.topology.mode=standalone # Sentinel — the port is a sentinel, and the monitored primary has to be named -REDIS_VERSION=7.4 docker compose -f infra/redis-sdk/sentinel/compose.yml up -d --wait +REDIS_VERSION=7.4 docker compose -f src/adapter/outbound/redis-sdk/compose/sentinel/compose.yml up -d --wait cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest :adapter:outbound:redis-sdk:redisTopologyTest \ -Predis.topology.host=localhost -Predis.topology.port=27010 \ -Predis.topology.mode=sentinel -Predis.topology.master=skeleton @@ -86,7 +86,7 @@ cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest :adapter:o # Cluster — `up --wait` waits for the `ready` gate, not just for six servers that answer PING. # Slot assignment finishes after the nodes are healthy, and a client that connects in between sees # CLUSTERDOWN for reasons that have nothing to do with the SDK. -REDIS_VERSION=7.4 docker compose -f infra/redis-sdk/cluster/compose.yml up -d --wait +REDIS_VERSION=7.4 docker compose -f src/adapter/outbound/redis-sdk/compose/cluster/compose.yml up -d --wait cd src && ./gradlew :adapter:outbound:redis-runtime:redisTopologyTest :adapter:outbound:redis-sdk:redisTopologyTest :adapter:outbound:cache-redis:redisTopologyTest \ -Predis.topology.host=localhost -Predis.topology.port=7100 -Predis.topology.mode=cluster ``` @@ -102,7 +102,7 @@ declare fails instead of running nothing, so run only the leaves listed for the | cluster | `LiveRedisCompositionTest` | `LiveRedisClusterTest`, `LiveRedisClusterTransactionTest` | `LiveRedisSemanticPortsTest`, `LiveRedisSemanticScriptAclProbeTest` | | tls | `LiveRedisTlsTest` | — | — | -Tear a lane down with `docker compose -f infra/redis-sdk//compose.yml down -v`. +Tear a lane down with `docker compose -f src/adapter/outbound/redis-sdk/compose//compose.yml down -v`. | Lane | Ports | Notes | | --- | --- | --- | diff --git a/infra/redis-sdk/cluster/compose.yml b/src/adapter/outbound/redis-sdk/compose/cluster/compose.yml similarity index 98% rename from infra/redis-sdk/cluster/compose.yml rename to src/adapter/outbound/redis-sdk/compose/cluster/compose.yml index aefe63ff..3439d338 100644 --- a/infra/redis-sdk/cluster/compose.yml +++ b/src/adapter/outbound/redis-sdk/compose/cluster/compose.yml @@ -25,7 +25,7 @@ x-node: &node image: "redis:${REDIS_VERSION:-7.4}" network_mode: host volumes: - - ../acl:/etc/redis/acl:ro + - ../../../../../../compose/redis/acl:/etc/redis/acl:ro entrypoint: - /bin/sh - -c diff --git a/infra/redis-sdk/sentinel/compose.yml b/src/adapter/outbound/redis-sdk/compose/sentinel/compose.yml similarity index 98% rename from infra/redis-sdk/sentinel/compose.yml rename to src/adapter/outbound/redis-sdk/compose/sentinel/compose.yml index 9aab8f37..db059a38 100644 --- a/infra/redis-sdk/sentinel/compose.yml +++ b/src/adapter/outbound/redis-sdk/compose/sentinel/compose.yml @@ -29,7 +29,7 @@ x-data-node: &data-node image: "redis:${REDIS_VERSION:-7.4}" network_mode: host volumes: - - ../acl:/etc/redis/acl:ro + - ../../../../../../compose/redis/acl:/etc/redis/acl:ro entrypoint: - /bin/sh - -c diff --git a/infra/redis-sdk/standalone/compose.yml b/src/adapter/outbound/redis-sdk/compose/standalone/compose.yml similarity index 93% rename from infra/redis-sdk/standalone/compose.yml rename to src/adapter/outbound/redis-sdk/compose/standalone/compose.yml index ea8f4be0..5d983bbc 100644 --- a/infra/redis-sdk/standalone/compose.yml +++ b/src/adapter/outbound/redis-sdk/compose/standalone/compose.yml @@ -16,7 +16,7 @@ services: - --aclfile - /etc/redis/acl/lane-fixture-accounts.acl volumes: - - ../acl:/etc/redis/acl:ro + - ../../../../../../compose/redis/acl:/etc/redis/acl:ro ports: - "${REDIS_PORT:-6379}:6379" healthcheck: diff --git a/infra/redis-sdk/tls/compose.yml b/src/adapter/outbound/redis-sdk/compose/tls/compose.yml similarity index 97% rename from infra/redis-sdk/tls/compose.yml rename to src/adapter/outbound/redis-sdk/compose/tls/compose.yml index 218adb92..a679849f 100644 --- a/infra/redis-sdk/tls/compose.yml +++ b/src/adapter/outbound/redis-sdk/compose/tls/compose.yml @@ -38,7 +38,7 @@ services: certs: condition: service_completed_successfully volumes: - - ../acl:/etc/redis/acl:ro + - ../../../../../../compose/redis/acl:/etc/redis/acl:ro - tls:/tls:ro command: - redis-server diff --git a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java index 67ee210b..26832b4c 100644 --- a/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java +++ b/src/adapter/outbound/redis-sdk/src/test/java/dev/caskeleton/adapter/outbound/cache/redis/sdk/RedisTopologyContractTest.java @@ -29,11 +29,11 @@ import org.junit.jupiter.api.Test; * so selecting it without an endpoint is an error rather than a skip. * *

What lives here is what the in-memory gateway is honest about not proving. The ACL assertions - * below are the first of those: the accounts in {@code infra/redis-sdk/acl} are the last - * enforcement boundary, and whether they actually grant what the command policy catalog says each - * access level may issue is a question only the server answers. Writing this test already found one - * defect — the advanced account granted {@code SMEMBERS} and {@code SORT}, which are {@code - * RAW_ONLY} and belong to the raw gateway account alone. + * below are the first of those: the accounts in {@code compose/redis/acl} are the last enforcement + * boundary, and whether they actually grant what the command policy catalog says each access level + * may issue is a question only the server answers. Writing this test already found one defect — the + * advanced account granted {@code SMEMBERS} and {@code SORT}, which are {@code RAW_ONLY} and belong + * to the raw gateway account alone. */ @Tag("redis-topology") @Tag("lane-standalone") diff --git a/src/adapter/outbound/support/CLAUDE.md b/src/adapter/outbound/support/CLAUDE.md index 3e8f0d3d..3afa2f32 100644 --- a/src/adapter/outbound/support/CLAUDE.md +++ b/src/adapter/outbound/support/CLAUDE.md @@ -27,9 +27,9 @@ Package roots: `dev.caskeleton.adapter.outbound` and Fileserver's `LocalStorageFailures`); nothing here knows an error code. - Own `StrictSettingsBinder`, the one strict settings binding. It is also the only support class an inbound leaf may use: `adapter:inbound:web` binds `app.security` with it (registry edge and a - class-named ArchUnit exemption, review 2026-11-01 07-10). An empty value for a setting the type + class-named ArchUnit exemption, since 2026-11-01). An empty value for a setting the type has (`APP_FILESERVER_PLATFORM_QUOTA_NAMESPACE_LIMIT=`) binds as unset; an empty value under a name - the type does not have is still refused (review 15절, r3-I). + the type does not have is still refused (decided 2026-11-03). - Keep feature-specific clients and routing policies in their owning leaf. ## Boundaries diff --git a/src/app-bootstrap/CLAUDE.md b/src/app-bootstrap/CLAUDE.md index d562ec1e..e12f76f1 100644 --- a/src/app-bootstrap/CLAUDE.md +++ b/src/app-bootstrap/CLAUDE.md @@ -46,7 +46,7 @@ Package root: `dev.caskeleton.bootstrap`. ## 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`, BOOT-006 / BOOT-007). Half the +(`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 @@ -65,12 +65,10 @@ configurations, Redis as one 376-line class. 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 (the sample takes the - idempotency one too). A capability's role→permission mapping ships in its own - `config/module-defaults` file, not in `config/security.yml`. The runtime wiring both composition roots need — + 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`, which the sample - takes by the same line instead of carrying copies. + (`PrivacySettings`) and the actuator chain — is `composition:service-runtime`. - **`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: diff --git a/src/app-bootstrap/README.md b/src/app-bootstrap/README.md index 82a299da..3881e831 100644 --- a/src/app-bootstrap/README.md +++ b/src/app-bootstrap/README.md @@ -130,7 +130,7 @@ README의 "startup" 절에 있다. - **prod 에서 깨지면 부팅 자체를 거부하는 fail-fast 가드다.** 두 가지 prod 불변식을 context refresh 완료 전에 강제한다. (1) `__LOCAL_DEV_` 접두사를 가진 dev/local 가짜 자격증명 값이 prod 프로파일에 도달하는 것은 잘못 로드된 사고이므로 부팅을 중단시킨다. 비밀값이 `fixture-`로 시작해도 같다. 이 저장소가 - lane용으로 적어 둔 공개 비밀번호(`infra/redis-sdk/acl`의 Redis ACL fixture, compose lane의 + lane용으로 적어 둔 공개 비밀번호(`compose/redis/acl`의 Redis ACL fixture, compose lane의 `REDIS_LANE_*`)라서, lane 환경이나 lane ACL 파일을 베낀 배포가 그대로 운영에 뜨는 것을 막는다 (review 2026-11-03 RR-07-04). 이 검사는 비밀값만 본다 — 레지스트리의 `secret` 행 (`CLASSIFIED_SECRETS`), 모듈이 기여한 비밀, 환경 값에 든 `secret://…/` 참조가 가리키는 변수 @@ -302,8 +302,7 @@ DB 연결이 꼭 필요한 persistence-jpa의 datasource 버전 검사는 bean executor 조립(`IdempotencyAutoConfiguration`)과 수명 정책(`IdempotencySettings`, strict 바인딩), 설정 기본값(`config/module-defaults/idempotency.yml`, 예전 `config/capabilities.yml`)은 -`composition:idempotency`로 옮겼다(소유자 결정 3). 이 leaf는 `runtimeOnly` 한 줄로 받고, -sample-portfolio도 같은 줄을 쓴다. 근거는 [그 모듈의 README](../composition/idempotency/README.md). +`composition:idempotency`로 옮겼다(소유자 결정 3). 이 leaf는 `runtimeOnly` 한 줄로 받는다. 근거는 [그 모듈의 README](../composition/idempotency/README.md). ## outbox — 트랜잭셔널 아웃박스 릴레이 (composition:outbox-relay로 이동) @@ -474,12 +473,12 @@ app-bootstrap 은 합성 루트라 "왜 이 의존성이, 왜 이 scope 로" 결 - **`spring-security-test`** — `@WithMockUser`로 actuator 보안 인가(permit-all 프로브 / 인증 필요한 링크 / 노출 안 한 loggers)를 검증한다. - **`snakeyaml`** — `docs/registries/*.yaml` 같은 checked-in YAML 레지스트리를 contract 테스트가 - 읽는다. `config/messaging/*.yaml` 카드 검증(`MessagingCapabilityRegistryContractTest`)은 소유자 + 읽는다. `adapter/outbound/messaging/release/*.yaml` 카드 검증(`MessagingCapabilityRegistryContractTest`)은 소유자 결정 29로 `adapter:outbound:messaging` 테스트로 옮겼다. ### Messaging qualification scaffold -`config/messaging/`은 first polling-producer tuple의 machine-readable 계획 truth만 보관한다. +`adapter/outbound/messaging/release/`는 first polling-producer tuple의 machine-readable 계획 truth만 보관한다. 현재 card 11개는 모두 `maturity: not-implemented`, `evidenceFingerprint: ""`이고 consumer, CDC, EOS, schema-registry 확장 row는 없다. `verifyMessagingContracts`는 application-core· shared-contract의 exact qualification test를 실행하고 `contracts-schema/manifest.json`을 쓴 뒤 그 @@ -501,12 +500,14 @@ ArchUnit 규칙이 **금지**하는 타입을 fixture 가 일부러 import 해 - `graphql-java` (`architectureTestCompileOnly`) — `SYSTEM_CALLERS_ARE_SYSTEM_DRIVEN_INBOUND_ADAPTERS`의 사용자 전송 타입 목록 중 `graphql..` 항목을 증명하는 fixture(`GraphQlJavaSystemCallerFixture`)가 graphql-java 타입 하나만 쓴다. runtime 은 GraphQL adapter 가 이미 같은 버전을 싣는다(lock 동일). +- `spring-messaging` (`architectureTestCompileOnly`) — 사용자 전송 타입 목록의 STOMP channel interceptor + 항목(`ChannelInterceptor`·`ExecutorChannelInterceptor`)을 증명하는 위반 fixture + (`violations/configuration/stomp/`)와 허용 fixture(inbound channel 설정만 하는 + `SystemCallerBesideStompBrokerSetupFixture`, 따로 둔 interceptor 설정 `FrameInterceptorConfigurationFixture`)가 쓴다. runtime 은 WebSocket adapter 가 이미 같은 버전을 + 싣는다(lock 동일). - `spring-cloud-context` — `@RefreshScope` 금지(no-refresh-scope) fixture 용. Spring Cloud 는 production 에 없고 규칙은 애너테이션을 FQN 문자열로 참조한다. BOM 이 spring-cloud 좌표를 관리하지 않아 버전을 명시 고정한다. -- **`testImplementation project(':sample-portfolio')`** — ArchUnit 이 템플릿 reference 구현을 분석하려고 - test 경로에만 둔다. **production 은 절대 sample-portfolio 에 의존 금지** — - `production_code_does_not_depend_on_sample_portfolio` 규칙이 강제한다. ### 빌드 설정 - **test JVM UTC 고정(`-Duser.timezone=UTC`)** — `RuntimeHealthLifecycleContractTest`가 diff --git a/src/app-bootstrap/build.gradle b/src/app-bootstrap/build.gradle index 3568cbf1..e2a7b6bd 100644 --- a/src/app-bootstrap/build.gradle +++ b/src/app-bootstrap/build.gradle @@ -124,7 +124,7 @@ sourceSets { // Every capability a service can select — the commented runtimeOnly lines below — listed once. // Three consumers read it — the environment contract's metadata classpath (verifyEnvKeys, below) // and these two: the whole-repository ArchUnit import (spec §7: the architecture suite sees -// every module of this build and the sample, the shipped runtime only the selected ones; the +// every module of this build, the shipped runtime only the selected ones; the // optional-platforms build is held by its own Gradle direction gate instead) and the qualification artifact the // Compose lanes boot (qualificationBootJar, below). None of them reaches `bootJar`, `test` or // `systemTest`, because a capability on a classpath is switched on there by its mere presence. @@ -169,26 +169,22 @@ dependencies { // runtimeOnly project(':composition:notification-platform') // 알림 (persistence-jpa·persistence-notification을 함께 가져온다) // 기본 조립에 있는 application composition. 셋 다 포트만 보고, 필요한 것(outbox store, 멱등성 - // provider)이 없으면 아무것도 만들지 않는다. sample-portfolio도 같은 멱등성 모듈을 쓴다. + // provider)이 없으면 아무것도 만들지 않는다. runtimeOnly project(':composition:outbox-relay') // outbox relay (store·발행 포트가 있을 때만) runtimeOnly project(':composition:idempotency') // 요청 멱등성 executor (provider≠disabled) runtimeOnly project(':composition:durable-operation') // /operations (operation store·outbox가 있을 때만) // 모든 서비스가 받는 runtime 배선: tracing, metrics 계약 filter, domain context, user principal - // 가명화, actuator 보안 chain. sample-portfolio도 같은 줄을 쓴다. + // 가명화, actuator 보안 chain. runtimeOnly project(':composition:service-runtime') // Contract tests pin those pieces by type (tracing gauge, metrics filters, actuator chain). testImplementation project(':composition:service-runtime') integrationTestImplementation project(':composition:service-runtime') capabilityProjects.each { architectureTestRuntimeOnly project(it) } - // The sample is the reference adopters copy, so the whole-repository rules read it too (review - // BUILD-중복-8). Architecture-test runtime only: no production configuration reaches it. - // // What this import does NOT see: the optional-platforms build (`grpc:*`, `grpc-advanced:*`). // It is a separate Gradle build, so its classes cannot be on this classpath; its registered - // leaves are held by the Gradle direction gate (`-p optional-platforms ci` runs + // leaves are held by the Gradle direction gate (`-p platforms/optional-build ci` runs // verifyCleanArchitectureDependencies), which is the whole of what the owner decided it needs. - architectureTestRuntimeOnly project(':sample-portfolio') // The capability integration lane selects Fileserver and object storage together, as a service // would, and turns off whichever one a test is not about. @@ -282,6 +278,11 @@ dependencies { // type list is a raw graphql-java data fetcher. The adapter brings graphql-java onto this source // set's runtime already (capabilityProjects); compile-only here so no shipped graph changes. architectureTestCompileOnly 'com.graphql-java:graphql-java' + // architecture-only: the STOMP fixtures for the channel-interceptor entries of the user-transport + // type list implement spring-messaging's ChannelInterceptor. The websocket adapter brings it onto + // this source set's runtime already (capabilityProjects); compile-only here so no shipped graph + // changes. + architectureTestCompileOnly 'org.springframework:spring-messaging' // Kafka producer ownership lives in adapter:outbound:messaging. The composition root sees only // the adapter module; it no longer implements the broker seam itself. testCompileOnly 'jakarta.ws.rs:jakarta.ws.rs-api' // jakarta.ws.rs.. @@ -340,14 +341,16 @@ def repositoryRootForContractTests = rootProject.projectDir.parentFile def repositoryContractExcludes = ['**/build/**', '**/.gradle/**', '**/node_modules/**'] def repositoryContractInputs = files( fileTree(repositoryRootForContractTests) { - include '.github/**', 'infra/**', 'scripts/**', '*.yml', '*.example', '.tool-versions' + include '.github/**', 'compose/**', 'scripts/**', '*.yml', '*.yaml', '*.example', '.tool-versions' exclude '**/*.md' exclude repositoryContractExcludes }, fileTree(rootProject.projectDir) { include 'config/**', '**/*.gradle', 'gradle/*.toml', 'Dockerfile*', '.env*', '**/src/main/**' - // SampleRuntimeDefaultsContractTest compares the sample's runtime defaults with these. - include 'sample-portfolio/src/main/resources/application.yml' + // The compose lane fixtures this leaf owns (the lane contract, overlays, smoke clients). + include 'app-bootstrap/compose-lanes/**' + // The release data a capability leaf owns (readiness cards, release registries). + include 'adapter/outbound/*/release/**' exclude '**/*.md' exclude repositoryContractExcludes }) @@ -406,7 +409,7 @@ tasks.named('conditionalTransportBuildContractTest', Test) { } tasks.named('integrationTest', Test) { inputs.files(fileTree(repositoryRootForContractTests) { - include '*.yml', 'infra/**' + include 'compose.yaml', 'compose/**', 'scripts/*compose*.sh', 'src/app-bootstrap/compose-lanes/**' exclude repositoryContractExcludes }).withPathSensitivity(PathSensitivity.RELATIVE).withPropertyName('composeFiles') } @@ -476,7 +479,7 @@ def compositionRuntimeClasspath = { String name -> } // The qualification artifact: this composition with every capability on the classpath. It is what -// the Compose lanes (config/runtime/compose-profile-contracts.json) boot, because a lane that turns +// the Compose lanes (compose-lanes/compose-profile-contracts.json) boot, because a lane that turns // JPA or Kafka on needs the module in the image, and `bootJar` — the default composition a service // ships — carries none of them. It is never released: `release.yml` builds `stageDockerJar`. // Each capability is on while present, so a lane switches off what it is not about. diff --git a/src/config/runtime/compose-profile-contracts.json b/src/app-bootstrap/compose-lanes/compose-profile-contracts.json similarity index 83% rename from src/config/runtime/compose-profile-contracts.json rename to src/app-bootstrap/compose-lanes/compose-profile-contracts.json index a5a000ab..927caecb 100644 --- a/src/config/runtime/compose-profile-contracts.json +++ b/src/app-bootstrap/compose-lanes/compose-profile-contracts.json @@ -1,14 +1,13 @@ { - "$comment": "The lane SSOT. Each row fixes a Compose profile, a file stack, an explicit Spring runtime and the exact set of services that stack must render — exact, not a superset, because a lane that quietly gains a service is a lane whose evidence describes something else. A Compose profile selects services and never implies a Spring profile; the wrapper injects the runtime named here.", + "$comment": "The lane SSOT. Each row fixes the Compose profiles it enables, a file stack, an explicit Spring runtime and the exact set of services that stack must render — exact, not a superset, because a lane that quietly gains a service is a lane whose evidence describes something else. A Compose profile selects services and never implies a Spring profile; the wrapper injects the runtime named here. The base file is the development stack (compose.yaml), whose backing services carry capability profiles (jpa, redis, kafka, mongo, objectstorage, auth, mail); the lane-only services in lane-services.yaml carry their own (schema-streams, smoke-*).", "minimumComposeVersion": "2.24.4", "composeFiles": { - "base": "docker-compose.yml", - "infra": "docker-compose.infra.yml", - "local": "docker-compose.local.yml", - "dev": "docker-compose.dev.yml", - "prod-smoke": "docker-compose.prod-smoke.yml", - "tls": "docker-compose.tls.yml", - "fileserver": "infra/fileserver/compose/docker-compose.fileserver.yml" + "base": "compose.yaml", + "lane": "src/app-bootstrap/compose-lanes/lane-services.yaml", + "dev": "src/app-bootstrap/compose-lanes/dev.yaml", + "prod-smoke": "src/app-bootstrap/compose-lanes/prod-smoke.yaml", + "tls": "src/app-bootstrap/compose-lanes/tls.yaml", + "fileserver": "src/app-bootstrap/compose-lanes/fileserver.yaml" }, "$serviceRoles": "Every service a lane renders plays exactly one of three roles, and the wrapper treats them differently: longRunningServices are the only `up --wait` targets, preStartServices run with `run --rm` before the application starts because it depends on what they do, and oneShotServices run with `run --rm` after it is healthy because they exercise it. The two catalogues below name every service that is not a --wait target anywhere; a one-shot passed to `up --wait` waits forever for a container built to exit.", "preStartServices": [ @@ -27,10 +26,9 @@ "lanes": [ { "id": "off-local", - "composeProfile": null, + "composeProfiles": [], "files": [ - "base", - "local" + "base" ], "springRuntime": "local", "services": [ @@ -47,7 +45,7 @@ }, { "id": "off-dev", - "composeProfile": null, + "composeProfiles": [], "files": [ "base", "dev" @@ -67,7 +65,7 @@ }, { "id": "off-prod", - "composeProfile": null, + "composeProfiles": [], "files": [ "base", "prod-smoke" @@ -87,11 +85,11 @@ }, { "id": "local-jpa", - "composeProfile": "local-jpa", + "composeProfiles": [ + "jpa" + ], "files": [ - "base", - "infra", - "local" + "base" ], "springRuntime": "local", "services": [ @@ -118,11 +116,11 @@ }, { "id": "local-mongo", - "composeProfile": "local-mongo", + "composeProfiles": [ + "mongo" + ], "files": [ - "base", - "infra", - "local" + "base" ], "springRuntime": "local", "services": [ @@ -151,11 +149,11 @@ }, { "id": "local-messaging", - "composeProfile": "local-messaging", + "composeProfiles": [ + "kafka" + ], "files": [ - "base", - "infra", - "local" + "base" ], "springRuntime": "local", "services": [ @@ -181,11 +179,12 @@ }, { "id": "local-messaging-outbox", - "composeProfile": "local-messaging-outbox", + "composeProfiles": [ + "jpa", + "kafka" + ], "files": [ - "base", - "infra", - "local" + "base" ], "springRuntime": "local", "services": [ @@ -221,11 +220,15 @@ }, { "id": "local-notification-ingest", - "composeProfile": "local-notification-ingest", + "composeProfiles": [ + "jpa", + "auth", + "schema-streams", + "smoke-notification" + ], "files": [ "base", - "infra", - "local" + "lane" ], "springRuntime": "local", "services": [ @@ -270,11 +273,16 @@ }, { "id": "local-notification-serving", - "composeProfile": "local-notification-serving", + "composeProfiles": [ + "jpa", + "auth", + "mail", + "schema-streams", + "smoke-notification" + ], "files": [ "base", - "infra", - "local" + "lane" ], "springRuntime": "local", "services": [ @@ -331,11 +339,16 @@ }, { "id": "local-notification-handoff", - "composeProfile": "local-notification-handoff", + "composeProfiles": [ + "jpa", + "auth", + "mail", + "schema-streams", + "smoke-notification" + ], "files": [ "base", - "infra", - "local" + "lane" ], "springRuntime": "local", "services": [ @@ -400,11 +413,14 @@ }, { "id": "local-graphql", - "composeProfile": "local-graphql", + "composeProfiles": [ + "auth", + "smoke-auth", + "smoke-graphql" + ], "files": [ "base", - "infra", - "local" + "lane" ], "springRuntime": "local", "services": [ @@ -433,11 +449,11 @@ }, { "id": "local-redis", - "composeProfile": "local-redis", + "composeProfiles": [ + "redis" + ], "files": [ - "base", - "infra", - "local" + "base" ], "springRuntime": "local", "services": [ @@ -467,11 +483,13 @@ { "id": "local-fileserver", "$comment": "The Fileserver keeps its metadata in PostgreSQL through JPA (FileserverJpaPersistenceConfig needs the entityManagerFactory), so the lane without a database could never start: the application refused at startup and the lane reported an unhealthy container. PostgreSQL, the JPA module, and the fileserver schema stream installed and promoted before the application starts, the way the notification lanes get theirs.", - "composeProfile": "local-fileserver", + "composeProfiles": [ + "jpa", + "schema-streams" + ], "files": [ "base", - "infra", - "local", + "lane", "fileserver" ], "springRuntime": "local", @@ -515,10 +533,9 @@ }, { "id": "local-httpclient", - "composeProfile": "local-httpclient", + "composeProfiles": [], "files": [ - "base", - "local" + "base" ], "springRuntime": "local", "services": [ @@ -546,11 +563,16 @@ }, { "id": "shared-infra-local", - "composeProfile": "shared-infra", + "composeProfiles": [ + "jpa", + "auth", + "objectstorage", + "smoke-auth", + "smoke-objectstorage" + ], "files": [ "base", - "infra", - "local" + "lane" ], "springRuntime": "local", "services": [ @@ -588,10 +610,16 @@ }, { "id": "shared-infra-dev", - "composeProfile": "shared-infra", + "composeProfiles": [ + "jpa", + "auth", + "objectstorage", + "smoke-auth", + "smoke-objectstorage" + ], "files": [ "base", - "infra", + "lane", "dev" ], "springRuntime": "dev", @@ -630,10 +658,16 @@ }, { "id": "prod-smoke", - "composeProfile": "prod-smoke", + "composeProfiles": [ + "jpa", + "auth", + "objectstorage", + "smoke-auth", + "smoke-objectstorage" + ], "files": [ "base", - "infra", + "lane", "prod-smoke", "tls" ], @@ -673,14 +707,26 @@ }, { "id": "all-adapters", - "composeProfile": "all-adapters", + "composeProfiles": [ + "jpa", + "mongo", + "kafka", + "redis", + "auth", + "mail", + "schema-streams", + "smoke-auth", + "smoke-graphql", + "smoke-notification" + ], "files": [ "base", - "infra", - "local", + "lane", "fileserver" ], "springRuntime": "local", + "$memoryComment": "Every capability on at once does not fit the 512m the development stack gives the application: the JVM sized its heap to 75% of the limit and the rest (metaspace for every module, code cache, threads) took the container past it, so the kernel killed it and restart: unless-stopped hid the kill whenever it missed the smoke requests (integration-r9, 2026-11-07). The lane raises the limit for itself; the wrapper writes it into the generated overlay and fails a lane whose containers restarted.", + "appMemoryLimit": "1g", "services": [ "app", "auth-smoke", @@ -795,6 +841,6 @@ "redis" ], "$vendorComment": "expectedPersistenceVendor is the vendor the application must report, not the one the lane started: info.capabilities.persistence-jpa.vendor while JPA is on, none while it is off. A reported postgresql is the database the queries go to, because the JPA module refuses to start when the selected vendor is postgresql and the datasource it reaches is not PostgreSQL (JpaDataSourceProfileValidator). local-jpa passed for a while against H2 while a PostgreSQL container it never touched sat beside it, because application-local.yml pins an in-memory URL that outranks the lane's environment.", - "$redisComment": "The lanes that switch Redis on authenticate the way a deployment does. Their Redis loads infra/redis-sdk/acl/lane-fixture-accounts.acl, which turns the passwordless default user off, and the application connects as the two named accounts that file provisions: ca-skeleton-application for ordinary commands and ca-skeleton-application-advanced for registered scripts. Both references use the secret://@environment/ form; without the account part the client authenticates as the disabled default user. The two REDIS_LANE_* values are that file's fixture passwords (infra/redis-sdk/acl/README.md), not deployment credentials, and deliberately carry no APP_ prefix: they are not application settings, only what these references point at. APP_REDIS_NAMESPACE_ENVIRONMENT is prod because the fixture accounts are fenced to ~prod:*, the namespace every other test against that file uses; under the default local namespace the first key a capability wrote would be refused with NOPERM after startup had reported healthy. Before this the lanes declared anonymous-access-accepted against an open Redis, and the two startup warnings that trade prints (no credential, no advanced account) failed their startup-is-silent check — which is right, because in production both are risks. scripts/verify-compose-profile-contracts.sh check 7 holds a Redis lane's references, passwords and namespace to the account lines of the file its Redis actually mounts.", + "$redisComment": "The lanes that switch Redis on authenticate the way a deployment does. Their Redis loads compose/redis/acl/lane-fixture-accounts.acl, which turns the passwordless default user off, and the application connects as the two named accounts that file provisions: ca-skeleton-application for ordinary commands and ca-skeleton-application-advanced for registered scripts. Both references use the secret://@environment/ form; without the account part the client authenticates as the disabled default user. The two REDIS_LANE_* values are that file's fixture passwords (compose/redis/acl/README.md), not deployment credentials, and deliberately carry no APP_ prefix: they are not application settings, only what these references point at. APP_REDIS_NAMESPACE_ENVIRONMENT is prod because the fixture accounts are fenced to ~prod:*, the namespace every other test against that file uses; under the default local namespace the first key a capability wrote would be refused with NOPERM after startup had reported healthy. Before this the lanes declared anonymous-access-accepted against an open Redis, and the two startup warnings that trade prints (no credential, no advanced account) failed their startup-is-silent check — which is right, because in production both are risks. scripts/verify-compose-profile-contracts.sh check 7 holds a Redis lane's references, passwords and namespace to the account lines of the file its Redis actually mounts.", "$flywayComment": "SPRING_FLYWAY_LOCATIONS is deliberately absent. Seven lanes listed every capability stream there, and it could never have worked: the db/migration/jpa/* streams each declare a V1, so one Flyway instance over all of them fails with 'Found more than one migration with version 1'. Each stream is its own stream with its own history table by design. The setting was inert until Wave 2 stopped PostgreSqlPersistenceConfig from overriding spring.flyway.locations, and the lanes passed while their own configuration was being discarded. Applying a capability stream needs a Flyway execution per stream — the operator sequence PostgreSqlNotificationPersistenceUnitIntegrationTest and FileserverRoundTripContractTest both perform in their fixtures — and that is what the notification lanes still need." } diff --git a/docker-compose.dev.yml b/src/app-bootstrap/compose-lanes/dev.yaml similarity index 90% rename from docker-compose.dev.yml rename to src/app-bootstrap/compose-lanes/dev.yaml index b81721bb..38456b5c 100644 --- a/docker-compose.dev.yml +++ b/src/app-bootstrap/compose-lanes/dev.yaml @@ -1,8 +1,11 @@ # ============================================================================= # feature-container-runtime-contract — dev environment override # -# Merge with base: -# docker compose -f docker-compose.yml -f docker-compose.dev.yml up +# The off-dev and shared-infra-dev compose lanes merge it onto the development stack: +# docker compose -f compose.yaml -f src/app-bootstrap/compose-lanes/dev.yaml up +# +# It checks that the `dev` deployment profile boots; it is not the development environment, which +# is compose.yaml alone. # # Dev intent: # - Relaxes read-only filesystem (writable, no tmpfs constraint) so developers @@ -35,7 +38,7 @@ services: # environment the application believes it is in, and the two drifting is how a dev stack ends # up running local's settings. SPRING_PROFILES_ACTIVE: "dev" - # The datasource address, owned here like the local and prod-smoke overlays own theirs. It was + # The datasource address, owned here like compose.yaml and the prod-smoke overlay own theirs. It was # the only one of the three missing, and the gap was invisible while the qualification wrapper # supplied a URL to every lane: the dev stack ran on a value that came from the test harness # rather than from the file that describes the dev environment. With the wrapper no longer @@ -86,7 +89,7 @@ services: target: /var/tmp/heap bind: create_host_path: true - # The same network the shared infrastructure lives on. The local overlay joins it and the dev + # The same network the shared infrastructure lives on. The local stack (now compose.yaml) joins it and the dev # overlay did not, so a dev lane that started PostgreSQL beside the application put the two on # different networks: `UnknownHostException: db`, from a container that was running and healthy # a metre away. Compose puts a service with no `networks:` on `default`, which is a network of @@ -96,6 +99,6 @@ services: - caskeleton-infra networks: - # Defined in docker-compose.infra.yml, where the services that share it live. + # Defined in compose.yaml, where the services that share it live. caskeleton-infra: external: false diff --git a/infra/fileserver/compose/docker-compose.fileserver.yml b/src/app-bootstrap/compose-lanes/fileserver.yaml similarity index 84% rename from infra/fileserver/compose/docker-compose.fileserver.yml rename to src/app-bootstrap/compose-lanes/fileserver.yaml index 726c3288..650b6708 100644 --- a/infra/fileserver/compose/docker-compose.fileserver.yml +++ b/src/app-bootstrap/compose-lanes/fileserver.yaml @@ -3,19 +3,18 @@ # # Usage, on top of a stack whose image carries the fileserver module (a service that selected # `:composition:fileserver-platform`, or COMPOSITION=qualification): -# docker compose -f docker-compose.yml -f docker-compose.local.yml \ -# -f infra/fileserver/compose/docker-compose.fileserver.yml up +# docker compose -f compose.yaml -f src/app-bootstrap/compose-lanes/fileserver.yaml up # # Why a file of its own (review 2026-11-01 07-08, capability criterion 7): the default image and -# docker-compose.yml carry no fileserver, so they no longer carry its volume either. Before, every +# compose.yaml carry no fileserver, so they no longer carry its volume either. Before, every # container — default composition included — mounted a volume for a module it did not have, and the -# image declared it a VOLUME. It sits with the rest of the capability's infrastructure -# (infra/fileserver), so removing the capability removes it with that directory. +# image declared it a VOLUME. It is a compose lane fixture (the lanes local-fileserver and +# all-adapters add it); a service that selects the capability adds the same volume to its own stack. # # The volume is a named volume, not a tmpfs and not the read-only root: published content must # outlive the container that wrote it. Back it with real storage in any deployment that keeps files. -# Kubernetes does the same job with a PersistentVolumeClaim and the pod's fsGroup -# (infra/fileserver/kubernetes/pvc-certification-job.yaml). +# Kubernetes does the same job with a PersistentVolumeClaim and the pod's fsGroup; the conditions +# are in docs/fileserver/operations.md. # # Ownership. The application runs as the image's non-root `app` account (src/Dockerfile). Docker # seeds a fresh named volume's owner from the image directory at the mount point, and the image has diff --git a/src/app-bootstrap/compose-lanes/lane-services.yaml b/src/app-bootstrap/compose-lanes/lane-services.yaml new file mode 100644 index 00000000..1c4ba2e2 --- /dev/null +++ b/src/app-bootstrap/compose-lanes/lane-services.yaml @@ -0,0 +1,245 @@ +# ============================================================================= +# compose lane 전용 서비스 — 개발 환경(저장소 루트 compose.yaml)에는 없다. +# +# 스키마 적용 one-shot 둘과 smoke client 넷이다. 모두 profile이 있어서 lane이 그 profile을 댈 때만 뜬다. +# 어느 lane이 무엇을 쓰는지는 compose-profile-contracts.json이 정한다. 이 파일은 compose.yaml 뒤에 +# -f로 합쳐지므로 경로는 저장소 루트 기준이다. +# +# profile 서비스 +# schema-streams db-migrate-capabilities, db-promote-capabilities +# smoke-auth auth-smoke +# smoke-graphql graphql-smoke +# smoke-objectstorage object-storage-smoke +# smoke-notification notification-smoke +# ============================================================================= + +# The object storage smoke client runs the MinIO server image (see below). YAML anchors do not cross +# files, so this is a second copy of compose.yaml's default; ComposeMinioImageMatchesEvidenceTest +# holds both to the measured evidence digest. +x-local-minio-image: &local-minio-image "${LOCAL_MINIO_IMAGE:-pgsty/minio@sha256:b6bfe7239bfc83fb90d31612d9704d86039dd714f7904b3f1ad68f211e602372}" + +services: + # ---- Capability schema streams ------------------------------------------------ + # Two pre-start one-shots, in this order, because a capability stream is an operator sequence + # rather than a property. + # + # Install: each stream under db/migration/jpa keeps its own Flyway history table — they all declare + # a V1, so one Flyway pointed at all of them fails outright — and each registers itself + # INSTALLED_INACTIVE. + # + # Promote: an operator sanctions the installed schema, and the application refuses to start until + # that has happened. That is the fail-closed half of the same design, so it cannot be folded into + # the install step without making "the tables exist" and "this is sanctioned" the same event. + # + # They are also two images because they must be: flyway/flyway ships no psql, so the promotion + # could not have run in the migration container at all. + # + # Both run before `up`, not with the smoke clients after it — the application is what they are a + # precondition for. The lane contract's preStartServices carries that ordering. + db-migrate-capabilities: + profiles: + - schema-streams + image: flyway/flyway:11.1.0 + depends_on: + db: + condition: service_healthy + entrypoint: ["/bin/sh", "/opt/capability-streams/apply-capability-streams.sh"] + environment: + PGHOST: "db" + PGUSER: "${APP_DATASOURCE_USERNAME:-ca_skeleton}" + PGPASSWORD: "${APP_DATASOURCE_PASSWORD:-ca_skeleton}" + PGDATABASE: "${POSTGRES_DB:-ca_skeleton}" + CAPABILITY_STREAMS: "${CAPABILITY_STREAMS:-}" + volumes: + - type: bind + source: ./src/app-bootstrap/compose-lanes/postgres/apply-capability-streams.sh + target: /opt/capability-streams/apply-capability-streams.sh + read_only: true + - type: bind + source: ./src/adapter/outbound/persistence-jpa/src/main/resources/db/migration + target: /flyway/sql + read_only: true + - type: bind + source: ./src/adapter/outbound/persistence-notification/src/main/resources/db/migration/jpa/notification-platform + target: /flyway/streams/notification-platform + read_only: true + - type: bind + source: ./src/adapter/outbound/persistence-fileserver/src/main/resources/db/migration/jpa/fileserver + target: /flyway/streams/fileserver + read_only: true + networks: + - caskeleton-infra + restart: "no" + + db-promote-capabilities: + profiles: + - schema-streams + image: postgres:16-alpine + depends_on: + db: + condition: service_healthy + entrypoint: ["/bin/sh", "/opt/capability-streams/promote-capability-streams.sh"] + environment: + PGHOST: "db" + PGUSER: "${APP_DATASOURCE_USERNAME:-ca_skeleton}" + PGPASSWORD: "${APP_DATASOURCE_PASSWORD:-ca_skeleton}" + PGDATABASE: "${POSTGRES_DB:-ca_skeleton}" + CAPABILITY_STREAMS: "${CAPABILITY_STREAMS:-}" + volumes: + - type: bind + source: ./src/app-bootstrap/compose-lanes/postgres/promote-capability-streams.sh + target: /opt/capability-streams/promote-capability-streams.sh + read_only: true + networks: + - caskeleton-infra + restart: "no" + + # ---- One-shot smoke clients -------------------------------------------------- + # Never `up --wait` targets. Each is run with `run --rm` and must exit zero; a missing, skipped or + # non-zero one fails its lane rather than being treated as "not applicable". + graphql-smoke: + profiles: + - smoke-graphql + image: curlimages/curl:8.10.1 + depends_on: + keycloak: + condition: service_healthy + # uid 0 for the mounted 0600 client secret, same as auth-smoke. + user: "0:0" + entrypoint: ["/bin/sh", "/opt/smoke/graphql-smoke.sh"] + environment: + APP_BASE_URL: "http://app:8080" + KEYCLOAK_ISSUER: "http://keycloak:8080/realms/ca-skeleton" + KEYCLOAK_CLIENT_ID: "ca-skeleton-api" + # Spring for GraphQL serves its own endpoint through a router function rather than an + # annotated controller, so the presentation base-path prefix does not apply to it. + GRAPHQL_PATH: "${GRAPHQL_PATH:-/graphql}" + volumes: + - type: bind + source: ./src/app-bootstrap/compose-lanes/smoke + target: /opt/smoke + read_only: true + secrets: + - keycloak-graphql-smoke-client-secret + networks: + - caskeleton-infra + restart: "no" + + auth-smoke: + profiles: + - smoke-auth + image: curlimages/curl:8.10.1 + depends_on: + keycloak: + condition: service_healthy + # The client secret is written on the host at mode 0600 by the qualification wrapper and mounted + # in. The Keycloak image happens to run as the same uid the wrapper writes as; this image runs as + # uid 100, so it read "Permission denied" and the lane failed on the smoke client rather than on + # anything it was checking. Compose ignores the secret's uid/gid/mode options outside swarm, so + # the container reads it as root instead. The two alternatives are both worse: loosening the host + # file to world-readable leaves a credential readable by every process on the machine, and passing + # the value as an environment variable puts it in `docker compose config` output and in ps. + user: "0:0" + entrypoint: ["/bin/sh", "/opt/smoke/auth-smoke.sh"] + environment: + # The same issuer URL the application is given. A token obtained from one URL and validated + # against another proves nothing, and localhost means a different host inside each container. + KEYCLOAK_ISSUER: "http://keycloak:8080/realms/ca-skeleton" + KEYCLOAK_CLIENT_ID: "ca-skeleton-api" + APP_BASE_URL: "http://app:8080" + # Supplied per runtime, because the same endpoint has two addresses: application-local.yml + # pins presentation.api-base-path to /api and the shipped default is /v1. The qualification + # wrapper exports the value that matches the lane's Spring runtime. + APP_HEALTH_PATH: "${APP_HEALTH_PATH:-/v1/healthcheck}" + volumes: + - type: bind + source: ./src/app-bootstrap/compose-lanes/smoke + target: /opt/smoke + read_only: true + secrets: + - keycloak-graphql-smoke-client-secret + networks: + - caskeleton-infra + restart: "no" + + # The server image, not the mc client image: the mc image ships no sed, grep or cmp, and the round-trip + # client needs a digest tool. See smoke/object-storage-smoke.sh for how that went unnoticed. The + # lane already pulls this image for the server itself. + object-storage-smoke: + profiles: + - smoke-objectstorage + image: *local-minio-image + depends_on: + minio-init: + condition: service_completed_successfully + entrypoint: ["/bin/sh", "/opt/smoke/object-storage-smoke.sh"] + environment: + MINIO_ENDPOINT: "http://minio:9000" + MINIO_ROOT_USER: "${MINIO_ROOT_USER:-caskeleton}" + MINIO_ROOT_PASSWORD: "${MINIO_ROOT_PASSWORD:-caskeleton-local}" + MINIO_BUCKET: "${MINIO_BUCKET:-ca-skeleton-objects}" + volumes: + - type: bind + source: ./src/app-bootstrap/compose-lanes/smoke + target: /opt/smoke + read_only: true + networks: + - caskeleton-infra + restart: "no" + + notification-smoke: + profiles: + - smoke-notification + image: curlimages/curl:8.10.1 + depends_on: + keycloak: + condition: service_healthy + # uid 0 for the same reason auth-smoke uses it: the mounted client secret is mode 0600 on the + # host and this image otherwise runs as uid 100, which reads "Permission denied". The lane then + # fails on the smoke client rather than on anything it was checking. + user: "0:0" + entrypoint: ["/bin/sh", "/opt/smoke/notification-smoke.sh"] + environment: + APP_BASE_URL: "http://app:8080" + MAILPIT_BASE_URL: "http://mailpit:8025" + # ingest | serving | handoff-verify — which phase of the lane this invocation is. + # + # No default, deliberately. It defaulted to `ingest`, and local-notification-serving therefore + # ran the ingest assertions — "accepted, and nothing was delivered" — against an application in + # SERVING mode. The lane passed while testing the opposite of what it is named for, and would + # have kept passing for as long as the check happened to run before the dispatch worker. An + # unset value now renders empty and the client refuses it. + # `:-` and not a value: an explicit empty default keeps Compose from warning about an unset + # variable on every lane that never runs this client, while still rendering empty so the + # client refuses it. + NOTIFICATION_SMOKE_PHASE: "${NOTIFICATION_SMOKE_PHASE:-}" + APP_BASE_PATH: "${APP_BASE_PATH:-/api}" + # Submission and template publication are authenticated like every other non-public path, so + # this client obtains a token the same way auth-smoke does — client credentials against the + # same issuer URL the application validates against. + KEYCLOAK_ISSUER: "http://keycloak:8080/realms/ca-skeleton" + KEYCLOAK_CLIENT_ID: "ca-skeleton-api" + volumes: + - type: bind + source: ./src/app-bootstrap/compose-lanes/smoke + target: /opt/smoke + read_only: true + # The handoff lane runs this client twice in one project and the second run needs the request + # id the first accepted, so the state lives in a named volume that outlives a `run --rm` + # container and is removed with the project by the teardown's --volumes. + # + # Its own path, not a subdirectory of the script mount above: a volume nested inside a + # read-only bind cannot be created, because the runtime has to mkdir the mountpoint in a + # filesystem it was just told is read-only. + - type: volume + source: caskeleton-notification-smoke-state + target: /opt/notification-smoke-state + secrets: + - keycloak-graphql-smoke-client-secret + networks: + - caskeleton-infra + restart: "no" + +volumes: + caskeleton-notification-smoke-state: + driver: local diff --git a/infra/postgres/apply-capability-streams.sh b/src/app-bootstrap/compose-lanes/postgres/apply-capability-streams.sh similarity index 97% rename from infra/postgres/apply-capability-streams.sh rename to src/app-bootstrap/compose-lanes/postgres/apply-capability-streams.sh index 79acdbdc..675977d2 100755 --- a/infra/postgres/apply-capability-streams.sh +++ b/src/app-bootstrap/compose-lanes/postgres/apply-capability-streams.sh @@ -22,7 +22,7 @@ # # Each stream registers itself INSTALLED_INACTIVE. Nothing here promotes anything — a table existing # is not the same as a capability being sanctioned to use it, and this image has no psql to blur the -# two with even if that were wanted. infra/postgres/promote-capability-streams.sh is the operator +# two with even if that were wanted. promote-capability-streams.sh is the operator # half, and NotificationSchemaActivation refusing startup until it has run is the fail-closed third. # # CAPABILITY_STREAMS is a space-separated list of stream names (the directory names under diff --git a/infra/postgres/entrypoint.sh b/src/app-bootstrap/compose-lanes/postgres/entrypoint.sh similarity index 100% rename from infra/postgres/entrypoint.sh rename to src/app-bootstrap/compose-lanes/postgres/entrypoint.sh diff --git a/infra/postgres/promote-capability-streams.sh b/src/app-bootstrap/compose-lanes/postgres/promote-capability-streams.sh similarity index 100% rename from infra/postgres/promote-capability-streams.sh rename to src/app-bootstrap/compose-lanes/postgres/promote-capability-streams.sh diff --git a/infra/postgres/tls/.gitignore b/src/app-bootstrap/compose-lanes/postgres/tls/.gitignore similarity index 100% rename from infra/postgres/tls/.gitignore rename to src/app-bootstrap/compose-lanes/postgres/tls/.gitignore diff --git a/docker-compose.prod-smoke.yml b/src/app-bootstrap/compose-lanes/prod-smoke.yaml similarity index 100% rename from docker-compose.prod-smoke.yml rename to src/app-bootstrap/compose-lanes/prod-smoke.yaml diff --git a/infra/keycloak/smoke/auth-smoke.sh b/src/app-bootstrap/compose-lanes/smoke/auth-smoke.sh similarity index 100% rename from infra/keycloak/smoke/auth-smoke.sh rename to src/app-bootstrap/compose-lanes/smoke/auth-smoke.sh diff --git a/infra/graphql/smoke/graphql-smoke.sh b/src/app-bootstrap/compose-lanes/smoke/graphql-smoke.sh similarity index 100% rename from infra/graphql/smoke/graphql-smoke.sh rename to src/app-bootstrap/compose-lanes/smoke/graphql-smoke.sh diff --git a/infra/notification/smoke/notification-smoke.sh b/src/app-bootstrap/compose-lanes/smoke/notification-smoke.sh similarity index 100% rename from infra/notification/smoke/notification-smoke.sh rename to src/app-bootstrap/compose-lanes/smoke/notification-smoke.sh diff --git a/infra/minio/smoke/object-storage-smoke.sh b/src/app-bootstrap/compose-lanes/smoke/object-storage-smoke.sh similarity index 100% rename from infra/minio/smoke/object-storage-smoke.sh rename to src/app-bootstrap/compose-lanes/smoke/object-storage-smoke.sh diff --git a/docker-compose.tls.yml b/src/app-bootstrap/compose-lanes/tls.yaml similarity index 85% rename from docker-compose.tls.yml rename to src/app-bootstrap/compose-lanes/tls.yaml index 0868be92..de7879c9 100644 --- a/docker-compose.tls.yml +++ b/src/app-bootstrap/compose-lanes/tls.yaml @@ -8,7 +8,7 @@ # # So the lane brings a real certificate instead. The qualification wrapper generates a CA and a # server certificate for the host name `db` per run, at mode 0600, and removes both on teardown; the -# realm-secret pattern, applied to a keypair. Nothing here is committed: infra/postgres/tls holds +# realm-secret pattern, applied to a keypair. Nothing here is committed: compose-lanes/postgres/tls holds # only a .gitignore. # # `verify-full` is deliberate rather than `verify-ca`. `verify-ca` proves the certificate was issued @@ -19,7 +19,7 @@ services: db: # Runs as root just long enough to install the key where postgres can read it, then hands over - # to the official entrypoint. See infra/postgres/entrypoint.sh for why a bind mount cannot do it. + # to the official entrypoint. See compose-lanes/postgres/entrypoint.sh for why a bind mount cannot do it. entrypoint: ["/bin/sh", "/opt/postgres-entrypoint/entrypoint.sh"] command: - "postgres" @@ -31,11 +31,11 @@ services: - "ssl_key_file=/etc/postgresql-tls/server.key" volumes: - type: bind - source: ./infra/postgres/entrypoint.sh + source: ./src/app-bootstrap/compose-lanes/postgres/entrypoint.sh target: /opt/postgres-entrypoint/entrypoint.sh read_only: true - type: bind - source: ./infra/postgres/tls + source: ./src/app-bootstrap/compose-lanes/postgres/tls target: /opt/postgres-tls read_only: true @@ -47,4 +47,4 @@ services: secrets: postgres-ca: - file: ./infra/postgres/tls/ca.crt + file: ./src/app-bootstrap/compose-lanes/postgres/tls/ca.crt diff --git a/src/app-bootstrap/gradle.lockfile b/src/app-bootstrap/gradle.lockfile index 5f322c6e..be76571d 100644 --- a/src/app-bootstrap/gradle.lockfile +++ b/src/app-bootstrap/gradle.lockfile @@ -361,7 +361,7 @@ org.springframework:spring-context:7.0.9=architectureTestCompileClasspath,archit org.springframework:spring-core:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-expression:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,compileClasspath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,productionRuntimeClasspath,qualificationRuntimeClasspath,runtimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-jdbc:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath -org.springframework:spring-messaging:7.0.9=architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath +org.springframework:spring-messaging:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,conditionalTransportBuildContractTestRuntimeClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,testRuntimeClasspath org.springframework:spring-orm:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-test:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,systemTestCompileClasspath,systemTestRuntimeClasspath,testCompileClasspath,testRuntimeClasspath org.springframework:spring-tx:7.0.9=architectureTestCompileClasspath,architectureTestRuntimeClasspath,bootRunH2Classpath,integrationTestCompileClasspath,integrationTestRuntimeClasspath,qualificationRuntimeClasspath,systemTestCompileClasspath,testCompileClasspath,testRuntimeClasspath diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java index 24e4f6ef..41c77504 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ApplicationBoundaryArchitectureTest.java @@ -459,43 +459,80 @@ class ApplicationBoundaryArchitectureTest { }; /** - * What makes a class a way in for a user request: a user-transport adapter package or the - * framework types an endpoint is built from. {@code org.springframework.messaging} is named only - * for STOMP ({@code simp}, {@code @MessageMapping}): a broker listener's {@code @Payload} and - * {@code @Header} live beside them and are a system consumer's, not a user's. + * The framework packages user-transport endpoints are built from, each with its subpackages. + * {@code org.springframework.messaging} is named only for STOMP ({@code simp} here; {@code + * MessageMapping} and the channel interceptors in {@link #USER_TRANSPORT_TYPE_NAMES}): a broker + * listener's {@code @Payload} and {@code @Header} live beside them and are a system consumer's, + * not a user's. * - *

The framework half is a list, unlike the package allowlist above: a transport library - * missing from it is not recognised as one. A service that brings in a new transport library adds - * its packages here (review 2026-11-04 RR3-01-02). + *

This is a list, unlike the package allowlist above: a transport library missing from it is + * not recognised as one. A service that brings in a new transport library adds its packages here + * (review 2026-11-04 RR3-01-02). + */ + static final List USER_TRANSPORT_FRAMEWORK_PACKAGES = + List.of( + "org.springframework.web", + "org.springframework.graphql", + "org.springframework.messaging.simp", + "io.grpc", + "jakarta.servlet", + "jakarta.websocket", + "jakarta.ws.rs", + "graphql"); + + /** + * The single user-transport types named beside the framework packages. A STOMP client-inbound + * channel interceptor sees every frame a client sends and needs no {@code simp} type to act on + * one, so the two interceptor types are named here (review 2026-11-07 RR8-02-01); the rest of + * their package is a broker's plumbing, not an endpoint. + */ + static final Set USER_TRANSPORT_TYPE_NAMES = + Set.of( + "org.springframework.stereotype.Controller", + "org.springframework.messaging.handler.annotation.MessageMapping", + "org.springframework.messaging.support.ChannelInterceptor", + "org.springframework.messaging.support.ExecutorChannelInterceptor"); + + /** + * What makes a class a way in for a user request: a user-transport adapter package, or the + * framework types an endpoint is built from ({@link #USER_TRANSPORT_FRAMEWORK_PACKAGES}, {@link + * #USER_TRANSPORT_TYPE_NAMES}). */ private static final DescribedPredicate ARE_USER_TRANSPORT_TYPES = JavaClass.Predicates.resideInAnyPackage( "..adapter.inbound.web..", "..adapter.inbound.graphql..", "..adapter.inbound.grpc..", - "..adapter.inbound.websocket..", - "org.springframework.web..", - "org.springframework.graphql..", - "org.springframework.messaging.simp..", - "io.grpc..", - "jakarta.servlet..", - "jakarta.websocket..", - "jakarta.ws.rs..", - "graphql..") + "..adapter.inbound.websocket..") .or( - com.tngtech.archunit.core.domain.properties.HasName.Predicates.name( - "org.springframework.stereotype.Controller")) - .or( - com.tngtech.archunit.core.domain.properties.HasName.Predicates.name( - "org.springframework.messaging.handler.annotation.MessageMapping")) - .as("user-transport types (web, JAX-RS, GraphQL, gRPC, WebSocket/STOMP endpoints)"); + JavaClass.Predicates.resideInAnyPackage( + withSubpackages(USER_TRANSPORT_FRAMEWORK_PACKAGES))) + .or(namedAnyOf("user-transport annotations", USER_TRANSPORT_TYPE_NAMES)) + .as( + "user-transport types (web, JAX-RS, GraphQL, gRPC, WebSocket/STOMP endpoints and" + + " STOMP channel interceptors)"); /** Spring's configuration stereotype, which {@code @AutoConfiguration} carries as well. */ private static final String CONFIGURATION = "org.springframework.context.annotation.Configuration"; + /** + * The packages, with their subpackages, of the framework types request-handling code is written + * against or registered with. {@link #ARE_REQUEST_HANDLER_TYPES} names them. + */ + static final List REQUEST_HANDLER_PACKAGES = + List.of( + "org.springframework.web.bind.annotation", + "org.springframework.web.servlet.function", + "org.springframework.web.reactive.function.server", + "org.springframework.web.socket.handler", + "org.springframework.graphql.data.method.annotation", + "org.springframework.graphql.server", + "jakarta.servlet.http", + "graphql.schema"); + /** The single request-handler types {@code ARE_REQUEST_HANDLER_TYPES} names beside packages. */ - private static final Set REQUEST_HANDLER_TYPE_NAMES = + static final Set REQUEST_HANDLER_TYPE_NAMES = Set.of( "org.springframework.stereotype.Controller", "org.springframework.messaging.handler.annotation.MessageMapping", @@ -516,77 +553,143 @@ class ApplicationBoundaryArchitectureTest { "io.grpc.ServerCallHandler", "io.grpc.ServerInterceptor", "io.grpc.ServerCall", - "io.grpc.stub.StreamObserver"); + "io.grpc.stub.StreamObserver", + "org.springframework.messaging.support.ChannelInterceptor", + "org.springframework.messaging.support.ExecutorChannelInterceptor"); /** - * The framework types request-handling code is written against: an annotated controller, a - * functional route or handler function, a servlet, filter or handler interceptor, a WebSocket - * handler, a GraphQL data fetcher, runtime wiring or request interceptor, a gRPC service, call - * handler or server interceptor. A configuration names one only when request-handling code is in - * it — a route or data fetcher written as a lambda compiles into a method of the configuration - * itself — and then the configuration is an endpoint (review 2026-11-05 RR6-01-01). The types a - * configuration names to set a transport up — {@code WebMvcConfigurer}, {@code CorsRegistry}, the - * controller beans it builds — are not here (RR4-01-02). + * The framework types request-handling code is written against or registered with: an annotated + * controller, a functional route or handler function, a servlet, filter or handler interceptor, a + * WebSocket handler, a GraphQL data fetcher, runtime wiring or request interceptor, a gRPC + * service, call handler or server interceptor, a STOMP channel interceptor. A configuration that + * names one holds or registers request-handling code, and then the configuration is an endpoint: + * a route or data fetcher written as a lambda compiles into a method of the configuration itself + * (review 2026-11-05 RR6-01-01), a route registered by method reference names the same route + * builder although its handling code is in another class (review 2026-11-06 RR7-01-02). A + * configuration that is the channel interceptor it registers runs its own method on every client + * frame, and one that hands an interceptor out as a bean names the interceptor type as route + * registration names the builder (review 2026-11-07 RR8-02-01). Setting the inbound channel up + * names only {@code ChannelRegistration}, a setup type. Class dependencies cannot tell that + * registration from handling code, so routes and interceptors are registered in a configuration + * apart from the one that builds a system caller. The types a configuration names to set a + * transport up — {@link #ARE_TRANSPORT_SETUP_TYPES}, the controller beans it builds — do not + * count (RR4-01-02). * - *

Like the type list above, this is a list: a request-handler type missing from it is not - * recognised in a configuration (manual 07 「규칙이 못 보는 길」). + *

Only a configuration itself is read with this list; a class nested in one is read with the + * wider user-transport list (RR7-01-01). Like that list, this one is a list: a request-handler + * type missing from it is not recognised in a configuration (manual 07 「규칙이 못 보는 길」). Every entry + * is a user-transport type too, so an endpoint moved from a configuration into a class nested in + * it is still caught ({@code UserTransportTypeListsTest}). */ private static final DescribedPredicate ARE_REQUEST_HANDLER_TYPES = - JavaClass.Predicates.resideInAnyPackage( - "org.springframework.web.bind.annotation..", - "org.springframework.web.servlet.function..", - "org.springframework.web.reactive.function.server..", - "org.springframework.web.socket.handler..", - "org.springframework.graphql.data.method.annotation..", - "org.springframework.graphql.server..", - "jakarta.servlet.http..", - "graphql.schema..") - .or( - DescribedPredicate.describe( - "request-handler interfaces", - type -> REQUEST_HANDLER_TYPE_NAMES.contains(type.getName()))) + JavaClass.Predicates.resideInAnyPackage(withSubpackages(REQUEST_HANDLER_PACKAGES)) + .or(namedAnyOf("request-handler interfaces", REQUEST_HANDLER_TYPE_NAMES)) .as("request-handler types (controllers, routes, servlets, filters, interceptors, ...)"); + /** + * The packages, with their subpackages, of the types a configuration names to set a transport up + * rather than to handle a request: Spring MVC's, WebFlux's and WebSocket's configurers and + * registries, the STOMP broker registry, and CORS settings. Their code runs while the application + * starts. A class that implements one of them for a request — a CORS source, a CORS processor — + * takes the request as a parameter, and that type counts. + */ + static final List TRANSPORT_SETUP_PACKAGES = + List.of( + "org.springframework.web.servlet.config.annotation", + "org.springframework.web.reactive.config", + "org.springframework.web.socket.config.annotation", + "org.springframework.messaging.simp.config", + "org.springframework.web.cors"); + + /** + * The single setup types: the HTTP method values a CORS mapping lists, which live among the + * controller annotations (review 2026-11-06 RR7-01-02). + */ + static final Set TRANSPORT_SETUP_TYPE_NAMES = + Set.of("org.springframework.web.bind.annotation.RequestMethod"); + + /** + * The types a configuration names to set a transport up: they make neither a configuration nor a + * class nested in one a way in. An anonymous {@code WebMvcConfigurer} that reads the + * configuration's field is part of the configuration (review 2026-11-05 RR6-01-02). + * + *

A setup type missing from here fails the build: the configurer naming it is read as a + * transport. A request-handler type added here would hide an endpoint instead, so no entry may + * cover one ({@code UserTransportTypeListsTest}). + */ + private static final DescribedPredicate ARE_TRANSPORT_SETUP_TYPES = + JavaClass.Predicates.resideInAnyPackage(withSubpackages(TRANSPORT_SETUP_PACKAGES)) + .or(namedAnyOf("transport setup values", TRANSPORT_SETUP_TYPE_NAMES)) + .as("transport setup types (configurers, registries, CORS settings)"); + + /** What makes a configuration a way in: a request-handler type that is no setup type. */ + private static final DescribedPredicate MAKE_A_CONFIGURATION_A_WAY_IN = + ARE_REQUEST_HANDLER_TYPES.and(DescribedPredicate.not(ARE_TRANSPORT_SETUP_TYPES)); + + /** What makes a class nested in a configuration a way in: any user-transport type but setup. */ + private static final DescribedPredicate MAKE_A_NESTED_CLASS_A_WAY_IN = + ARE_USER_TRANSPORT_TYPES.and(DescribedPredicate.not(ARE_TRANSPORT_SETUP_TYPES)); + /** * A class a user request comes in through: it lives in a user-transport package; or it is a - * configuration, or nested in one, that is built from a request-handler type; or it is any other - * class built from a user-transport type. + * configuration built from a request-handler type; or it is nested in a configuration and built + * from a user-transport type other than a setup type; or it is any other class built from a + * user-transport type. * *

A configuration is the composition root, and naming a web type does not make it a way in: a * feature's configuration registers its message handler beside a {@code WebMvcConfigurer} or its * controller without any request passing through it (review 2026-11-04 RR4-01-02). A controller * it builds is checked itself, by its package or its own transport types. What does make it a way - * in is request-handling code written in it: a functional route or a data fetcher is a lambda, - * compiled into the configuration's own method, so the configuration that holds one is the - * endpoint (review 2026-11-05 RR6-01-01). A class nested in a configuration — an anonymous {@code - * WebMvcConfigurer} reading the configuration's field — is read the same way, request handlers - * nested there included (RR6-01-02). + * in is request-handling code it holds or registers: a functional route or a data fetcher written + * as a lambda compiles into the configuration's own method (review 2026-11-05 RR6-01-01), and a + * route registered by method reference names the route builder (review 2026-11-06 RR7-01-02). + * + *

A class nested in a configuration is read like any other class, with the full user-transport + * list, so an endpoint of any transport library kept there is caught — a JAX-RS resource or an + * annotated JSR-356 endpoint as much as a handler function — and so is one that runs the job + * through the configuration that holds it (review 2026-11-06 RR7-01-01). Only setup types are + * left out: an anonymous {@code WebMvcConfigurer} reading the configuration's field is part of + * the configuration (RR6-01-02). */ private static final DescribedPredicate ARE_USER_TRANSPORTS = new DescribedPredicate<>( - "are user transports (in a user-transport package, a configuration with request-handling" - + " code, or another class built from a user-transport type)") { + "are user transports (in a user-transport package, a configuration that holds or registers" + + " request-handling code, or another class built from a user-transport type)") { @Override public boolean test(JavaClass candidate) { if (ARE_USER_TRANSPORT_TYPES.test(candidate)) { return true; } - DescribedPredicate wayIn = - isOrIsNestedInAConfiguration(candidate) - ? ARE_REQUEST_HANDLER_TYPES - : ARE_USER_TRANSPORT_TYPES; + DescribedPredicate wayIn = waysInFor(candidate); return candidate.getDirectDependenciesFromSelf().stream() .anyMatch(dependency -> wayIn.test(dependency.getTargetClass())); } }; - private static boolean isOrIsNestedInAConfiguration(JavaClass candidate) { - for (JavaClass type = candidate; type != null; type = type.getEnclosingClass().orElse(null)) { - if (type.isAnnotatedWith(CONFIGURATION) || type.isMetaAnnotatedWith(CONFIGURATION)) { - return true; + private static DescribedPredicate waysInFor(JavaClass candidate) { + if (isAConfiguration(candidate)) { + return MAKE_A_CONFIGURATION_A_WAY_IN; + } + for (JavaClass type = candidate.getEnclosingClass().orElse(null); + type != null; + type = type.getEnclosingClass().orElse(null)) { + if (isAConfiguration(type)) { + return MAKE_A_NESTED_CLASS_A_WAY_IN; } } - return false; + return ARE_USER_TRANSPORT_TYPES; + } + + private static boolean isAConfiguration(JavaClass type) { + return type.isAnnotatedWith(CONFIGURATION) || type.isMetaAnnotatedWith(CONFIGURATION); + } + + private static String[] withSubpackages(List packages) { + return packages.stream().map(name -> name + "..").toArray(String[]::new); + } + + private static DescribedPredicate namedAnyOf(String description, Set names) { + return DescribedPredicate.describe(description, type -> names.contains(type.getName())); } /** @@ -692,16 +795,17 @@ class ApplicationBoundaryArchitectureTest { * no permission guards (review 2026-11-04 RR3-01-01). Reaching the job's own interface, or any * project type the job extends or implements, counts as reaching the job: that is the type the * endpoint is handed when it injects by interface (RR4-01-01). A configuration may register the - * handler beside web beans (RR4-01-02), but not beside request-handling code of its own, such as - * a functional route (RR6-01-01). + * handler beside web beans (RR4-01-02), but not beside request-handling code it holds or + * registers, such as a functional route, whether written as a lambda (RR6-01-01) or a method + * reference (review 2026-11-06 RR7-01-02). * *

It reads class dependencies, so it sees every typed path, including {@code * ObjectProvider} and {@code getBean(TheJob.class)}: both name the type. It cannot see a * path that names no type the job is handed as — a lookup by bean name or by {@code Object}, or a * configuration that passes a user transport a function wrapping the job ({@code job::run} as a - * {@code Runnable}) — nor request-handling code in a configuration written against a type {@code - * ARE_REQUEST_HANDLER_TYPES} does not list. Manual 07 「시스템이 부르는 쓰기」 lists those paths and what - * holds them. + * {@code Runnable}) — nor request-handling code in a configuration itself written against a type + * {@code ARE_REQUEST_HANDLER_TYPES} does not list. Manual 07 「시스템이 부르는 쓰기」 lists those paths and + * what holds them. */ @ArchTest static final ArchRule USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS = @@ -711,13 +815,17 @@ class ApplicationBoundaryArchitectureTest { .transitivelyDependOnClassesThat(ARE_TYPES_A_SYSTEM_CALLER_IS_HANDED_AS) .as( "USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS: a class a user request comes in " - + "through (a user-transport package; a configuration, or a class nested in one, " - + "with request-handling code such as a functional route or a data fetcher; any " - + "other class built from a web, JAX-RS, GraphQL, gRPC or WebSocket type) does " - + "not reach a @SystemCaller or a " + + "through (a user-transport package; a configuration that holds or registers " + + "request-handling code such as a functional route, a data fetcher or an " + + "interceptor; a class nested in a configuration built from a web, JAX-RS, " + + "GraphQL, gRPC, WebSocket or STOMP type — a channel interceptor among them — " + + "other than a setup type such as WebMvcConfigurer; any other class built from " + + "one of those types) does not " + + "reach a @SystemCaller or a " + "project type one extends or implements, directly or through other classes — " - + "the system caller runs a @SystemInvoked write with no permission check. A " - + "user-triggered run of the same work is its own use case with " + + "the system caller runs a @SystemInvoked write with no permission check. " + + "Register routes, data fetchers and interceptors in a configuration apart from " + + "the one that builds the system caller. A user-triggered run of the same work is its own use case with " + "@RequiresPermission (manual 07 「시스템이 부르는 쓰기」)") .allowEmptyShould(true); diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java index 0b82c1e1..c6e997b5 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/ArchitectureViolationFixtureTest.java @@ -13,9 +13,17 @@ import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.S import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerWithNestedValueTypesFixture; import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.web.PingControllerFixture; import dev.caskeleton.bootstrap.architecture.allowed.application.CleanProjectionQueryPort; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.FrameCountingInterceptorFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.FrameInterceptorConfigurationFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.OrderHandlerFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.OrderRoutesConfigurationFixture; import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideControllerRegistrationFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideCorsMappingFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideCorsSourceFixture; import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideFieldReadingWebMvcConfigurerFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideStompBrokerSetupFixture; import dev.caskeleton.bootstrap.architecture.allowed.configuration.SystemCallerBesideWebMvcRegistrationFixture; +import dev.caskeleton.bootstrap.architecture.allowed.persistence.flyway.SchemaPolicyFlywayFixture; import dev.caskeleton.bootstrap.architecture.fixtures.application.RootWriteTransactionBoundaryUseCase; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.SystemCallerRestControllerFixture; import dev.caskeleton.bootstrap.architecture.violations.adapter.inbound.messaging.UnmarkedSystemInvokedHandlerFixture; @@ -44,15 +52,23 @@ import dev.caskeleton.bootstrap.architecture.violations.application.OutboundWith import dev.caskeleton.bootstrap.architecture.violations.application.RawLeakQueryPort; import dev.caskeleton.bootstrap.architecture.violations.application.ReadOnlyRepositoryWriteUseCase; import dev.caskeleton.bootstrap.architecture.violations.application.SystemInvokedFixtureUseCase; +import dev.caskeleton.bootstrap.architecture.violations.configuration.RoutesBesideASystemCallerConfigurationFixture; import dev.caskeleton.bootstrap.architecture.violations.configuration.RunNowHandlerFunctionConfigurationFixture; import dev.caskeleton.bootstrap.architecture.violations.configuration.RunNowRouteConfigurationFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.AnnotatedPublicNoArgValueObjectFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.JakartaValidationDomainFixture; import dev.caskeleton.bootstrap.architecture.violations.domain.entity.FakeDomainEntity; import dev.caskeleton.bootstrap.architecture.violations.domain.vo.PackagePublicNoArgValueObjectFixture; +import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.ClassicConfigurationFlywayFixture; +import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.ConfigureCallingFlywayFixture; +import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.FluentConfigurationFlywayFixture; +import dev.caskeleton.bootstrap.architecture.violations.persistence.flyway.ReferencedConfigurationFlywayFixture; import dev.caskeleton.bootstrap.architecture.violations.streaming.JakartaWebSocketEndpointFixture; import dev.caskeleton.bootstrap.architecture.violations.streaming.SpringWebSocketHandlerFixture; +import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.ValueSource; /** * Negative ("violations-as-data") tests proving each architecture rule actually catches the @@ -322,9 +338,8 @@ class ArchitectureViolationFixtureTest { "dev.caskeleton.bootstrap.architecture.violations.configuration.graphqljava", "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging"); - // RR6-01-02: a class nested in a configuration is read as the configuration is — a request - // handler - // nested there is still a transport, a configurer reading the configuration's field is not. + // RR6-01-02: a request handler nested in a configuration is still a transport; a configurer + // reading the configuration's field names only setup types and is not. private static final JavaClasses HANDLER_FUNCTION_NESTED_IN_A_CONFIGURATION_FIXTURE_ONLY = new ClassFileImporter() .importClasses( @@ -345,6 +360,94 @@ class ArchitectureViolationFixtureTest { SystemCallerBesideFieldReadingWebMvcConfigurerFixture.class, SystemCallerHandlerFixture.class)); + // Review 2026-11-06 RR7-01-01: endpoints a configuration keeps nested in it, built from types the + // request-handler list does not name — a JAX-RS resource, one that runs the job through its + // configuration, an annotated JSR-356 endpoint. importPackages, so the compile-only JAX-RS and + // WebSocket types are never linked. + private static final String NESTED_JAXRS_FIXTURES = + "dev.caskeleton.bootstrap.architecture.violations.configuration.jaxrs"; + + private static final JavaClasses JAXRS_RESOURCES_IN_A_CONFIGURATION_FIXTURE_ONLY = + new ClassFileImporter() + .importPackages( + NESTED_JAXRS_FIXTURES, + "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging"); + + private static final JavaClasses SERVER_ENDPOINT_IN_A_CONFIGURATION_FIXTURE_ONLY = + new ClassFileImporter() + .importPackages( + "dev.caskeleton.bootstrap.architecture.violations.configuration.jsr356", + "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging"); + + // RR8-02-01: a STOMP client-inbound channel interceptor runs on every frame a client sends, so it + // is a way in wherever it is kept — nested in a configuration, on its own, or the configuration + // itself — whether or not it reads a STOMP header, and a configuration handing one out as a bean + // is read as one registering routes is. Setting the inbound channel's threads up beside a system + // caller registers no interceptor and is setup; the interceptor bean in a configuration of its + // own passes. + private static final String STOMP_INTERCEPTOR_FIXTURES = + "dev.caskeleton.bootstrap.architecture.violations.configuration.stomp"; + + private static final JavaClasses STOMP_INTERCEPTORS_CALLING_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importPackages( + STOMP_INTERCEPTOR_FIXTURES, + "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging"); + + private static final JavaClasses SYSTEM_CALLER_BESIDE_STOMP_BROKER_SETUP_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + SystemCallerBesideStompBrokerSetupFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + private static final JavaClasses INTERCEPTOR_APART_FROM_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + FrameInterceptorConfigurationFixture.class, + FrameCountingInterceptorFixture.class, + SystemCallerHandlerRegistrationFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + // RR7-01-02: routes registered by method reference make their configuration an endpoint, so the + // configuration that also builds a system caller is caught and the same routes in a configuration + // of their own pass. A CORS setup naming RequestMethod is setup, in the configuration and in its + // configurer alike. + private static final JavaClasses ROUTES_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + RoutesBesideASystemCallerConfigurationFixture.class, + OrderHandlerFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + private static final JavaClasses ROUTES_APART_FROM_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + OrderRoutesConfigurationFixture.class, + OrderHandlerFixture.class, + SystemCallerHandlerRegistrationFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + private static final JavaClasses CORS_SOURCE_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importClasses( + SystemCallerBesideCorsSourceFixture.class, + SystemCallerHandlerFixture.class, + SystemInvokedFixtureUseCase.class); + + // The anonymous configurer has no class literal, as above. + private static final JavaClasses CORS_MAPPING_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY = + new ClassFileImporter() + .importPackages( + "dev.caskeleton.bootstrap.architecture.allowed.configuration", + "dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging") + .that( + JavaClass.Predicates.belongToAnyOf( + SystemCallerBesideCorsMappingFixture.class, SystemCallerHandlerFixture.class)); + // RR6-01-03: a system caller's nested record, enum and exception, and a system caller that is a // record — none of them a type an endpoint injects it as. private static final JavaClasses SYSTEM_CALLER_WITH_NESTED_VALUE_TYPES_FIXTURE_ONLY = @@ -626,6 +729,158 @@ class ArchitectureViolationFixtureTest { assertThat(result.getFailureReport().getDetails()).isEmpty(); } + @Test + void aJaxRsResourceNestedInAConfigurationThatCallsASystemCallerIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + JAXRS_RESOURCES_IN_A_CONFIGURATION_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "<" + + NESTED_JAXRS_FIXTURES + + ".RunNowResourceConfigurationFixture$RunNowResource>") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void aNestedEndpointThatRunsASystemCallerThroughItsConfigurationIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + JAXRS_RESOURCES_IN_A_CONFIGURATION_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "<" + + NESTED_JAXRS_FIXTURES + + ".RunNowThroughTheConfigurationFixture$RunNowResource>") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void anAnnotatedWebSocketEndpointNestedInAConfigurationThatCallsASystemCallerIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + SERVER_ENDPOINT_IN_A_CONFIGURATION_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @ParameterizedTest + @ValueSource( + strings = { + "RunNowOnFrameConfigurationFixture$1", + "RunNowOnFrameConfigurationFixture$RunNowAfterHandling", + "RunNowOnFrameInterceptorFixture", + "RunNowInterceptingConfigurationFixture", + "InterceptorBesideASystemCallerConfigurationFixture" + }) + void aStompChannelInterceptorThatCallsASystemCallerIsCaughtWhereverItIsKept(String interceptor) { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + STOMP_INTERCEPTORS_CALLING_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains("<" + STOMP_INTERCEPTOR_FIXTURES + "." + interceptor + ">") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void aStompBrokerSetUpBesideASystemCallerPasses() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + SYSTEM_CALLER_BESIDE_STOMP_BROKER_SETUP_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + + @Test + void aChannelInterceptorHandedOutApartFromTheSystemCallersConfigurationPasses() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + INTERCEPTOR_APART_FROM_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + + @Test + void aConfigurationThatRegistersMethodReferenceRoutesBesideASystemCallerIsCaught() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + ROUTES_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()) + .anySatisfy( + detail -> + assertThat(detail) + .contains( + "<" + RoutesBesideASystemCallerConfigurationFixture.class.getName() + ">") + .contains(SystemCallerHandlerFixture.class.getName())); + } + + @Test + void routesRegisteredApartFromTheSystemCallersConfigurationPass() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + ROUTES_APART_FROM_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + + @Test + void aConfigurationNamingRequestMethodForCorsMayRegisterASystemCaller() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + CORS_SOURCE_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + + @Test + void aCorsConfigurerNestedInAConfigurationMayNameRequestMethodAndReadTheConfigurationsField() { + // when + EvaluationResult result = + ApplicationBoundaryArchitectureTest.USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS.evaluate( + CORS_MAPPING_BESIDE_A_SYSTEM_CALLER_FIXTURE_ONLY); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } + @Test void aSystemCallersNestedRecordEnumAndExceptionPassTheSupertypeRule() { // when @@ -1383,4 +1638,44 @@ class ArchitectureViolationFixtureTest { + "it references no broker/HTTP type") .isFalse(); } + + @ParameterizedTest + @ValueSource( + classes = { + ConfigureCallingFlywayFixture.class, + FluentConfigurationFlywayFixture.class, + ClassicConfigurationFlywayFixture.class, + ReferencedConfigurationFlywayFixture.class + }) + @DisplayName("FlywaySchemaPolicy를 거치지 않고 Flyway를 만드는 길은 어느 것이든 Flyway 규칙에 걸린다") + void everyWayToBuildAFlywayPastTheSchemaPolicyIsCaught(Class fixture) { + // given + JavaClasses fixtureOnly = new ClassFileImporter().importClasses(fixture); + + // when + EvaluationResult result = + JpaProductionArchitectureTest.EVERY_FLYWAY_STARTS_FROM_THE_SCHEMA_POLICY.evaluate( + fixtureOnly); + + // then + assertThat(result.hasViolation()) + .as("%s builds a Flyway past FlywaySchemaPolicy.configure()", fixture.getSimpleName()) + .isTrue(); + } + + @Test + @DisplayName("FlywaySchemaPolicy.configure()에서 시작한 Flyway는 빌더로도 생성자로도 Flyway 규칙에 걸리지 않는다") + void aFlywayBuiltFromTheSchemaPolicyIsNotFlagged() { + // given + JavaClasses fixtureOnly = + new ClassFileImporter().importClasses(SchemaPolicyFlywayFixture.class); + + // when + EvaluationResult result = + JpaProductionArchitectureTest.EVERY_FLYWAY_STARTS_FROM_THE_SCHEMA_POLICY.evaluate( + fixtureOnly); + + // then + assertThat(result.getFailureReport().getDetails()).isEmpty(); + } } diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java index a17fdf6b..07ea43dc 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/JpaProductionArchitectureTest.java @@ -3,8 +3,12 @@ package dev.caskeleton.bootstrap.architecture; import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; import static org.assertj.core.api.Assertions.assertThat; +import com.tngtech.archunit.base.DescribedPredicate; +import com.tngtech.archunit.core.domain.JavaAccess; import com.tngtech.archunit.core.domain.JavaClasses; +import com.tngtech.archunit.core.domain.JavaConstructor; import com.tngtech.archunit.core.importer.ClassFileImporter; +import com.tngtech.archunit.lang.ArchRule; import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy; import dev.caskeleton.adapter.outbound.persistence.testkit.arch.JpaArchitectureRules; import jakarta.persistence.Entity; @@ -164,29 +168,63 @@ class JpaProductionArchitectureTest { .check(productionClasses); } + /** + * A call to, or a reference to ({@code FluentConfiguration::new}), a constructor of a type that + * is a Flyway {@code Configuration}. + */ + private static final DescribedPredicate> CONSTRUCTS_A_FLYWAY_CONFIGURATION = + DescribedPredicate.describe( + "a constructor of a Flyway Configuration", + access -> + JavaConstructor.CONSTRUCTOR_NAME.equals(access.getTarget().getName()) + && access + .getTargetOwner() + .isAssignableTo("org.flywaydb.core.api.configuration.Configuration")); + + /** + * Every Flyway the template builds starts from {@code FlywaySchemaPolicy.configure()}. + * + *

Flyway's PostgreSQL default holds its lock in a transaction left open for the whole run, and + * a concurrent index build waits for it without end (re-review 2026-11-03 round 6, RR6-03-01). + * FlywaySchemaPolicy.configure() holds it for the session; a stream that builds its own Flyway + * gets the default back. The inbox stream of adapter:inbound:messaging may not depend on + * persistence-jpa and keeps its own copy, held to the same value by its own test. + * + *

A Flyway has two starts besides the policy: {@code Flyway.configure()}, and a configuration + * built directly — {@code new FluentConfiguration()}, {@code new ClassicConfiguration()}, or a + * class of its own that extends or implements one — which {@code load()} or {@code new + * Flyway(...)} turns into a Flyway. The rule refuses both: the method, and constructing anything + * that is a Flyway {@code Configuration}, by a call or a constructor reference. {@code new + * Flyway(...)} itself stays allowed; over the policy's configuration it is the policy's Flyway + * (round 7, RR7-03-06: the rule saw only the method). The fixtures in {@code + * ..violations.persistence.flyway} and {@code ..allowed.persistence.flyway} show it catches the + * method, both constructors and a constructor reference, and passes the policy. A subclass has no + * fixture: SpotBugs cannot analyse a class that extends Flyway's configuration (it misses {@code + * lombok.Generated}, which the build treats as a failed analysis). Its constructor calls the + * configuration's, the access this rule refuses. + */ + static final ArchRule EVERY_FLYWAY_STARTS_FROM_THE_SCHEMA_POLICY = + noClasses() + .that() + .doNotHaveFullyQualifiedName(FlywaySchemaPolicy.class.getName()) + .and() + .doNotHaveFullyQualifiedName( + "dev.caskeleton.adapter.inbound.messaging.MessagingInboxSchemaStream") + .should() + .callMethod("org.flywaydb.core.Flyway", "configure") + .orShould() + .callMethod("org.flywaydb.core.Flyway", "configure", "java.lang.ClassLoader") + .orShould() + .accessTargetWhere(CONSTRUCTS_A_FLYWAY_CONFIGURATION) + .because( + "every Flyway the template builds starts from FlywaySchemaPolicy.configure(), which" + + " holds Flyway's PostgreSQL lock for the session (docs/jpa/migration-guide.md," + + " \"Concurrent index builds\")"); + @Test - @DisplayName("Flyway.configure()를 부르는 운영 코드는 FlywaySchemaPolicy뿐이다") + @DisplayName("Flyway.configure()를 부르거나 Flyway 설정 객체를 직접 만드는 운영 코드는 FlywaySchemaPolicy뿐이다") void everyProductionFlywayIsConfiguredThroughTheSchemaPolicy() { - // Flyway's PostgreSQL default holds its lock in a transaction left open for the whole run, and - // a concurrent index build waits for it without end (re-review 2026-11-03 round 6, RR6-03-01). - // FlywaySchemaPolicy.configure() holds it for the session; a stream that builds its own Flyway - // gets the default back. The inbox stream of adapter:inbound:messaging may not depend on - // persistence-jpa and keeps its own copy, held to the same value by its own test. - noClasses() - .that() - .doNotHaveFullyQualifiedName(FlywaySchemaPolicy.class.getName()) - .and() - .doNotHaveFullyQualifiedName( - "dev.caskeleton.adapter.inbound.messaging.MessagingInboxSchemaStream") - .should() - .callMethod("org.flywaydb.core.Flyway", "configure") - .orShould() - .callMethod("org.flywaydb.core.Flyway", "configure", "java.lang.ClassLoader") - .because( - "every Flyway the template builds starts from FlywaySchemaPolicy.configure(), which" - + " holds Flyway's PostgreSQL lock for the session (docs/jpa/migration-guide.md," - + " \"Concurrent index builds\")") - .check(productionClasses); + EVERY_FLYWAY_STARTS_FROM_THE_SCHEMA_POLICY.check(productionClasses); } @Test diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/RuntimeProfileAccessArchitectureTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/RuntimeProfileAccessArchitectureTest.java index f32f513e..f47f24c6 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/RuntimeProfileAccessArchitectureTest.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/RuntimeProfileAccessArchitectureTest.java @@ -46,7 +46,7 @@ class RuntimeProfileAccessArchitectureTest { .that() .resideInAPackage("dev.caskeleton..") .and() - .resideOutsideOfPackages("dev.caskeleton.messaging..", "dev.caskeleton.sample..") + .resideOutsideOfPackage("dev.caskeleton.messaging..") .and(DescribedPredicate.not(A_NAMED_PROFILE_READER)) .should() .callMethod(Environment.class, "getActiveProfiles") diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java new file mode 100644 index 00000000..766ce6fc --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/UserTransportTypeListsTest.java @@ -0,0 +1,81 @@ +package dev.caskeleton.bootstrap.architecture; + +import static org.assertj.core.api.Assertions.assertThat; + +import java.util.Collection; +import java.util.List; +import java.util.stream.Stream; +import org.junit.jupiter.api.Test; + +/** + * The three type lists {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS} reads a class with stay + * in the shape that keeps the rule closed. + * + *

A configuration is read with the request-handler list, a class nested in one with the full + * user-transport list, and both leave out setup types. The two lists drifted apart once: the + * request-handler list named no JAX-RS type, and while nested classes were read with it, a JAX-RS + * resource kept in a configuration passed (review 2026-11-06 RR7-01-01). So every request-handler + * entry has to be a user-transport type too — then moving an endpoint from a configuration into a + * class nested in it cannot hide it — and no setup entry may cover a request-handler type, or it + * would hide that endpoint in both places. + */ +class UserTransportTypeListsTest { + + @Test + void everyRequestHandlerAndSetupEntryIsAUserTransportType() { + // given + List entries = + Stream.>of( + ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_PACKAGES, + ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_TYPE_NAMES, + ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_PACKAGES, + ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_TYPE_NAMES) + .flatMap(Collection::stream) + .toList(); + + // when + List outsideTheUserTransportTypes = + entries.stream() + .filter( + entry -> + !ApplicationBoundaryArchitectureTest.USER_TRANSPORT_TYPE_NAMES.contains(entry) + && !isInAnyOf( + entry, + ApplicationBoundaryArchitectureTest.USER_TRANSPORT_FRAMEWORK_PACKAGES)) + .toList(); + + // then + assertThat(outsideTheUserTransportTypes).isEmpty(); + } + + @Test + void noSetupEntryCoversARequestHandlerType() { + // given + List setupPackages = ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_PACKAGES; + List handlerPackages = ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_PACKAGES; + + // when + List handlerNamesTreatedAsSetup = + ApplicationBoundaryArchitectureTest.REQUEST_HANDLER_TYPE_NAMES.stream() + .filter( + name -> + ApplicationBoundaryArchitectureTest.TRANSPORT_SETUP_TYPE_NAMES.contains(name) + || isInAnyOf(name, setupPackages)) + .toList(); + List overlappingPackages = + Stream.concat( + setupPackages.stream().filter(setup -> isInAnyOf(setup, handlerPackages)), + handlerPackages.stream().filter(handler -> isInAnyOf(handler, setupPackages))) + .toList(); + + // then + assertThat(handlerNamesTreatedAsSetup).isEmpty(); + assertThat(overlappingPackages).isEmpty(); + } + + /** Whether a type or package name is one of the packages or inside one of them. */ + private static boolean isInAnyOf(String name, List packages) { + return packages.stream() + .anyMatch(container -> name.equals(container) || name.startsWith(container + ".")); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/FrameCountingInterceptorFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/FrameCountingInterceptorFixture.java new file mode 100644 index 00000000..126786a0 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/FrameCountingInterceptorFixture.java @@ -0,0 +1,18 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import java.util.concurrent.atomic.AtomicLong; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.support.ChannelInterceptor; + +/** A STOMP client-inbound channel interceptor that only counts the frames it sees. */ +public final class FrameCountingInterceptorFixture implements ChannelInterceptor { + + private final AtomicLong frames = new AtomicLong(); + + @Override + public Message preSend(Message message, MessageChannel channel) { + frames.incrementAndGet(); + return message; + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/FrameInterceptorConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/FrameInterceptorConfigurationFixture.java new file mode 100644 index 00000000..bad9fc1b --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/FrameInterceptorConfigurationFixture.java @@ -0,0 +1,20 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.support.ChannelInterceptor; + +/** + * A feature's channel interceptor bean in a configuration of its own, apart from the one that + * builds the message handler. Handing an interceptor out names a request-handler type, as + * registering a route does, so it does not sit beside a system caller (review 2026-11-07 + * RR8-02-01). + */ +@Configuration(proxyBeanMethods = false) +public class FrameInterceptorConfigurationFixture { + + @Bean + ChannelInterceptor frameCountingInterceptor() { + return new FrameCountingInterceptorFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderHandlerFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderHandlerFixture.java new file mode 100644 index 00000000..e120ae40 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderHandlerFixture.java @@ -0,0 +1,12 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import org.springframework.web.servlet.function.ServerRequest; +import org.springframework.web.servlet.function.ServerResponse; + +/** A feature's functional-endpoint handler, which reaches no system caller. */ +public final class OrderHandlerFixture { + + public ServerResponse list(ServerRequest request) { + return ServerResponse.ok().build(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderRoutesConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderRoutesConfigurationFixture.java new file mode 100644 index 00000000..0297ace6 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/OrderRoutesConfigurationFixture.java @@ -0,0 +1,21 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.RouterFunctions; +import org.springframework.web.servlet.function.ServerResponse; + +/** + * A feature's route registration in a configuration of its own, apart from the configuration that + * builds the feature's message handler ({@code SystemCallerHandlerRegistrationFixture}). This + * configuration is an endpoint, and it reaches no system caller (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class OrderRoutesConfigurationFixture { + + @Bean + RouterFunction orderRoutes(OrderHandlerFixture orders) { + return RouterFunctions.route().GET("/orders", orders::list).build(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsMappingFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsMappingFixture.java new file mode 100644 index 00000000..2ba2e538 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsMappingFixture.java @@ -0,0 +1,42 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.servlet.config.annotation.CorsRegistry; +import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; + +/** + * One feature configuration: a CORS mapping that reads the configuration's own max age, and the + * feature's message handler. The anonymous configurer names only setup types — the configurer, the + * registry and {@code RequestMethod} — so it is part of the configuration, not a way in, although + * it reaches the handler through the field it reads (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class SystemCallerBesideCorsMappingFixture { + + private final long corsMaxAgeSeconds; + + public SystemCallerBesideCorsMappingFixture(long corsMaxAgeSeconds) { + this.corsMaxAgeSeconds = corsMaxAgeSeconds; + } + + @Bean + WebMvcConfigurer featureCorsMapping() { + return new WebMvcConfigurer() { + @Override + public void addCorsMappings(CorsRegistry registry) { + registry + .addMapping("/features/**") + .allowedMethods(RequestMethod.GET.name(), RequestMethod.HEAD.name()) + .maxAge(corsMaxAgeSeconds); + } + }; + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsSourceFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsSourceFixture.java new file mode 100644 index 00000000..4b15f3f6 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideCorsSourceFixture.java @@ -0,0 +1,33 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import java.util.List; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.bind.annotation.RequestMethod; +import org.springframework.web.cors.CorsConfiguration; +import org.springframework.web.cors.CorsConfigurationSource; +import org.springframework.web.cors.UrlBasedCorsConfigurationSource; + +/** + * One feature configuration: its CORS source and its message handler. The configuration names + * {@code RequestMethod} for the methods it allows. That enum lives among the controller annotations + * but is a setup value, not request-handling code (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class SystemCallerBesideCorsSourceFixture { + + @Bean + CorsConfigurationSource featureCorsSource() { + CorsConfiguration cors = new CorsConfiguration(); + cors.setAllowedMethods(List.of(RequestMethod.GET.name(), RequestMethod.HEAD.name())); + UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(); + source.registerCorsConfiguration("/features/**", cors); + return source; + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideStompBrokerSetupFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideStompBrokerSetupFixture.java new file mode 100644 index 00000000..3c127238 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/SystemCallerBesideStompBrokerSetupFixture.java @@ -0,0 +1,32 @@ +package dev.caskeleton.bootstrap.architecture.allowed.configuration; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.simp.config.ChannelRegistration; +import org.springframework.messaging.simp.config.MessageBrokerRegistry; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + +/** + * One feature configuration: its STOMP broker and the client-inbound channel's threads, set up + * beside the feature's message handler. Setting the channel up registers no interceptor, so no + * client frame runs code of this configuration (review 2026-11-07 RR8-02-01). + */ +@Configuration(proxyBeanMethods = false) +public class SystemCallerBesideStompBrokerSetupFixture implements WebSocketMessageBrokerConfigurer { + + @Override + public void configureMessageBroker(MessageBrokerRegistry registry) { + registry.enableSimpleBroker("/topic"); + } + + @Override + public void configureClientInboundChannel(ChannelRegistration registration) { + registration.taskExecutor().corePoolSize(2); + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java index dd3860fc..f73016cf 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/configuration/package-info.java @@ -1,9 +1,11 @@ /** * "Allowed-as-data" composition for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a * feature's configuration that registers its message handler beside its web beans — a {@code - * WebMvcConfigurer}, or the feature's controller. A configuration is the composition root, not a - * way a user request comes in, so naming a web type does not make it a user transport (review - * 2026-11-04 RR4-01-02). Manual 09 「소비」 step 4 registers the handler in "this leaf's configuration - * class", which is where both kinds of bean meet. + * WebMvcConfigurer}, a CORS setup, a STOMP broker setup, or the feature's controller. A + * configuration is the composition root, not a way a user request comes in, so naming a web type + * does not make it a user transport (review 2026-11-04 RR4-01-02); registering routes does, so the + * feature's routes sit in a configuration of their own (review 2026-11-06 RR7-01-02), and so does + * its STOMP channel interceptor bean (review 2026-11-07 RR8-02-01). Manual 09 「소비」 step 4 registers + * the handler in "this leaf's configuration class", which is where both kinds of bean meet. */ package dev.caskeleton.bootstrap.architecture.allowed.configuration; diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/persistence/flyway/SchemaPolicyFlywayFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/persistence/flyway/SchemaPolicyFlywayFixture.java new file mode 100644 index 00000000..39f0c4a7 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/persistence/flyway/SchemaPolicyFlywayFixture.java @@ -0,0 +1,17 @@ +package dev.caskeleton.bootstrap.architecture.allowed.persistence.flyway; + +import dev.caskeleton.adapter.outbound.persistence.migration.FlywaySchemaPolicy; +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; + +/** Builds a Flyway from the schema policy, the two ways a stream does. */ +public class SchemaPolicyFlywayFixture { + + public Flyway flyway(DataSource dataSource) { + return FlywaySchemaPolicy.configure().dataSource(dataSource).load(); + } + + public Flyway flywayFromTheConstructor(DataSource dataSource) { + return new Flyway(FlywaySchemaPolicy.configure().dataSource(dataSource)); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/persistence/flyway/package-info.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/persistence/flyway/package-info.java new file mode 100644 index 00000000..c2487b8a --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/allowed/persistence/flyway/package-info.java @@ -0,0 +1,6 @@ +/** + * "Allowed-as-data" for {@code EVERY_FLYWAY_STARTS_FROM_THE_SCHEMA_POLICY}: a Flyway built from + * {@code FlywaySchemaPolicy.configure()}, by its builder or by the {@code Flyway} constructor over + * the policy's configuration, is what the rule asks for and is not flagged. + */ +package dev.caskeleton.bootstrap.architecture.allowed.persistence.flyway; diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RoutesBesideASystemCallerConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RoutesBesideASystemCallerConfigurationFixture.java new file mode 100644 index 00000000..4b7a6dbe --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RoutesBesideASystemCallerConfigurationFixture.java @@ -0,0 +1,32 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.OrderHandlerFixture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.servlet.function.RouterFunction; +import org.springframework.web.servlet.function.RouterFunctions; +import org.springframework.web.servlet.function.ServerResponse; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: one feature + * configuration registers its functional routes and builds its message handler. The handling code + * is in {@link OrderHandlerFixture}, referenced by method, so no request runs through this class. + * Registering the route still names the route builder, a request-handler type, and class + * dependencies cannot tell the registration from handling code: the configuration is read as an + * endpoint that reaches the handler. The routes go in a configuration of their own ({@code + * OrderRoutesConfigurationFixture}) (review 2026-11-06 RR7-01-02). + */ +@Configuration(proxyBeanMethods = false) +public class RoutesBesideASystemCallerConfigurationFixture { + + @Bean + RouterFunction orderRoutes(OrderHandlerFixture orders) { + return RouterFunctions.route().GET("/orders", orders::list).build(); + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java index 46b43112..05036900 100644 --- a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/RunNowHandlerFunctionConfigurationFixture.java @@ -10,8 +10,9 @@ import org.springframework.web.servlet.function.ServerResponse; /** * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: the configuration * itself names no request-handler type, but the handler function it registers is a class nested in - * it. A class nested in a configuration is read as the configuration is, request handlers included, - * so the nested endpoint is still a user transport (review 2026-11-05 RR6-01-02). + * it. A class nested in a configuration is a user transport when it is built from a user-transport + * type other than a setup type, so the nested endpoint is caught (review 2026-11-05 RR6-01-02, + * 2026-11-06 RR7-01-01). */ @Configuration(proxyBeanMethods = false) public class RunNowHandlerFunctionConfigurationFixture { diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowResourceConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowResourceConfigurationFixture.java new file mode 100644 index 00000000..609d6c2f --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowResourceConfigurationFixture.java @@ -0,0 +1,33 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.jaxrs; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import org.springframework.context.annotation.Configuration; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a JAX-RS "run now" + * resource kept in the feature configuration. The request-handler list a configuration is read with + * names no JAX-RS type; a class nested in a configuration is read with the full user-transport + * list, so the resource is still a transport (review 2026-11-06 RR7-01-01). Loaded with {@code + * importPackages}: {@code jakarta.ws.rs-api} is compile-only here, so JUnit must never link it. + */ +@Configuration(proxyBeanMethods = false) +public class RunNowResourceConfigurationFixture { + + /** The resource, kept beside the configuration. */ + @Path("/admin/nightly/run-now") + public static final class RunNowResource { + + private final SystemCallerHandlerFixture handler; + + public RunNowResource(SystemCallerHandlerFixture handler) { + this.handler = handler; + } + + @POST + public void runNow() { + handler.handle(); + } + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowThroughTheConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowThroughTheConfigurationFixture.java new file mode 100644 index 00000000..6aa24dd7 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jaxrs/RunNowThroughTheConfigurationFixture.java @@ -0,0 +1,34 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.jaxrs; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import jakarta.ws.rs.POST; +import jakarta.ws.rs.Path; +import org.springframework.context.annotation.Configuration; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a "run now" resource + * nested in the configuration that holds the system caller. The resource never names the caller; it + * asks the configuration to run it. The path through the enclosing configuration is followed like + * any other, so the resource is caught — which is why a configurer reading the configuration's + * field is let through by its setup types, not by skipping that path (review 2026-11-06 RR7-01-01). + * Loaded with {@code importPackages}: {@code jakarta.ws.rs-api} is compile-only here. + */ +@Configuration(proxyBeanMethods = false) +public class RunNowThroughTheConfigurationFixture { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + void runNightly() { + handler.handle(); + } + + /** The resource, an inner class that runs the job through its configuration. */ + @Path("/admin/nightly/run-now") + public final class RunNowResource { + + @POST + public void runNow() { + runNightly(); + } + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jsr356/RunNowEndpointConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jsr356/RunNowEndpointConfigurationFixture.java new file mode 100644 index 00000000..219b2b64 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/jsr356/RunNowEndpointConfigurationFixture.java @@ -0,0 +1,29 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.jsr356; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import jakarta.websocket.OnMessage; +import jakarta.websocket.server.ServerEndpoint; +import org.springframework.context.annotation.Configuration; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: an annotated JSR-356 + * "run now" endpoint kept in the feature configuration. Like the JAX-RS resource beside it, it is + * built from types only the full user-transport list names (review 2026-11-06 RR7-01-01). Loaded + * with {@code importPackages}: {@code jakarta.websocket-api} is compile-only here. + */ +@Configuration(proxyBeanMethods = false) +public class RunNowEndpointConfigurationFixture { + + /** The endpoint, kept beside the configuration. */ + @ServerEndpoint("/admin/nightly/run-now") + public static final class RunNowEndpoint { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + @OnMessage + public String onMessage(String message) { + handler.handle(); + return message; + } + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/InterceptorBesideASystemCallerConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/InterceptorBesideASystemCallerConfigurationFixture.java new file mode 100644 index 00000000..9af97864 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/InterceptorBesideASystemCallerConfigurationFixture.java @@ -0,0 +1,29 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.stomp; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import dev.caskeleton.bootstrap.architecture.allowed.configuration.FrameCountingInterceptorFixture; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.support.ChannelInterceptor; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: one feature + * configuration hands a channel interceptor out as a bean, the usual way to register one, and + * builds its message handler. The interceptor itself runs no job. Handing it out still names the + * interceptor type, a request-handler type, so the configuration is read as an endpoint that + * reaches the handler, as one registering routes is. The interceptor bean goes in a configuration + * of its own ({@code FrameInterceptorConfigurationFixture}) (review 2026-11-07 RR8-02-01). + */ +@Configuration(proxyBeanMethods = false) +public class InterceptorBesideASystemCallerConfigurationFixture { + + @Bean + ChannelInterceptor frameCountingInterceptor() { + return new FrameCountingInterceptorFixture(); + } + + @Bean + SystemCallerHandlerFixture systemCallerHandler() { + return new SystemCallerHandlerFixture(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/RunNowInterceptingConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/RunNowInterceptingConfigurationFixture.java new file mode 100644 index 00000000..f43d3ff0 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/RunNowInterceptingConfigurationFixture.java @@ -0,0 +1,33 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.stomp; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.simp.config.ChannelRegistration; +import org.springframework.messaging.support.ChannelInterceptor; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a feature configuration + * that is itself the channel interceptor it registers. Its own method runs on each client frame, so + * the configuration is the endpoint, as one holding a route written as a lambda is (review + * 2026-11-07 RR8-02-01). + */ +@Configuration(proxyBeanMethods = false) +public class RunNowInterceptingConfigurationFixture + implements WebSocketMessageBrokerConfigurer, ChannelInterceptor { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + @Override + public void configureClientInboundChannel(ChannelRegistration registration) { + registration.interceptors(this); + } + + @Override + public Message preSend(Message message, MessageChannel channel) { + handler.handle(); + return message; + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/RunNowOnFrameConfigurationFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/RunNowOnFrameConfigurationFixture.java new file mode 100644 index 00000000..e074609f --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/RunNowOnFrameConfigurationFixture.java @@ -0,0 +1,51 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.stomp; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import org.springframework.context.annotation.Configuration; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.MessageHandler; +import org.springframework.messaging.simp.config.ChannelRegistration; +import org.springframework.messaging.support.ChannelInterceptor; +import org.springframework.messaging.support.ExecutorChannelInterceptor; +import org.springframework.web.socket.config.annotation.WebSocketMessageBrokerConfigurer; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: STOMP client-inbound + * channel interceptors a feature configuration registers beside the system caller it holds. Every + * frame a client sends passes through them, so each is a way a user request comes in, although the + * configuration names only setup types and neither interceptor reads a STOMP header (review + * 2026-11-07 RR8-02-01). The anonymous one runs the job before the frame is sent on, the nested one + * after the frame is handled on the channel's executor. Loaded with {@code importPackages}: + * spring-messaging is compile-only here. + */ +@Configuration(proxyBeanMethods = false) +public class RunNowOnFrameConfigurationFixture implements WebSocketMessageBrokerConfigurer { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + @Override + public void configureClientInboundChannel(ChannelRegistration registration) { + registration.interceptors( + new ChannelInterceptor() { + @Override + public Message preSend(Message message, MessageChannel channel) { + handler.handle(); + return message; + } + }, + new RunNowAfterHandling()); + } + + /** Runs the job after each client frame is handled on the inbound channel's executor. */ + public static final class RunNowAfterHandling implements ExecutorChannelInterceptor { + + private final SystemCallerHandlerFixture job = new SystemCallerHandlerFixture(); + + @Override + public void afterMessageHandled( + Message message, MessageChannel channel, MessageHandler handler, Exception failure) { + job.handle(); + } + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/RunNowOnFrameInterceptorFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/RunNowOnFrameInterceptorFixture.java new file mode 100644 index 00000000..53a02e4e --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/configuration/stomp/RunNowOnFrameInterceptorFixture.java @@ -0,0 +1,23 @@ +package dev.caskeleton.bootstrap.architecture.violations.configuration.stomp; + +import dev.caskeleton.bootstrap.architecture.allowed.adapter.inbound.messaging.SystemCallerHandlerFixture; +import org.springframework.messaging.Message; +import org.springframework.messaging.MessageChannel; +import org.springframework.messaging.support.ChannelInterceptor; + +/** + * Negative fixture for {@code USER_TRANSPORTS_DO_NOT_REACH_SYSTEM_CALLERS}: a STOMP client-inbound + * channel interceptor of its own, outside every user-transport package, that runs the job on each + * frame a client sends. It reads no STOMP header, so it names no {@code simp} type (review + * 2026-11-07 RR8-02-01). + */ +public final class RunNowOnFrameInterceptorFixture implements ChannelInterceptor { + + private final SystemCallerHandlerFixture handler = new SystemCallerHandlerFixture(); + + @Override + public Message preSend(Message message, MessageChannel channel) { + handler.handle(); + return message; + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/ClassicConfigurationFlywayFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/ClassicConfigurationFlywayFixture.java new file mode 100644 index 00000000..2725ccd4 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/ClassicConfigurationFlywayFixture.java @@ -0,0 +1,15 @@ +package dev.caskeleton.bootstrap.architecture.violations.persistence.flyway; + +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.ClassicConfiguration; + +/** Builds a Flyway around {@code new ClassicConfiguration()}, the mutable configuration. */ +public class ClassicConfigurationFlywayFixture { + + public Flyway flyway(DataSource dataSource) { + ClassicConfiguration configuration = new ClassicConfiguration(); + configuration.setDataSource(dataSource); + return new Flyway(configuration); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/ConfigureCallingFlywayFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/ConfigureCallingFlywayFixture.java new file mode 100644 index 00000000..3754f095 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/ConfigureCallingFlywayFixture.java @@ -0,0 +1,12 @@ +package dev.caskeleton.bootstrap.architecture.violations.persistence.flyway; + +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; + +/** Builds a Flyway from {@code Flyway.configure()} instead of the schema policy. */ +public class ConfigureCallingFlywayFixture { + + public Flyway flyway(DataSource dataSource) { + return Flyway.configure().dataSource(dataSource).load(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/FluentConfigurationFlywayFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/FluentConfigurationFlywayFixture.java new file mode 100644 index 00000000..2f7fdea3 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/FluentConfigurationFlywayFixture.java @@ -0,0 +1,13 @@ +package dev.caskeleton.bootstrap.architecture.violations.persistence.flyway; + +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.FluentConfiguration; + +/** Builds a Flyway from {@code new FluentConfiguration()}, the builder without the method call. */ +public class FluentConfigurationFlywayFixture { + + public Flyway flyway(DataSource dataSource) { + return new FluentConfiguration().dataSource(dataSource).load(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/ReferencedConfigurationFlywayFixture.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/ReferencedConfigurationFlywayFixture.java new file mode 100644 index 00000000..b8ecc0fd --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/ReferencedConfigurationFlywayFixture.java @@ -0,0 +1,16 @@ +package dev.caskeleton.bootstrap.architecture.violations.persistence.flyway; + +import java.util.function.Supplier; +import javax.sql.DataSource; +import org.flywaydb.core.Flyway; +import org.flywaydb.core.api.configuration.FluentConfiguration; + +/** Builds a Flyway through a constructor reference, {@code FluentConfiguration::new}. */ +public class ReferencedConfigurationFlywayFixture { + + private final Supplier configurations = FluentConfiguration::new; + + public Flyway flyway(DataSource dataSource) { + return configurations.get().dataSource(dataSource).load(); + } +} diff --git a/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/package-info.java b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/package-info.java new file mode 100644 index 00000000..62dfada3 --- /dev/null +++ b/src/app-bootstrap/src/architectureTest/java/dev/caskeleton/bootstrap/architecture/violations/persistence/flyway/package-info.java @@ -0,0 +1,8 @@ +/** + * "Violations-as-data" for {@code EVERY_FLYWAY_STARTS_FROM_THE_SCHEMA_POLICY}: each class builds a + * Flyway past {@code FlywaySchemaPolicy.configure()}, one way per class, and so gets Flyway's + * PostgreSQL lock default back — a lock held in a transaction that a concurrent index build waits + * for without end (re-review 2026-11-03 round 6, RR6-03-01; round 7, RR7-03-06: the rule saw only + * {@code Flyway.configure()}). + */ +package dev.caskeleton.bootstrap.architecture.violations.persistence.flyway; diff --git a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java index 59751f90..2091cfa5 100644 --- a/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java +++ b/src/app-bootstrap/src/integrationTest/java/dev/caskeleton/bootstrap/compose/ComposeMergeCharacterizationTest.java @@ -27,21 +27,15 @@ class ComposeMergeCharacterizationTest { private static final Path REPOSITORY_ROOT = repositoryRoot(); @Test - @DisplayName("the base stack renders") - void baseStackRenders() { - assertStackRenders("docker-compose.yml"); + @DisplayName("the development stack renders") + void developmentStackRenders() { + assertStackRenders("compose.yaml"); } @Test - @DisplayName("the local stack renders") - void localStackRenders() { - assertStackRenders("docker-compose.yml", "docker-compose.local.yml"); - } - - @Test - @DisplayName("the dev stack renders") + @DisplayName("the dev lane stack renders") void devStackRenders() { - assertStackRenders("docker-compose.yml", "docker-compose.dev.yml"); + assertStackRenders("compose.yaml", "src/app-bootstrap/compose-lanes/dev.yaml"); } /** @@ -112,7 +106,7 @@ class ComposeMergeCharacterizationTest { private static Path repositoryRoot() { Path candidate = Path.of("").toAbsolutePath(); - while (candidate != null && !Files.isRegularFile(candidate.resolve("docker-compose.yml"))) { + while (candidate != null && !Files.isRegularFile(candidate.resolve("compose.yaml"))) { candidate = candidate.getParent(); } if (candidate == null) { diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfig.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfig.java index cfe6ec07..3c725869 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfig.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/async/AsyncExecutorConfig.java @@ -27,8 +27,8 @@ public class AsyncExecutorConfig { * How long close waits for queued async work. It is spent after the web server's graceful drain * ({@code spring.lifecycle.timeout-per-shutdown-phase}, 30s) has finished, because Spring stops * lifecycle beans before it destroys this executor — so the two add up. The container grace in - * the root {@code docker-compose.yml} is sized to that sum; {@code - * DeveloperExperienceContractTest} fails when it is not (07-07). + * the root {@code compose.yaml} is sized to that sum; {@code DeveloperExperienceContractTest} + * fails when it is not (07-07). */ public static final int AWAIT_TERMINATION_SECONDS = 19; diff --git a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java index b7303d11..e51191f1 100644 --- a/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java +++ b/src/app-bootstrap/src/main/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidator.java @@ -36,13 +36,13 @@ public final class SecretSourceValidator implements StartupRule { /** * Prefix of the passwords this repository writes down for its lanes: the Redis ACL fixtures in - * {@code infra/redis-sdk/acl} and the Compose lanes' {@code REDIS_LANE_*} values that connect - * with them. They are public — anyone who can read the repository has them — so under {@code - * prod} a secret holding one is refused (review 2026-11-03 RR-07-04). A deployment that copied a - * lane's environment — which is also what an application needs to authenticate against a Redis - * that loaded the lane ACL file — would start with credentials it does not own. It cannot see a - * Redis server that loaded that file while the application uses real passwords; the ACL README - * says why no deployment loads it. + * {@code compose/redis/acl} and the Compose lanes' {@code REDIS_LANE_*} values that connect with + * them. They are public — anyone who can read the repository has them — so under {@code prod} a + * secret holding one is refused (review 2026-11-03 RR-07-04). A deployment that copied a lane's + * environment — which is also what an application needs to authenticate against a Redis that + * loaded the lane ACL file — would start with credentials it does not own. It cannot see a Redis + * server that loaded that file while the application uses real passwords; the ACL README says why + * no deployment loads it. * *

Only secrets are read for it (review 2026-11-04 RR2-04-01, owner decision): {@code fixture-} * is an ordinary word before it is this repository's password prefix, and a pod named after a @@ -202,7 +202,7 @@ public final class SecretSourceValidator implements StartupRule { + secret + " holds a lane fixture password ('" + REPOSITORY_FIXTURE_PREFIX - + "…', public in infra/redis-sdk/acl)")); + + "…', public in compose/redis/acl)")); } } diff --git a/src/app-bootstrap/src/main/resources/config/observability.yml b/src/app-bootstrap/src/main/resources/config/observability.yml index 6aedc565..06babdfb 100644 --- a/src/app-bootstrap/src/main/resources/config/observability.yml +++ b/src/app-bootstrap/src/main/resources/config/observability.yml @@ -92,7 +92,7 @@ management: enabled: true # The `info.*` tree only, not the environment: each capability module ships an # info.capabilities. entry beside its switch, and the Compose smoke lanes read it to check - # which capabilities the application actually turned on (compose-profile-contracts.json). + # which capabilities the application actually turned on (compose-lanes/compose-profile-contracts.json). env: enabled: true diff --git a/src/app-bootstrap/src/main/resources/config/security.yml b/src/app-bootstrap/src/main/resources/config/security.yml index 4ed3b8a6..5037d38a 100644 --- a/src/app-bootstrap/src/main/resources/config/security.yml +++ b/src/app-bootstrap/src/main/resources/config/security.yml @@ -35,8 +35,7 @@ app: # wildcards — least-privilege, OWASP-AUTHZ-C4). A capability's own permissions arrive with it, in # that module's config/module-defaults file (notification, fileserver, durable-operation), and # leave with its build line (07-08). Map entries from every source merge, so a deployment adds its - # own roles in its profile file or environment beside them. Sample-domain permissions live in - # sample-portfolio. + # own roles in its profile file or environment beside them. cors: # true | false enabled: ${APP_SECURITY_CORS_ENABLED:false} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStorageOverlayContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStorageOverlayContractTest.java index 62d45bdd..6ed29094 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStorageOverlayContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/CapabilityStorageOverlayContractTest.java @@ -24,14 +24,13 @@ import org.yaml.snakeyaml.constructor.SafeConstructor; * criterion 7: the only place that knows a module is the module). * *

The default image used to create the fileserver storage directory and declare it a {@code - * VOLUME}, and {@code docker-compose.yml} mounted a {@code fileserver-data} volume into every - * container — in a composition that has no fileserver module at all. A reader took the volume as a - * sign the capability was on, and every plain {@code docker run} created an anonymous volume nobody - * wrote to. The volume now lives in {@code infra/fileserver/compose/docker-compose.fileserver.yml}, - * beside the rest of the capability's infrastructure, which a lane or a developer adds with the - * capability. Its ownership is set by a one-shot that runs as root in the application's own image, - * so a fresh volume, a reused one and a bind mount all end up owned by the account the application - * runs as. + * VOLUME}, and the root Compose file mounted a {@code fileserver-data} volume into every container + * — in a composition that has no fileserver module at all. A reader took the volume as a sign the + * capability was on, and every plain {@code docker run} created an anonymous volume nobody wrote + * to. The volume now lives in {@code src/app-bootstrap/compose-lanes/fileserver.yaml}, an overlay a + * lane (or a service that selects the capability) adds with the capability. Its ownership is set by + * a one-shot that runs as root in the application's own image, so a fresh volume, a reused one and + * a bind mount all end up owned by the account the application runs as. */ @Tag("repository-contract") class CapabilityStorageOverlayContractTest { @@ -39,7 +38,9 @@ class CapabilityStorageOverlayContractTest { private static final Path REPOSITORY_ROOT = RepositoryContractResources.fromSystemProperty().repositoryRoot(); - private static final String OVERLAY = "infra/fileserver/compose/docker-compose.fileserver.yml"; + private static final String OVERLAY = "src/app-bootstrap/compose-lanes/fileserver.yaml"; + private static final String CONTRACTS = + "src/app-bootstrap/compose-lanes/compose-profile-contracts.json"; private static final String OVERLAY_KEY = "fileserver"; private static final String STORAGE_INIT = "fileserver-storage-init"; private static final String STORAGE_ROOT = "/var/lib/backend/files"; @@ -53,7 +54,7 @@ class CapabilityStorageOverlayContractTest { @DisplayName("기본 Dockerfile과 기본 compose는 선택 capability 이름을 담지 않는다") void theDefaultImageAndComposeNameNoOptionalCapability() throws IOException { // given - List defaultContainerFiles = List.of("src/Dockerfile", "docker-compose.yml"); + List defaultContainerFiles = List.of("src/Dockerfile", "compose.yaml"); // when List mentions = new ArrayList<>(); @@ -116,7 +117,7 @@ class CapabilityStorageOverlayContractTest { void theFileserverVolumeIsHandedToTheApplicationAccountBeforeTheApplicationStarts() throws IOException { // given - Map base = yaml(read("docker-compose.yml")); + Map base = yaml(read("compose.yaml")); Map overlay = yaml(read(OVERLAY)); // when @@ -144,7 +145,7 @@ class CapabilityStorageOverlayContractTest { @DisplayName("fileserver를 켜는 lane만, 그리고 모두 fileserver overlay와 소유권 one-shot을 쓴다") void exactlyTheLanesThatSwitchTheFileserverOnBringItsOverlay() throws IOException { // given - Map contracts = yaml(read("src/config/runtime/compose-profile-contracts.json")); + Map contracts = yaml(read(CONTRACTS)); // when List mismatched = new ArrayList<>(); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java index 546ec57d..af7bb788 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/DeveloperExperienceContractTest.java @@ -72,14 +72,18 @@ class DeveloperExperienceContractTest { @Test @Tag("repository-contract") void localComposeSupportsDatabaseMigrationAndPublicHealthSmoke() throws IOException { - String base = read("docker-compose.yml"); - String local = read("docker-compose.local.yml"); + String compose = read("compose.yaml"); - assertThat(base).contains("RELEASE_VERSION:").contains("GIT_SHA:").contains("SOURCE_URL:"); - assertThat(local) + assertThat(compose) + .contains("RELEASE_VERSION:") + .contains("GIT_SHA:") + .contains("SOURCE_URL:") .contains("env_file:") .contains("./src/.env") .doesNotContain("5432:5432") + .contains("http://localhost:9001/actuator/health/readiness"); + assertThat(read("scripts/bootstrap-local.sh")) + .contains("compose.yaml") .contains("http://localhost:8080/api/healthcheck"); } @@ -88,10 +92,9 @@ class DeveloperExperienceContractTest { * database the compose stack keeps on its internal network only is unreachable from there, and * every host-side run dies in the startup migration phase with a connection refusal. * - *

The service moved to docker-compose.infra.yml when infrastructure stopped being spread - * across environment overlays, and it now carries Compose profiles — so starting it means naming - * one (`--profile local-jpa`) rather than getting it for free with the local overlay. The port - * contract this asserts is unchanged; only the file that owns it is. + *

The service lives in the development stack, compose.yaml, under the capability profile + * {@code jpa}: starting it means naming the profile or the service. The port contract this + * asserts is unchanged; only the file that owns it is. */ @Test @Tag("repository-contract") @@ -108,16 +111,16 @@ class DeveloperExperienceContractTest { .as("the committed datasource default is host-side, so it must resolve to the loopback") .isIn("localhost", "127.0.0.1"); - Map infra = parseYamlMap(read("docker-compose.infra.yml")); - Map database = requireMap(requireMap(infra, "services"), "db"); + Map compose = parseYamlMap(read("compose.yaml")); + Map database = requireMap(requireMap(compose, "services"), "db"); assertThat(requireStringList(database, "ports")) .as("a host-side run cannot reach a database the compose stack never publishes") .contains("127.0.0.1:" + hostPort + ":5432"); assertThat(requireStringList(database, "profiles")) .as( - "the service is profiled, so a developer starts it by naming a lane; without this the " - + "port assertion above would pass for a service no lane ever brings up") - .contains("local-jpa"); + "the service is profiled, so a developer starts it by naming the profile; without this " + + "the port assertion above would pass for a service nothing ever brings up") + .contains("jpa"); } @Test @@ -368,38 +371,19 @@ class DeveloperExperienceContractTest { // and the dependency verifier, and none of those runs a lane whose category is INTEGRATION. // A lane nobody runs is not coverage, so both halves are pinned here — the aggregate that // covers the category, and the workflow that executes the aggregate. - assertThat(read("src/optional-platforms/build.gradle")) + assertThat(read("src/platforms/optional-build/build.gradle")) .as("the optional platform build must aggregate its integration-category lanes") .contains("tasks.register('integrationCheck')") .contains(":integrationTestLaneCheck"); - assertThat(read("src/grpc/grpc-operation-ledger-jpa/build.gradle")) + assertThat(read("src/platforms/grpc/grpc-operation-ledger-jpa/build.gradle")) .as("the operation ledger lane this contract protects must still be declared") .contains("lane('integrationTest')") .contains("integration()"); assertThat(read(".github/workflows/integration-main.yml")) .as("a workflow must actually execute the optional platform integration aggregate") - .contains("./gradlew -p optional-platforms integrationCheck"); - } - - @Test - @Tag("repository-contract") - @DisplayName("샘플 이미지의 의존성 단계는 릴리스 이미지와 같은 파일을 같은 순서로 복사한다") - void theSampleImageDependencyStageCopiesWhatTheReleaseImageCopies() throws IOException { - // given - String release = read("src/Dockerfile"); - String sample = read("src/Dockerfile.sample"); - - // when - List releaseCopies = dependencyStageCopies(release); - List sampleCopies = dependencyStageCopies(sample); - - // then - // The sample's copy of this stage once missed gradle.properties and build-logic/, so settings - // could not resolve the convention plugins and the image did not build at all (07-04). - assertThat(sampleCopies).isNotEmpty().isEqualTo(releaseCopies); - assertDockerDependencyCacheContract("src/Dockerfile.sample", sample); + .contains("./gradlew -p platforms/optional-build integrationCheck"); } @Test @@ -407,8 +391,7 @@ class DeveloperExperienceContractTest { @DisplayName("compose 종료 유예 시간은 웹 drain, async 대기, preStop, 여유를 모두 더한 값 이상이다") void theComposeStopGraceCoversEveryShutdownWaitInSequence() throws IOException { // given - Map app = - requireMap(requireMap(parseYamlMap(read("docker-compose.yml")), "services"), "app"); + Map app = requireMap(requireMap(parseYamlMap(read("compose.yaml")), "services"), "app"); // The web drain is the value this service runs with — APP_SERVER_SHUTDOWN_TIMEOUT's fallback in // the same Compose service — not a number copied here, so a changed default changes the sum // (review 2026-11-03 RR-06-08). @@ -439,7 +422,10 @@ class DeveloperExperienceContractTest { void composePublishesTheManagementPortOnLoopbackOnly() throws IOException { // given List composeFiles = - List.of("docker-compose.yml", "docker-compose.dev.yml", "docker-compose.local.yml"); + List.of( + "compose.yaml", + "src/app-bootstrap/compose-lanes/dev.yaml", + "src/app-bootstrap/compose-lanes/prod-smoke.yaml"); // when List exposed = @@ -491,11 +477,6 @@ class DeveloperExperienceContractTest { return mappings; } - private static List dependencyStageCopies(String dockerfile) { - String prefix = dockerfile.substring(0, dockerfile.indexOf("./gradlew")); - return prefix.lines().filter(line -> line.startsWith("COPY ")).toList(); - } - @Test @Tag("repository-contract") void dockerBuildConsumesOnlyTheGradleStagedExecutableJar() throws IOException { @@ -564,7 +545,9 @@ class DeveloperExperienceContractTest { .isEqualTo("/build/src"); assertThat(dependencyCachePrefix) .as("dependency-cache inputs before Gradle in %s", dockerfile) - .contains("COPY config/ ./config/"); + .contains("COPY config/ ./config/") + // The JPA leaf's build script parses release/readiness-cards.yaml while it configures. + .contains("COPY --parents **/release/*.yaml **/release/*.json ./"); } private static void assertDockerJarSelectionContract( diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockAcquisitionTimeoutClassificationContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockAcquisitionTimeoutClassificationContractTest.java index bd60c7a7..711e42c8 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockAcquisitionTimeoutClassificationContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/LockAcquisitionTimeoutClassificationContractTest.java @@ -4,6 +4,7 @@ import static org.assertj.core.api.Assertions.assertThat; import dev.caskeleton.application.lock.LockAcquisitionTimeoutException; import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; +import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.OperationalError; import java.io.InputStream; @@ -90,6 +91,16 @@ class LockAcquisitionTimeoutClassificationContractTest { .isEqualTo(OperationalError.LOCK_ACQUISITION_TIMEOUT); } + /** + * The code reaches a client only through {@link ApiErrorCarrier}: every transport reads a + * failure's code from that hook and answers anything else as {@code INTERNAL_ERROR}. + */ + @Test + void lockAcquisitionTimeoutExceptionIsTheCarrierTransportsReadTheCodeFrom() { + assertThat(new LockAcquisitionTimeoutException("test-key", Duration.ofSeconds(3))) + .isInstanceOf(ApiErrorCarrier.class); + } + // ---- registry-row leg ----------------------------------------------------- @Tag("document-contract") diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java index 5f561936..2e80b2ed 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/OperationalErrorRegistryContractTest.java @@ -2,9 +2,11 @@ package dev.caskeleton.bootstrap.contract; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.adapter.inbound.web.observability.RetryAfterAdvisor; import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; import dev.caskeleton.shared.error.Category; import dev.caskeleton.shared.error.ClientErrorMessages; +import dev.caskeleton.shared.error.OperationalError; import java.io.IOException; import java.io.UncheckedIOException; import java.nio.file.Files; @@ -12,7 +14,9 @@ import java.nio.file.Path; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; +import java.util.OptionalInt; import java.util.Set; +import java.util.TreeMap; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -98,6 +102,69 @@ class OperationalErrorRegistryContractTest { assertThat(actual).isNotEmpty().isEqualTo(expected); } + /** + * The log level is not a registry column. The failure's kind and path decide it — {@code + * ServerFailureLog} on every transport, {@code AuthErrorResponseWriter} in the security filter — + * not the code, so a per-row value can only drift from what is logged, as the column that was + * removed did (docs/design/2026-11-06-error-code-log-level-design.md). + */ + @Test + void noRegistryRowCarriesALogLevel() { + List rowsWithALogLevel = + registryRows().stream() + .filter(row -> row.containsKey("log_level")) + .map(row -> String.valueOf(row.get("code"))) + .toList(); + + assertThat(rowsWithALogLevel) + .as("%s rows with a log_level; the code decides the level, not the registry", REGISTRY) + .isEmpty(); + } + + /** + * {@code RetryAfterAdvisor} is the one place the web adapter turns a code into a {@code + * Retry-After} header, and its table copies the registry's {@code retry_after_seconds} column. + * The enum-registry comparison above covers category, status and retryability only, and the + * advisor's unit tests copy values code by code, so seven registered delays were missing from the + * table and nothing failed (review 2026-11-07). This compares every code: a registered delay is + * the header, and no registered delay is no header. + */ + @Test + void everyRegisteredRetryAfterIsTheHeaderTheWebAdapterSends() { + // given + Map> rows = registryRowsByCode(); + Map registered = new TreeMap<>(); + Map advised = new TreeMap<>(); + + // when + for (OperationalError code : OperationalError.values()) { + Object seconds = rows.getOrDefault(code.code(), Map.of()).get("retry_after_seconds"); + registered.put(code.code(), seconds == null ? "none" : String.valueOf(seconds)); + OptionalInt header = RetryAfterAdvisor.retryAfterSeconds(code); + advised.put(code.code(), header.isPresent() ? String.valueOf(header.getAsInt()) : "none"); + } + + // then + assertThat(advised).isNotEmpty().isEqualTo(registered); + } + + /** Every registry row with a code, from every section, by its code. */ + @SuppressWarnings("unchecked") + private static Map> registryRowsByCode() { + Object loaded = new Yaml(new SafeConstructor(new LoaderOptions())).load(read(REGISTRY)); + Map> rows = new LinkedHashMap<>(); + for (Object section : ((Map) loaded).values()) { + if (section instanceof List entries) { + for (Object entry : entries) { + if (entry instanceof Map row && row.get("code") instanceof String code) { + rows.put(code, row); + } + } + } + } + return rows; + } + @SuppressWarnings("unchecked") private static List> registryRows() { Object loaded = new Yaml(new SafeConstructor(new LoaderOptions())).load(read(REGISTRY)); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java deleted file mode 100644 index 805a300f..00000000 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/SampleRuntimeDefaultsContractTest.java +++ /dev/null @@ -1,214 +0,0 @@ -package dev.caskeleton.bootstrap.contract; - -import static org.assertj.core.api.Assertions.assertThat; - -import dev.caskeleton.bootstrap.contract.support.RepositoryContractResources; -import java.io.IOException; -import java.io.UncheckedIOException; -import java.nio.file.Files; -import java.nio.file.Path; -import java.util.ArrayDeque; -import java.util.ArrayList; -import java.util.Deque; -import java.util.LinkedHashMap; -import java.util.LinkedHashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Stream; -import org.junit.jupiter.api.DisplayName; -import org.junit.jupiter.api.Tag; -import org.junit.jupiter.api.Test; -import org.yaml.snakeyaml.LoaderOptions; -import org.yaml.snakeyaml.Yaml; -import org.yaml.snakeyaml.constructor.SafeConstructor; - -/** - * The sample keeps the default composition's runtime defaults, so a number measured on the sample — - * thread count, pool wait — says something about the composition a service ships (09-08), and it - * carries only settings something on its classpath reads. It reads configuration files, build - * scripts and production sources, so it runs in the pull-request {@code repository-contract} lane - * (08-03). - */ -@Tag("repository-contract") -class SampleRuntimeDefaultsContractTest { - - private static final Path REPOSITORY_ROOT = repositoryRoot(); - private static final Pattern DEFAULT = Pattern.compile("^\\$\\{[A-Z0-9_]+:(.*)}$"); - - @Test - @DisplayName("샘플은 가상 스레드와 앱 로그 레벨 기본값을 기본 조합과 같게 둔다") - void theSampleKeepsTheDefaultCompositionRuntimeDefaults() throws IOException { - // given - Map bootstrap = new LinkedHashMap<>(); - flatten("", load("src/app-bootstrap/src/main/resources/application.yml"), bootstrap); - flatten("", load("src/app-bootstrap/src/main/resources/config/observability.yml"), bootstrap); - Map sample = new LinkedHashMap<>(); - flatten("", load("src/sample-portfolio/src/main/resources/application.yml"), sample); - - // when - Map differing = new LinkedHashMap<>(); - for (String key : - new String[] {"spring.threads.virtual.enabled", "logging.level.dev.caskeleton"}) { - String expected = defaultOf(bootstrap.get(key)); - String actual = defaultOf(sample.get(key)); - if (actual != null && !actual.equals(expected)) { - differing.put(key, actual + " (default composition: " + expected + ")"); - } - } - - // then - assertThat(differing).isEmpty(); - } - - @Test - @DisplayName("샘플은 persistence-jpa 모듈의 풀 대기 시간 기본값을 덮어쓰지 않는다") - void theSampleDoesNotOverrideTheModulePoolWait() throws IOException { - // given - Map sample = new LinkedHashMap<>(); - flatten("", load("src/sample-portfolio/src/main/resources/application.yml"), sample); - - // when - Object connectionTimeout = sample.get("spring.datasource.hikari.connection-timeout"); - - // then - // The module's 5000 ms is a fail-fast decision; the sample's 30000 made a dry pool wait six - // times longer there than in the default composition. - assertThat(connectionTimeout).isNull(); - } - - @Test - @DisplayName("샘플 application.yml의 app.* 설정 묶음은 샘플 classpath에 있는 모듈 코드가 읽는다") - void everySampleAppSettingGroupIsReadByAModuleOnTheSampleClasspath() throws IOException { - // given - Set groups = new TreeSet<>(); - for (Object document : loadAll("src/sample-portfolio/src/main/resources/application.yml")) { - if (document instanceof Map map && map.get("app") instanceof Map app) { - app.keySet().forEach(key -> groups.add(String.valueOf(key))); - } - } - Set classpath = sampleRuntimeModules(); - - // when - Set unread = new TreeSet<>(); - for (String group : groups) { - Pattern reader = Pattern.compile("app\\." + Pattern.quote(group) + "[\".}]"); - if (classpath.stream().noneMatch(module -> anyMainSourceMatches(module, reader))) { - unread.add("app." + group); - } - } - - // then - // The sample is copied first. A block nothing on its classpath reads — the HTTP client's - // timeouts with no HTTP client module, a messaging broker with no messaging module — is a - // setting the copier believes is in force and is not (review 2026-11-03 RR-06-06, 09-08). - assertThat(unread) - .as("app.* groups in the sample's application.yml that nothing reads") - .isEmpty(); - } - - /** The source directories of the sample and every project its production configurations reach. */ - private static Set sampleRuntimeModules() throws IOException { - String registry = - Files.readString(REPOSITORY_ROOT.resolve("src/config/architecture/modules.json")); - Map sourceOf = new LinkedHashMap<>(); - Matcher module = - Pattern.compile("\"gradle_path\":\\s*\"([^\"]+)\",\\s*\"source_path\":\\s*\"([^\"]+)\"") - .matcher(registry); - while (module.find()) { - sourceOf.put(module.group(1), module.group(2)); - } - sourceOf.put(":sample-portfolio", "src/sample-portfolio"); - Pattern edge = - Pattern.compile( - "(?m)^\\s*(?:api|implementation|runtimeOnly)\\s*\\(?\\s*project\\(\\s*['\"](:[^'\"]+)['\"]"); - Set reached = new LinkedHashSet<>(); - Deque pending = new ArrayDeque<>(List.of(":sample-portfolio")); - Set seen = new LinkedHashSet<>(); - while (!pending.isEmpty()) { - String path = pending.pop(); - String source = sourceOf.get(path); - if (!seen.add(path) || source == null) { - continue; - } - Path directory = REPOSITORY_ROOT.resolve(source); - reached.add(directory); - Matcher dependency = edge.matcher(Files.readString(directory.resolve("build.gradle"))); - while (dependency.find()) { - pending.add(dependency.group(1)); - } - } - return reached; - } - - private static boolean anyMainSourceMatches(Path module, Pattern reader) { - Path sources = module.resolve("src/main/java"); - if (!Files.isDirectory(sources)) { - return false; - } - try (Stream files = Files.walk(sources)) { - return files - .filter(file -> file.toString().endsWith(".java")) - .anyMatch( - file -> { - try { - return reader.matcher(Files.readString(file)).find(); - } catch (IOException failure) { - throw new UncheckedIOException(failure); - } - }); - } catch (IOException failure) { - throw new UncheckedIOException(failure); - } - } - - private static List loadAll(String relative) throws IOException { - LoaderOptions options = new LoaderOptions(); - options.setMaxAliasesForCollections(0); - List documents = new ArrayList<>(); - new Yaml(new SafeConstructor(options)) - .loadAll(Files.readString(REPOSITORY_ROOT.resolve(relative))) - .forEach(documents::add); - return documents; - } - - private static String defaultOf(Object value) { - if (value == null) { - return null; - } - String text = String.valueOf(value).trim(); - Matcher matcher = DEFAULT.matcher(text); - return matcher.matches() ? matcher.group(1) : text; - } - - private static Map load(String relative) throws IOException { - LoaderOptions options = new LoaderOptions(); - options.setMaxAliasesForCollections(0); - Object first = - new Yaml(new SafeConstructor(options)) - .loadAll(Files.readString(REPOSITORY_ROOT.resolve(relative))) - .iterator() - .next(); - assertThat(first).as(relative).isInstanceOf(Map.class); - return (Map) first; - } - - private static void flatten(String prefix, Map map, Map into) { - map.forEach( - (key, value) -> { - String name = prefix.isEmpty() ? String.valueOf(key) : prefix + "." + key; - if (value instanceof Map child) { - flatten(name, child, into); - } else { - into.put(name, value); - } - }); - } - - private static Path repositoryRoot() { - return RepositoryContractResources.fromSystemProperty().repositoryRoot(); - } -} diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java index d1f2468c..3b4b7159 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/graphql/GraphQlResolverReachabilityTest.java @@ -54,7 +54,7 @@ class GraphQlResolverReachabilityTest { @Test @DisplayName("the lane sends an authenticated query and inspects the body, not the status") void theLaneProvesTheRequestPath() { - Path smoke = repositoryRoot().resolve("infra/graphql/smoke/graphql-smoke.sh"); + Path smoke = repositoryRoot().resolve("src/app-bootstrap/compose-lanes/smoke/graphql-smoke.sh"); assertThat(Files.exists(smoke)) .as("without a request against /graphql, the resolver gap is invisible to every gate") diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java index 143039be..2554634a 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingAuthorityContractTest.java @@ -51,7 +51,7 @@ class MessagingAuthorityContractTest { Pattern.compile("String PREFIX\\s*=\\s*\"app\\.messaging\""); private static final List MESSAGING_SOURCES = - loadSources("adapter/outbound/messaging", "messaging", "app-bootstrap"); + loadSources("adapter/outbound/messaging", "platforms/messaging", "app-bootstrap"); private static final List CORE_SOURCES = loadSources("application-core", "domain-core"); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingPublicSurfaceContractTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingPublicSurfaceContractTest.java index 922d9399..22527fd2 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingPublicSurfaceContractTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/contract/messaging/MessagingPublicSurfaceContractTest.java @@ -34,8 +34,8 @@ import org.junit.jupiter.api.Test; * *

So the rule is one-directional and mechanical: a vendor library named in a public or protected * signature is declared {@code api}; one used only behind private members stays {@code - * implementation}. {@code src/messaging/CLAUDE.md} states it as policy — this holds it to the - * source so the two cannot drift. + * implementation}. {@code src/platforms/messaging/CLAUDE.md} states it as policy — this holds it to + * the source so the two cannot drift. * *

The libraries checked are the ones an adopter would otherwise have to reverse-engineer into * their own build: broker clients, codec libraries, the metrics registry, the reactive facade. @@ -345,7 +345,7 @@ class MessagingPublicSurfaceContractTest { } private static List messagingLeaves() { - Path family = repositoryRoot().resolve("src/messaging"); + Path family = repositoryRoot().resolve("src/platforms/messaging"); try (Stream children = Files.list(family)) { return children .filter(Files::isDirectory) diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/ReleaseManifestTaskExistenceTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/ReleaseManifestTaskExistenceTest.java index 82746f04..73fea2a7 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/ReleaseManifestTaskExistenceTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/registry/ReleaseManifestTaskExistenceTest.java @@ -66,7 +66,8 @@ class ReleaseManifestTaskExistenceTest { // Only the blocking set. experimental_contracts is explicitly not promoted and is never // aggregated into a release manifest, so a task it names is allowed not to exist yet. List named = - blockingTaskNamesIn(root.resolve("src/config/mongodb/release-contracts.json")); + blockingTaskNamesIn( + root.resolve("src/adapter/outbound/persistence-mongo/release/release-contracts.json")); List registered = registeredTaskNamesIn(root.resolve("src/adapter/outbound/persistence-mongo/build.gradle")); diff --git a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java index db81d0a3..0e6bd225 100644 --- a/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java +++ b/src/app-bootstrap/src/test/java/dev/caskeleton/bootstrap/runtime/SecretSourceValidatorTest.java @@ -116,7 +116,7 @@ class SecretSourceValidatorTest { .withInitializer(ctx -> ctx.getEnvironment().setActiveProfiles("prod")) .withPropertyValues(allRequiredSecretsPresent()) // The Compose Redis lanes' shape: a credential reference, and the variable it names - // holding a public password from infra/redis-sdk/acl. A deployment that copied the + // holding a public password from compose/redis/acl. A deployment that copied the // lane's environment would carry both into production. .withPropertyValues( "APP_REDIS_AUTHENTICATION_CREDENTIAL_REFERENCE=" diff --git a/src/application-core/CLAUDE.md b/src/application-core/CLAUDE.md index 366e2dbe..0d8b3171 100644 --- a/src/application-core/CLAUDE.md +++ b/src/application-core/CLAUDE.md @@ -37,11 +37,11 @@ Package root: `dev.caskeleton.application`. - 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 — D3). +- `org.springframework.transaction.annotation.Transactional` (use `TransactionPort` instead). - `org.springframework.context.ApplicationContext` — direct dependency forbidden - (`getBean(Class)` reflection-style bypass blocked by ArchUnit D11). String-key + (`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 per D12 — guard via code review checklist. + 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. @@ -171,7 +171,7 @@ Enforcement: 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 (review 2026-11-01 01-10 (b): clearer + `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). ## Canonical use case shape @@ -239,7 +239,7 @@ beans but no enforcing advisor fails startup too (`composition:service-runtime` Both `inWrite` and `inRootWrite` satisfy the direct boundary fitness rule for a `WRITE_REPOSITORY + WRITE` use case. READ and REQUIRES_NEW mappings remain exclusive. -### Callback signature contract (D11) +### Callback signature contract `TransactionPort` callbacks are `Supplier` / `Runnable` and cannot throw checked exceptions. This matches Spring's `TransactionCallback` constraint. Wrap domain @@ -247,7 +247,7 @@ checked exceptions into `RuntimeException` subclasses (`DomainException extends RuntimeException`); `IOException` → `UncheckedIOException`; `SQLException` is auto-translated by Spring's `DataAccessException` hierarchy. -### `inNew` pool-sizing constraint (D12) +### `inNew` pool-sizing constraint `inNew` acquires a new physical JDBC connection. Pool size MUST satisfy: @@ -274,7 +274,7 @@ generation; the V1 `IdempotencyScope`/`tryBegin` API is gone. - **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 sample config. + 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`; @@ -285,9 +285,21 @@ generation; the V1 `IdempotencyScope`/`tryBegin` API is gone. 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, re-review RR5-01-02·03). 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 - (re-review 2026-11-04 RR-01-11, RR-03-11, RR3-03-04). + (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, + `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). The former ArchUnit freeze rule `inbound_port_implementations_do_not_declare_keyed_idempotency` and its fixture were removed when this branch merged. @@ -298,35 +310,34 @@ 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 → `WorkLog` | -| **Projection (CQRS-lite)** | application-layer projection DTO via a `*QueryPort` | read shape ≠ write, or to skip aggregate hydration / lazy-collection joins | `QueryUseCase` → `*QueryPort` → `WorkLogSummary` (record); query via JPQL `SELECT new` / JdbcTemplate | +| **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 | -- **D1 — purity guardrail (core, machine-enforced):** a read port whose simple name ends +- **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`). Enforced by ArchUnit `query_ports_do_not_leak_domain_jpa_or_web_types`. - Projection usage itself is **opt-in**, not a forced default; the demo lives in - `sample-portfolio` (`WorkLogSummaryQueryPort` / `WorkLogSummary`). -- **D3 — Strict ceremony:** every read goes through a `QueryUseCase` bean. There is no thin + 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. -- **D4 — transaction:** reads default to `TransactionPort.inRead`. A no-tx (autocommit) read +- **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`. -- **D5 — capability:** a repository-backed projection read is still +- **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 (**D2**) is out of scope — escalation only. +- Full CQRS with a separate physical read store is out of scope — escalation only. ## ArchUnit guardrails (enforced) - `application_does_not_depend_on_adapters_or_transport` - `application_does_not_use_spring_transactional_annotation` -- `application_does_not_depend_on_application_context` (D11) +- `application_does_not_depend_on_application_context` - `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` (query-bypass D1 — `*QueryPort` return purity) +- `query_ports_do_not_leak_domain_jpa_or_web_types` (`*QueryPort` return purity) ## Test diff --git a/src/application-core/README.md b/src/application-core/README.md index 541e8917..cce525f4 100644 --- a/src/application-core/README.md +++ b/src/application-core/README.md @@ -270,8 +270,14 @@ application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장 - processing lease 와 replay TTL 은 따로 간다. 넘겨받을 수 있는 것은 만료된 `CLAIMED` 와 재시도 가능한 실패뿐이고, 다음 claim 이 누구든 넘겨받는다 — 같은 attempt 를 다시 보낸 caller 도 새 attempt 번호로 넘겨받는다(라운드6 RR6-02-01: 전에는 같은 attempt 가 이 기록을 재생받아 시작을 다시 거절당했다). 넘겨받기 전 - 핸들은 같은 attempt 가 들고 있어도 낡은 핸들이라 시작이 확인되지 않는다. 한 attempt 를 두 호출이 동시에 쓰는 - 것은 가려내지 못하므로 재시도는 앞 호출이 돌아온 뒤에 한다. + 핸들은 같은 attempt 가 들고 있어도 낡은 핸들이라 시작이 확인되지 않는다. 이미 적용된 전이(start·renew· + complete·markFailed·release)를 "이미 처리됨"으로 확인받는 것은 그 전이를 적용한 핸들뿐이다. 넘겨받은 뒤에 + 일어난 complete·markFailed 를 넘겨받기 전 핸들로 다시 보내면 `NOT_OWNER` 다(2026-11-06 소유자 결정). renew 를 + 적용한 핸들로 start 해도 `NOT_OWNER` 다 — 기록은 그 핸들보다 revision 이 하나 높지만 거기로 옮긴 것은 start 가 + 아니라 renew 다. markFailed 를 적용한 핸들이 다른 disposition 으로 다시 보내면 `OPERATION_CONFLICT`(기록된 실패는 + 그대로), retention 만 다르면 "이미 처리됨"이다. retention 은 complete 의 replay TTL 처럼 비교하지 않는다(2026-11-07 + 소유자 결정). 한 attempt 를 + 두 호출이 동시에 쓰는 것은 가려내지 못하므로 재시도는 앞 호출이 돌아온 뒤에 한다. 만료된 `EXECUTING` 은 다른 caller 에게 `RECOVERY_REQUIRED` 로 답하되 기록은 그대로 둔다. 주인이 늦게 보고한 결과·실패는 기록된다 — 먼저 온 보고 하나만 남고 뒤의 보고는 거절된다(2026-11-04 소유자 결정, 재리뷰 RR5-01-03). lease 가 이미 끝났으면 주인도 시작(`markExecutionStarted`)과 `renew` 를 할 수 없고 @@ -280,7 +286,7 @@ application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장 실행 중이면 주인은 여전히 `complete`·`markFailed` 할 수 있다(RR5-01-02). - 생성은 app-bootstrap `IdempotencyProviderSelectionConfig` 가 한 번 한다(`IdempotencySettings`: processing lease 30s, replay TTL 24h(최대 72h), failure retention 24h(replay TTL 이상), codec id `json-v2`, - policy revision 2). 유스케이스나 샘플 설정이 직접 만들지 않는다. + policy revision 2). 유스케이스나 서비스 설정이 직접 만들지 않는다. - 이 계약은 요청 재생(replay) 근거를 남길 뿐이다. store 와 비즈니스 DB 사이의 exactly-once 를 보장하지 않는다. @@ -301,8 +307,7 @@ application 계층이 claim·replay·복구 **정책** 을 소유하고, 저장 HMAC-SHA-256 으로 digest** 한 값이다(`digest`, `keyDigestVersion`, `operationCode`). - raw 클라이언트 key 와 principal 은 executor·store·로그·메트릭 어디에도 닿지 않는다. 예외 메시지의 진단 문자열도 이 digest 로만 만든다. -- digest 를 만드는 쪽(키 링, 버전 교체)은 adapter 나 유스케이스 소유다. 예: sample 의 - `HmacPosterImageIdempotencyScopeDigester`. +- digest 를 만드는 쪽(키 링, 버전 교체)은 adapter 나 유스케이스 소유다. ### RequestFingerprint @@ -577,8 +582,13 @@ application 계층은 락 획득/해제 계약만 알고, 실제 구현은 adapt - `OperationalError.LOCK_ACQUISITION_TIMEOUT`(CONFLICT, 409, retryable=true)을 운반한다. 락 경합은 일시적이다 — 현재 보유자가 임계 구역을 떠나거나 lease TTL 이 만료되면 재시도가 획득한다(D6 효율 락). -- web adapter 가 `errorCode()` + 고정 client-safe 메시지로 409 를 만든다. 진단용 `getMessage()` - (key·waitTime 포함)는 서버 로그 전용이고 API 클라이언트에 전달하면 안 된다. +- `ApiErrorCarrier` 를 구현한다. 그래서 전송이 따로 처리기를 두지 않아도 web 은 409 + + `Retry-After: 1`(레지스트리 값), GraphQL·gRPC 는 같은 코드로 답하고, 4xx 라 서버 로그를 남기지 않는다. 전에는 + carrier 가 아니어서 모든 전송이 500 `INTERNAL_ERROR`(재시도 불가)와 "unhandled" ERROR 로 답했다(재리뷰 + RR7-01-04). `getMessage()`(key·waitTime 포함)는 클라이언트에 보내지 않고, 로그에도 남지 않는다. 4xx carrier 라 + 어느 전송도 남기지 않고, 락 adapter 도 timeout 을 남기지 않는다. 어느 락이 막혔는지 기록이 필요하면 호출자가 + `key()` 를 직접 남긴다(엔티티 id 는 빼고). 운영 절차는 `docs/runbooks/lock-acquisition-timeout.md` + (`lock.acquisition` metric, `INT_LOCK` 보유자 조회)다(재리뷰 RR8-01-02). --- @@ -596,7 +606,7 @@ leaf의 코드 Javadoc과 `docs/notification/`이 정본이다. R1 오케스트 ### CorrelationIdPort - 현재 application invocation의 correlation id를 `Optional`으로 읽는 framework-free - 경계다. application/sample use case는 MDC나 SLF4J를 직접 알지 않는다. + 경계다. application use case는 MDC나 SLF4J를 직접 알지 않는다. - inbound web adapter가 sanitized `correlation_id` MDC 슬롯을 구현 세부로 읽는다. - 값이 없거나 blank이면 event publisher는 생성한 event id를 correlation id로 재사용해 기존 self-correlation 동작을 유지한다. diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java index c325e0eb..205acb69 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyCompleteOutcome.java @@ -3,11 +3,22 @@ package dev.caskeleton.application.idempotency; /** Outcomes of an owner-safe EXECUTING to COMPLETED transition. */ public enum IdempotencyCompleteOutcome { COMPLETED, + /** + * This completion, from the handle presented, was already recorded with the same result (a lost + * reply). Only the handle the completion was applied from is told so; another handle of the same + * attempt — one from before a takeover — is {@link #NOT_OWNER} (owner decision 2026-11-06: the + * Redis and PostgreSQL stores confirmed it). + */ ALREADY_COMPLETED_SAME_RESULT, + /** The handle the completion was applied from resent it with another result. */ RESPONSE_CONFLICT, ABSENT, NOT_OWNER, NOT_IN_PROGRESS, + /** + * The call names an operation other than the one the record was claimed under; nothing was + * recorded (owner decision 2026-11-06). + */ OPERATION_CONFLICT, INDETERMINATE, UNAVAILABLE diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java index efee562e..ffa97ff1 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyFailOutcome.java @@ -4,10 +4,25 @@ package dev.caskeleton.application.idempotency; public enum IdempotencyFailOutcome { MARKED_RETRYABLE, MARKED_ABANDONED, + /** + * This failure, from the handle presented, was already recorded (a lost reply). Only the handle + * the failure was applied from is told so; another handle of the same attempt — one from before a + * takeover — is {@link #NOT_OWNER} (owner decision 2026-11-06: the Redis store confirmed it and + * the PostgreSQL store answered {@link #OPERATION_CONFLICT}; the in-memory fake refused even the + * handle that applied it). A resend with another retention is this too: the retention is how long + * the failure is kept, not what it decided, and the record keeps the first one (owner decision + * 2026-11-07 — the PostgreSQL store answered {@link #OPERATION_CONFLICT}). + */ ALREADY_MARKED_SAME_OPERATION, ABSENT, NOT_OWNER, NOT_IN_PROGRESS, + /** + * The call names an operation other than the one the record was claimed under (owner decision + * 2026-11-06), or the failure the handle presented applied was already recorded with another + * disposition (owner decision 2026-11-07 — every store answered {@link #NOT_OWNER}). Nothing + * changed: the recorded disposition stays. + */ OPERATION_CONFLICT, INDETERMINATE, UNAVAILABLE diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java index b8ed05d6..a60b6341 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyInspectionOutcome.java @@ -16,6 +16,10 @@ public enum IdempotencyInspectionOutcome { */ ABANDONED, FINGERPRINT_MISMATCH, + /** + * The attempt's owner token holds the record under another operation. It is the answer in every + * state, a completed record included: its response is not replayed to it. + */ OPERATION_CONFLICT, UNAVAILABLE } diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java index 952f8012..fe066580 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyReleaseOutcome.java @@ -3,10 +3,19 @@ package dev.caskeleton.application.idempotency; /** Outcomes of releasing a claim only while business execution has not started. */ public enum IdempotencyReleaseOutcome { RELEASED_BEFORE_EXECUTION, + /** This release was already applied: a store that keeps released records recognises it. */ ALREADY_RELEASED_SAME_OPERATION, + /** + * No record exists: it expired, was never there, or was released by a store that deletes what it + * releases — that store cannot tell its own release's retry apart, so it confirms nothing. + */ ABSENT, NOT_OWNER, EXECUTION_ALREADY_STARTED, + /** + * The call names an operation other than the one the record was claimed under; nothing was + * released (owner decision 2026-11-06). + */ OPERATION_CONFLICT, INDETERMINATE, UNAVAILABLE diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java index 7e94d129..a0093c4d 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyRenewOutcome.java @@ -10,7 +10,12 @@ package dev.caskeleton.application.idempotency; public enum IdempotencyRenewOutcome { /** The lease was extended; the returned handle carries the advanced revision. */ RENEWED(true), - /** This exact renewal was already applied (a lost reply); the handle is the current one. */ + /** + * This exact renewal was already applied (a lost reply); the handle is the current one. Only the + * handle the renewal was applied from is told so; the handle that renewal returned renews again, + * and any other is {@link #NOT_OWNER} (owner decision 2026-11-06: the PostgreSQL store answered + * both {@link #OPERATION_CONFLICT}). + */ ALREADY_RENEWED_SAME_OPERATION(true), /** No record exists: it expired, or was never there. */ ABSENT(false), @@ -29,7 +34,11 @@ public enum IdempotencyRenewOutcome { * with the same handle are still recorded (owner decision 2026-11-04). */ LEASE_EXPIRED(false), - /** The same operation id already renewed with different arguments. */ + /** + * The call names an operation other than the one the record was claimed under (owner decision + * 2026-11-06), or this renewal was already applied, from this handle, asking for a different + * lease. Nothing changed. + */ OPERATION_CONFLICT(false), /** The store may have applied the renewal; inspect before relying on either answer. */ INDETERMINATE(false), diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java index 2a4c52d0..d4a1a540 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStartOutcome.java @@ -10,14 +10,22 @@ public enum IdempotencyStartOutcome { * already executing is not this: one from before a takeover is {@link #NOT_OWNER}, the current * one a replayed claim returned is {@link #NOT_CLAIMED} (round6 RR6-02-01 — the Redis store * confirmed both and the action ran twice; the PostgreSQL store answered {@link - * #OPERATION_CONFLICT}). + * #OPERATION_CONFLICT}). Nor is a start through the handle a renewal was applied from: the record + * is executing one revision past it, but the renewal moved it there, so the handle is stale and + * the answer is {@link #NOT_OWNER} (round8 RR8-04-02 — the Redis store confirmed it). */ ALREADY_STARTED_SAME_OPERATION(true), - /** No record exists: it expired, was released, or was never there. */ + /** + * No record exists: it expired, was released, or was never there. A start through a released + * handle is this or {@link #NOT_OWNER}, by whether the store forgets a released record (Redis, + * the in-memory fake) or keeps it one revision past the handle (PostgreSQL). Both refuse it and + * nothing starts; a caller treats them alike (owner decision 2026-11-06). + */ ABSENT(false), /** * The record belongs to somebody else — the claim was taken over — or this handle's revision is - * stale. + * stale, as after the handle released the claim in a store that keeps the released record (see + * {@link #ABSENT}). */ NOT_OWNER(false), /** The record is not a claim waiting to start: it is executing or has ended. */ @@ -33,7 +41,11 @@ public enum IdempotencyStartOutcome { * store started it). */ LEASE_EXPIRED(false), - /** The same operation id already started this record with different arguments. */ + /** + * The handle's owner token holds the record, but the call names an operation other than the one + * the record was claimed under; nothing changed. Every store refuses it (owner decision + * 2026-11-06 — the PostgreSQL store started it). + */ OPERATION_CONFLICT(false), /** The store may have applied the start; inspect before relying on either answer. */ INDETERMINATE(false), diff --git a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java index 062c4675..7635f032 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/idempotency/IdempotencyStorePort.java @@ -21,6 +21,17 @@ import java.time.Duration; * record from its holder. Only the record's own lifetime ends it: once it is gone, every call * answers {@code ABSENT} (owner decision 2026-11-04; re-review 2026-11-04 RR5-01-02·03; {@code * IdempotencyStoreContract}). + * + *

Every transition names the operation its record was claimed under — the handle's {@link + * IdempotencyOwner#claimOperationId()}. A holder naming another one is answered {@code + * OPERATION_CONFLICT} and nothing changes; a claim that brings the owner token under another + * operation to a record still in progress is {@link + * IdempotencyClaimOutcome.OwnerOperationConflict}, and an inspection is {@code OPERATION_CONFLICT} + * in every state (owner decision 2026-11-06). For renew and failure {@code OPERATION_CONFLICT} also + * still means the same transition was already applied, from the handle presented, with other + * arguments: another lease for a renewal, another disposition for a failure. A failure's retention + * is not one of them — like a completion's replay TTL, it is how long the result is kept, and a + * resend with another one is confirmed (owner decision 2026-11-07). */ public interface IdempotencyStorePort { diff --git a/src/application-core/src/main/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutException.java b/src/application-core/src/main/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutException.java index 25724ba9..4f247129 100644 --- a/src/application-core/src/main/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutException.java +++ b/src/application-core/src/main/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutException.java @@ -1,16 +1,25 @@ package dev.caskeleton.application.lock; +import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.OperationalError; import java.time.Duration; /** * Thrown by {@link DistributedLockPort#tryAcquire(String, Duration, Duration)} when the lock could * not be acquired within the bounded {@code waitTime}. Carries {@link - * OperationalError#LOCK_ACQUISITION_TIMEOUT} (CONFLICT, 409, retryable — contention is transient). - * The web adapter maps it to 409 with a client-safe message; {@link #getMessage()} is - * server-log-only. See README. + * OperationalError#LOCK_ACQUISITION_TIMEOUT} (CONFLICT, 409, retryable — contention is transient) + * through {@link ApiErrorCarrier}, the hook every inbound transport reads a code from: the web + * adapter answers 409 with {@code Retry-After}, GraphQL and gRPC the same code, and none of them + * logs it as an unhandled failure. Without the hook it was answered as a 500 {@code INTERNAL_ERROR} + * (review 2026-11-06 RR7-01-04). + * + *

{@link #getMessage()} names the key and the wait time. It is never sent to a client, and no + * transport logs it either: a 4xx carrier is an answer, not an incident, so this timeout leaves no + * server line, and the lock adapters do not log one. A caller that wants a record of which lock + * timed out logs {@link #key()} itself, keeping entity ids out of the line. See README. */ -public final class LockAcquisitionTimeoutException extends RuntimeException { +public final class LockAcquisitionTimeoutException extends RuntimeException + implements ApiErrorCarrier { private static final long serialVersionUID = 1L; @@ -41,6 +50,7 @@ public final class LockAcquisitionTimeoutException extends RuntimeException { * Returns {@link OperationalError#LOCK_ACQUISITION_TIMEOUT}, the stable client-facing error code * for a distributed-lock timeout. */ + @Override public OperationalError errorCode() { return OperationalError.LOCK_ACQUISITION_TIMEOUT; } diff --git a/src/application-core/src/test/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutExceptionTest.java b/src/application-core/src/test/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutExceptionTest.java index 811d5a32..913d86d4 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutExceptionTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/lock/LockAcquisitionTimeoutExceptionTest.java @@ -2,6 +2,7 @@ package dev.caskeleton.application.lock; import static org.assertj.core.api.Assertions.assertThat; +import dev.caskeleton.shared.error.ApiErrorCarrier; import dev.caskeleton.shared.error.OperationalError; import java.time.Duration; import org.junit.jupiter.api.Test; @@ -25,6 +26,12 @@ class LockAcquisitionTimeoutExceptionTest { assertThat(ex.errorCode()).isEqualTo(OperationalError.LOCK_ACQUISITION_TIMEOUT); } + @Test + void isAnApiErrorCarrier() { + assertThat(new LockAcquisitionTimeoutException("orders/42", Duration.ofSeconds(3))) + .isInstanceOf(ApiErrorCarrier.class); + } + @Test void messageContainsKey() { LockAcquisitionTimeoutException ex = diff --git a/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java b/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java index 24f219ab..80fe518e 100644 --- a/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java +++ b/src/application-core/src/test/java/dev/caskeleton/application/messaging/contract/IntegrationEventContractContributionTest.java @@ -133,7 +133,7 @@ class IntegrationEventContractContributionTest { void descriptorContainsOnlyBoundedProviderNeutralContractMetadata() { ContractDescriptor descriptor = descriptor(); - assertThat(descriptor.ownerModule()).isEqualTo("sample-portfolio"); + assertThat(descriptor.ownerModule()).isEqualTo("example-feature"); assertThat(descriptor.logicalDestination()) .isEqualTo(new LogicalDestinationId("portfolio-domain-events")); assertThat(descriptor.maximumPayloadBytes()).isEqualTo(64 * 1024); @@ -152,7 +152,7 @@ class IntegrationEventContractContributionTest { assertThatThrownBy( () -> new ContractDescriptor( - "sample-portfolio", + "example-feature", new LogicalDestinationId("portfolio-domain-events"), "json-envelope-v1", true, @@ -165,7 +165,7 @@ class IntegrationEventContractContributionTest { private static ContractDescriptor descriptor() { return new ContractDescriptor( - "sample-portfolio", + "example-feature", new LogicalDestinationId("portfolio-domain-events"), "json-envelope-v1", true, diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java index 1eb77aa8..619de7bb 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/IdempotencyStoreContract.java @@ -514,6 +514,536 @@ public abstract class IdempotencyStoreContract { .isGreaterThan(claimed.stateRevision()); } + // Every transition names the operation its record was claimed under. A holder naming another one + // is refused as OPERATION_CONFLICT and the record is left as it was: the Redis store refused it, + // the PostgreSQL store and the in-memory fake applied it — the PostgreSQL store wrote the named + // operation beside the claim's and read the claim's from the handle (owner decision 2026-11-06). + + @Test + void startingUnderAnotherOperationThanTheClaimIsAConflictThatStartsNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner claimed = acquire(store); + + // when + IdempotencyMutationResult conflict = + store.markExecutionStarted(claimed, OTHER_OPERATION); + + // then + assertThat(conflict.outcome()).isEqualTo(IdempotencyStartOutcome.OPERATION_CONFLICT); + assertThat(store.markExecutionStarted(claimed, OPERATION).outcome()) + .isEqualTo(IdempotencyStartOutcome.STARTED); + } + + @Test + void renewingUnderAnotherOperationThanTheClaimIsAConflictThatRenewsNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + + // when + IdempotencyMutationResult conflict = + store.renew(executing, Duration.ofSeconds(30), OTHER_OPERATION); + + // then + assertThat(conflict.outcome()).isEqualTo(IdempotencyRenewOutcome.OPERATION_CONFLICT); + // The revision did not move, so the handle the start returned still completes the record. + assertThat(store.complete(executing, new StoredResponse("{}"), Duration.ofHours(1), OPERATION)) + .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); + } + + @Test + void completingUnderAnotherOperationThanTheClaimIsAConflictThatRecordsNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + + // when + IdempotencyCompleteOutcome conflict = + store.complete( + executing, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OTHER_OPERATION); + + // then + assertThat(conflict).isEqualTo(IdempotencyCompleteOutcome.OPERATION_CONFLICT); + // No response was recorded: another one completes the record rather than conflicting with it. + assertThat( + store.complete( + executing, new StoredResponse("{\"v\":2}"), Duration.ofHours(1), OPERATION)) + .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); + } + + @Test + void markingFailedUnderAnotherOperationThanTheClaimIsAConflictThatMarksNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + + // when + IdempotencyFailOutcome conflict = + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OTHER_OPERATION); + + // then + assertThat(conflict).isEqualTo(IdempotencyFailOutcome.OPERATION_CONFLICT); + assertThat(store.complete(executing, new StoredResponse("{}"), Duration.ofHours(1), OPERATION)) + .isEqualTo(IdempotencyCompleteOutcome.COMPLETED); + } + + @Test + void releasingUnderAnotherOperationThanTheClaimIsAConflictThatReleasesNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner claimed = acquire(store); + + // when + IdempotencyReleaseOutcome conflict = store.releaseBeforeExecution(claimed, OTHER_OPERATION); + + // then + assertThat(conflict).isEqualTo(IdempotencyReleaseOutcome.OPERATION_CONFLICT); + assertThat(store.markExecutionStarted(claimed, OPERATION).outcome()) + .isEqualTo(IdempotencyStartOutcome.STARTED); + } + + @Test + void anotherAttemptCompletingARecordCompletedUnderTheSameOperationIsNotItsOwner() { + // given + // One operation id on two attempts — a caller that keeps its operation id across resends. The + // second attempt took the retryable failure over and completed it; the first attempt's late + // completion is not that completion. The PostgreSQL store confirmed it, because its replay + // check read the operation id and not the owner. + IdempotencyStorePort store = subject(); + IdempotencyOwner first = executing(store); + store.markFailed( + first, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION); + IdempotencyOwner second = + started(store, ownerOf(store.claim(claim(store.newClaimAttempt(OPERATION), FINGERPRINT)))); + store.complete(second, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); + + // when + IdempotencyCompleteOutcome late = + store.complete(first, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); + + // then + assertThat(late).isEqualTo(IdempotencyCompleteOutcome.NOT_OWNER); + } + + @Test + void aClaimWithTheOwnerTokenUnderAnotherOperationIsAnOwnerOperationConflict() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner claimed = ownerOf(store.claim(claim(attempt, FINGERPRINT))); + + // when + IdempotencyClaimOutcome conflict = + store.claim( + claim(new IdempotencyClaimAttempt(attempt.ownerToken(), OTHER_OPERATION), FINGERPRINT)); + + // then + assertThat(conflict).isInstanceOf(IdempotencyClaimOutcome.OwnerOperationConflict.class); + assertThat(store.markExecutionStarted(claimed, OPERATION).outcome()) + .isEqualTo(IdempotencyStartOutcome.STARTED); + } + + @Test + void inspectingAClaimWithTheOwnerTokenUnderAnotherOperationIsAnOperationConflict() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + store.claim(claim(attempt, FINGERPRINT)); + + // when + IdempotencyInspection inspection = + store.inspect( + new IdempotencyInspectionRequest( + SCOPE, + FINGERPRINT, + new IdempotencyClaimAttempt(attempt.ownerToken(), OTHER_OPERATION))); + + // then + assertThat(inspection.outcome()).isEqualTo(IdempotencyInspectionOutcome.OPERATION_CONFLICT); + } + + @Test + void inspectingACompletedRecordWithTheOwnerTokenUnderAnotherOperationIsAnOperationConflict() { + // given + // In every state, a completed record included: the Redis store refused it, the PostgreSQL + // store and the in-memory fake replayed the response to it. + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + store.complete( + started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))), + new StoredResponse("{\"ok\":true}"), + Duration.ofHours(1), + OPERATION); + + // when + IdempotencyInspection inspection = + store.inspect( + new IdempotencyInspectionRequest( + SCOPE, + FINGERPRINT, + new IdempotencyClaimAttempt(attempt.ownerToken(), OTHER_OPERATION))); + + // then + assertThat(inspection.outcome()).isEqualTo(IdempotencyInspectionOutcome.OPERATION_CONFLICT); + } + + @Test + void releasingAScopeWithNoRecordIsAbsent() { + // given + // A handle whose record is gone — expired, reaped — stands in here as one for a scope nobody + // claimed. Nothing was found, so nothing is confirmed: the Redis store answered that it had + // already released it. + IdempotencyStorePort store = subject(); + IdempotencyOwner gone = + new IdempotencyOwner(SCOPE, store.newClaimAttempt(OPERATION).ownerToken(), 1, 1, OPERATION); + + // when + IdempotencyReleaseOutcome released = store.releaseBeforeExecution(gone, OPERATION); + + // then + assertThat(released).isEqualTo(IdempotencyReleaseOutcome.ABSENT); + } + + @Test + void aReleaseRetriedAfterItWasAppliedReleasesNothingMore() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner claimed = acquire(store); + store.releaseBeforeExecution(claimed, OPERATION); + + // when + IdempotencyReleaseOutcome again = store.releaseBeforeExecution(claimed, OPERATION); + + // then + // A store that keeps the released record recognises the release (PostgreSQL); one that forgets + // it finds no record (Redis, the in-memory fake). Neither releases a second time. + assertThat(again) + .isIn( + IdempotencyReleaseOutcome.ALREADY_RELEASED_SAME_OPERATION, + IdempotencyReleaseOutcome.ABSENT); + } + + @Test + void releasingThroughTheHandleFromBeforeTheAttemptTookItsClaimOverIsRefusedAsAStaleOwner() { + // given + // The same attempt took its retryable failure over, so the record is a claim again under the + // same owner token and operation. The Redis program read no revision and released it. + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner before = ownerOf(store.claim(claim(attempt, FINGERPRINT))); + store.markFailed( + started(store, before), + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + IdempotencyOwner current = ownerOf(store.claim(claim(attempt, FINGERPRINT))); + + // when + IdempotencyReleaseOutcome released = store.releaseBeforeExecution(before, OPERATION); + + // then + assertThat(released).isEqualTo(IdempotencyReleaseOutcome.NOT_OWNER); + assertThat(store.markExecutionStarted(current, OPERATION).outcome()) + .isEqualTo(IdempotencyStartOutcome.STARTED); + } + + // A transition already applied is confirmed only to the handle it was applied from — the record + // one revision past it — and any other handle is refused as a stale owner, the same attempt's + // handle from before a takeover included (owner decision 2026-11-06). The stores used to differ: + // the Redis store confirmed an applied completion or failure to every handle of its operation; + // the PostgreSQL store confirmed a completion to every handle of its owner token and answered + // another handle's failure, renewal or release OPERATION_CONFLICT — the holder's own second + // renewal included; the in-memory fake confirmed a completion and nothing else. + + @Test + @DisplayName("같은 attempt가 넘겨받기 전 핸들로, 넘겨받은 뒤 적용된 complete를 다시 보내면 확인하지 않고 NOT_OWNER다") + void theHandleFromBeforeATakeoverIsNotConfirmedTheCompletionThatFollowedIt() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner before = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.markFailed( + before, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION); + IdempotencyOwner after = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.complete(after, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); + + // when + IdempotencyCompleteOutcome resent = + store.complete(before, new StoredResponse("{\"v\":1}"), Duration.ofHours(1), OPERATION); + + // then + assertThat(resent).isEqualTo(IdempotencyCompleteOutcome.NOT_OWNER); + } + + @Test + @DisplayName("같은 attempt가 넘겨받기 전 핸들로, 넘겨받은 뒤 적용된 markFailed를 다시 보내면 확인하지 않고 NOT_OWNER다") + void theHandleFromBeforeATakeoverIsNotConfirmedTheFailureThatFollowedIt() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner before = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.markFailed( + before, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION); + IdempotencyOwner after = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.markFailed( + after, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION); + + // when + IdempotencyFailOutcome resent = + store.markFailed( + before, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // then + assertThat(resent).isEqualTo(IdempotencyFailOutcome.NOT_OWNER); + } + + @Test + @DisplayName("markFailed를 적용한 핸들이 같은 인자로 다시 보내면 이미 처리됨으로 확인한다") + void aFailureResentThroughTheHandleItWasAppliedFromIsConfirmed() { + // given + // The reply was lost, so the caller still holds the handle it sent the failure with. + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // when + IdempotencyFailOutcome resent = + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // then + assertThat(resent).isEqualTo(IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION); + } + + @Test + @DisplayName("markFailed를 적용한 핸들이 다른 retention으로 다시 보내면 이미 처리됨으로 확인한다") + void aFailureResentThroughTheHandleItWasAppliedFromWithAnotherRetentionIsConfirmed() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // when + IdempotencyFailOutcome resent = + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(2), + OPERATION); + + // then + // The retention is how long the recorded failure is kept, not what it decided, so a resend is + // not compared on it — as a completion's replay TTL is not (owner decision 2026-11-07: the + // Redis store and the fake confirmed it, the PostgreSQL store answered OPERATION_CONFLICT). + assertThat(resent).isEqualTo(IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION); + } + + @Test + @DisplayName("markFailed를 적용한 핸들이 다른 disposition으로 다시 보내면 OPERATION_CONFLICT이고 기록된 실패는 그대로다") + void aFailureResentThroughTheHandleItWasAppliedFromWithAnotherDispositionIsAConflict() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + store.markFailed( + executing, + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + + // when + IdempotencyFailOutcome resent = + store.markFailed( + executing, + IdempotencyFailureDisposition.EFFECT_UNKNOWN_ABANDONED, + Duration.ofHours(1), + OPERATION); + + // then + // The failure this handle applied, asked for again with other arguments: the same id with + // other arguments is OPERATION_CONFLICT (owner decision 2026-11-07). Every store answered + // NOT_OWNER, which tells the handle that applied the failure that the record went to somebody + // else. The recorded disposition stays, so the next claim still takes the record over. + assertThat(resent).isEqualTo(IdempotencyFailOutcome.OPERATION_CONFLICT); + assertThat(store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT))) + .isInstanceOf(IdempotencyClaimOutcome.TakenOverClaimed.class); + } + + @Test + @DisplayName("release한 핸들로 start하면 ABSENT나 NOT_OWNER로 거절되고 아무것도 시작되지 않는다") + void startingThroughAReleasedHandleStartsNothing() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner claimed = acquire(store); + store.releaseBeforeExecution(claimed, OPERATION); + + // when + IdempotencyMutationResult started = + store.markExecutionStarted(claimed, OPERATION); + + // then + // A store that forgets the released record finds none (Redis, the in-memory fake); one that + // keeps it finds the handle one revision behind it (PostgreSQL). Either way nothing started + // and the next claim owns the scope (owner decision 2026-11-06). + assertThat(started.outcome()) + .isIn(IdempotencyStartOutcome.ABSENT, IdempotencyStartOutcome.NOT_OWNER); + IdempotencyClaimOutcome next = + store.claim(claim(store.newClaimAttempt(OTHER_OPERATION), FINGERPRINT)); + assertThat(store.markExecutionStarted(ownerOf(next), OTHER_OPERATION).outcome()) + .isEqualTo(IdempotencyStartOutcome.STARTED); + } + + @Test + @DisplayName("start를 적용한 핸들이 다시 보내면 이미 시작됨과 현재 핸들을 받는다") + void aStartResentThroughTheHandleItWasAppliedFromIsConfirmedWithTheCurrentHandle() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner claimed = acquire(store); + IdempotencyOwner started = started(store, claimed); + + // when + IdempotencyMutationResult resent = + store.markExecutionStarted(claimed, OPERATION); + + // then + assertThat(resent.outcome()).isEqualTo(IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION); + assertThat(resent.owner().orElseThrow().stateRevision()).isEqualTo(started.stateRevision()); + } + + @Test + @DisplayName("start가 돌려준 핸들로 renew한 뒤 그 핸들로 start하면 이미 시작됨이 아니라 NOT_OWNER다") + void aStartThroughTheHandleARenewalWasAppliedFromIsNotConfirmed() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // when + IdempotencyMutationResult started = + store.markExecutionStarted(executing, OPERATION); + + // then + // The record is executing one revision past this handle, but a renewal moved it there, not a + // start, so the handle is stale. The Redis store read only the state and the revision and + // confirmed the start, and the executor runs the action on that answer — a second run of an + // execution that is already running. + assertThat(started.outcome()).isEqualTo(IdempotencyStartOutcome.NOT_OWNER); + } + + @Test + @DisplayName("renew를 적용한 핸들이 같은 lease로 다시 보내면 이미 renew됨과 현재 핸들을 받는다") + void aRenewalResentThroughTheHandleItWasAppliedFromIsConfirmedWithTheCurrentHandle() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + IdempotencyOwner renewed = + store.renew(executing, Duration.ofSeconds(30), OPERATION).owner().orElseThrow(); + + // when + IdempotencyMutationResult resent = + store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(resent.outcome()).isEqualTo(IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION); + assertThat(resent.owner().orElseThrow().stateRevision()).isEqualTo(renewed.stateRevision()); + } + + @Test + @DisplayName("renew를 적용한 핸들이 다른 lease로 다시 보내면 OPERATION_CONFLICT다") + void aRenewalResentThroughTheHandleItWasAppliedFromWithAnotherLeaseIsAConflict() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + store.renew(executing, Duration.ofSeconds(30), OPERATION); + + // when + IdempotencyMutationResult resent = + store.renew(executing, Duration.ofSeconds(45), OPERATION); + + // then + assertThat(resent.outcome()).isEqualTo(IdempotencyRenewOutcome.OPERATION_CONFLICT); + } + + @Test + @DisplayName("renew가 돌려준 핸들로 다시 renew하면 한 번 더 renew된다") + void aHolderRenewsAgainThroughTheHandleItsRenewalReturned() { + // given + IdempotencyStorePort store = subject(); + IdempotencyOwner executing = executing(store); + IdempotencyOwner renewed = + store.renew(executing, Duration.ofSeconds(30), OPERATION).owner().orElseThrow(); + + // when + IdempotencyMutationResult again = + store.renew(renewed, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(again.outcome()).isEqualTo(IdempotencyRenewOutcome.RENEWED); + assertThat(again.owner().orElseThrow().stateRevision()).isGreaterThan(renewed.stateRevision()); + } + + @Test + @DisplayName("같은 attempt가 넘겨받기 전 핸들로 renew하면, 넘겨받은 뒤 적용된 renew로 확인하지 않고 NOT_OWNER다") + void theHandleFromBeforeATakeoverIsNotConfirmedTheRenewalThatFollowedIt() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner before = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.markFailed( + before, IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, Duration.ofHours(1), OPERATION); + IdempotencyOwner after = started(store, ownerOf(store.claim(claim(attempt, FINGERPRINT)))); + store.renew(after, Duration.ofSeconds(30), OPERATION); + + // when + IdempotencyMutationResult resent = + store.renew(before, Duration.ofSeconds(30), OPERATION); + + // then + assertThat(resent.outcome()).isEqualTo(IdempotencyRenewOutcome.NOT_OWNER); + } + + @Test + @DisplayName("같은 attempt가 넘겨받기 전 핸들로 release하면, 넘겨받은 뒤 적용된 release로 확인하지 않는다") + void theHandleFromBeforeATakeoverIsNotConfirmedTheReleaseThatFollowedIt() { + // given + IdempotencyStorePort store = subject(); + IdempotencyClaimAttempt attempt = store.newClaimAttempt(OPERATION); + IdempotencyOwner before = ownerOf(store.claim(claim(attempt, FINGERPRINT))); + store.markFailed( + started(store, before), + IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE, + Duration.ofHours(1), + OPERATION); + IdempotencyOwner after = ownerOf(store.claim(claim(attempt, FINGERPRINT))); + store.releaseBeforeExecution(after, OPERATION); + + // when + IdempotencyReleaseOutcome resent = store.releaseBeforeExecution(before, OPERATION); + + // then + // As for a start through a released handle: a store that forgets the released record finds + // none, one that keeps it finds the handle stale. + assertThat(resent).isIn(IdempotencyReleaseOutcome.ABSENT, IdempotencyReleaseOutcome.NOT_OWNER); + } + @Test @DisplayName("실행 중인 자기 기록을 inspect하면 기록 수명이 아니라 claim이 받은 처리 lease 만료 시각이 나온다") void inspectingAnOwnExecutionReportsItsProcessingLeaseNotTheRecordLifetime() { diff --git a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java index 12589761..77800bac 100644 --- a/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java +++ b/src/application-core/src/testFixtures/java/dev/caskeleton/application/idempotency/testkit/InMemoryIdempotencyStore.java @@ -34,7 +34,9 @@ import java.util.Random; * attempt against an in-flight record is always {@code InProgress}. Leases and replay windows are * reported as {@link Instant#MAX}. What it keeps exact is what a test of a caller relies on: one * claim wins, the owner handle's revision advances on every transition, a completed response - * replays, a different fingerprint is refused, and a retryable failure can be claimed again. + * replays, a different fingerprint is refused, a retryable failure can be claimed again, an owner + * naming an operation other than its claim's is refused, and a transition resent after a lost reply + * is confirmed to the handle it was applied from and to no other. */ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { @@ -82,6 +84,10 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { && row.owner.claimOperationId().equals(request.claimAttempt().operationId())) { return new IdempotencyClaimOutcome.ReplayedAcquire(row.owner, Instant.MAX); } + // The owner token under another operation is refused, not reported in progress. + if (row.owner.ownerToken().equals(request.claimAttempt().ownerToken())) { + return new IdempotencyClaimOutcome.OwnerOperationConflict(); + } return new IdempotencyClaimOutcome.InProgress(Duration.ZERO, row.owner.attempt()); } @@ -92,17 +98,20 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { IdempotencyStartOutcome outcome = row == null ? IdempotencyStartOutcome.ABSENT - : !row.owner.equals(owner) - ? IdempotencyStartOutcome.NOT_OWNER - : row.state != IdempotencyState.CLAIMED - ? IdempotencyStartOutcome.NOT_CLAIMED - : IdempotencyStartOutcome.STARTED; - if (outcome != IdempotencyStartOutcome.STARTED) { - return new IdempotencyMutationResult<>(outcome, null, IdempotencyStartOutcome::carriesOwner); + : row.namesAnotherOperation(owner, operationId) + ? IdempotencyStartOutcome.OPERATION_CONFLICT + : row.repeats(owner, Transition.START) + ? IdempotencyStartOutcome.ALREADY_STARTED_SAME_OPERATION + : !row.owner.equals(owner) + ? IdempotencyStartOutcome.NOT_OWNER + : row.state != IdempotencyState.CLAIMED + ? IdempotencyStartOutcome.NOT_CLAIMED + : IdempotencyStartOutcome.STARTED; + if (outcome == IdempotencyStartOutcome.STARTED) { + row.advance(IdempotencyState.EXECUTING, owner, Transition.START, null); } - row.advance(IdempotencyState.EXECUTING); return new IdempotencyMutationResult<>( - outcome, row.owner, IdempotencyStartOutcome::carriesOwner); + outcome, outcome.carriesOwner() ? row.owner : null, IdempotencyStartOutcome::carriesOwner); } @Override @@ -111,20 +120,27 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { Row row = rows.get(owner.scope().digest()); // Only a running execution has a processing lease to extend; the stores answer a claim that // has not started with NOT_IN_PROGRESS, and IdempotencyStoreContract holds the fake to that. - IdempotencyRenewOutcome refused = + // A renewal resent from the handle it was applied from is confirmed for the same lease and a + // conflict for another, as the stores answer. + IdempotencyRenewOutcome outcome = row == null ? IdempotencyRenewOutcome.ABSENT - : !row.owner.equals(owner) - ? IdempotencyRenewOutcome.NOT_OWNER - : row.state != IdempotencyState.EXECUTING - ? IdempotencyRenewOutcome.NOT_IN_PROGRESS - : null; - if (refused != null) { - return new IdempotencyMutationResult<>(refused, null, IdempotencyRenewOutcome::carriesOwner); + : row.namesAnotherOperation(owner, operationId) + ? IdempotencyRenewOutcome.OPERATION_CONFLICT + : row.repeats(owner, Transition.RENEW) + ? processingLeaseTtl.equals(row.applied.argument()) + ? IdempotencyRenewOutcome.ALREADY_RENEWED_SAME_OPERATION + : IdempotencyRenewOutcome.OPERATION_CONFLICT + : !row.owner.equals(owner) + ? IdempotencyRenewOutcome.NOT_OWNER + : row.state != IdempotencyState.EXECUTING + ? IdempotencyRenewOutcome.NOT_IN_PROGRESS + : IdempotencyRenewOutcome.RENEWED; + if (outcome == IdempotencyRenewOutcome.RENEWED) { + row.advance(row.state, owner, Transition.RENEW, processingLeaseTtl); } - row.advance(row.state); return new IdempotencyMutationResult<>( - IdempotencyRenewOutcome.RENEWED, row.owner, IdempotencyRenewOutcome::carriesOwner); + outcome, outcome.carriesOwner() ? row.owner : null, IdempotencyRenewOutcome::carriesOwner); } @Override @@ -137,7 +153,10 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyCompleteOutcome.ABSENT; } - if (row.state == IdempotencyState.COMPLETED && owner.equals(row.completedBy)) { + if (row.namesAnotherOperation(owner, operationId)) { + return IdempotencyCompleteOutcome.OPERATION_CONFLICT; + } + if (row.repeats(owner, Transition.COMPLETE)) { // The completing handle retried, as after a lost reply: the same result is a no-op, another // result is a conflict, exactly as the stores answer. return row.response.equals(response) @@ -151,8 +170,7 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { return IdempotencyCompleteOutcome.NOT_IN_PROGRESS; } row.response = response; - row.completedBy = owner; - row.advance(IdempotencyState.COMPLETED); + row.advance(IdempotencyState.COMPLETED, owner, Transition.COMPLETE, null); return IdempotencyCompleteOutcome.COMPLETED; } @@ -166,6 +184,17 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyFailOutcome.ABSENT; } + if (row.namesAnotherOperation(owner, operationId)) { + return IdempotencyFailOutcome.OPERATION_CONFLICT; + } + // The failing handle retried, as after a lost reply: the same disposition is a no-op, another + // disposition is a conflict, exactly as the stores answer. The retention is not compared: it is + // how long the failure is kept, and the first one stays (owner decision 2026-11-07). + if (row.repeats(owner, Transition.FAIL)) { + return disposition.equals(row.applied.argument()) + ? IdempotencyFailOutcome.ALREADY_MARKED_SAME_OPERATION + : IdempotencyFailOutcome.OPERATION_CONFLICT; + } if (!row.owner.equals(owner)) { return IdempotencyFailOutcome.NOT_OWNER; } @@ -173,7 +202,11 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { return IdempotencyFailOutcome.NOT_IN_PROGRESS; } boolean retryable = disposition == IdempotencyFailureDisposition.NO_EFFECT_RETRYABLE; - row.advance(retryable ? IdempotencyState.FAILED_RETRYABLE : IdempotencyState.ABANDONED); + row.advance( + retryable ? IdempotencyState.FAILED_RETRYABLE : IdempotencyState.ABANDONED, + owner, + Transition.FAIL, + disposition); return retryable ? IdempotencyFailOutcome.MARKED_RETRYABLE : IdempotencyFailOutcome.MARKED_ABANDONED; @@ -186,6 +219,9 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (row == null) { return IdempotencyReleaseOutcome.ABSENT; } + if (row.namesAnotherOperation(owner, operationId)) { + return IdempotencyReleaseOutcome.OPERATION_CONFLICT; + } if (!row.owner.equals(owner)) { return IdempotencyReleaseOutcome.NOT_OWNER; } @@ -205,6 +241,11 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { if (!row.fingerprint.equals(request.requestFingerprint())) { return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.FINGERPRINT_MISMATCH); } + // The stores' order: the owner token under another operation is refused in every state. + if (row.owner.ownerToken().equals(request.claimAttempt().ownerToken()) + && !row.owner.claimOperationId().equals(request.claimAttempt().operationId())) { + return IdempotencyInspection.outcome(IdempotencyInspectionOutcome.OPERATION_CONFLICT); + } if (row.state == IdempotencyState.COMPLETED) { return new IdempotencyInspection( IdempotencyInspectionOutcome.COMPLETED_REPLAY, @@ -257,7 +298,7 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { private IdempotencyOwner owner; private IdempotencyState state = IdempotencyState.CLAIMED; private StoredResponse response; - private IdempotencyOwner completedBy; + private Applied applied; Row(RequestFingerprint fingerprint, IdempotencyClaimRequest request, long attempt, long rev) { this.fingerprint = fingerprint; @@ -270,9 +311,48 @@ public final class InMemoryIdempotencyStore implements IdempotencyStorePort { request.claimAttempt().operationId()); } - void advance(IdempotencyState next) { + /** Applies a transition from {@code from}, remembering it for a resend of the same call. */ + void advance(IdempotencyState next, IdempotencyOwner from, Transition kind, Object argument) { owner = owner.withStateRevision(owner.stateRevision() + 1); state = next; + applied = new Applied(from, kind, argument); + } + + /** + * Whether {@code caller} resends the last transition applied, from the handle it was applied + * from. Only that handle is told the transition was already applied; any other is not, the same + * attempt's handle from before a takeover included (owner decision 2026-11-06). + */ + boolean repeats(IdempotencyOwner caller, Transition kind) { + return applied != null && applied.kind() == kind && applied.from().equals(caller); + } + + /** + * Whether the record's owner names an operation other than its claim's. The stores refuse that + * before anything else is read, whatever the handle's revision ({@code + * IdempotencyStoreContract}). + */ + boolean namesAnotherOperation(IdempotencyOwner caller, OperationId operationId) { + return owner.ownerToken().equals(caller.ownerToken()) + && !owner.claimOperationId().equals(operationId); } } + + /** The transitions a handle can resend after a lost reply. */ + private enum Transition { + START, + RENEW, + COMPLETE, + FAIL + } + + /** + * The last transition applied to a record. + * + * @param from the handle it was applied from + * @param kind which transition + * @param argument what it decided besides the handle: the lease of a renewal, the disposition of + * a failure; {@code null} for the others + */ + private record Applied(IdempotencyOwner from, Transition kind, Object argument) {} } diff --git a/src/build-logic/README.md b/src/build-logic/README.md index 22a7340b..279ff8c3 100644 --- a/src/build-logic/README.md +++ b/src/build-logic/README.md @@ -15,8 +15,8 @@ capability, and the files it reads are declared as that test task's inputs. | `ca.quality-conventions` | Spotless, Checkstyle, Error Prone, SpotBugs/FindSecBugs wiring shared by Java leaves | | `ca.java-library` / `ca.spring-library` / `ca.spring-config` | leaf-level composition of the Java/quality conventions for plain and Spring libraries | | `ca.platform-module` / `ca.grpc-platform-module` | what a vendored platform leaf (`messaging:*`, `grpc:*`, `grpc-advanced:*`) is: `java-library`, plus the gRPC BOM for the leaves that had it | -| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | -| `ca.strict-lane-stages` (root of each build with strict lanes: the main build and optional-platforms) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane of that build that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow. The workflows are read together (`WorkflowGradleInvocations.readAll`, so a reusable workflow is judged by its callers) and their `run:` scripts parsed as bash (`ShellScript`: quotes, comments, heredoc bodies, substitutions and compound commands are read as the shell reads them, so a `cd` in a heredoc or a string is data). A command does not count when Gradle runs no task with it — `--dry-run`/`-m` (also in a bundle such as `-qm`), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground` (also in a bundle such as `-qv`) — or rejects it: a short-option bundle whose later letter takes a value (`-mx`: only the first letter of a bundle takes one), or a value given to an option that takes none (`-m=yes`). The reader follows Gradle 9.0's parser. `GradleCommandLineTest` holds its option tables to the `--help` of the Gradle that runs build-logic — an upgrade that adds an option, as 9.2 adds `--task-graph`, fails until the option is placed — and runs the launcher with each no-task option but `--stop` and `--foreground` (both return a daemon action, not a build, in Gradle's `BuildActionsFactory`); which options take a value was probed against 9.0.0 in round 9 and is not re-run. Nor does a command for another build count (the build a command starts is its step's `working-directory`, or the job's or workflow's `defaults.run.working-directory`, moved by each `cd ` the same `run:` shell surely ran before it — alone in its list, or before the command in the same `&&` list — then joined with `-p`; the plugin reads this build's own directory from where it sits under the repository that holds `.github/workflows`). Every other command that does not count gives one of three reasons. **Its failure may not fail its step**: `\|\| true`, `\|\| :` or any `\|\|` but `\|\| exit `, a pipe's left side without `pipefail` (on with `shell: bash` or a top-level `set -o pipefail`), `!`, `&`, an `if`/`while` condition, the part before `&&` of a list that is not the script's last command, after `set +e`, after a `trap` whose `EXIT` or `ERR` action may `exit` with status 0 (a bare `exit` keeps the status in an `EXIT` trap, not in an `ERR` one), and `continue-on-error`. **It may not run**: after `\|\|`, after `&&` in a list that is not the script's last command, inside `if`/`while`/`for`/`case` or a function body, after a top-level `exit`, `exec ` or `set -n`, after one elsewhere — in a compound command, an and-or list or a function the script calls — that may end the script with status 0 (`exit 0`, a bare `exit` other than right after `\|\|`, `exit "$code"`), replace it or stop it running commands (`set -o noexec`), under an `if:` other than `always()`/`success()`/`!cancelled()`, in a workflow that starts only on events someone or something asks for (`workflow_dispatch`, `repository_dispatch`, `issue_comment`, a pull request with `types: [labeled]`, `workflow_run`, …; `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule` and `release` count), in a reusable (`workflow_call`-only) workflow that no counted job calls with `uses: ./.github/workflows/`, and in a job that `needs`, directly or through other jobs, a job with such an `if:` or with `continue-on-error`, unless its own `if:` is `always()` or `!cancelled()`. **This check does not read it**, although its failure would fail the step (a false failure on purpose): `\|\| exit 1`, `\|\| { …; exit 1; }`, inside `{ }` or `( )`, `$( )`, `bash -c`, `gradlew` as another command's argument (`timeout 60 ./gradlew`), after a directory change the reader does not follow (`cd "$VAR"`, `cd -`, `cd ~`, an absolute path, `pushd`/`popd`, `builtin cd`, `eval`/`source`, a `cd` anywhere inside a compound command or a function body, one joined with `\|\|`, piped or in the background, and the lines after a `cd` that shares an `&&` list with other commands — not guessed), a step whose `shell:` is not `bash` or `sh`, and a step with no `shell:` in a job whose `runs-on` may be a Windows runner, whose default shell is `pwsh` (a Windows label, an expression such as `${{ matrix.os }}`, a self-hosted label set without `linux` or `macos`; Linux and macOS runners default to `bash -e` and a `container:` job to `sh -e`, which are read alike). An `exit` that fails the step — `exit 1`, or `cmd \|\| exit` — and one in an uncalled function, a `( )` subshell or `$( )` stop nothing after them from counting. The failure names every command that names the stage but does not execute it, with its reason or the other build it starts, and says to run the stage as `./gradlew` on a line of its own. A lane the command removes with `-x` is not covered — matched the way Gradle matches task and project names, abbreviations included (`TaskSelectors`, a copy of Gradle's internal `NameMatcher`). A `run:` input of a `uses:` step is not a command. The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, owner decision 2026-11-04 on `cd`, RR5-02-01/02/03 in round 9, 2026-11-05 RR6-04-01..06) | +| `ca.strict-test-lane` | the one "named tests ran, none skipped" mechanism: tagged / named / own-source-set `Test` lanes that fail when they execute nothing, miss a `requires` class, or (with `rejectSkipped`) skip anything. A `performance()` lane always rejects skips and runs with `performance.assertions.enabled=true`; a build (`-P`, `GRADLE_OPTS`) or lane that sets another value fails it before a test runs. `mainStage()` moves a tagged lane out of `test` into the leaf's `mainCheck`; `explicitOnly(reason)` keeps a lane that needs an outside input out of every aggregate, and the aggregate prints the reason. Extra test source sets are Gradle `jvm-test-suite` suites declared in the leaf (`testing { suites { … } }`); a lane named after its suite makes the suite's own `Test` task strict, and `ca.java-conventions` gives every suite the BOM's JUnit | +| `ca.strict-lane-stages` (root of each build with strict lanes: the main build and optional-platforms) | the other half of the lane mechanism: `verifyStrictLaneStages --dry-run` fails when a strict lane of that build that is not `explicitOnly` is in the task plan of no declared stage that a workflow executes, or when a declared stage is executed by no workflow. The workflows are read together (`WorkflowGradleInvocations.readAll`, so a reusable workflow is judged by its callers) and their `run:` scripts parsed as bash (`ShellScript`: quotes, comments, heredoc bodies, substitutions and compound commands are read as the shell reads them, so a `cd` in a heredoc or a string is data). A command does not count when Gradle runs no task with it — `--dry-run`/`-m` (also in a bundle such as `-qm`), `-v`/`--version`, `-h`/`-?`/`--help`, `--status`, `--stop`, `--foreground` (also in a bundle such as `-qv`) — or rejects it: a short-option bundle whose later letter takes a value (`-mx`: only the first letter of a bundle takes one), or a value given to an option that takes none (`-m=yes`). The reader follows Gradle 9.0's parser. `GradleCommandLineTest` holds its option tables to the `--help` of the Gradle that runs build-logic — an upgrade that adds an option, as 9.2 adds `--task-graph`, fails until the option is placed — and runs the launcher with each no-task option but `--stop` and `--foreground` (both return a daemon action, not a build, in Gradle's `BuildActionsFactory`); which options take a value was probed against 9.0.0 in round 9 and is not re-run. Nor does a command for another build count (the build a command starts is its step's `working-directory`, or the job's or workflow's `defaults.run.working-directory`, moved by each `cd ` the same `run:` shell surely ran before it — alone in its list, or before the command in the same `&&` list — then joined with `-p`; the plugin reads this build's own directory from where it sits under the repository that holds `.github/workflows`). Every other command that does not count gives one of three reasons. **Its failure may not fail its step**: `\|\| true`, `\|\| :` or any `\|\|` but `\|\| exit `, a pipe's left side without `pipefail` (on with `shell: bash` or a top-level `set -o pipefail`), `!`, `&`, an `if`/`while` condition, the part before `&&` of a list that is not the script's last command, after `set +e`, after a `trap` whose `EXIT` or `ERR` action may `exit` with status 0 (a bare `exit` keeps the status in an `EXIT` trap, not in an `ERR` one), and `continue-on-error`. **It may not run**: after `\|\|`, after `&&` in a list that is not the script's last command, inside `if`/`while`/`for`/`case` or a function body, after a top-level `exit`, `exec ` or `set -n`, after one elsewhere — in a compound command, an and-or list or a function the script calls — that may end the script with status 0 (`exit 0`, a bare `exit` other than right after `\|\|`, `exit "$code"`), replace it or stop it running commands (`set -o noexec`), under an `if:` other than `always()`/`success()`/`!cancelled()`, in a workflow that starts only on events someone or something asks for (`workflow_dispatch`, `repository_dispatch`, `issue_comment`, a pull request with `types: [labeled]`, `workflow_run`, …; `push`, `pull_request`, `pull_request_target`, `merge_group`, `schedule` and `release` count), in a workflow whose change-flow triggers all carry a `paths` or `paths-ignore` filter (a change outside those paths does not start it; owner decision 2026-11-06), for any stage but `:releaseCheck` in a workflow that starts without a request or a path filter only on the release flow — `release`, or a `push` with `tags`/`tags-ignore` and no `branches`/`branches-ignore`, which a branch push does not start (owner decision 2026-11-07; `:releaseCheck` is the tag-only stage) — in a reusable (`workflow_call`-only) workflow that no counted job calls with `uses: ./.github/workflows/`, and in a job that `needs`, directly or through other jobs, a job with such an `if:` or with `continue-on-error`, unless its own `if:` is `always()` or `!cancelled()`. **This check does not read it**, although its failure would fail the step (a false failure on purpose): `\|\| exit 1`, `\|\| { …; exit 1; }`, inside `{ }` or `( )`, `$( )`, `bash -c`, `gradlew` as another command's argument (`timeout 60 ./gradlew`), after a directory change the reader does not follow (`cd "$VAR"`, `cd -`, `cd ~`, an absolute path, `pushd`/`popd`, `builtin cd`, `eval`/`source`, a `cd` anywhere inside a compound command or a function body, one joined with `\|\|`, piped or in the background, and the lines after a `cd` that shares an `&&` list with other commands — not guessed), a step whose `shell:` is not `bash` or `sh`, and a step with no `shell:` in a job whose `runs-on` may be a Windows runner, whose default shell is `pwsh` (a Windows label, an expression such as `${{ matrix.os }}`, a self-hosted label set without `linux` or `macos`; Linux and macOS runners default to `bash -e` and a `container:` job to `sh -e`, which are read alike). An `exit` that fails the step — `exit 1`, or `cmd \|\| exit` — and one in an uncalled function, a `( )` subshell or `$( )` stop nothing after them from counting. The failure names every command that names the stage but does not execute it, with its reason or the other build it starts, and says to run the stage as `./gradlew` on a line of its own. A lane the command removes with `-x` is not covered — matched the way Gradle matches task and project names, abbreviations included (`TaskSelectors`, a copy of Gradle's internal `NameMatcher`). A `run:` input of a `uses:` step is not a command. The plan is Gradle's own; the workflows are read for their `run:` steps with YAML folding applied (review 2026-11-01 08-01, 2026-11-03 RR-06-03/04, 2026-11-04 RR2-04-04, owner decision 2026-11-04 on `cd`, RR5-02-01/02/03 in round 9, 2026-11-05 RR6-04-01..06, 2026-11-06 RR7-05-01, owner decision 2026-11-07 on the release flow) | | `ca.redis-topology-lane` | the Redis topology lane (mode selection, `-P` property validation, per-mode required classes) the redis-sdk-topology workflow drives | | `ca.api-surface` | read-only public API surface verification with a separate update task, wired into the leaf's `check` (owner decision 20); optionally holds other leaves' imports to a reviewed adopter subset (`adopterBaseline`) | | `ca.config-contract` | app-bootstrap's `verifyEnvKeys` (moved from the deleted build-tools included build; owner decision 4 keeps the task in app-bootstrap) | diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/MainBuild.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/MainBuild.java new file mode 100644 index 00000000..c64083b9 --- /dev/null +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/MainBuild.java @@ -0,0 +1,78 @@ +package dev.caskeleton.buildlogic; + +import java.io.File; +import java.io.IOException; +import java.io.UncheckedIOException; +import org.gradle.api.GradleException; + +/** + * Where the main build is, seen from any build of this repository. + * + *

The main build is the Gradle root that owns the module registry ({@code + * config/architecture/modules.json}); the repository root is its parent. The optional platform build + * lives inside it ({@code src/platforms/optional-build}), and the code that needs the registry, the + * shared tool configuration or the test image catalog used to reach the main build by taking one + * parent of the optional build's root. That held only while the optional build sat directly under + * the main build; it is found by walking up instead, so the optional build's depth is not a fact + * every caller repeats. + */ +public final class MainBuild { + /** The registry, relative to the main build: what makes a directory the main build. */ + public static final String REGISTRY = "config/architecture/modules.json"; + + private MainBuild() {} + + /** + * The main build's directory: {@code buildRoot} itself or the nearest directory above it that + * holds the module registry. + * + * @param buildRoot the root directory of the build asking (its settings or root project directory) + * @return the canonical main build directory + */ + public static File directory(File buildRoot) { + File registry = nearest(buildRoot, REGISTRY); + if (registry == null) { + throw new GradleException( + "No " + REGISTRY + " at or above " + buildRoot + "; this build is not inside the repository"); + } + return registry.getParentFile().getParentFile().getParentFile(); + } + + /** + * The nearest {@code relativePath} at or above {@code buildRoot}: in the build's own root first, + * then in each parent. A file or a directory; {@code null} when no ancestor has it. + * + * @param buildRoot the root directory of the build asking + * @param relativePath the path to look for, relative to each candidate directory + * @return the canonical path found, or {@code null} + */ + public static File nearest(File buildRoot, String relativePath) { + for (File directory = canonical(buildRoot); + directory != null; + directory = directory.getParentFile()) { + File candidate = new File(directory, relativePath); + if (candidate.exists()) { + return candidate; + } + } + return null; + } + + /** + * The repository root: the main build's parent. + * + * @param buildRoot the root directory of the build asking + * @return the canonical repository root + */ + public static File repositoryRoot(File buildRoot) { + return directory(buildRoot).getParentFile(); + } + + private static File canonical(File file) { + try { + return file.getCanonicalFile(); + } catch (IOException exception) { + throw new UncheckedIOException("cannot resolve " + file, exception); + } + } +} diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java index 3e5d1008..a15d3d92 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java @@ -1,9 +1,8 @@ package dev.caskeleton.buildlogic.architecture; +import dev.caskeleton.buildlogic.MainBuild; import dev.caskeleton.buildlogic.ModuleRegistry; import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; import java.nio.file.Path; import java.util.ArrayList; import java.util.HashSet; @@ -33,15 +32,9 @@ public final class ArchitecturePlugin implements Plugin { Project root = project.getRootProject(); boolean optionalGrpcBuild = root.getName().equals("optional-platforms"); String buildName = optionalGrpcBuild ? "optional-grpc" : "main"; - File mainBuildDirectory = - optionalGrpcBuild ? root.getProjectDir().getParentFile() : root.getProjectDir(); - File registryFile = new File(mainBuildDirectory, "config/architecture/modules.json"); - File repositoryRoot; - try { - repositoryRoot = mainBuildDirectory.getParentFile().getCanonicalFile(); - } catch (IOException exception) { - throw new UncheckedIOException("failed to resolve repository root", exception); - } + File mainBuildDirectory = MainBuild.directory(root.getProjectDir()); + File registryFile = new File(mainBuildDirectory, MainBuild.REGISTRY); + File repositoryRoot = mainBuildDirectory.getParentFile(); ModuleRegistry registry = ModuleRegistry.read(registryFile, repositoryRoot); List modules = registry.modulesForBuild(buildName); List registryViolations = registryViolations(registry, modules); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java index bf045466..62b0d5fe 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/config/ConfigContractPlugin.java @@ -42,7 +42,8 @@ public final class ConfigContractPlugin implements Plugin { tree.exclude("app-bootstrap/**"); tree.exclude("**/build/**"); })); - // What an operator edits or runs: the root Compose files, the Logback + // What an operator edits or runs: the development Compose file and the lane + // overlays that run the application, the Logback // configuration, and the Compose lane contract with the smoke wrapper that drives it // (each lane's activationEnv, the wrapper's CAPABILITIES_OFF). Their APP_ names must // be registered and read (07-10, RR-06-07), and a lane's other variables must be read @@ -51,16 +52,17 @@ public final class ConfigContractPlugin implements Plugin { // by hand. task.getOperatorFiles() .from( + root.file("../compose.yaml"), root.fileTree( - root.file(".."), + root.file("app-bootstrap/compose-lanes"), tree -> { - tree.include("docker-compose*.yml"); - // The infrastructure stack: its APP_* variables belong to smoke-test - // clients and other services, not to this application. - tree.exclude("docker-compose.infra.yml"); + tree.include("*.yaml"); + // The lane-only services: their APP_* variables belong to the smoke + // clients, not to this application. + tree.exclude("lane-services.yaml"); }), root.file("app-bootstrap/src/main/resources/logback-spring.xml"), - root.file("config/runtime/compose-profile-contracts.json"), + root.file("app-bootstrap/compose-lanes/compose-profile-contracts.json"), root.file("../scripts/run-compose-runtime-smoke.sh")); task.getRegistryFile().fileValue(root.file("../docs/registries/env-keys.yaml")); // No module path here: the typed properties come from the configuration metadata on diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java index 8452995f..8e9b2cb9 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/java/JavaConventionsPlugin.java @@ -1,5 +1,6 @@ package dev.caskeleton.buildlogic.java; +import dev.caskeleton.buildlogic.MainBuild; import io.spring.gradle.dependencymanagement.dsl.DependencyManagementExtension; import java.io.File; import java.io.IOException; @@ -282,11 +283,12 @@ public final class JavaConventionsPlugin implements Plugin { public static final String CONTAINER_IMAGE_PROPERTY_PREFIX = "ca.test.image."; private static File containerImageCatalog(Project project) { + // The optional platform build's root is a directory inside the main build, which owns the + // catalog. File root = project.getRootProject().getProjectDir(); - File catalog = new File(root, "config/testing/container-images.properties"); - if (!catalog.isFile()) { - // The optional-platforms build's root is a directory inside the main build. - catalog = new File(root.getParentFile(), "config/testing/container-images.properties"); + File catalog = MainBuild.nearest(root, "config/testing/container-images.properties"); + if (catalog == null) { + catalog = new File(root, "config/testing/container-images.properties"); } if (!catalog.isFile()) { throw new GradleException("Missing test container image catalog: " + catalog); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java index a6c5724d..82b53c5f 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/quality/QualityConventionsPlugin.java @@ -5,6 +5,7 @@ import com.github.spotbugs.snom.Confidence; import com.github.spotbugs.snom.SpotBugsExtension; import com.github.spotbugs.snom.SpotBugsReport; import com.github.spotbugs.snom.SpotBugsTask; +import dev.caskeleton.buildlogic.MainBuild; import java.io.File; import java.util.List; import net.ltgt.gradle.errorprone.ErrorProneOptions; @@ -36,11 +37,14 @@ public final class QualityConventionsPlugin implements Plugin { SourceSet main = javaExtension.getSourceSets().getByName(SourceSet.MAIN_SOURCE_SET_NAME); SourceSet test = javaExtension.getSourceSets().getByName(SourceSet.TEST_SOURCE_SET_NAME); - File repositoryConfigDirectory = project.getRootProject().file("config"); - if (!repositoryConfigDirectory.isDirectory()) { - repositoryConfigDirectory = - new File(project.getRootProject().getProjectDir().getParentFile(), "config"); - } + // The optional platform build's root is a directory inside the main build, which owns the tool + // configuration. + File repositoryConfigDirectory = + MainBuild.nearest(project.getRootProject().getProjectDir(), "config/checkstyle"); + repositoryConfigDirectory = + repositoryConfigDirectory == null + ? project.getRootProject().file("config") + : repositoryConfigDirectory.getParentFile(); SpotlessExtension spotless = project.getExtensions().getByType(SpotlessExtension.class); spotless.java( diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyContract.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyContract.java index 66862553..631748fe 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyContract.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyContract.java @@ -59,7 +59,7 @@ public final class RedisTopologyContract { throw new IllegalStateException( "redisTopologyTest was selected without " + String.join(", ", missing) - + "; start a lane from infra/redis-sdk and pass -P=."); + + "; start a lane from src/adapter/outbound/redis-sdk/compose and pass -P=."); } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePlugin.java index 78010885..33ba01e0 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/redis/RedisTopologyLanePlugin.java @@ -60,16 +60,16 @@ public final class RedisTopologyLanePlugin implements Plugin { lane -> { lane.integration(); if ("unset".equals(declaredMode)) { - // The lane needs a running topology from infra/redis-sdk and its coordinates; without + // The lane needs a running topology from redis-sdk/compose and its coordinates; without // them it can only fail, so the repository's integrationCheck leaves it out and says // so rather than failing on an input it was never given (review NEW-16). lane.explicitOnly( "it needs -Predis.topology.mode= and the topology" - + " coordinates from infra/redis-sdk (redis-sdk-topology.yml passes them)"); + + " coordinates from redis-sdk/compose (redis-sdk-topology.yml passes them)"); } lane.setTag("redis-topology & lane-" + declaredMode); lane.setDescription( - "Runs this leaf's Redis contracts against a real topology declared in infra/redis-sdk."); + "Runs this leaf's Redis contracts against a real topology declared in redis-sdk/compose."); lane.customize( test -> configureTopologyTask(test, declaredMode, propertyValues, extension)); }); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/settings/OptionalArchitectureRegistrySettingsPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/settings/OptionalArchitectureRegistrySettingsPlugin.java index 6580a552..90b41b7c 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/settings/OptionalArchitectureRegistrySettingsPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/settings/OptionalArchitectureRegistrySettingsPlugin.java @@ -1,23 +1,17 @@ package dev.caskeleton.buildlogic.settings; +import dev.caskeleton.buildlogic.MainBuild; import dev.caskeleton.buildlogic.ModuleRegistrySettingsInstaller; import java.io.File; -import java.io.IOException; -import java.io.UncheckedIOException; import org.gradle.api.Plugin; import org.gradle.api.initialization.Settings; public final class OptionalArchitectureRegistrySettingsPlugin implements Plugin { @Override public void apply(Settings settings) { - try { - File mainBuildDirectory = settings.getSettingsDir().getParentFile().getCanonicalFile(); - File repositoryRoot = mainBuildDirectory.getParentFile().getCanonicalFile(); - File registryFile = new File(mainBuildDirectory, "config/architecture/modules.json"); - ModuleRegistrySettingsInstaller.install( - settings, registryFile, repositoryRoot, "optional-grpc"); - } catch (IOException exception) { - throw new UncheckedIOException("failed to resolve optional architecture registry paths", exception); - } + File mainBuildDirectory = MainBuild.directory(settings.getSettingsDir()); + File registryFile = new File(mainBuildDirectory, MainBuild.REGISTRY); + ModuleRegistrySettingsInstaller.install( + settings, registryFile, mainBuildDirectory.getParentFile(), "optional-grpc"); } } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java index 6a140481..03d1dd51 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesExtension.java @@ -18,7 +18,7 @@ public abstract class StrictLaneStagesExtension { * command executes this build's stages only when it starts in this build's directory from there * — its step's {@code working-directory} joined with its {@code -p}. The directory is read from * where the build is, so no build states it (review 2026-11-04 RR2-04-04: a {@code -p} value - * alone missed {@code working-directory: src/optional-platforms} with {@code ../gradlew}). + * alone missed {@code working-directory: src/platforms/optional-build} with {@code ../gradlew}). */ public abstract DirectoryProperty getWorkflowDirectory(); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java index e9e0f980..891cdf22 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesPlugin.java @@ -33,7 +33,8 @@ import org.gradle.api.execution.TaskExecutionGraph; * as a workflow runs it — a lane the command removes with {@code -x} is not covered, matched * the way Gradle matches it, abbreviations included ({@link TaskSelectors}); *

  • every declared stage is executed by a workflow. Not counted ({@code NOT_COUNTED}; review - * 2026-11-03 RR-06-04, 2026-11-04 RR2-04-04, RR5-02-02, 2026-11-05 RR6-04-01..06): a command + * 2026-11-03 RR-06-04, 2026-11-04 RR2-04-04, RR5-02-02, 2026-11-05 RR6-04-01..06, 2026-11-06 + * RR7-05-01, owner decision 2026-11-07 on the release flow): a command * after which Gradle runs no task ({@code --dry-run}, {@code -v}, {@code --help}, …) or that * Gradle rejects (a short-option bundle such as {@code -mx}), one for another build, and one * that does not gate for one of three reasons — its failure may not fail its step, it may not @@ -66,13 +67,17 @@ public final class StrictLaneStagesPlugin implements Plugin { + " script's last command, after set +e or a trap that exits 0, continue-on-error); one" + " that may not run (after ||, inside if/while/for/case or a function, after an exit 0," + " exec or set -n, under an if: other than always()/success()/!cancelled(), in a" - + " workflow that starts only on a request or a reusable one no counted job calls, in a" - + " job that needs a job that may be skipped); and one this check does not read although" + + " workflow that starts only on a request, or on changes only through a paths or" + + " paths-ignore filter, or a reusable one no counted job calls, in a" + + " job that needs a job that may be skipped, and for any stage but :releaseCheck in a" + + " workflow that starts only on a tag push or a release); and one this check does not" + + " read although" + " its failure" + " would fail the step (|| exit 1, inside { } or ( ), $( ), bash -c, gradlew as" + " another command's argument, after a cd it does not follow, a shell other than bash" + " or sh, a runner that may be Windows). Run the stage as ./gradlew on a line of its" - + " own, in a step and job that run on every push, pull request or schedule"; + + " own, in a step and job that run on every push, pull request or schedule, with no" + + " paths or paths-ignore filter (:releaseCheck may run on a tag push or a release)"; @Override public void apply(Project project) { @@ -228,7 +233,7 @@ public final class StrictLaneStagesPlugin implements Plugin { + ": gradlew " + String.join(" ", invocation.tasks()) + " — " - + invocation.whyNotExecuting(buildDirectory)))); + + invocation.whyNotExecuting(stage, buildDirectory)))); return lines.isEmpty() ? "" : "; commands that name it but do not count:\n " + String.join("\n ", lines); @@ -293,7 +298,7 @@ public final class StrictLaneStagesPlugin implements Plugin { /** * This build's directory from the repository root, which holds {@code .github/workflows}: {@code - * src} for the main build, {@code src/optional-platforms} for the optional one. + * src} for the main build, {@code src/platforms/optional-build} for the optional one. */ private static String buildDirectory(Project root, File workflowDirectory) { File repository = workflowDirectory.getAbsoluteFile().getParentFile().getParentFile(); diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java index 104671df..628cea88 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLanePlugin.java @@ -10,12 +10,26 @@ import org.gradle.api.NamedDomainObjectContainer; import org.gradle.api.Plugin; import org.gradle.api.Project; import org.gradle.api.plugins.JavaPluginExtension; +import org.gradle.api.provider.Provider; import org.gradle.api.tasks.SourceSet; import org.gradle.api.tasks.TaskProvider; import org.gradle.api.tasks.testing.Test; import org.gradle.testing.base.TestingExtension; public final class StrictTestLanePlugin implements Plugin { + /** + * The switch a performance lane's machine-dependent bounds used to sit behind, now always on. + * + *

    Each leaf declared it with its own default — {@code false} for the httpclient lane, {@code + * true} for the Mongo lane — and only the workflows set it. {@code ./gradlew :performanceCheck} + * typed by hand therefore passed with the httpclient heap bound compared to nothing (the + * 2026-11-05 desktop gate). The convention owns it now: every performance lane's test JVM gets + * {@code true}, so a test that still reads the switch asserts, and a build that sets it to + * anything else fails before the lane runs. Nothing in this repository reads it any more; the + * value is for tests written against the old switch, such as a derived service's. + */ + static final String PERFORMANCE_ASSERTIONS = "performance.assertions.enabled"; + @Override public void apply(Project project) { project.getPluginManager().withPlugin("java", ignored -> configure(project)); @@ -229,7 +243,8 @@ public final class StrictTestLanePlugin implements Plugin { // judge the lane again rather than reuse a result produced under the looser policy. Without // this a lane that skipped a test stayed green, up to date and from the build cache, after // rejectSkipped was switched on (review 2026-11-03 RR-06-02). - test.getInputs().property("strictLane.rejectSkipped", project.provider(lane::isRejectSkipped)); + test.getInputs() + .property("strictLane.rejectSkipped", project.provider(() -> rejectsSkipped(lane))); test.getInputs() .property("strictLane.requiredTests", project.provider(lane::getRequiredTests)); test.getInputs() @@ -243,6 +258,17 @@ public final class StrictTestLanePlugin implements Plugin { test.getOutputs().upToDateWhen(ignored -> false); test.getOutputs().doNotCacheIf(rerunReason, ignored -> true); } + boolean performance = lane.getCategory() == TestLaneCategory.PERFORMANCE; + if (performance) { + // Set before the lane's own JVM arguments and system properties — Gradle turns a -D in + // jvmArgs into a system property — so a lane that still declares the switch replaces this + // value and the check below sees the override, instead of the override disappearing silently. + test.systemProperty(PERFORMANCE_ASSERTIONS, "true"); + Provider requested = project.getProviders().gradleProperty(PERFORMANCE_ASSERTIONS); + String laneName = lane.getName(); + test.doFirst( + running -> requireAssertionsOn(laneName, ownerPath, requested.getOrNull(), (Test) running)); + } if (lane.getMaxHeapSize() != null && !lane.getMaxHeapSize().isBlank()) { test.setMaxHeapSize(lane.getMaxHeapSize()); } @@ -288,7 +314,7 @@ public final class StrictTestLanePlugin implements Plugin { + detail + " — a lane that runs nothing reports success for whatever it was meant to prove."); } - if (lane.isRejectSkipped() && tracker.skippedCount() > 0L) { + if (rejectsSkipped(lane) && tracker.skippedCount() > 0L) { throw new GradleException( "strict test lane '" + lane.getName() @@ -296,7 +322,10 @@ public final class StrictTestLanePlugin implements Plugin { + ownerPath + " forbids skipped tests but observed " + tracker.skippedCount() - + " skipped test(s)."); + + " skipped test(s)." + + (performance + ? " A performance lane always does: a skipped test is a bound nobody measured." + : "")); } if (!required.isEmpty()) { List absent = @@ -318,6 +347,55 @@ public final class StrictTestLanePlugin implements Plugin { } } + /** + * A performance lane rejects skipped tests whatever it declares: its tests are its bounds, and a + * skip is a bound the run reports as passed without comparing it to anything. + */ + private static boolean rejectsSkipped(StrictTestLaneSpec lane) { + return lane.isRejectSkipped() || lane.getCategory() == TestLaneCategory.PERFORMANCE; + } + + /** + * Fails a performance lane, before any test runs, when the build or the lane turns its bounds off. + * {@code true} from the build is accepted, so a command that still passes it keeps working. + */ + private static void requireAssertionsOn( + String laneName, String ownerPath, String requestedByBuild, Test test) { + if (requestedByBuild != null && !Boolean.parseBoolean(requestedByBuild.trim())) { + throw new GradleException( + "strict test lane '" + + laneName + + "' in " + + ownerPath + + " is a performance lane, and this build sets " + + PERFORMANCE_ASSERTIONS + + "=" + + requestedByBuild + + " (-P" + + PERFORMANCE_ASSERTIONS + + ", or -Dorg.gradle.project." + + PERFORMANCE_ASSERTIONS + + " in GRADLE_OPTS). A performance lane asserts its bounds in every run: one without" + + " them measures nothing it can fail on and still reports success. Remove the" + + " property or set it to true."); + } + Object effective = test.getSystemProperties().get(PERFORMANCE_ASSERTIONS); + if (effective == null || !Boolean.parseBoolean(String.valueOf(effective).trim())) { + throw new GradleException( + "strict test lane '" + + laneName + + "' in " + + ownerPath + + " is a performance lane, but its test JVM would get " + + PERFORMANCE_ASSERTIONS + + "=" + + effective + + " from this project's build (a lane systemProperty or jvmArgs, or a block that" + + " configures the task). The strict-lane convention sets it to true for every" + + " performance lane; delete the override."); + } + } + private static boolean startsARealServer(StrictTestLaneSpec lane) { return lane.getCategory() != TestLaneCategory.TEST && lane.getCategory() != TestLaneCategory.ARCHITECTURE; diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneSpec.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneSpec.java index f34537e8..197d1020 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneSpec.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneSpec.java @@ -137,6 +137,12 @@ public class StrictTestLaneSpec implements Named { category = TestLaneCategory.ARCHITECTURE; } + /** + * A lane whose tests are resource or latency bounds. Besides rerunning every time and taking the + * build-wide real-server slot, it rejects skipped tests and always runs with its bounds asserted: + * the convention sets {@code performance.assertions.enabled=true}, and a build or lane that sets + * it to anything else fails before a test runs. + */ public void performance() { category = TestLaneCategory.PERFORMANCE; } diff --git a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java index d02b7b13..365d2f31 100644 --- a/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java +++ b/src/build-logic/src/main/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocations.java @@ -2,6 +2,7 @@ package dev.caskeleton.buildlogic.strictlane; import java.util.ArrayDeque; import java.util.ArrayList; +import java.util.Collection; import java.util.Deque; import java.util.HashSet; import java.util.LinkedHashMap; @@ -44,7 +45,13 @@ import java.util.regex.Pattern; *

    When a workflow runs. A workflow counts when one of its triggers is part of the change * or release flow: {@code push}, {@code pull_request} or {@code pull_request_target} (with a {@code * types} list, only when it holds {@code opened}, {@code synchronize} or {@code reopened}), {@code - * merge_group}, {@code schedule}, {@code release}. One that starts only on other events — {@code + * merge_group}, {@code schedule}, {@code release} — and has no {@code paths} or {@code + * paths-ignore} filter: a change that touches none of the listed paths, or only ignored ones, does + * not start it (owner decision 2026-11-06, review RR7-05-01). A workflow whose only such triggers + * are the release flow — {@code release}, or a {@code push} with {@code tags} or {@code + * tags-ignore} and no {@code branches} or {@code branches-ignore}, which a branch push does not + * start — counts only for {@code :releaseCheck}, the tag-only stage (owner decision 2026-11-07). + * One that starts only on other events — {@code * workflow_dispatch}, {@code repository_dispatch}, {@code issue_comment}, a {@code labeled} pull * request, {@code workflow_run} and the rest — runs only when someone or something asks (review * 2026-11-04 RR2-04-04, RR6-04-06). A workflow that starts only on {@code workflow_call} counts @@ -98,6 +105,15 @@ public final class WorkflowGradleInvocations { /** The pull-request activity types that come with every new change. */ private static final Set PULL_REQUEST_CHANGE_TYPES = Set.of("opened", "synchronize", "reopened"); + /** The trigger filters that start a workflow only for changes to some files. */ + private static final List PATH_FILTERS = List.of("paths", "paths-ignore"); + /** The push filters that start it for tags; with no branch filter, a branch push does not. */ + private static final List TAG_FILTERS = List.of("tags", "tags-ignore"); + private static final List BRANCH_FILTERS = List.of("branches", "branches-ignore"); + private static final List FILTERS = + List.of("paths", "paths-ignore", "tags", "tags-ignore", "branches", "branches-ignore"); + /** The only stage a workflow of the release flow counts for: the tag-only one. */ + private static final String RELEASE_STAGE = ":releaseCheck"; private static final String REUSABLE_WORKFLOWS = "./.github/workflows/"; /** * Gradle 9.0's command-line options that take a value, by every name it accepts. Probed against @@ -171,6 +187,8 @@ public final class WorkflowGradleInvocations { * @param uncountedReason why the command gates nothing although it names tasks — it may not run, * its failure may not fail its step, this reader does not read it, or Gradle runs no task — * or {@code null} + * @param releaseFlowReason why the command gates only {@code :releaseCheck} — its workflow + * starts, of the triggers that need no request, only on the release flow — or {@code null} */ public record Invocation( String workingDirectory, @@ -178,12 +196,18 @@ public final class WorkflowGradleInvocations { List tasks, boolean dryRun, List excludedTasks, - String uncountedReason) { + String uncountedReason, + String releaseFlowReason) { public Invocation { tasks = List.copyOf(tasks); excludedTasks = List.copyOf(excludedTasks); } + private Invocation releaseFlowOnly(String reason) { + return new Invocation( + workingDirectory, projectDir, tasks, dryRun, excludedTasks, uncountedReason, reason); + } + /** * The directory of the build this command starts, from the repository root: the step's working * directory joined with {@code -p}. {@code .} is the repository root. @@ -201,11 +225,24 @@ public final class WorkflowGradleInvocations { * the repository root such as {@code src}. */ public boolean executes(String taskPath, String buildDirectory) { - return requests(taskPath) && whyNotExecuting(buildDirectory) == null; + return requests(taskPath) && whyNotExecuting(taskPath, buildDirectory) == null; } /** - * Why this command does not execute and gate on the tasks it names in the build in {@code + * Why this command does not execute and gate on the task at {@code taskPath} in the build in + * {@code buildDirectory}, or {@code null} when it does: a reason that holds for every task it + * names, or that its workflow is of the release flow and the task is not {@code :releaseCheck}. + */ + public String whyNotExecuting(String taskPath, String buildDirectory) { + String reason = whyNotExecuting(buildDirectory); + if (reason != null || releaseFlowReason == null) { + return reason; + } + return absolute(taskPath).equals(RELEASE_STAGE) ? null : releaseFlowReason; + } + + /** + * Why this command does not execute and gate on any task it names in the build in {@code * buildDirectory}, or {@code null} when it does: its uncounted reason, another build, or a dry * run. */ @@ -256,9 +293,49 @@ public final class WorkflowGradleInvocations { ShellScript.Options shell, String uncountedReason) {} - /** One workflow file: its name, its lines, its triggers with their {@code types}, its jobs. */ + /** One workflow file: its name, its lines, its triggers by event name, its jobs. */ private record Workflow( - String file, List lines, Map> triggers, Map jobs) {} + String file, List lines, Map triggers, Map jobs) {} + + /** + * One trigger's filters that decide whether it runs on every change. + * + * @param types its {@code types} list, or {@code null} when it has none + * @param pathFilters which of {@code paths} and {@code paths-ignore} it has + * @param tagsOnly whether it filters tags and no branches, so that only a tag push starts it + */ + private record Trigger(List types, List pathFilters, boolean tagsOnly) { + private static final Trigger UNFILTERED = new Trigger(null, List.of(), false); + + private static Trigger of(List types, Collection filters) { + return new Trigger( + types, + PATH_FILTERS.stream().filter(filters::contains).toList(), + TAG_FILTERS.stream().anyMatch(filters::contains) + && BRANCH_FILTERS.stream().noneMatch(filters::contains)); + } + } + + /** How a trigger takes part in the stages (owner decisions 2026-11-06 and 2026-11-07). */ + private enum Flow { + /** Starts on every change: counts for every stage. */ + CHANGE, + /** Starts on a release or a tag push: counts for {@code :releaseCheck} only. */ + RELEASE, + /** Starts on a change only when it touches some files: counts for no stage. */ + PATH_FILTERED, + /** Starts only when someone or something asks: counts for no stage. */ + REQUEST + } + + /** + * When a workflow starts, as the stages see it: on every change (both {@code null}), only on + * the release flow ({@code releaseFlow} says why it counts for {@code :releaseCheck} alone), or + * not without being asked ({@code notStarted} says why). + */ + private record Start(String notStarted, String releaseFlow) { + private static final Start EVERY_CHANGE = new Start(null, null); + } /** A job: its id, the line of its key, and the column of its own keys (-1 when it has none). */ private record Job(String id, int header, int keyIndent) {} @@ -289,10 +366,13 @@ public final class WorkflowGradleInvocations { workflowsByFile.forEach((file, text) -> workflows.put(file, parse(file, text))); Map> invocations = new LinkedHashMap<>(); for (Workflow workflow : workflows.values()) { - String notStarted = startReason(workflow, workflows, new HashSet<>()); + Start start = start(workflow, workflows, new HashSet<>()); List commands = new ArrayList<>(); - for (RunStep step : runSteps(workflow, notStarted)) { - commands.addAll(stepInvocations(step)); + for (RunStep step : runSteps(workflow, start.notStarted())) { + for (Invocation command : stepInvocations(step)) { + commands.add( + start.releaseFlow() == null ? command : command.releaseFlowOnly(start.releaseFlow())); + } } invocations.put(workflow.file(), List.copyOf(commands)); } @@ -476,12 +556,9 @@ public final class WorkflowGradleInvocations { // --------------------------------------------------------------------------------------------- // When the workflow runs - /** - * The workflow's triggers, each with its {@code types} list, or {@code null} when it has none; - * empty when no {@code on:} is written. - */ - private static Map> triggers(List lines) { - Map> triggers = new LinkedHashMap<>(); + /** The workflow's triggers with their filters; empty when no {@code on:} is written. */ + private static Map triggers(List lines) { + Map triggers = new LinkedHashMap<>(); for (int index = 0; index < lines.size(); index++) { Matcher on = TRIGGER_KEY.matcher(lines.get(index)); if (!on.matches()) { @@ -494,7 +571,7 @@ public final class WorkflowGradleInvocations { int colon = entry.indexOf(':'); triggers.put( stripScalarComment(colon < 0 ? entry : entry.substring(0, colon)), - colon < 0 ? null : flowTypes(entry.substring(colon + 1).trim())); + colon < 0 ? Trigger.UNFILTERED : flowTrigger(entry.substring(colon + 1).trim())); } } else if (!inline.isEmpty()) { String list = @@ -502,7 +579,7 @@ public final class WorkflowGradleInvocations { ? inline.substring(1, inline.length() - 1) : inline; for (String trigger : flowItems(list)) { - triggers.put(trigger, null); + triggers.put(trigger, Trigger.UNFILTERED); } } else { blockTriggers(lines, index, triggers); @@ -514,7 +591,7 @@ public final class WorkflowGradleInvocations { /** The triggers of a block {@code on:} at {@code onLine}: a mapping or a list. */ private static void blockTriggers( - List lines, int onLine, Map> triggers) { + List lines, int onLine, Map triggers) { int childIndent = childIndent(lines, onLine); for (int next = onLine + 1; next < lines.size(); next++) { String line = lines.get(next); @@ -532,61 +609,111 @@ public final class WorkflowGradleInvocations { boolean item = key.startsWith("-"); key = item ? key.substring(1).trim() : key; int colon = key.indexOf(':'); - List types = null; + Trigger trigger = Trigger.UNFILTERED; String inlineDetail = colon < 0 ? "" : key.substring(colon + 1).trim(); if (!item && inlineDetail.startsWith("{")) { - types = flowTypes(stripScalarComment(inlineDetail)); + trigger = flowTrigger(stripScalarComment(inlineDetail)); } else if (!item && colon >= 0) { int detailIndent = childIndent(lines, next); - int typesLine = - detailIndent > childIndent ? mappingKey(lines, next + 1, detailIndent, "types") : -1; - types = typesLine < 0 ? null : listValue(lines, typesLine); + if (detailIndent > childIndent) { + int typesLine = mappingKey(lines, next + 1, detailIndent, "types"); + List filters = new ArrayList<>(); + for (String filter : FILTERS) { + if (mappingKey(lines, next + 1, detailIndent, filter) >= 0) { + filters.add(filter); + } + } + trigger = Trigger.of(typesLine < 0 ? null : listValue(lines, typesLine), filters); + } } - triggers.put(stripScalarComment(colon < 0 ? key : key.substring(0, colon)), types); + triggers.put(stripScalarComment(colon < 0 ? key : key.substring(0, colon)), trigger); } } - /** The {@code types} of a flow-mapping trigger value such as {@code {types: [created]}}. */ - private static List flowTypes(String value) { - if (!value.startsWith("{") || !value.endsWith("}")) { - return null; - } - for (String entry : flowItems(value.substring(1, value.length() - 1))) { - int colon = entry.indexOf(':'); - if (colon >= 0 && stripScalarComment(entry.substring(0, colon)).equals("types")) { - String types = entry.substring(colon + 1).trim(); - return types.startsWith("[") && types.endsWith("]") - ? flowItems(types.substring(1, types.length() - 1)) - : List.of(stripScalarComment(types)); - } - } - return null; - } - /** - * Why the workflow does not run on every change, or {@code null} when it does or writes no {@code - * on:}. A reusable workflow runs through its callers ({@code visiting} guards a cycle). + * The filters of a flow-mapping trigger value such as {@code {types: [created]}} or {@code + * {paths: [docs/**]}}. */ - private static String startReason( - Workflow workflow, Map workflows, Set visiting) { - Map> triggers = workflow.triggers(); - if (triggers.isEmpty()) { - return null; + private static Trigger flowTrigger(String value) { + if (!value.startsWith("{") || !value.endsWith("}")) { + return Trigger.UNFILTERED; } - for (Map.Entry> trigger : triggers.entrySet()) { - if (runsOnChanges(trigger.getKey(), trigger.getValue())) { - return null; + List types = null; + List filters = new ArrayList<>(); + for (String entry : flowItems(value.substring(1, value.length() - 1))) { + int colon = entry.indexOf(':'); + if (colon < 0) { + continue; + } + String key = stripScalarComment(entry.substring(0, colon)); + String detail = entry.substring(colon + 1).trim(); + if (key.equals("types")) { + types = + detail.startsWith("[") && detail.endsWith("]") + ? flowItems(detail.substring(1, detail.length() - 1)) + : List.of(stripScalarComment(detail)); + } else if (FILTERS.contains(key)) { + filters.add(key); } } + return Trigger.of(types, filters); + } + + /** + * When the workflow starts, as the stages see it; on every change when it writes no {@code on:}. + * A reusable workflow runs through its callers ({@code visiting} guards a cycle). + */ + private static Start start( + Workflow workflow, Map workflows, Set visiting) { + Map triggers = workflow.triggers(); + if (triggers.isEmpty()) { + return Start.EVERY_CHANGE; + } + Map pathFiltered = new LinkedHashMap<>(); + Map releaseFlow = new LinkedHashMap<>(); + for (Map.Entry trigger : triggers.entrySet()) { + switch (flow(trigger.getKey(), trigger.getValue())) { + case CHANGE -> { + return Start.EVERY_CHANGE; + } + case PATH_FILTERED -> pathFiltered.put(trigger.getKey(), trigger.getValue()); + case RELEASE -> releaseFlow.put(trigger.getKey(), trigger.getValue()); + case REQUEST -> { + // counted only through a caller, below, when it is workflow_call + } + } + } + String release = + releaseFlow.isEmpty() + ? null + : "its workflow starts without a request or a path filter only on the release flow (" + + describe(releaseFlow) + + "), not on every push, pull request or schedule, so it counts only for " + + RELEASE_STAGE; String described = describe(triggers); if (!triggers.containsKey("workflow_call")) { - return "its workflow starts only on " - + described - + ", which happen only when someone or something asks, not on every push, pull request" - + " or schedule, so it may not run"; + if (release != null) { + return new Start(null, release); + } + if (!pathFiltered.isEmpty()) { + return new Start( + "its workflow starts on changes only through " + + describe(pathFiltered) + + ", which a change that touches none of the listed paths, or only ignored ones," + + " does not start, so it may not run", + null); + } + return new Start( + "its workflow starts only on " + + described + + ", which happen only when someone or something asks, not on every push, pull" + + " request or schedule, so it may not run", + null); } if (!visiting.add(workflow.file())) { - return "its workflow is called only through a cycle of workflow_call"; + return release != null + ? new Start(null, release) + : new Start("its workflow is called only through a cycle of workflow_call", null); } List callers = new ArrayList<>(); for (Workflow caller : workflows.values()) { @@ -600,38 +727,73 @@ public final class WorkflowGradleInvocations { reason = needsReason(caller, job); } if (reason == null) { - reason = startReason(caller, workflows, new HashSet<>(visiting)); - } - if (reason == null) { - return null; + Start callerStart = start(caller, workflows, new HashSet<>(visiting)); + if (callerStart.equals(Start.EVERY_CHANGE)) { + return Start.EVERY_CHANGE; + } + if (callerStart.notStarted() == null && release == null) { + release = + "its workflow is called by " + + caller.file() + + " job " + + job.id() + + ", and " + + callerStart.releaseFlow(); + } + reason = + callerStart.notStarted() == null + ? callerStart.releaseFlow() + : callerStart.notStarted(); } callers.add(caller.file() + " job " + job.id() + ": " + reason); } } - return "its workflow starts only on " - + described - + ", and no workflow that runs on every change calls it (" - + (callers.isEmpty() - ? "no workflow in this directory calls it" - : String.join("; ", callers)) - + "), so it may not run"; - } - - private static boolean runsOnChanges(String trigger, List types) { - if (!CHANGE_TRIGGERS.contains(trigger)) { - return false; + if (release != null) { + return new Start(null, release); } - return types == null - || !trigger.startsWith("pull_request") - || types.stream().anyMatch(PULL_REQUEST_CHANGE_TYPES::contains); + return new Start( + "its workflow starts only on " + + described + + ", and no workflow that runs on every change calls it (" + + (callers.isEmpty() + ? "no workflow in this directory calls it" + : String.join("; ", callers)) + + "), so it may not run", + null); } - private static String describe(Map> triggers) { + private static Flow flow(String name, Trigger trigger) { + if (!CHANGE_TRIGGERS.contains(name)) { + return Flow.REQUEST; + } + if (trigger.types() != null + && name.startsWith("pull_request") + && trigger.types().stream().noneMatch(PULL_REQUEST_CHANGE_TYPES::contains)) { + return Flow.REQUEST; + } + if (!trigger.pathFilters().isEmpty()) { + return Flow.PATH_FILTERED; + } + if (name.equals("release") || name.equals("push") && trigger.tagsOnly()) { + return Flow.RELEASE; + } + return Flow.CHANGE; + } + + private static String describe(Map triggers) { List described = new ArrayList<>(); triggers.forEach( - (trigger, types) -> - described.add( - types == null ? trigger : trigger + " (types: " + String.join(", ", types) + ")")); + (name, trigger) -> { + List filters = new ArrayList<>(); + if (trigger.types() != null) { + filters.add("types: " + String.join(", ", trigger.types())); + } + filters.addAll(trigger.pathFilters()); + if (trigger.tagsOnly()) { + filters.add("tags only"); + } + described.add(filters.isEmpty() ? name : name + " (" + String.join("; ", filters) + ")"); + }); return String.join(", ", described); } @@ -1220,7 +1382,7 @@ public final class WorkflowGradleInvocations { if (reason == null) { reason = rejected != null ? rejected : runsNoTask; } - return new Invocation(workingDirectory, projectDir, tasks, dryRun, excluded, reason); + return new Invocation(workingDirectory, projectDir, tasks, dryRun, excluded, reason, null); } private static boolean isFlag(String name) { diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java index 6a135273..a91b3602 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/ModuleRegistryTest.java @@ -38,7 +38,7 @@ class ModuleRegistryTest { read( registry( entry("app-bootstrap", ":app-bootstrap", "src/alpha"), - entry("sample-portfolio", ":sample-portfolio", "src/beta"), + entry("example-app", ":example-app", "src/beta"), entry("app-bootstrap", ":other", "src/alpha")))); assertTrue(failure.getMessage().contains("duplicate module id"), failure.getMessage()); } @@ -52,7 +52,7 @@ class ModuleRegistryTest { read( registry( entry("app-bootstrap", ":app-bootstrap", "src/alpha"), - entry("sample-portfolio", ":sample-portfolio", "src/beta"), + entry("example-app", ":example-app", "src/beta"), entry("aliased", ":aliased", "src/beta/../alpha")))); assertTrue(failure.getMessage().contains("duplicate or aliased"), failure.getMessage()); } @@ -66,10 +66,10 @@ class ModuleRegistryTest { "app-bootstrap", ":app-bootstrap", "src/alpha", - "[\"sample-portfolio\",\"unknown\",\"app-bootstrap\"]"), - entry("sample-portfolio", ":sample-portfolio", "src/beta"))); + "[\"example-app\",\"unknown\",\"app-bootstrap\"]"), + entry("example-app", ":example-app", "src/beta"))); assertEquals( - List.of("sample-portfolio", "unknown", "app-bootstrap"), + List.of("example-app", "unknown", "app-bootstrap"), parsed.byId("app-bootstrap").allowedDependencies()); } @@ -81,7 +81,7 @@ class ModuleRegistryTest { {"id":"app-bootstrap","gradle_path":":app-bootstrap","source_path":"src/alpha"}, %s]} """ - .formatted(entry("sample-portfolio", ":sample-portfolio", "src/beta")); + .formatted(entry("example-app", ":example-app", "src/beta")); IllegalStateException failure = assertThrows(IllegalStateException.class, () -> read(json)); assertTrue(failure.getMessage().contains("allowed_dependencies"), failure.getMessage()); } @@ -158,7 +158,7 @@ class ModuleRegistryTest { private String valid() { return registry( entry("app-bootstrap", ":app-bootstrap", "src/alpha"), - entry("sample-portfolio", ":sample-portfolio", "src/beta")); + entry("example-app", ":example-app", "src/beta")); } private static String entry(String id, String path, String source) { diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java index 6936c661..2543a1ac 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/CleanArchitectureResolvedClasspathFunctionalTest.java @@ -28,19 +28,19 @@ class CleanArchitectureResolvedClasspathFunctionalTest { } @Test - void samplePortfolioCompositionRootIsGovernedByTheSameDependencyPolicy( + void aSecondCompositionRootIsGovernedByTheSameDependencyPolicy( @TempDir Path temporaryRoot) throws IOException { Path repository = temporaryRoot.resolve("repository"); Path project = repository.resolve("src"); Files.createDirectories(project.resolve("config/architecture")); Files.createDirectories(project.resolve("a")); - Files.createDirectories(project.resolve("sample-portfolio")); + Files.createDirectories(project.resolve("example-app")); Files.writeString( project.resolve("settings.gradle"), """ rootProject.name = 'main' - include 'a', 'sample-portfolio' + include 'a', 'example-app' """, UTF_8); Files.writeString( @@ -48,7 +48,7 @@ class CleanArchitectureResolvedClasspathFunctionalTest { """ plugins { id 'ca.architecture' } subprojects { apply plugin: 'java-library' } - project(':sample-portfolio') { + project(':example-app') { dependencies { implementation project(':a') } } """, @@ -65,9 +65,9 @@ class CleanArchitectureResolvedClasspathFunctionalTest { "allowed_dependencies": [] }, { - "id": "sample-portfolio", - "gradle_path": ":sample-portfolio", - "source_path": "src/sample-portfolio", + "id": "example-app", + "gradle_path": ":example-app", + "source_path": "src/example-app", "allowed_dependencies": [] } ] @@ -78,7 +78,7 @@ class CleanArchitectureResolvedClasspathFunctionalTest { BuildResult result = runner(project, "verifyCleanArchitectureDependencies").buildAndFail(); assertThat(result.getOutput()) - .contains("Module ':sample-portfolio' has forbidden project dependencies [a]"); + .contains("Module ':example-app' has forbidden project dependencies [a]"); } @Test diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/VerifyNoIgnoredSourcePackagesFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/VerifyNoIgnoredSourcePackagesFunctionalTest.java index c81c00bd..3d974e64 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/VerifyNoIgnoredSourcePackagesFunctionalTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/architecture/VerifyNoIgnoredSourcePackagesFunctionalTest.java @@ -30,12 +30,12 @@ class VerifyNoIgnoredSourcePackagesFunctionalTest { } @Test - void sourceInAnIgnoredPackageOfTheSamplePortfolioFailsTheGate(@TempDir Path temporaryRoot) + void sourceInAnIgnoredPackageOfAnyLeafFailsTheGate(@TempDir Path temporaryRoot) throws IOException { // given - Path project = fixture(temporaryRoot, "sample-portfolio"); - source(project, "sample-portfolio/src/main/java/example/Ok.java"); - source(project, "sample-portfolio/src/main/java/example/build/Ignored.java"); + Path project = fixture(temporaryRoot, "example-app"); + source(project, "example-app/src/main/java/example/Ok.java"); + source(project, "example-app/src/main/java/example/build/Ignored.java"); // when BuildResult result = runner(project).buildAndFail(); diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java index d482e37a..63042580 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/config/EnvContractVerifierTest.java @@ -204,7 +204,7 @@ class EnvContractVerifierTest { fixture.registry(), Files.readString(fixture.registry()) + "- name: APP_LOG_JSON_ENABLED\n type: boolean\n default: true\n"); - Path compose = fixture.repositoryRoot().resolve("docker-compose.yml"); + Path compose = fixture.repositoryRoot().resolve("compose.yaml"); Files.writeString(compose, "services:\n app:\n environment:\n APP_LOG_JSON_ENABLED: \"true\"\n"); // when @@ -231,7 +231,7 @@ class EnvContractVerifierTest { void anOperatorFileKeyMissingFromTheRegistryFails(@TempDir Path temp) throws Exception { // given Fixture fixture = fixture(temp); - Path compose = fixture.repositoryRoot().resolve("docker-compose.yml"); + Path compose = fixture.repositoryRoot().resolve("compose.yaml"); Files.writeString(compose, "services:\n app:\n environment:\n APP_UNREGISTERED: x\n"); // when @@ -257,7 +257,7 @@ class EnvContractVerifierTest { void anOperatorFileKeyTheConfigurationReadsPasses(@TempDir Path temp) throws Exception { // given Fixture fixture = fixture(temp); - Path compose = fixture.repositoryRoot().resolve("docker-compose.yml"); + Path compose = fixture.repositoryRoot().resolve("compose.yaml"); Files.writeString(compose, "services:\n app:\n environment:\n APP_REQUIRED: x\n"); // when @@ -357,7 +357,7 @@ class EnvContractVerifierTest { fixture.registry(), Files.readString(fixture.registry()) + "- name: APP_GHOST_ENABLED\n property: app.ghost.enabled\n type: boolean\n"); - Path compose = fixture.repositoryRoot().resolve("docker-compose.yml"); + Path compose = fixture.repositoryRoot().resolve("compose.yaml"); Files.writeString( compose, "services:\n app:\n environment:\n APP_GHOST_ENABLED: \"true\"\n"); @@ -387,7 +387,7 @@ class EnvContractVerifierTest { Files.writeString( ghostClasses.resolve(ConfigurationMetadataClasspath.METADATA), "{\"properties\":[{\"name\":\"app.ghost.enabled\"}]}"); - Path compose = fixture.repositoryRoot().resolve("docker-compose.yml"); + Path compose = fixture.repositoryRoot().resolve("compose.yaml"); Files.writeString( compose, "services:\n app:\n environment:\n APP_GHOST_ENABLED: \"true\"\n"); diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java index 4c0a2a18..7a0b09ee 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictLaneStagesFunctionalTest.java @@ -698,6 +698,63 @@ class StrictLaneStagesFunctionalTest { .doesNotContain("stage :ci is executed by no workflow"); } + @Test + @DisplayName("태그 push로만 도는 workflow의 단계 명령은 releaseCheck에만 세고, 다른 단계는 실행되지 않은 것으로 본다") + void aReleaseFlowWorkflowCountsOnlyForTheReleaseStage() throws Exception { + // given + Files.writeString( + gradleRoot.resolve("build.gradle"), + """ + plugins { id 'ca.strict-lane-stages' } + tasks.register('ci') { dependsOn ':leaf:check' } + tasks.register('integrationCheck') { dependsOn ':leaf:integrationTestLaneCheck' } + tasks.register('releaseCheck') + strictLaneStages { + stage ':ci', ':integrationCheck', ':releaseCheck' + workflowDirectory = layout.projectDirectory.dir('../.github/workflows') + } + """); + leafLanes( + """ + lane('databaseLane') { integration(); tag = 'db'; description = 'Real database.' } + """); + workflow( + """ + on: pull_request + jobs: + gate: + runs-on: ubuntu-latest + steps: + - working-directory: src + run: ./gradlew :ci --stacktrace + """); + Files.writeString( + repository.resolve(".github/workflows/release.yml"), + """ + on: + push: + tags: ['v*'] + jobs: + release: + runs-on: ubuntu-latest + steps: + - working-directory: src + run: ./gradlew :releaseCheck + - working-directory: src + run: ./gradlew :integrationCheck --continue + """); + + // when + BuildResult result = runner(":verifyStrictLaneStages", "--dry-run").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("stage :integrationCheck is executed by no workflow") + .contains("release.yml: gradlew :integrationCheck") + .contains("counts only for :releaseCheck") + .doesNotContain("stage :releaseCheck is executed by no workflow"); + } + private void leafLanes(String lanes) throws Exception { Files.writeString( gradleRoot.resolve("leaf/build.gradle"), diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java index 5cda0950..208f2cde 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/StrictTestLaneConventionTest.java @@ -611,6 +611,147 @@ class StrictTestLaneConventionTest { assertThat(result.getOutput()).contains("rulesLane=false").contains("databaseLane=true"); } + @Test + void aPerformanceLaneFailsOnAnExceededBoundWhenTheBuildSetsNoAssertionsProperty() + throws Exception { + // given + buildFile(performanceLane("")); + writePerformanceTest( + "BoundTest.java", + """ + import org.junit.jupiter.api.Test; + class BoundTest { + @Test void staysInsideTheBound() { + long p99Millis = 900; + // The shape the httpclient lane had: the machine-dependent bound behind the switch. + if (Boolean.parseBoolean(System.getProperty("performance.assertions.enabled", "false")) + && p99Millis > 500) { + throw new AssertionError("p99 900ms above the 500ms bound"); + } + } + } + """); + + // when + BuildResult result = runner("performanceTestLaneCheck").buildAndFail(); + + // then + assertThat(result.getOutput()).contains("BoundTest > staysInsideTheBound() FAILED"); + } + + @Test + void aPerformanceLaneFailsBeforeTestingWhenTheBuildTurnsItsAssertionsOff() throws Exception { + // given + buildFile(performanceLane("")); + writePerformanceTest( + "MeasuredTest.java", + """ + import org.junit.jupiter.api.Test; + class MeasuredTest { + @Test void measured() { throw new AssertionError("the lane ran a test"); } + } + """); + + // when + BuildResult result = + runner("performanceTestLaneCheck", "-Pperformance.assertions.enabled=false") + .buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("this build sets performance.assertions.enabled=false") + .contains("set it to true") + .doesNotContain("MeasuredTest > measured() FAILED"); + } + + @Test + void aPerformanceLaneFailsWhenItsOwnDeclarationTurnsTheAssertionsOff() throws Exception { + // given + buildFile( + performanceLane( + """ + systemProperty 'performance.assertions.enabled', + providers.gradleProperty('performance.assertions.enabled').orElse('false').get() + """)); + writePerformanceTest( + "MeasuredTest.java", + """ + import org.junit.jupiter.api.Test; + class MeasuredTest { @Test void measured() {} } + """); + + // when + BuildResult result = runner("performanceTestLaneCheck").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("its test JVM would get performance.assertions.enabled=false") + .contains("delete the override"); + } + + @Test + void aPerformanceLaneFailsWhenItsJvmArgumentsTurnTheAssertionsOff() throws Exception { + // given + buildFile(performanceLane("jvmArgs '-Dperformance.assertions.enabled=false'")); + writePerformanceTest( + "MeasuredTest.java", + """ + import org.junit.jupiter.api.Test; + class MeasuredTest { @Test void measured() {} } + """); + + // when + BuildResult result = runner("performanceTestLaneCheck").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("its test JVM would get performance.assertions.enabled=false") + .contains("delete the override"); + } + + @Test + void aPerformanceLaneFailsWhenOneOfItsTestsIsSkipped() throws Exception { + // given + buildFile(performanceLane("")); + writePerformanceTest( + "PartlyMeasuredTest.java", + """ + import org.junit.jupiter.api.Disabled; + import org.junit.jupiter.api.Test; + class PartlyMeasuredTest { + @Test void measured() {} + @Test @Disabled("too slow on this machine") void quarantined() {} + } + """); + + // when + BuildResult result = runner("performanceTestLaneCheck").buildAndFail(); + + // then + assertThat(result.getOutput()) + .contains("forbids skipped tests") + .contains("a skipped test is a bound nobody measured"); + } + + @Test + void aPerformanceLaneAcceptsABuildThatTurnsItsAssertionsOnExplicitly() throws Exception { + // given + buildFile(performanceLane("")); + writePerformanceTest( + "MeasuredTest.java", + """ + import org.junit.jupiter.api.Test; + class MeasuredTest { @Test void measured() {} } + """); + + // when + BuildResult result = + runner("performanceTestLaneCheck", "-Pperformance.assertions.enabled=true").build(); + + // then + assertThat(result.task(":loadLane").getOutcome()).isEqualTo(TaskOutcome.SUCCESS); + } + private void buildFile(String laneBlock) throws Exception { Files.writeString( projectDir.resolve("build.gradle"), @@ -631,6 +772,32 @@ class StrictTestLaneConventionTest { Files.writeString(testSource.resolve(fileName), source); } + private void writePerformanceTest(String fileName, String source) throws Exception { + Path performanceSource = projectDir.resolve("src/performance/java"); + Files.createDirectories(performanceSource); + Files.writeString(performanceSource.resolve(fileName), source); + } + + private static String performanceLane(String extraDeclarations) { + return """ + sourceSets { performance } + dependencies { + performanceImplementation platform('org.junit:junit-bom:5.11.3') + performanceImplementation 'org.junit.jupiter:junit-jupiter' + performanceRuntimeOnly 'org.junit.platform:junit-platform-launcher' + } + strictTestLanes { + lane('loadLane') { + performance() + sourceSet = 'performance' + description = 'Measures a resource bound.' + %s + } + } + """ + .formatted(extraDeclarations); + } + private static String junitDependencies() { return """ dependencies { diff --git a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java index 8f1c7769..ab24e44b 100644 --- a/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java +++ b/src/build-logic/src/test/java/dev/caskeleton/buildlogic/strictlane/WorkflowGradleInvocationsTest.java @@ -134,7 +134,7 @@ class WorkflowGradleInvocationsTest { // given String workflow = """ - - run: ./gradlew integrationCheck sample-portfolio:check --tests '*Contract*' + - run: ./gradlew integrationCheck example-app:check --tests '*Contract*' """; // when @@ -144,7 +144,7 @@ class WorkflowGradleInvocationsTest { assertThat(invocations).singleElement().satisfies( invocation -> { assertThat(invocation.executes(":integrationCheck", ".")).isTrue(); - assertThat(invocation.executes(":sample-portfolio:check", ".")).isTrue(); + assertThat(invocation.executes(":example-app:check", ".")).isTrue(); assertThat(invocation.tasks()).doesNotContain("*Contract*"); }); } @@ -1218,8 +1218,8 @@ class WorkflowGradleInvocationsTest { } @Test - @DisplayName("push·pull_request·merge_group·schedule·release 중 하나로도 시작하는 workflow의 명령은 센다") - void aWorkflowThatAlsoStartsOnTheChangeOrReleaseFlowCounts() { + @DisplayName("push·pull_request·merge_group·schedule 중 하나로도 시작하는 workflow의 명령은 센다") + void aWorkflowThatAlsoStartsOnTheChangeFlowCounts() { // given List workflows = List.of( @@ -1252,16 +1252,6 @@ class WorkflowGradleInvocationsTest { run: ./gradlew :ci """, """ - on: - release: - types: [published] - jobs: - main: - steps: - - working-directory: src - run: ./gradlew :ci - """, - """ on: pull_request: types: [opened, synchronize, labeled] @@ -1279,10 +1269,167 @@ class WorkflowGradleInvocationsTest { // then assertThat(invocations) - .hasSize(5) + .hasSize(4) .allSatisfy(invocation -> assertThat(invocation.executes(":ci", "src")).isTrue()); } + @Test + @DisplayName("paths·paths-ignore 필터가 붙은 change trigger로만 시작하는 workflow의 명령은 세지 않는다") + void aWorkflowThatStartsOnChangesOnlyThroughAPathFilterGatesNothing() { + // given + List workflows = + List.of( + """ + on: + pull_request: + paths: ["docs/**"] + push: + branches: [main] + paths: + - "docs/**" + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :ci + """, + """ + on: {push: {paths-ignore: ["docs/**"]}, workflow_dispatch: {}} + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :ci + """, + """ + on: + pull_request: {types: [opened, synchronize], paths: ["src/**"]} + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :ci + """); + + // when + List invocations = + workflows.stream().flatMap(workflow -> WorkflowGradleInvocations.read(workflow).stream()) + .toList(); + + // then + assertThat(invocations) + .hasSize(3) + .allSatisfy(invocation -> assertThat(invocation.executes(":ci", "src")).isFalse()); + assertThat(invocations).extracting(Invocation::uncountedReason) + .satisfiesExactly( + reason -> assertThat(reason).contains("pull_request (paths)", "push (paths)"), + reason -> assertThat(reason).contains("push (paths-ignore)"), + reason -> + assertThat(reason).contains("pull_request (types: opened, synchronize; paths)")); + } + + @Test + @DisplayName("paths 필터가 붙은 trigger 옆에 필터 없는 change trigger가 있으면 그 workflow의 명령은 센다") + void aWorkflowWithAnUnfilteredChangeTriggerBesidesAPathFilterCounts() { + // given + String workflow = + """ + on: + pull_request: + paths: ["docs/**"] + schedule: + - cron: '0 3 * * *' + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :ci + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).singleElement().satisfies( + invocation -> assertThat(invocation.executes(":ci", "src")).isTrue()); + } + + @Test + @DisplayName("태그 push나 release로만 시작하는 workflow의 명령은 releaseCheck에만 센다") + void aWorkflowThatStartsOnlyOnTheReleaseFlowCountsOnlyForReleaseCheck() { + // given + List workflows = + List.of( + """ + on: + push: + tags: ['v*'] + jobs: + release: + steps: + - working-directory: src + run: ./gradlew :releaseCheck :integrationCheck + """, + """ + on: + release: + types: [published] + workflow_dispatch: + jobs: + release: + steps: + - working-directory: src + run: ./gradlew :releaseCheck :integrationCheck + """, + """ + on: {push: {tags-ignore: ['nightly-*']}} + jobs: + release: + steps: + - working-directory: src + run: ./gradlew :releaseCheck :integrationCheck + """); + + // when + List invocations = + workflows.stream().flatMap(workflow -> WorkflowGradleInvocations.read(workflow).stream()) + .toList(); + + // then + assertThat(invocations) + .hasSize(3) + .allSatisfy( + invocation -> { + assertThat(invocation.executes(":releaseCheck", "src")).isTrue(); + assertThat(invocation.executes(":integrationCheck", "src")).isFalse(); + }); + } + + @Test + @DisplayName("태그와 함께 브랜치도 받는 push로 시작하는 workflow의 명령은 모든 단계에 센다") + void aPushWithBranchesBesidesTagsCountsForEveryStage() { + // given + String workflow = + """ + on: + push: + branches: [main] + tags: ['v*'] + jobs: + main: + steps: + - working-directory: src + run: ./gradlew :integrationCheck + """; + + // when + List invocations = WorkflowGradleInvocations.read(workflow); + + // then + assertThat(invocations).singleElement().satisfies( + invocation -> assertThat(invocation.executes(":integrationCheck", "src")).isTrue()); + } + @Test @DisplayName("workflow_call로만 시작하는 재사용 workflow의 명령은 매 변경에 도는 호출 job이 있을 때만 센다") void aReusableWorkflowCountsOnlyThroughACallerThatRunsOnEveryChange() { diff --git a/src/build.gradle b/src/build.gradle index 06cc4633..8e15f199 100644 --- a/src/build.gradle +++ b/src/build.gradle @@ -1,6 +1,6 @@ plugins { - // Spring Boot stays on the root build script classpath because two leaves apply it by id - // (`app-bootstrap`, `sample-portfolio`) and a leaf resolves plugin classes from the root. + // Spring Boot stays on the root build script classpath because a leaf applies it by id + // (`app-bootstrap`) and a leaf resolves plugin classes from the root. // // Spotless, SpotBugs, Error Prone and Spring's dependency-management are NOT here any more. They // were declared `apply false` for a `configure(subprojects)` block that applied them to every @@ -52,9 +52,7 @@ tasks.register('resolveAndLockAll') { tasks.register('verifyDependencyLocks') { group = 'verification' description = 'Verifies strict dependency lock state for production CI subprojects.' - dependsOn subprojects.findAll { - it.childProjects.isEmpty() && it.path != ':sample-portfolio' - }.collect { "${it.path}:verifyDependencyLocks" } + dependsOn subprojects.findAll { it.childProjects.isEmpty() }.collect { "${it.path}:verifyDependencyLocks" } } // feature-developer-experience-contract D3 — the ordered local bootstrap lifecycle is @@ -69,9 +67,9 @@ tasks.register('verifyDependencyLocks') { // qualityCheck SpotBugs + FindSecBugs across every leaf (ca.quality-conventions) // ci the pull-request gate: leaf checks + architectureCheck + qualityCheck // mainCheck the main-branch stage: environment contract, full-boot qualification, -// sample web contract, public-path baseline, transport and messaging -// qualification lanes, each leaf's document-contract lanes, and the -// feature generator round trip (verifyFeatureScaffold) +// public-path baseline, transport and messaging qualification lanes, each +// leaf's document-contract lanes, and the feature generator round trip +// (verifyFeatureScaffold) // integrationCheck the declared strict integration lanes (several need a container runtime) // performanceCheck the declared strict performance lanes (load, shutdown, pool and resource // bounds; real servers and containers) @@ -82,9 +80,7 @@ tasks.register('verifyDependencyLocks') { // Task PATHS, not TaskProviders: a leaf's tasks are created by convention plugins after the root is // evaluated, and a path is resolved when the task graph is built. // --------------------------------------------------------------------------------------------- -List leafPaths = subprojects.findAll { - it.childProjects.isEmpty() && it.path != ':sample-portfolio' -}.collect { it.path }.toSorted() +List leafPaths = subprojects.findAll { it.childProjects.isEmpty() }.collect { it.path }.toSorted() tasks.register('qualityCheck') { group = 'verification' @@ -100,13 +96,11 @@ tasks.register('configContractCheck') { // A lane that needs an input this build was not given (the Redis topology coordinates, the protected // AWS sandbox authority) is explicit-only: the aggregate leaves it out and names it when it runs -// (review NEW-16). The sample's integration lanes are here although the sample is not a production -// leaf, because nothing else ran its strict PostgreSQL lanes (review NEW-13e). +// (review NEW-16). tasks.register('integrationCheck') { group = 'verification' - description = "Runs every production CI leaf's and the sample's integration-category test lanes. Several need a container runtime." + description = "Runs every production CI leaf's integration-category test lanes. Several need a container runtime." dependsOn leafPaths.collect { "${it}:integrationTestLaneCheck" } - dependsOn ':sample-portfolio:integrationTestLaneCheck' } // Performance lanes are not the pull request's or the main stage's: their bounds need a machine that @@ -145,13 +139,6 @@ tasks.register('testQualityCheck') { group = 'verification' description = 'Runs SpotBugs and FindSecBugs over every leaf\'s test source sets.' dependsOn leafPaths.collect { "${it}:testQualityCheck" } - dependsOn ':sample-portfolio:testQualityCheck' -} - -tasks.register('sampleWebContractCheck') { - group = 'verification' - description = 'Runs the real-server sample HTTP/OpenAPI contract source set without pulling every sample lane into CI.' - dependsOn ':sample-portfolio:webSystemTest' } // The feature generator's round trip (review 2026-11-01 개선 순서 4): scripts/new-feature.sh writes @@ -179,8 +166,7 @@ tasks.register('verifyMessagingContracts') { group = 'verification' description = 'Qualifies the application integration-event contract and the shared envelope schema.' dependsOn ':application-core:messagingApplicationContractQualificationTest', - ':shared-contract:messagingSharedSchemaQualificationTest', - ':sample-portfolio:messagingSampleContractQualificationTest' + ':shared-contract:messagingSharedSchemaQualificationTest' } tasks.register('ci') { @@ -197,10 +183,6 @@ tasks.register('mainCheck') { dependsOn leafPaths.collect { "${it}:mainCheck" } dependsOn tasks.named('configContractCheck') dependsOn tasks.named('qualificationCheck') - dependsOn tasks.named('sampleWebContractCheck') - // The standalone sample booted whole against real PostgreSQL. The sample is outside `leafPaths`, - // so systemTestCheck does not reach it, and no stage ran it (review 2026-11-01 08-01). - dependsOn ':sample-portfolio:systemTest' dependsOn tasks.named('verifyPublicPathSnapshot') dependsOn tasks.named('conditionalTransportQualification') dependsOn tasks.named('verifyMessagingContracts') @@ -214,8 +196,7 @@ tasks.register('mainCheck') { // one failed closed (review 2026-11-01 08-01). A new lane joins a stage through its category // aggregate; no workflow line names it. strictLaneStages { - stage ':ci', ':sample-portfolio:check', ':mainCheck', ':integrationCheck', ':performanceCheck', - ':releaseCheck' + stage ':ci', ':mainCheck', ':integrationCheck', ':performanceCheck', ':releaseCheck' workflowDirectory = layout.projectDirectory.dir('../.github/workflows') } diff --git a/src/composition/fileserver-platform/README.md b/src/composition/fileserver-platform/README.md index 3f4304e6..3affcc56 100644 --- a/src/composition/fileserver-platform/README.md +++ b/src/composition/fileserver-platform/README.md @@ -53,13 +53,13 @@ SSOT다. 설명은 `docs/fileserver/configuration.md`. ## 필요한 마운트 저장 루트(`/var/lib/backend/files`)는 쓰기 가능한 전용 volume이어야 한다. 기본 이미지와 기본 -`docker-compose.yml`은 이 모듈이 없으므로 volume도 갖지 않는다(리뷰 07-08). 이 모듈을 고른 서비스가 +`compose.yaml`은 이 모듈이 없으므로 volume도 갖지 않는다(리뷰 07-08). 이 모듈을 고른 서비스가 volume을 붙인다. | 실행 환경 | 붙이는 방법 | | --- | --- | -| Compose | `-f infra/fileserver/compose/docker-compose.fileserver.yml`을 더한다. `fileserver-data` named volume을 마운트하고, 앱보다 먼저 `fileserver-storage-init`이 앱 이미지 안에서 root로 한 번 돌아 volume 소유자를 이미지의 `app` 계정으로 바꾼다(0750). 새 volume, 재사용한 volume, bind mount 모두 같다 | -| Kubernetes | PersistentVolumeClaim을 같은 경로에 마운트하고 pod `securityContext.fsGroup`을 앱 그룹으로 둔다(`infra/fileserver/kubernetes/pvc-certification-job.yaml`) | +| Compose | `-f src/app-bootstrap/compose-lanes/fileserver.yaml`을 더한다(compose lane fixture다. 서비스는 같은 volume 정의를 자기 compose에 둔다). `fileserver-data` named volume을 마운트하고, 앱보다 먼저 `fileserver-storage-init`이 앱 이미지 안에서 root로 한 번 돌아 volume 소유자를 이미지의 `app` 계정으로 바꾼다(0750). 새 volume, 재사용한 volume, bind mount 모두 같다 | +| Kubernetes | PersistentVolumeClaim을 같은 경로에 마운트하고 pod `securityContext.fsGroup`을 앱 그룹으로 둔다(조건: `docs/fileserver/operations.md` 「운영 환경이 지켜야 할 조건」) | | `docker run` | `-v :/var/lib/backend/files`. volume 소유자를 이미지의 `app` 계정으로 먼저 맞춘다 | 소유자가 맞지 않으면 모든 쓰기가 거부되고, 저장소 probe가 기동 때 `storage root is not writable`로 diff --git a/src/composition/idempotency/README.md b/src/composition/idempotency/README.md index 547cac62..379b0459 100644 --- a/src/composition/idempotency/README.md +++ b/src/composition/idempotency/README.md @@ -25,13 +25,13 @@ composition:idempotency - 설정 바인딩은 `StrictSettingsBinder`다. 같은 prefix 아래 Redis 저장소가 자기 키(`key-version`, `command-timeout`)를 두므로 그 두 키만 빼고 엄격하게 본다. 수명 정책 키를 잘못 쓰면 기본값이 조용히 쓰이는 대신 기동이 실패한다. -- app-bootstrap과 sample-portfolio가 같은 한 줄을 쓴다. 예전의 sample 복사본 +- app-bootstrap이 이 한 줄을 쓴다. 예전의 샘플 모듈 복사본 (`SampleIdempotencyConfig`, 상한 검증 없이 `Binder`로 읽고 저장소를 하나로 가정)은 삭제했다. ## 추가할 한 줄 ```groovy -// app-bootstrap/build.gradle (sample-portfolio/build.gradle 도 같다) +// app-bootstrap/build.gradle runtimeOnly project(':composition:idempotency') // 요청 멱등성 executor ``` diff --git a/src/composition/idempotency/build.gradle b/src/composition/idempotency/build.gradle index 17053ed3..69730efb 100644 --- a/src/composition/idempotency/build.gradle +++ b/src/composition/idempotency/build.gradle @@ -10,7 +10,7 @@ plugins { // It builds the one IdempotencyExecutor over whichever IdempotencyStorePort the selected provider // contributes (Redis from cache-redis, PostgreSQL from persistence-jpa), and ships the lifecycle // settings (config/module-defaults/idempotency.yml). It names no provider module: the store is a -// port. app-bootstrap and sample-portfolio take the same line, so the executor is built one way. +// port. // // Not a composition root: it composes one capability and does not run. Same shape as // :composition:notification-platform. diff --git a/src/composition/service-runtime/README.md b/src/composition/service-runtime/README.md index d6ae10d0..0fcd9479 100644 --- a/src/composition/service-runtime/README.md +++ b/src/composition/service-runtime/README.md @@ -7,8 +7,8 @@ ## 제공하는 것 -capability와 무관하게 서비스 구성 루트 둘(app-bootstrap, sample-portfolio)이 모두 필요로 하는 -runtime 배선이다. 예전에는 app-bootstrap에 있었고 sample이 그 복사본을 들고 있었다. +capability와 무관하게 서비스 구성 루트가 필요로 하는 runtime 배선이다. 예전에는 app-bootstrap에 +있었고, 지금은 지운 샘플 모듈이 그 복사본을 들고 있었다. ``` composition:service-runtime @@ -43,16 +43,15 @@ composition:service-runtime `app.tracing.*` 값을 Boot 키로 옮기고 끄는 스위치만 둔다(아래 "tracing" 절). - 설정 키는 옮기지 않았다: `app.tracing.*`, `app.privacy.*`. 값은 각 구성 루트의 `application.yml`/`config/observability.yml`에 있다. - actuator chain은 servlet 웹 애플리케이션에서만 만들어지고, 구성 루트가 같은 이름 - `actuatorSecurityFilterChain`의 bean을 두면 물러난다. sample-portfolio는 공개 데모라 그렇게 - 모든 요청을 허용하는 자기 chain을 둔다. -- sample 복사본과의 차이 중 원본을 따른 것: 샘플 레이트는 `RuntimeEnvironment` 어휘(prod 0.01, + `actuatorSecurityFilterChain`의 bean을 두면 물러난다. +- 옛 샘플 복사본과의 차이 중 원본을 따른 것: 샘플 레이트는 `RuntimeEnvironment` 어휘(prod 0.01, 그 밖 1.0)이고 `staging=0.10` 분기는 없다. 설정 검증 실패는 `IllegalStateException`이 아니라 `StartupFailures.envValidation`이다. ## 추가할 한 줄 ```groovy -// app-bootstrap/build.gradle (sample-portfolio/build.gradle 도 같다) +// app-bootstrap/build.gradle runtimeOnly project(':composition:service-runtime') ``` diff --git a/src/composition/service-runtime/build.gradle b/src/composition/service-runtime/build.gradle index cacd1ff2..f6bdb43e 100644 --- a/src/composition/service-runtime/build.gradle +++ b/src/composition/service-runtime/build.gradle @@ -9,10 +9,6 @@ plugins { // // runtimeOnly project(':composition:service-runtime') // -// app-bootstrap and sample-portfolio take the same line. Before this module the sample carried a -// copy of each piece, and the copies had already drifted (a `staging` sampling rate the runtime -// vocabulary does not have, IllegalStateException where the original raised typed startup failures). -// // Not a composition root: it assembles shared runtime infrastructure and does not run. dependencies { implementation project(':application-core') diff --git a/src/config/architecture/modules.json b/src/config/architecture/modules.json index e26259d2..162d6d0f 100644 --- a/src/config/architecture/modules.json +++ b/src/config/architecture/modules.json @@ -383,34 +383,16 @@ "composition-durable-operation" ] }, - { - "id": "sample-portfolio", - "gradle_path": ":sample-portfolio", - "source_path": "src/sample-portfolio", - "allowed_dependencies": [ - "domain-core", - "application-core", - "adapter-outbound-persistence-jpa", - "adapter-outbound-identifier", - "adapter-outbound-objectstorage", - "adapter-outbound-support", - "adapter-inbound-web", - "shared-contract", - "application-objectstorage", - "composition-idempotency", - "composition-service-runtime" - ] - }, { "id": "messaging-core-api", "gradle_path": ":messaging:messaging-core-api", - "source_path": "src/messaging/messaging-core-api", + "source_path": "src/platforms/messaging/messaging-core-api", "allowed_dependencies": [] }, { "id": "messaging-schema-json", "gradle_path": ":messaging:messaging-schema-json", - "source_path": "src/messaging/messaging-schema-json", + "source_path": "src/platforms/messaging/messaging-schema-json", "allowed_dependencies": [ "messaging-core-api" ] @@ -418,7 +400,7 @@ { "id": "messaging-schema-avro", "gradle_path": ":messaging:messaging-schema-avro", - "source_path": "src/messaging/messaging-schema-avro", + "source_path": "src/platforms/messaging/messaging-schema-avro", "allowed_dependencies": [ "messaging-core-api" ] @@ -426,7 +408,7 @@ { "id": "messaging-schema-protobuf", "gradle_path": ":messaging:messaging-schema-protobuf", - "source_path": "src/messaging/messaging-schema-protobuf", + "source_path": "src/platforms/messaging/messaging-schema-protobuf", "allowed_dependencies": [ "messaging-core-api" ] @@ -434,7 +416,7 @@ { "id": "messaging-cloudevents", "gradle_path": ":messaging:messaging-cloudevents", - "source_path": "src/messaging/messaging-cloudevents", + "source_path": "src/platforms/messaging/messaging-cloudevents", "allowed_dependencies": [ "messaging-core-api" ] @@ -442,7 +424,7 @@ { "id": "messaging-policy", "gradle_path": ":messaging:messaging-policy", - "source_path": "src/messaging/messaging-policy", + "source_path": "src/platforms/messaging/messaging-policy", "allowed_dependencies": [ "messaging-core-api" ] @@ -450,7 +432,7 @@ { "id": "messaging-transport-spi", "gradle_path": ":messaging:messaging-transport-spi", - "source_path": "src/messaging/messaging-transport-spi", + "source_path": "src/platforms/messaging/messaging-transport-spi", "allowed_dependencies": [ "messaging-core-api", "messaging-policy" @@ -459,7 +441,7 @@ { "id": "messaging-runtime-core", "gradle_path": ":messaging:messaging-runtime-core", - "source_path": "src/messaging/messaging-runtime-core", + "source_path": "src/platforms/messaging/messaging-runtime-core", "allowed_dependencies": [ "messaging-core-api", "messaging-policy", @@ -471,7 +453,7 @@ { "id": "messaging-observability", "gradle_path": ":messaging:messaging-observability", - "source_path": "src/messaging/messaging-observability", + "source_path": "src/platforms/messaging/messaging-observability", "allowed_dependencies": [ "messaging-core-api" ] @@ -479,7 +461,7 @@ { "id": "messaging-security", "gradle_path": ":messaging:messaging-security", - "source_path": "src/messaging/messaging-security", + "source_path": "src/platforms/messaging/messaging-security", "allowed_dependencies": [ "messaging-core-api" ] @@ -487,7 +469,7 @@ { "id": "messaging-kafka", "gradle_path": ":messaging:messaging-kafka", - "source_path": "src/messaging/messaging-kafka", + "source_path": "src/platforms/messaging/messaging-kafka", "allowed_dependencies": [ "messaging-core-api", "messaging-policy", @@ -500,7 +482,7 @@ { "id": "messaging-reliability-api", "gradle_path": ":messaging:messaging-reliability-api", - "source_path": "src/messaging/messaging-reliability-api", + "source_path": "src/platforms/messaging/messaging-reliability-api", "allowed_dependencies": [ "messaging-core-api" ] @@ -508,7 +490,7 @@ { "id": "messaging-reliability", "gradle_path": ":messaging:messaging-reliability", - "source_path": "src/messaging/messaging-reliability", + "source_path": "src/platforms/messaging/messaging-reliability", "allowed_dependencies": [ "messaging-core-api", "messaging-reliability-api" @@ -517,7 +499,7 @@ { "id": "messaging-reliability-jdbc-postgresql", "gradle_path": ":messaging:messaging-reliability-jdbc-postgresql", - "source_path": "src/messaging/messaging-reliability-jdbc-postgresql", + "source_path": "src/platforms/messaging/messaging-reliability-jdbc-postgresql", "allowed_dependencies": [ "messaging-core-api", "messaging-reliability-api", @@ -528,7 +510,7 @@ { "id": "messaging-claim-check", "gradle_path": ":messaging:messaging-claim-check", - "source_path": "src/messaging/messaging-claim-check", + "source_path": "src/platforms/messaging/messaging-claim-check", "allowed_dependencies": [ "messaging-core-api", "messaging-reliability-api" @@ -537,7 +519,7 @@ { "id": "messaging-admin", "gradle_path": ":messaging:messaging-admin", - "source_path": "src/messaging/messaging-admin", + "source_path": "src/platforms/messaging/messaging-admin", "allowed_dependencies": [ "messaging-core-api", "messaging-observability" @@ -546,7 +528,7 @@ { "id": "messaging-spring-boot-starter", "gradle_path": ":messaging:messaging-spring-boot-starter", - "source_path": "src/messaging/messaging-spring-boot-starter", + "source_path": "src/platforms/messaging/messaging-spring-boot-starter", "allowed_dependencies": [ "messaging-admin", "messaging-core-api", @@ -564,7 +546,7 @@ { "id": "messaging-spring-boot-starter-kafka", "gradle_path": ":messaging:messaging-spring-boot-starter-kafka", - "source_path": "src/messaging/messaging-spring-boot-starter-kafka", + "source_path": "src/platforms/messaging/messaging-spring-boot-starter-kafka", "allowed_dependencies": [ "messaging-spring-boot-starter", "messaging-kafka", @@ -580,7 +562,7 @@ { "id": "messaging-testkit", "gradle_path": ":messaging:messaging-testkit", - "source_path": "src/messaging/messaging-testkit", + "source_path": "src/platforms/messaging/messaging-testkit", "allowed_dependencies": [ "messaging-core-api", "messaging-policy", @@ -590,21 +572,21 @@ { "id": "grpc-contract", "gradle_path": ":grpc:grpc-contract", - "source_path": "src/grpc/grpc-contract", + "source_path": "src/platforms/grpc/grpc-contract", "allowed_dependencies": [], "build": "optional-grpc" }, { "id": "grpc-core-api", "gradle_path": ":grpc:grpc-core-api", - "source_path": "src/grpc/grpc-core-api", + "source_path": "src/platforms/grpc/grpc-core-api", "allowed_dependencies": [], "build": "optional-grpc" }, { "id": "grpc-observability", "gradle_path": ":grpc:grpc-observability", - "source_path": "src/grpc/grpc-observability", + "source_path": "src/platforms/grpc/grpc-observability", "allowed_dependencies": [ "grpc-core-api" ], @@ -613,7 +595,7 @@ { "id": "grpc-operation-ledger-jpa", "gradle_path": ":grpc:grpc-operation-ledger-jpa", - "source_path": "src/grpc/grpc-operation-ledger-jpa", + "source_path": "src/platforms/grpc/grpc-operation-ledger-jpa", "allowed_dependencies": [ "grpc-core-api" ], @@ -622,7 +604,7 @@ { "id": "grpc-runtime", "gradle_path": ":grpc:grpc-runtime", - "source_path": "src/grpc/grpc-runtime", + "source_path": "src/platforms/grpc/grpc-runtime", "allowed_dependencies": [ "grpc-core-api" ], @@ -631,7 +613,7 @@ { "id": "grpc-spring-boot-starter", "gradle_path": ":grpc:grpc-spring-boot-starter", - "source_path": "src/grpc/grpc-spring-boot-starter", + "source_path": "src/platforms/grpc/grpc-spring-boot-starter", "allowed_dependencies": [ "grpc-core-api", "grpc-runtime", @@ -642,7 +624,7 @@ { "id": "grpc-testkit", "gradle_path": ":grpc:grpc-testkit", - "source_path": "src/grpc/grpc-testkit", + "source_path": "src/platforms/grpc/grpc-testkit", "allowed_dependencies": [ "grpc-core-api", "grpc-runtime", @@ -654,7 +636,7 @@ { "id": "grpc-advanced", "gradle_path": ":grpc-advanced:grpc-advanced", - "source_path": "src/grpc-advanced/grpc-advanced", + "source_path": "src/platforms/grpc-advanced/grpc-advanced", "allowed_dependencies": [ "grpc-core-api", "grpc-runtime" @@ -664,7 +646,7 @@ { "id": "grpc-advanced-compat", "gradle_path": ":grpc-advanced:grpc-advanced-compat", - "source_path": "src/grpc-advanced/grpc-advanced-compat", + "source_path": "src/platforms/grpc-advanced/grpc-advanced-compat", "allowed_dependencies": [ "grpc-core-api", "grpc-runtime" diff --git a/src/config/spotbugs/exclude-test.xml b/src/config/spotbugs/exclude-test.xml index 0e823942..cd9764ff 100644 --- a/src/config/spotbugs/exclude-test.xml +++ b/src/config/spotbugs/exclude-test.xml @@ -143,15 +143,6 @@ - - - - - - - diff --git a/src/config/spotbugs/exclude.xml b/src/config/spotbugs/exclude.xml index d1a4707a..23795b3b 100644 --- a/src/config/spotbugs/exclude.xml +++ b/src/config/spotbugs/exclude.xml @@ -20,9 +20,9 @@ and the actuator chain authenticate a stateless JWT bearer token (no session cookies, no ambient credential a browser would attach), so CSRF protection has nothing to protect. FindSecBugs flags it for classic cookie-session web apps; it is a false positive here. - Named classes, not `~.*SecurityConfig`: that pattern also matched the sample's HTTP Basic - chain, for which this reason is false — a browser re-sends Basic credentials on its own — - and would have hidden a copied Basic chain's CSRF exposure (review 2026-11-03 RR-07-05). --> + Named classes, not `~.*SecurityConfig`: that pattern would also match an HTTP Basic chain, + for which this reason is false — a browser re-sends Basic credentials on its own — and would + hide a Basic chain's CSRF exposure (review 2026-11-03 RR-07-05). --> @@ -31,24 +31,6 @@ - - - - - - - - - - - -