Files
clean-architecture-backend-…/build-logic/src/main/java/dev/caskeleton/buildlogic/architecture/ArchitecturePlugin.java
T
DongHyeonka 6a792b8144 refactor(layout)!: 옮긴 경로를 부르는 곳을 모두 새 배치에 맞춘다
문제: 앞 커밋이 Gradle 루트를 저장소 루트로 옮기고 계층 폴더를 묶었다.
빌드 스크립트·build-logic·시험·workflow·스크립트·문서가 아직 옛 배치
(Gradle 루트 = src/)를 가정해 빌드가 되지 않는다.

고른 방법:
- Gradle 경로와 registry id는 그대로 둔다(:app-bootstrap, :application-core,
  :composition:*). registry의 source_path만 새 폴더를 가리킨다. 폴더에 맞춘
  이름(:domain:core, :application:core)은 프로젝트 이름 core가 둘이 되어
  boot jar의 BOOT-INF/lib와 기본 capability가 겹치고, 파생 서비스의 모든
  project(':…') 줄을 바꾸게 한다.
- registry는 gradle/modules.json, 시험 이미지 목록은
  gradle/container-images.properties: 버전 카탈로그 옆, 빌드가 고정하는 것.
  config/는 코드 검사 도구 설정만 둔다.
- build-logic: settings·architecture 플러그인의 저장소 루트를 Gradle 루트로
  (getParentFile 제거). config contract의 파일 트리는 src/만 훑는다(루트를
  훑으면 docs·.claude/worktrees까지 줍는다).
- 빌드 스크립트: rootProject.projectDir.parentFile → rootProject.projectDir,
  rootProject.file('../…') → rootProject.file('…'), 옛 src 기준 include에
  src/를 붙인다. notification API surface의 application-notification 소스
  루트를 새 폴더로(놓치면 272개 타입이 surface에서 말없이 빠진다).
- 시험: 옛 src 기준 모듈 목록과 ../ 개수를 고친다. 없는 폴더를 말없이
  건너뛰던 목록(MessagingAuthority, NotificationPayloadAtRest 등)을 새
  폴더로, FileserverDocumentationCoverageTest는 Gradle 경로 → 폴더를
  registry로 찾는다. Docker 계약은 WORKDIR /build, 새 jar 경로.
- Docker: 빌드 context를 저장소 루트로, .dockerignore는 허용 목록으로 다시
  써서 전에 context였던 것만 들어가게 한다. compose의 build.context는 .,
  env_file은 ./.env.
