Skip to content

Commit 9a4fe3a

Browse files
Merge pull request #230 from refactorfirst/render-source-hierarchy
New Features - Class, package, and cycle reports now display nested package hierarchies with clearer relationship details. - Package reports include package relationships and source-directory links when available. - Graph links open in a new tab when available. - Maven users can generate JSON reports with the jsonReport goal. Bug Fixes - Anonymous Kotlin classes are associated with their enclosing class’s package; packageless anonymous classes no longer create package relationships. - Synthetic and anonymous classes that only appear as graph endpoints, and their connected edges, are omitted from visualizations. - Package matching handles anonymous and nested classes more accurately. - Documentation - Updated guidance for graph reports, anonymous classes, and JSON report generation.
2 parents d693d64 + 2e990d2 commit 9a4fe3a

27 files changed

Lines changed: 7381 additions & 1314 deletions

‎.refactorfirst/refactor-first.json‎

Lines changed: 4137 additions & 709 deletions
Large diffs are not rendered by default.

‎AGENTS.md‎

Lines changed: 103 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,8 +14,104 @@
1414
- Central DTO: `CodebaseGraphDTO` (JGraphT graphs + disharmony lists + metrics)
1515
- CLI entry point: `org.hjug.refactorfirst.Main` → `ReportCommand`
1616
- Fat jar location: `cli/target/cli-<version>.jar`
17-
- **Anonymous/synthetic classes are first-class graph members.** Java `Outer$N`/`Outer$` (anonymous/synthetic inner classes) and the Kotlin literal `"<anonymous>"` FQN are **not** sieved out by `GraphDependencyCollector`; they genuinely participate in cycles and can harbour antipatterns, so they are vertices in the class graph and rendered with `$` as the enclosing-class separator. `GraphDependencyCollector` keeps only the `from == to` self-edge guard, plus a degenerate-package guard so a packageless `"<anonymous>"` source never creates an `""` package-graph vertex. **Sink-only** anonymous/synthetic vertices (those with no outgoing edges) are suppressed only at render time in `HtmlReport.isSinkAnonymousOrSyntheticVertex` to keep the Class/Cycle Map DOT graph readable; active ones still render.
18-
- **Anonymous DOT node ids are source-file derived.** OpenRewrite attributes a Kotlin anonymous object / function-literal type with {@code "<anonymous>"} as the trailing simple-name segment of its FQN: standalone ({@code "<anonymous>"}) or, in real graphs (e.g. FXGL), prefixed by the enclosing class/package ({@code "dev.DeveloperWASDControl.<anonymous>"}). {@code HtmlReport.isAnonymousFqn(vertex)} detects a vertex when its trailing segment starts with {@code <}. {@code HtmlReport.renderSafeNodeId(vertex, codebaseGraphDTO)} then derives the enclosing owner from the vertex's mapped source-file path in {@code CodebaseGraphDTO.classToSourceFilePathMapping} (file base name without extension, e.g. {@code DeveloperWASDControl.kt} -> {@code DeveloperWASDControl}). The DOT node id renders as {@code DeveloperWASDControl_anonymous} and the human-readable label as {@code DeveloperWASDControl\$anonymous} ({@code $} escaped as {@code \$} for DOT). When no source path is mapped (or DTO is null) it degrades to the reversible {@code lt_}/{@code _gt} {@code <}/{@code >} encoding. The renderer is responsible for DOT/HTML-safe encoding of the literal {@code "<anonymous>"} FQN ({@code <}/{@code >} are illegal in Graphviz node ids; {@code <}/{@code >} escaping in HTML table labels).
17+
- **Anonymous/synthetic classes are first-class graph members.** Java `Outer$N`/`Outer$` (anonymous/synthetic inner classes) and the Kotlin literal `"<anonymous>"` FQN are **not** sieved out by `GraphDependencyCollector`; they genuinely participate in cycles and can harbour antipatterns, so they are vertices in the class graph and rendered with `$` as the enclosing-class separator. `GraphDependencyCollector` keeps only the `from == to` self-edge guard, plus a degenerate-package guard so an anonymous source never creates an `""` package-graph vertex: the package of a Kotlin anonymous FQN derives from its **enclosing class** (`dev.Owner.<anonymous>` → `dev`, and a packageless `Owner`/bare `"<anonymous>"` → no package edge), never a pseudo-package named after the owner — this keeps the package graph's names aligned with the class hierarchy's package derivation so the break-up lists in the Class and Package graphs match. **Sink-only** anonymous/synthetic vertices (those with no outgoing edges) are suppressed at hierarchy-build time in `HierarchyBuilder` (via the same `HtmlReport.isSinkAnonymousOrSyntheticVertex` static) to keep the Class/Cycle Map DOT graph readable; active ones still render, and edges touching a suppressed vertex are dropped with it.
18+
- **Anonymous DOT node ids are source-file derived.** OpenRewrite attributes a Kotlin anonymous object / function-literal type with {@code "<anonymous>"} as the trailing simple-name segment of its FQN: standalone ({@code "<anonymous>"}) or, in real graphs (e.g. FXGL), prefixed by the enclosing class/package ({@code "dev.DeveloperWASDControl.<anonymous>"}). {@code HtmlReport.isAnonymousFqn(vertex)} detects a vertex when its trailing segment starts with {@code <}. `HierarchyBuilder` resolves the id and label once, into the {@code ClassNodeDTO} (calling {@code HtmlReport.renderSafeNodeId(vertex, classGraph, codebaseGraphDTO)} / {@code anonymousOwnerLabel} / {@code getClassName}), deriving the enclosing owner from the vertex's mapped source-file path in {@code CodebaseGraphDTO.classToSourceFilePathMapping} (file base name without extension, e.g. {@code DeveloperWASDControl.kt} -> {@code DeveloperWASDControl}). The DOT node id renders as {@code DeveloperWASDControl_anonymous} and the human-readable label as {@code DeveloperWASDControl$anonymous}; labels are carried unescaped in the DTO and DOT-quoted at emission (the JS-template-literal wrapper additionally escapes {@code $} for the inline HTML report). When no source path is mapped (or DTO is null) it degrades to the reversible {@code lt_}/{@code _gt} {@code <}/{@code >} encoding. Note the render path (the 3-arg `renderSafeNodeId`) emits no hash discriminator, so same-named source files in different packages can collide — a pre-existing wart; the 2-arg overload's hash discriminator is not used for graphs.
19+
20+
## Nested graph hierarchy (HierarchyDTO + DOT synthesis)
21+
22+
Every generated graph (Class Map, Cycle Map, Package Map) renders as a nested
23+
package/class hierarchy. The pipeline is single-sourced:
24+
25+
`VertexInfo` graphs → `HierarchyBuilder` → `HierarchyDTO` → DOT emission.
26+
27+
- **`refactor-first.json` carries the hierarchy, not raw DOT** (0.11.0 breaking
28+
change): `classMap.dot`, `packageMap.dot` and
29+
`classCycles.largestCycle.dot` are gone, replaced by `.hierarchy` objects
30+
(`packages` tree + `edges` referencing pre-resolved node ids). Counts and
31+
gates (`dotThreshold`, `dotThresholdExceeded`, `hasEdges`) keep their names.
32+
There is no schema version and no legacy `.dot` fallback — reports published
33+
with older versions lose their graphs on hierarchy-only viewers until
34+
regenerated.
35+
- **`HierarchyBuilder`** (report module) builds the three hierarchies:
36+
`buildClassHierarchy` (endpoints of every class edge), `buildCycleHierarchy`
37+
(a cycle's members, ids still resolved against the FULL class graph), and
38+
`buildPackageHierarchy` (the package-map hierarchy **data**: relationship
39+
participants and break-up packages join the tree with their node ids,
40+
source paths, and `renderAsNode` leaf flags — rendering is the DOT
41+
builders' job, and `buildPackageDot` draws every participating package as
42+
a flat `shape=ellipse` node, never as rectangles under ancestor clusters).
43+
Nested `$`/Kotlin `<anonymous>` classes resolve to the owning package;
44+
packageless classes land in the synthetic `(default package)` bucket.
45+
Roots/children/classes/edges are sorted for determinism and single-child
46+
ancestor chains collapse into their deepest package (branching ancestors
47+
and content keep their boxes).
48+
- **Ids/labels are resolved once, into the DTO** (`ClassNodeDTO.id`/`label`,
49+
`PackageNodeDTO.id`/`nodeId`) and carried unescaped; renderers escape at
50+
emission. Class ids reuse the `HtmlReport.renderSafeNodeId` rules, package
51+
node ids are `package_<sha24>` (`renderSafePackageNodeId`), cluster ids are
52+
`cluster_<sha24>` (`HierarchyBuilder.clusterId`).
53+
- **`NestedDotBuilder`** emits the nested DOT in two modes.
54+
*Class/cycle maps* (`buildNestedDot(hierarchy, repoUrl, includeHyperlinks)`):
55+
packages as labelled `subgraph cluster_*` blocks (clusters BEFORE edges — in
56+
DOT a node belongs to the cluster where it is first defined), classes as
57+
`shape=ellipse` nodes. Removal colors: classes/edges keep
58+
`color=red style=filled`; flagged clusters fill pink. Every cluster
59+
declares an explicit fill — pink when flagged, `fillcolor=white` otherwise
60+
— because vizdom propagates a styled cluster's fill to its nested cluster
61+
rects; the explicit white keeps child packages of a pink cluster on their
62+
normal fill.
63+
*Package map* (`buildPackageDot(hierarchy)`): the flat relationship graph,
64+
matching the main-branch package map — every package that participates in
65+
at least one relationship (or was selected for removal to break cycles)
66+
renders once as a `shape=ellipse` node carrying its name, and the edges
67+
carry only the relationship weights. Break-up packages fill red
68+
(`color=red style=filled`), removal relationships render red, and the
69+
package map renders through **vizdom** like the class and cycle maps (no
70+
separate engine). Every graph's nodes are **hyperlinked**: class nodes link
71+
to their source files and package nodes to their source directories via
72+
`URL="<repoUrl><path>" target="_blank"` (http(s)-gated — payloads are
73+
untrusted on the page/viewer). vizdom honors node `URL` but drops
74+
`target`, so every render site restores it with a post-render
75+
`svg.replace(/<a href=/g, '<a target="_blank" href=')` (global — a graph
76+
hyperlinks many nodes). The full hierarchy
77+
— package tree, break-up flags, source directories (`path`), and edges
78+
— stays in `refactor-first.json` for LLM consumption; only the
79+
relationship information renders.
80+
`buildRawClassGraphDot`/`buildRawClassCycleDot`/`buildRawPackageGraphDot`
81+
in `HtmlReport` keep their signatures and delegate here, so the classic
82+
inline HTML report renders the graphs too.
83+
- **Render engine**: every graph — class, cycle, and package maps — renders
84+
through vizdom (`@vizdom/vizdom-ts-web@0.1.19`). The package map's flat DOT
85+
(ellipse nodes + edges) parses under the same vizdom path as the nested
86+
class/cycle DOT: the classic report's `printHead` prefetches the module and
87+
`generateDotImage` renders each container; the viewer and the report page
88+
mirror this. vizdom silently ignores `compound`/`ltail`/`lhead`, which is
89+
fine — the flat package map no longer uses them.
90+
- **The Class and Package maps
91+
flag identical break-up lists by construction**: every `packagesToRemove`
92+
member is seeded into both hierarchies (even when its classes/edges do not
93+
render) and flagged packages survive pruning and single-child collapse. The
94+
Cycle Map stays cycle-scoped: it flags only the break-up packages inside the
95+
displayed cycle.
96+
- **Three synthesis implementations must stay byte-identical** (their goldens
97+
mirror each other): Java `NestedDotBuilder` (`NestedDotBuilderTest`), the
98+
inline copy in `report/src/main/resources/viewer/index.html` (self-contained
99+
standalone viewer; pinned by `ViewerScriptTest`), and the report page's
100+
`lib/hierarchy-dot.js` (refactorfirst-page repo, pinned by
101+
`tests/unit/hierarchy-dot.test.js`) — each in both the class/cycle mode
102+
(`buildNestedDot`/`hierarchyToDot`) and the package mode
103+
(`buildPackageDot`/`packageHierarchyToDot`). The page copies add an
104+
`edgeFontColor` option: vizdom bakes label `fontcolor` into fill-only
105+
glyph paths at parse time, so the dark palette re-synthesizes with
106+
`fontcolor = "#9fb0c0"` on edges. Node and cluster labels sit on vizdom's
107+
white shapes and stay default-colored in both palettes. graphlib-dot
108+
creates a **node for every named subgraph** (one per package in the class
109+
map, labelled with the package name), so packages would appear as noise in
110+
the sigma/3D popups: all popup graph builders (2D `renderGraph`/`buildGraphologyGraph`
111+
and 3D `createForceGraph`, in the viewer, the classic report's popup scripts,
112+
and the page) identify subgraph nodes structurally with
113+
`graphlibGraph.children(node).length > 0` and drop them and any edge touching
114+
them, while keeping every class node, including ids such as `cluster_Helper`.
19115

20116
## Java 25 analysis (JEP 238 multi-release jar)
21117

@@ -131,6 +227,11 @@ is for build failures, not for "Kotlin is absent".
131227
Generate reports directly:
132228
`mvn org.hjug.refactorfirst.plugin:refactor-first-maven-plugin:0.9.0:htmlReport`
133229

230+
Generate the JSON report data (writes `.refactorfirst/refactor-first.json`
231+
at the project root; the dogfooded copy in this repo is regenerated with this
232+
goal on the current `0.11.0-SNAPSHOT`):
233+
`mvn org.hjug.refactorfirst.plugin:refactor-first-maven-plugin:0.11.0-SNAPSHOT:jsonReport`
234+
134235
Configuration options (most important):
135236
- `showDetails`: Shows God Class metrics in table (default: false)
136237
- `backEdgeAnalysisCount`: 0 = analyze all back edges (default: 50)

‎codebase-graph-builder/src/main/java/org/hjug/graphbuilder/GraphDependencyCollector.java‎

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -132,11 +132,24 @@ public DefaultWeightedEdge addPackageDependency(String fromClassFqn, String toCl
132132
}
133133

134134
protected String getPackageFromFqn(String fqn) {
135-
if (!fqn.contains(".")) {
135+
String name = fqn;
136+
int lastIndex = name.lastIndexOf('.');
137+
// A trailing "<anonymous>"-style segment names a Kotlin anonymous class, not a package
138+
// member: derive the package from the enclosing class so an anonymous class never
139+
// manufactures a package named after its owner (dev.Owner.<anonymous> -> "dev", and
140+
// Owner.<anonymous> -> "" like the bare packageless literal). This keeps the package
141+
// graph's package names aligned with the class hierarchy's package derivation, so the
142+
// break-up packages flagged in the Class and Package graphs match.
143+
if (lastIndex >= 0 && name.substring(lastIndex + 1).startsWith("<")) {
144+
name = name.substring(0, lastIndex);
145+
if (!name.contains(".")) {
146+
return "";
147+
}
148+
lastIndex = name.lastIndexOf('.');
149+
} else if (lastIndex < 0) {
136150
return "";
137151
}
138-
int lastIndex = fqn.lastIndexOf(".");
139-
return fqn.substring(0, lastIndex);
152+
return name.substring(0, lastIndex);
140153
}
141154

142155
/**

‎codebase-graph-builder/src/test/java/org/hjug/graphbuilder/GraphDependencyCollectorTest.java‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -157,6 +157,66 @@ void addPackageDependency_kotlinAnonymousSource_doesNotPollutePackageGraph() {
157157
assertTrue(pkgGraph.edgeSet().isEmpty());
158158
}
159159

160+
/**
161+
* A prefixed Kotlin anonymous FQN (e.g. {@code dev.DeveloperWASDControl.<anonymous>}) must not
162+
* manufacture a package named after its enclosing class: the package edge derives from the
163+
* enclosing class's package, so the Class and Package graphs agree on what the packages are
164+
* and the break-up lists rendered from them match.
165+
*/
166+
@DisplayName("addPackageDependency derives the enclosing class's package for a prefixed Kotlin <anonymous> source")
167+
@Test
168+
void addPackageDependency_prefixedKotlinAnonymousSource_derivesEnclosingClassPackage() {
169+
Graph<VertexInfo, DefaultWeightedEdge> classGraph = newClassGraph();
170+
Graph<VertexInfo, DefaultWeightedEdge> pkgGraph = newClassGraph();
171+
GraphDependencyCollector collector = new GraphDependencyCollector(classGraph, pkgGraph);
172+
173+
DefaultWeightedEdge edge = collector.addPackageDependency(
174+
"dev.DeveloperWASDControl.<anonymous>", "com.almasb.fxgl.app.GameApplication");
175+
176+
assertNotNull(edge, "the anonymous class's dependency must create the real package edge");
177+
assertEquals("dev", pkgGraph.getEdgeSource(edge).getName());
178+
assertEquals("com.almasb.fxgl.app", pkgGraph.getEdgeTarget(edge).getName());
179+
Set<String> packageNames =
180+
pkgGraph.vertexSet().stream().map(VertexInfo::getName).collect(java.util.stream.Collectors.toSet());
181+
assertEquals(
182+
Set.of("dev", "com.almasb.fxgl.app"),
183+
packageNames,
184+
"no pseudo-package named after the enclosing class may exist");
185+
}
186+
187+
/** Same rule for the target side: an anonymous target derives from its enclosing class's package. */
188+
@DisplayName("addPackageDependency derives the enclosing class's package for a prefixed Kotlin <anonymous> target")
189+
@Test
190+
void addPackageDependency_prefixedKotlinAnonymousTarget_derivesEnclosingClassPackage() {
191+
Graph<VertexInfo, DefaultWeightedEdge> classGraph = newClassGraph();
192+
Graph<VertexInfo, DefaultWeightedEdge> pkgGraph = newClassGraph();
193+
GraphDependencyCollector collector = new GraphDependencyCollector(classGraph, pkgGraph);
194+
195+
DefaultWeightedEdge edge = collector.addPackageDependency(
196+
"com.almasb.fxgl.app.GameApplication", "dev.DeveloperWASDControl.<anonymous>");
197+
198+
assertNotNull(edge);
199+
assertEquals("com.almasb.fxgl.app", pkgGraph.getEdgeSource(edge).getName());
200+
assertEquals("dev", pkgGraph.getEdgeTarget(edge).getName());
201+
assertFalse(
202+
pkgGraph.vertexSet().stream().anyMatch(v -> v.getName().equals("dev.DeveloperWASDControl")),
203+
"no pseudo-package named after the enclosing class may exist");
204+
}
205+
206+
/** An anonymous class whose enclosing class has no package is a no-op, like the bare literal. */
207+
@DisplayName("addPackageDependency with a packageless enclosing class is a no-op")
208+
@Test
209+
void addPackageDependency_packagelessEnclosingAnonymous_isNoOp() {
210+
Graph<VertexInfo, DefaultWeightedEdge> classGraph = newClassGraph();
211+
Graph<VertexInfo, DefaultWeightedEdge> pkgGraph = newClassGraph();
212+
GraphDependencyCollector collector = new GraphDependencyCollector(classGraph, pkgGraph);
213+
214+
DefaultWeightedEdge edge = collector.addPackageDependency("DeveloperWASDControl.<anonymous>", "com.bar.Other");
215+
216+
assertNull(edge, "an anonymous class in a packageless enclosing class has no package edge");
217+
assertTrue(pkgGraph.vertexSet().isEmpty(), "no package vertex may be created");
218+
}
219+
160220
/** Verifies that explicit registration retains anonymous and synthetic class vertices. */
161221
@DisplayName("registerClassVertex registers Java anonymous and Kotlin <anonymous> FQNs")
162222
@Test

0 commit comments

Comments
 (0)