- workflow: working-directory: src 기본값과 그것을 되돌리던 줄을 지운다.
- scripts: verify.sh, ci/*, bootstrap-local, new-feature,
  verify-feature-scaffold, mongo 검증, hooks, check-repo-layout 허용 목록.
  check-docs의 경로 검사는 build-logic/·gradle/로 시작하는 경로도 본다.
- 문서: AGENTS.md 지도, README 구조 표, leaf AGENTS.md의 cd src, gates·
  operate·결정 색인, src/bootstrap/AGENTS.md를 조립 계층 family 규칙으로
  다시 쓴다. 기록 문서(docs/design·history·reviews, 지난 upgrade 안내,
  capability-status 제거 표)는 머리 블록만 고친다. 파생 서비스용 안내
  docs/upgrade/2026-11-relayout.md를 더한다.

위험: bootRun working dir가 저장소 루트가 되어 .env와 상대 경로 설정이
루트 기준이다. 루트 .env는 compose 보간에도 읽힌다(upgrade 안내 5절).
파생 서비스는 태그 pre-relayout-2026-11까지 받은 뒤 이 묶음을 받는다.

검증: desktop에서 캐시 없이 scripts/verify.sh docs·pr·main·release,
compose smoke 18 lane, 빠른 시작(scripts/verify.sh app). 결과는 PR 본문.
구조 리뷰(arch-reviewer) 지적 5건을 반영했다.

BREAKING CHANGE: Gradle은 저장소 루트에서 돈다(cd src 없음). registry는
gradle/modules.json, 이미지 빌드 context는 저장소 루트다. 옛 경로 → 새 경로
표는 docs/upgrade/2026-11-relayout.md.
Refs: design-docs repo-structure/01-backend-layout.md 6.1절 가-2·가-3
2026-11-11 22:15:42 +09:00

340 lines
16 KiB
Java

package dev.caskeleton.buildlogic.architecture;
import dev.caskeleton.buildlogic.ModuleRegistry;
import java.io.File;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import org.gradle.api.Plugin;
import org.gradle.api.Project;
import org.gradle.api.artifacts.Configuration;
import org.gradle.api.artifacts.ExternalModuleDependency;
import org.gradle.api.artifacts.ProjectDependency;
import org.gradle.api.artifacts.result.ResolvedComponentResult;
import org.gradle.api.provider.Provider;
import org.gradle.api.tasks.SourceSet;
import org.gradle.api.tasks.SourceSetContainer;
public final class ArchitecturePlugin implements Plugin<Project> {
private static final List<String> PRODUCTION_DECLARATIONS =
List.of("api", "implementation", "compileOnly", "runtimeOnly");
private static final List<String> APPLICATION_CLASSPATHS =
List.of(
"compileClasspath", "runtimeClasspath", "testCompileClasspath", "testRuntimeClasspath");
@Override
public void apply(Project project) {
Project root = project.getRootProject();
// The Gradle root is the repository root: it owns the registry, and every source_path in the
// registry is relative to it.
File repositoryRoot = root.getProjectDir();
File registryFile = new File(repositoryRoot, "gradle/modules.json");
ModuleRegistry registry = ModuleRegistry.read(registryFile, repositoryRoot);
List<ModuleRegistry.Module> modules = registry.modulesForBuild("main");
List<String> registryViolations = registryViolations(registry, modules);
var clean =
project
.getTasks()
.register(
"verifyCleanArchitectureDependencies",
VerifyCleanArchitectureDependenciesTask.class,
task -> {
task.setGroup("verification");
task.setDescription("Verifies Clean Architecture project dependency direction.");
task.getRegistryFile().fileValue(registryFile);
task.getRegistryViolations().set(registryViolations);
task.getUnregisteredBuildScripts()
.set(registry.unregisteredBuildScripts(root.getProjectDir()));
});
var purity =
project
.getTasks()
.register(
"verifyApplicationCoreDependencyPurity",
task -> {
task.setGroup("verification");
task.setDescription(
"Verifies domain-core, shared-contract and every application-* module have only"
+ " project production dependencies and no framework on their classpaths.");
});
var ignoredSources =
project
.getTasks()
.register(
"verifyNoIgnoredSourcePackages",
VerifyNoIgnoredSourcePackagesTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Fails when a Java source file lives in a package that Git ignores or would"
+ " ignore.");
task.getBuildRoot().set(root.getLayout().getProjectDirectory());
});
project
.getGradle()
.projectsEvaluated(
ignored -> {
Set<String> declaredModules = new HashSet<>();
root.getSubprojects().stream()
.filter(sub -> sub.getChildProjects().isEmpty())
.forEach(sub -> declaredModules.add(sub.getPath().replaceFirst("^:", "")));
// One task per module, registered in the project that owns the configurations. The
// root task used to walk every other project and resolve its `compileClasspath`,
// which asks Gradle for state another project holds the lock on — with
// `org.gradle.parallel=true` that is a hard failure, and it is why the flag was
// turned off instead of the verification moved.
List<String> moduleTaskPaths = new ArrayList<>();
for (ModuleRegistry.Module module : modules) {
Project owner = root.project(module.gradlePath());
Set<String> allowed = new HashSet<>();
for (String dependencyId : module.allowedDependencies()) {
ModuleRegistry.Module dependency = registry.byId(dependencyId);
if (dependency != null) {
allowed.add(dependency.gradlePath().replaceFirst("^:", ""));
}
}
Set<String> declaredEdges = declaredProjectEdges(owner);
Set<String> declaredLibraries =
declaredLibraryEdges(owner, registry.libraryGroups());
Provider<ResolvedComponentResult> compileClasspathRoot =
owner
.getConfigurations()
.getByName("compileClasspath")
.getIncoming()
.getResolutionResult()
.getRootComponent();
String moduleName = module.gradlePath().replaceFirst("^:", "");
owner
.getTasks()
.register(
"verifyModuleDependencyDirection",
VerifyModuleDependencyDirectionTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Verifies this module's declared and compile-visible project edges"
+ " against the architecture registry.");
task.getModuleName().set(moduleName);
task.getAllowedDependencies().set(allowed);
task.getDeclaredProjectEdges().set(declaredEdges);
task.getLibraryGroups().set(registry.libraryGroups());
task.getAllowedLibraries().set(module.allowedLibraries());
task.getDeclaredLibraryEdges().set(declaredLibraries);
task.getCompileClasspathRoot().set(compileClasspathRoot);
});
moduleTaskPaths.add(module.gradlePath() + ":verifyModuleDependencyDirection");
}
clean.configure(
task -> {
task.getDeclaredModules().set(declaredModules);
task.getGovernedModules()
.set(
modules.stream()
.map(module -> module.gradlePath().replaceFirst("^:", ""))
.toList());
task.dependsOn(moduleTaskPaths);
});
// Same ownership rule as the direction check: the task that resolves a pure
// module's classpaths lives in that module. domain-core and shared-contract are pure
// too (HS1): without them a framework dependency added there passed the build and
// was caught only if some class happened to import it.
List<String> purityTaskPaths = new ArrayList<>();
for (ModuleRegistry.Module module : modules) {
if (!isPure(module.id())) {
continue;
}
Project application = root.project(module.gradlePath());
Map<String, List<String>> production = new LinkedHashMap<>();
for (String name : PRODUCTION_DECLARATIONS) {
Configuration configuration = application.getConfigurations().findByName(name);
if (configuration != null) {
production.put(name, productionDeclarations(configuration));
}
}
Map<String, Provider<ResolvedComponentResult>> classpathRoots =
new LinkedHashMap<>();
for (String name : APPLICATION_CLASSPATHS) {
classpathRoots.put(
name,
application
.getConfigurations()
.getByName(name)
.getIncoming()
.getResolutionResult()
.getRootComponent());
}
String applicationPath = module.gradlePath();
application
.getTasks()
.register(
"verifyModuleDependencyPurity",
VerifyApplicationCoreDependencyPurityTask.class,
task -> {
task.setGroup("verification");
task.setDescription(
"Verifies this application module declares only project production"
+ " dependencies and carries no diagnostic framework.");
task.getModulePath().set(applicationPath);
task.getProductionDeclarations().set(production);
classpathRoots.forEach(
(name, rootComponent) ->
task.getResolvedClasspathRoots().put(name, rootComponent));
});
purityTaskPaths.add(module.gradlePath() + ":verifyModuleDependencyPurity");
}
purity.configure(task -> task.dependsOn(purityTaskPaths));
// Every source set of every project — testFixtures, integrationTest, systemTest and
// the sample included — because a file Git drops is lost whichever lane owns it.
// Directories under a build directory are generated and never committed.
List<File> sourceRoots = new ArrayList<>();
for (Project sub : root.getSubprojects()) {
SourceSetContainer sourceSets =
sub.getExtensions().findByType(SourceSetContainer.class);
if (sourceSets == null) {
continue;
}
Path buildDirectory = sub.getLayout().getBuildDirectory().get().getAsFile().toPath();
for (SourceSet sourceSet : sourceSets) {
for (File sourceRoot : sourceSet.getJava().getSrcDirs()) {
if (!sourceRoot.toPath().startsWith(buildDirectory)) {
sourceRoots.add(sourceRoot);
}
}
}
}
ignoredSources.configure(task -> task.getSourceRoots().from(sourceRoots));
});
project
.getTasks()
.register(
"architectureCheck",
task -> {
task.setGroup("verification");
task.setDescription("Runs the build's architecture invariants.");
task.dependsOn(clean, purity, ignoredSources);
});
}
private static boolean isPure(String moduleId) {
return moduleId.startsWith("application-")
|| moduleId.equals("domain-core")
|| moduleId.equals("shared-contract");
}
/**
* This module's declared {@code project(...)} edges, read while the owning project is configured.
*
* <p>Read here rather than in the task action: a {@link Configuration} cannot be stored in the
* configuration cache, and every declaration this reads is final by {@code projectsEvaluated}.
*/
private static Set<String> declaredProjectEdges(Project owner) {
Set<String> edges = new TreeSet<>();
for (String name : PRODUCTION_DECLARATIONS) {
Configuration configuration = owner.getConfigurations().findByName(name);
if (configuration == null) {
continue;
}
configuration
.getDependencies()
.withType(ProjectDependency.class)
.forEach(dependency -> edges.add(dependency.getPath().replaceFirst("^:", "")));
}
return edges;
}
/**
* This module's declared dependencies on an owned library ({@code group:artifact}, the group under
* one of the registry's {@code library_groups}), read the same way and from the same production
* configurations as the project edges, {@code runtimeOnly} included.
*/
private static Set<String> declaredLibraryEdges(Project owner, List<String> libraryGroups) {
Set<String> edges = new TreeSet<>();
if (libraryGroups.isEmpty()) {
return edges;
}
for (String name : PRODUCTION_DECLARATIONS) {
Configuration configuration = owner.getConfigurations().findByName(name);
if (configuration == null) {
continue;
}
configuration
.getDependencies()
.withType(ExternalModuleDependency.class)
.forEach(
dependency -> {
if (ModuleRegistry.isOwnedGroup(libraryGroups, dependency.getGroup())) {
edges.add(dependency.getGroup() + ":" + dependency.getName());
}
});
}
return edges;
}
/**
* One production configuration's declarations, tagged by kind.
*
* <p>The tag, not a filter, is what is captured: deciding which kind is a violation is the purity
* task's rule, and moving it here would put the rule in the collector.
*/
private static List<String> productionDeclarations(Configuration configuration) {
List<String> declarations = new ArrayList<>();
configuration
.getDependencies()
.forEach(
dependency -> {
if (dependency instanceof ProjectDependency projectDependency) {
declarations.add(
VerifyApplicationCoreDependencyPurityTask.PROJECT_DECLARATION
+ ":"
+ projectDependency.getPath());
} else {
String group = dependency.getGroup() == null ? "<no-group>" : dependency.getGroup();
declarations.add("module:" + group + ":" + dependency.getName());
}
});
return List.copyOf(declarations);
}
private static List<String> registryViolations(
ModuleRegistry registry, List<ModuleRegistry.Module> modules) {
List<String> violations = new ArrayList<>();
for (ModuleRegistry.Module module : modules) {
// The layers stay free of the owner's libraries by the registry itself, not only because the
// purity check happens to refuse every non-project declaration in them.
if (isPure(module.id()) && !module.allowedLibraries().isEmpty()) {
violations.add(
"'"
+ module.id()
+ "' is a layer module (domain-core, shared-contract, application-*) and may allow no"
+ " library, but allows "
+ module.allowedLibraries());
}
for (String dependencyId : module.allowedDependencies()) {
if (dependencyId.equals(module.id())) {
violations.add("'" + module.id() + "' declares itself as an allowed dependency");
continue;
}
ModuleRegistry.Module dependency = registry.byId(dependencyId);
if (dependency == null) {
violations.add(
"'" + module.id() + "' allows unknown dependency id '" + dependencyId + "'");
} else if (!dependency.buildName().equals(module.buildName())) {
violations.add(
"'" + module.id() + "' allows cross-build dependency id '" + dependencyId + "'");
}
}
}
return List.copyOf(violations);
}
}