diff --git a/PLAN.md b/PLAN.md index db75d9af..87d5e9a2 100644 --- a/PLAN.md +++ b/PLAN.md @@ -8576,7 +8576,8 @@ asks for anchors. outbound rule on PetClinic classifies the repository interfaces by their supertype; it cannot tell a read from a write off `member`. Closing this is a resolution rule of its own (a `derived` edge to the external - ancestor, naming the member), not done. + ancestor, naming the member): done since, as the follow-up bullet "M24a, + Java, ancestor-attributed calls" below records; the five writes are edges. - **M24a, TypeScript** (2026-11-28, `m24/a-typescript`). The fixture names 14 of 18, the self-hosted model 29 641 of 47 493; nothing merges and nothing splits. @@ -8772,6 +8773,57 @@ asks for anchors. convention. - A concepts rule does not tell a read from a write: an adapter found this way has no member. +- **M24a, Java, ancestor-attributed calls** (2026-11-29, + `feat/java-ancestor-attribution`; the follow-up the Java bullet above left + open). The Python rule (`ancestor-attributed`), in the Java extractor: + `AncestorCallLookup`, a sibling of `UnboundCallLookup`. + - Traced drop path: a call inherited from a library type has a NULL + declaring type; `targetOf` gives it `UNKNOWN_TYPE_ID`, the member is not + whitelisted, and `emitTypeLevelCall` drops it on that id, counted in + `droppedUnidentifiedTargets`. Not `targetOf` itself. + - The rule fires only on such a call, so no edge that existed changes. It + writes an `invocation` (a `reference` outside every invocable) of the one + library ancestor's erased stub, the type the corpus WROTE (`JpaRepository`, + though `CrudRepository` declares `save`), naming the method, `derived`. + Conditions: the receiver is a written corpus type (field, parameter, local + not `var`), `this`, `super` (from the superclass: the class's own override + is no evidence against it), or the implicit `this` of an unqualified call + (every enclosing class); no corpus type of the closure declares the name; + exactly one library type there could answer (a JDK type only for a name + it has, `Object` never). Two: dropped, counted `ambiguous-ancestor`. + - Two conditions the brief did not name, each found by measuring, each + pinned by a test that keeps the call dropped. A corpus type of the closure + with a Lombok annotation: on apache/fineract 2 319 generated getters were + charged to Spring's `Persistable`. A static on-demand import, or a single + static import of the name, for an unqualified call: Mockito's `mock(…)` + arrives exactly as an inherited call does. + - The stderr summary gains `ancestor-attributed` and `ambiguous-ancestor`. + - Measured: PetClinic 891 → 896 edges, the five writes now edges to the + `JpaRepository` stub naming `save` / `saveAndFlush`, the ten reads + byte-identical, the model diff exactly the five lines; 13 with its tests, + 0 ambiguous. An outbound rule on `org.springframework.data.jpa.repository` + with `save*` → `write` files five `database` `write` rows where it found + none. BroadleafCommerce: 383 sites, 12 ambiguous; fineract: 313, 1 103; + in both, only additions. Samples read on both showed no false attribution. + - The fixture moved by one edge: `super.post(document)` in `LedgerAdapter` + (189 → 190, members named 21 of 62). The counts that move are restated + with the reason; explain's Java goldens moved (fake client) for + `LedgerAdapter.post`, its type and its module, the only units with a new + fact. The same holds for a real model: a unit with such a call gets a new + prompt line, so its fingerprint changes and its stored insight is re-asked. + - Not covered: reads the corpus redeclares (already edges), an interface + with two library parents (ambiguous), a receiver whose type is not written + (`var`, a call's result, an inferred lambda parameter), method references. + - Follow-up (lead's review). A type whose declaration is corpus source (an + anonymous class, a local class, an enum constant body) is walked as corpus + whatever its id, never a candidate. Measured first: pass 3's ids already + mapped an anonymous class to its declared id, so the outcome did not change + on any corpus; the tests now hold even when the id is the undeclared + `Outer.1` form (jMock's `new Expectations() {{ oneOf(x); }}` under + `TestCase`: ambiguous). `Iface.super.m()` was missed: Spoon writes the + interface as the super access's target, with no type; it now starts there. + PetClinic, BroadleafCommerce and fineract models are byte-identical to the + first version's. - **Known on this machine, older than the phase:** the website build stops on Hugo (`unknown output format "llms" for kind "home"`), and `scale.test.ts` can time out at its 5 s under a loaded full run; it passes diff --git a/docs/boundaries.md b/docs/boundaries.md index 3b098045..40bc469a 100644 --- a/docs/boundaries.md +++ b/docs/boundaries.md @@ -233,9 +233,15 @@ of an explain TYPE record (`TypeBlock.concept`, the closed vocabulary `outbound.concepts` rule names is one row, after every edge row, by type: `stub`, `member`, `effect`, `edge` and `provenance` null, `missing` `no edge`, `from` the type, `anchor` the type's own (a type without one gets no row). It - is filed whether or not an edge row exists for it: a Spring Data interface's - inherited `save` leaves no edge (§25.7, M24a Java), which is the case this - answers. + is filed whether or not an edge row exists for it. It was built for a Spring + Data interface whose inherited `save` left no edge (§25.7, M24a Java). Since + the Java ancestor rule (§25.7, its follow-up bullet) that `save` IS an edge: a + `derived` invocation of the `JpaRepository` stub naming `save`, which an + `outbound.modules` rule on `org.springframework.data.jpa.repository` with an + `effects` rule `save*` → `write` files as a write (five rows on PetClinic). + The concepts row still answers what no edge says: the reads the interface + redeclares are calls into the code, and a repository nothing calls has no + edge at all. - **The CLI's reader is M16c's.** Only when the file holds a concepts rule, the CLI opens `.insights.db` beside the first model (`--insights FILE` on `analyze`, `walk` and `explain` names another): `existsSync` first, an ordinary diff --git a/extractors/java/README.md b/extractors/java/README.md index d7d58f38..f985bbf7 100644 --- a/extractors/java/README.md +++ b/extractors/java/README.md @@ -136,6 +136,8 @@ RESOLUTION SUMMARY resolution rate : 87.5% entities : 642 (stubs: 118) edges : 2104 (self-edges dropped: 12) + ancestor-attributed : 5 (derived) + ambiguous-ancestor : 0 (dropped) ``` - **type references** — every type reference in the Spoon model, type variables @@ -152,6 +154,10 @@ RESOLUTION SUMMARY - **edges (self-edges dropped: n)** — the metamodel forbids `from == to` (METAMODEL.md §4). Recursion is legal Java, so those edges are dropped and counted rather than treated as an error. +- **ancestor-attributed / ambiguous-ancestor** — call sites with no declaring + type charged to the one library ancestor that could answer (`derived` edges, + below), and those dropped because two could. Named as the Python and Ruby + extractors name them. Note that "resolved" is **not** "internal". `java.lang.String` resolves and is external; an invented FQN does not resolve and is external too. Which is which is @@ -182,7 +188,8 @@ decided by `CorpusWhitelist` alone. enclosing type with a method of that name, then the one method whose arity fits — `declared` when every type consulted has its supertypes in the corpus, `derived` otherwise; same-arity overloads, `Object` method names, `this.m()`, - `super.m()` and method references stay dropped. Until this was fixed, + `super.m()` and method references are not resolved by it (the ancestor rule + below may still charge one to a library type). Until this was fixed, spring-petclinic's `cm -> cm.createCache("vets", cacheConfiguration())` left `cacheConfiguration()` with no caller. - **An edge to a stub names the member the site wrote** (MM-6, schema 1.1.0): @@ -193,9 +200,30 @@ decided by `CorpusWhitelist` alone. The member is part of the edge (`EdgeExtractor`'s `LinkedHashSet` and its `AccessKey`), so two members of one stub at one site are two edges, while a read and a write of one member at one site stay one access with both flags. - A call to a method a corpus interface inherits from a library type - (`owners.save(owner)` on a Spring Data repository) still yields no edge in - noClasspath, so it names nothing. +- **A call to a method inherited from a library type is charged to that type, + by elimination** (`AncestorCallLookup`). Without the jar, ECJ cannot see what + `JpaRepository` declares, so `owners.save(owner)` on + `OwnerRepository extends JpaRepository` arrives with no + declaring type, and was dropped. It is now an `invocation` of the + `JpaRepository` stub naming `save`, provenance `derived`, when: the receiver's + type is a corpus type that is written (a field, a parameter, a local not + `var`; `this`, `Outer.this` in `Outer` alone; `super`, from the superclass, + `Iface.super` from that interface; the implicit `this` of an unqualified call, + every enclosing class looked through). A type written in the corpus (an + anonymous or local class, an enum constant body) is walked as corpus whatever + its id, never a candidate. No corpus type of its + supertype closure declares the name or carries a Lombok annotation; and + exactly one library type there could answer (a JDK type only for a name it + has, `Object` never). The target is the type the corpus wrote, erased, even + where an ancestor of it really declares the method. Two candidates: dropped, + `ambiguous-ancestor`. An unqualified call in a file with a static on-demand + import, or a single static import of that name, stays dropped. Not covered: + a read the corpus redeclares (already an edge), an interface with two library + parents, a receiver whose type is not written, a method reference. A unit + with such a call gets a new fact: its explain prompt and fingerprint change, + and its stored insight is re-asked. The fixture's one case is + `super.post(document)` in `LedgerAdapter`; on spring-petclinic the five + repository writes. ## Layout diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/AncestorCallLookup.java b/extractors/java/src/main/java/dev/codegraph/spoon/AncestorCallLookup.java new file mode 100644 index 00000000..bd6e3a76 --- /dev/null +++ b/extractors/java/src/main/java/dev/codegraph/spoon/AncestorCallLookup.java @@ -0,0 +1,380 @@ +package dev.codegraph.spoon; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.TreeSet; +import java.util.function.Function; +import java.util.function.Predicate; +import spoon.experimental.CtUnresolvedImport; +import spoon.reflect.code.CtExpression; +import spoon.reflect.code.CtInvocation; +import spoon.reflect.code.CtLocalVariable; +import spoon.reflect.code.CtSuperAccess; +import spoon.reflect.code.CtThisAccess; +import spoon.reflect.code.CtTypeAccess; +import spoon.reflect.code.CtVariableRead; +import spoon.reflect.declaration.CtAnnotation; +import spoon.reflect.declaration.CtCompilationUnit; +import spoon.reflect.declaration.CtElement; +import spoon.reflect.declaration.CtField; +import spoon.reflect.declaration.CtImport; +import spoon.reflect.declaration.CtImportKind; +import spoon.reflect.declaration.CtMethod; +import spoon.reflect.declaration.CtParameter; +import spoon.reflect.declaration.CtType; +import spoon.reflect.declaration.CtTypeMember; +import spoon.reflect.declaration.CtVariable; +import spoon.reflect.reference.CtExecutableReference; +import spoon.reflect.reference.CtTypeParameterReference; +import spoon.reflect.reference.CtTypeReference; + +/** + * The library type a call names when the method is inherited from it. + * + *

Without the library's jar, ECJ cannot see what a library supertype declares, + * so {@code owners.save(owner)} on an {@code OwnerStore extends CrudStore} + * reaches Spoon with no declaring type and would be dropped. What is still decidable + * is elimination: the receiver's static type is written in the corpus, nothing in the + * corpus part of its supertype closure declares a method of that name, and exactly one + * library type in that closure could answer. The call is then that type's — an + * inference, never a fact: the edge is {@code derived}, and it names the type the + * corpus WROTE ({@code CrudStore}), not whichever of its own ancestors really + * declares the method, which only the jar could tell. + * + *

Receivers it reads: a variable whose declaration writes its type (a field, a + * parameter, a local not declared {@code var}), {@code this}, {@code super}, and the + * implicit {@code this} of an unqualified call. Anything else — a call's result, a + * {@code var}, an inferred lambda parameter, an array element — is left dropped. + */ +final class AncestorCallLookup { + + /** {@code java.lang.Object} answers these, and ECJ binds them without help: never a candidate. */ + private static final String OBJECT_TYPE_ID = EntityIds.PREFIX + "java.lang/Object"; + + private static final String LOMBOK_PACKAGE_PREFIX = "lombok."; + + /** What the lookup decided for a call that would otherwise be dropped. */ + sealed interface Outcome { + /** The one library type that could answer; {@code typeId} is its erased id. */ + record Attributed(String typeId) implements Outcome {} + + /** Two or more library types could answer: dropped, under its own count. */ + record Ambiguous(List typeIds) implements Outcome {} + } + + private final Function, Optional> typeIdOf; + private final Predicate declares; + + /** + * @param typeIdOf the id pass 3 gives a type reference (empty when it cannot name one) + * @param declares whether the corpus declares an id (the whitelist's answer) + */ + AncestorCallLookup(Function, Optional> typeIdOf, Predicate declares) { + this.typeIdOf = typeIdOf; + this.declares = declares; + } + + /** Empty unless the call has no declaring type and its receiver's closure decides it. */ + Optional resolve(CtInvocation call) { + CtExecutableReference executable = call.getExecutable(); + if (executable == null || executable.getDeclaringType() != null || executable.isConstructor()) { + return Optional.empty(); + } + String name = executable.getSimpleName(); + if (name == null || name.isBlank()) { + return Optional.empty(); + } + Optional>> scopes = scopesOf(call); + if (scopes.isEmpty()) { + return Optional.empty(); + } + Closure closure = new Closure(name); + for (CtTypeReference scope : scopes.get()) { + closure.visit(scope); + } + if (closure.unknowable || closure.corpusDeclares || closure.generatesMembers) { + return Optional.empty(); + } + int candidates = closure.candidates.size() + (closure.unnamedCandidate ? 1 : 0); + if (candidates > 1) { + return Optional.of(new Outcome.Ambiguous(List.copyOf(closure.candidates))); + } + // One candidate Spoon cannot name is no target: the call stays dropped as before. + return candidates == 1 && !closure.unnamedCandidate + ? Optional.of(new Outcome.Attributed(closure.candidates.first())) + : Optional.empty(); + } + + /** The type references whose closures the call's name is looked up in; empty when the receiver is out of reach. */ + private Optional>> scopesOf(CtInvocation call) { + CtExpression receiver = call.getTarget(); + // CtSuperAccess is a CtVariableRead in Spoon's hierarchy: it is asked first. + if (receiver instanceof CtVariableRead read && !(receiver instanceof CtSuperAccess)) { + CtVariable declaration = declarationOf(read); + if (declaration == null || isInferred(declaration)) { + return Optional.empty(); + } + CtTypeReference written = declaration.getType(); + return isCorpusType(written) ? Optional.of(List.of(written)) : Optional.empty(); + } + if (receiver instanceof CtSuperAccess access) { + // super.m() starts at the superclass (Iface.super.m() at the interface): + // the class's own override is not where the call lands. Spoon writes the + // interface of Iface.super as the access's target, with no type. + CtTypeReference start = + access.getTarget() instanceof CtTypeAccess qualifier ? qualifier.getAccessedType() : access.getType(); + if (start == null) { + CtType enclosing = enclosingType(call); + start = enclosing == null ? null : enclosing.getSuperclass(); + } + return start == null ? Optional.empty() : Optional.of(List.of(start)); + } + if (receiver instanceof CtThisAccess access && !access.isImplicit()) { + CtTypeReference self = access.getType(); + if (self == null) { + CtType enclosing = enclosingType(call); + self = enclosing == null ? null : enclosing.getReference(); + } + return isCorpusType(self) ? Optional.of(List.of(self)) : Optional.empty(); + } + if (receiver instanceof CtThisAccess && !staticImportMayBind(call, call.getExecutable().getSimpleName())) { + // No receiver written: JLS §15.12.1 looks through every enclosing class. + List> scopes = new ArrayList<>(); + for (CtType type = enclosingType(call); type != null; type = enclosingType(type)) { + scopes.add(type.getReference()); + } + return scopes.isEmpty() ? Optional.empty() : Optional.of(scopes); + } + return Optional.empty(); + } + + /** + * Whether a static import of the call's file may bind an unqualified name: an + * on-demand one ({@code import static org.mockito.Mockito.*}) whatever it names, + * a single one when it ends with that name. Its type's members are as invisible + * as a library ancestor's, so a miss in the corpus no longer singles the ancestor out. + */ + private static boolean staticImportMayBind(CtElement call, String name) { + CtCompilationUnit unit; + try { + unit = call.getPosition().getCompilationUnit(); + } catch (RuntimeException e) { + return true; + } + if (unit == null) { + return true; + } + for (CtImport statement : unit.getImports()) { + if (statement instanceof CtUnresolvedImport unresolved) { + if (!unresolved.isStatic()) { + continue; + } + String text = unresolved.getUnresolvedReference() == null ? "" : unresolved.getUnresolvedReference().trim(); + if (text.endsWith(".*") || text.endsWith("." + name)) { + return true; + } + continue; + } + CtImportKind kind = statement.getImportKind(); + if (kind == CtImportKind.ALL_STATIC_MEMBERS) { + return true; + } + if ((kind == CtImportKind.METHOD || kind == CtImportKind.FIELD) + && statement.getReference() != null + && name.equals(statement.getReference().getSimpleName())) { + return true; + } + } + return false; + } + + private static CtType enclosingType(CtElement element) { + try { + return element.getParent(CtType.class); + } catch (RuntimeException e) { + return null; + } + } + + private boolean isCorpusType(CtTypeReference reference) { + return reference != null + && !(reference instanceof CtTypeParameterReference) + && (isSource(declarationOf(reference)) || typeIdOf.apply(reference).filter(declares).isPresent()); + } + + /** + * The walk over a supertype closure. Corpus types are read for a method of that + * name; library types are the candidates. + */ + private final class Closure { + private final String name; + private final Set> visited = Collections.newSetFromMap(new IdentityHashMap<>()); + final TreeSet candidates = new TreeSet<>(); + + /** A corpus type whose declaration Spoon did not hand over: its members are unknown. */ + boolean unknowable; + + /** A corpus type of the closure declares a method of that name (private ones included). */ + boolean corpusDeclares; + + /** A library type that could answer but that Spoon cannot name: it still makes two. */ + boolean unnamedCandidate; + + /** + * A corpus type of the closure carries a Lombok annotation (on itself or on a + * member): it has members no source writes, so the corpus's silence about a + * name proves nothing (fineract's {@code @Getter} fields). + */ + boolean generatesMembers; + + Closure(String name) { + this.name = name; + } + + void visit(CtTypeReference reference) { + if (reference == null || reference instanceof CtTypeParameterReference) { + return; + } + // A type whose declaration is corpus SOURCE is the corpus's, whatever its + // id: an anonymous class, a local class, an enum constant body. It is + // walked, never taken for a library candidate. + CtType declaration = declarationOf(reference); + if (isSource(declaration)) { + visitCorpus(declaration); + return; + } + Optional id = typeIdOf.apply(reference); + if (id.isPresent() && declares.test(id.get())) { + // Declared, yet Spoon hands over no source for it: its members are unknown. + unknowable = true; + return; + } + if (id.isPresent() && id.get().equals(OBJECT_TYPE_ID)) { + return; + } + if (!couldAnswer(reference)) { + return; + } + if (id.isPresent()) { + candidates.add(id.get()); + } else { + unnamedCandidate = true; + } + } + + private void visitCorpus(CtType type) { + if (!visited.add(type)) { + return; + } + for (CtMethod method : type.getMethods()) { + if (name.equals(method.getSimpleName())) { + corpusDeclares = true; + } + } + if (carriesLombok(type)) { + generatesMembers = true; + } + for (CtTypeReference supertype : supertypesOf(type)) { + visit(supertype); + } + } + + /** + * A library type Spoon cannot see could declare anything. One it can see (the + * JDK, from the platform reference) answers only for the names it has, its own + * ancestors' included; a shadow that fails to list them is treated as unseen. + */ + private boolean couldAnswer(CtTypeReference reference) { + CtType visible = declarationOf(reference); + if (visible == null) { + return true; + } + try { + for (CtMethod method : visible.getAllMethods()) { + if (name.equals(method.getSimpleName())) { + return true; + } + } + return false; + } catch (RuntimeException e) { + return true; + } + } + } + + /** Built from an input file, not a shadow of a class on the classpath (the JDK). */ + private static boolean isSource(CtType type) { + if (type == null || type.isShadow()) { + return false; + } + try { + return type.getPosition() != null && type.getPosition().isValidPosition(); + } catch (RuntimeException e) { + return false; + } + } + + /** A {@code lombok.*} annotation on the type or on one of its fields or methods. */ + private static boolean carriesLombok(CtType type) { + if (isLombok(type.getAnnotations())) { + return true; + } + for (CtTypeMember member : type.getTypeMembers()) { + if ((member instanceof CtField || member instanceof CtMethod) && isLombok(member.getAnnotations())) { + return true; + } + } + return false; + } + + private static boolean isLombok(List> annotations) { + for (CtAnnotation annotation : annotations) { + CtTypeReference annotationType = annotation.getAnnotationType(); + String qualified = annotationType == null ? null : annotationType.getQualifiedName(); + if (qualified != null && qualified.startsWith(LOMBOK_PACKAGE_PREFIX)) { + return true; + } + } + return false; + } + + private static List> supertypesOf(CtType type) { + List> supertypes = new ArrayList<>(); + if (type.getSuperclass() != null) { + supertypes.add(type.getSuperclass()); + } + supertypes.addAll(type.getSuperInterfaces()); + return supertypes; + } + + private static CtVariable declarationOf(CtVariableRead read) { + try { + return read.getVariable() == null ? null : read.getVariable().getDeclaration(); + } catch (RuntimeException e) { + return null; + } + } + + /** {@code var x = …} and an untyped lambda parameter: the type is ECJ's inference, not written. */ + private static boolean isInferred(CtVariable variable) { + if (variable instanceof CtLocalVariable local) { + return local.isInferred(); + } + if (variable instanceof CtParameter parameter) { + return parameter.isInferred(); + } + return false; + } + + private static CtType declarationOf(CtTypeReference reference) { + try { + return reference.getTypeDeclaration(); + } catch (RuntimeException e) { + return null; + } + } +} diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/EdgeExtractor.java b/extractors/java/src/main/java/dev/codegraph/spoon/EdgeExtractor.java index e10f6a3a..3d984570 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/EdgeExtractor.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/EdgeExtractor.java @@ -124,7 +124,10 @@ * points at, silently inflating coupling metrics. Dropped and counted * ({@link #droppedUnidentifiedTargets()}) — except an unqualified call in * a lambda ECJ could not type, which {@link UnboundCallLookup} names by - * the language's own lookup when exactly one corpus method fits. + * the language's own lookup when exactly one corpus method fits, and a + * call to a method inherited from a library type, which + * {@link AncestorCallLookup} charges to the one library ancestor that could + * answer ({@code derived}; with two, dropped and counted apart). * */ public final class EdgeExtractor { @@ -157,6 +160,9 @@ public final class EdgeExtractor { /** Unqualified calls in a body ECJ never resolved; membership is the whitelist's answer. */ private final UnboundCallLookup unboundCalls; + /** Calls to a method a corpus type inherits from its one library ancestor. */ + private final AncestorCallLookup ancestorCalls; + // Per-run state, reset by every extract() call. private final Set edges = new LinkedHashSet<>(); private final Map accesses = new LinkedHashMap<>(); @@ -165,12 +171,17 @@ public final class EdgeExtractor { private int droppedSelfReferences; private int droppedUnidentifiedTargets; private int droppedUnanchoredFacts; + private int ancestorAttributedCalls; + private int ambiguousAncestorCalls; public EdgeExtractor(CorpusWhitelist whitelist, Anchors anchors) { this.whitelist = whitelist; this.anchors = anchors; this.unboundCalls = new UnboundCallLookup(reference -> typeIdOfReference(reference).filter(whitelist::declares).isPresent()); + this.ancestorCalls = + new AncestorCallLookup( + reference -> typeIdOfReference(reference).filter(id -> !UNKNOWN_TYPE_ID.equals(id)), whitelist::declares); } public CorpusWhitelist whitelist() { @@ -239,6 +250,16 @@ public int droppedUnanchoredFacts() { return droppedUnanchoredFacts; } + /** Call sites charged to the one library ancestor that could answer ({@code derived}). */ + public int ancestorAttributedCalls() { + return ancestorAttributedCalls; + } + + /** Call sites dropped because two library ancestors could answer; not in {@link #droppedUnidentifiedTargets()}. */ + public int ambiguousAncestorCalls() { + return ambiguousAncestorCalls; + } + // ------------------------------------------------------------------ import /** @@ -464,10 +485,39 @@ private void emitInvocations(CtModel model) { emitUnboundCall(site, unbound.get(), provenance.get()); continue; } + Optional inherited = + invocation instanceof CtInvocation call ? ancestorCalls.resolve(call) : Optional.empty(); + if (inherited.isPresent()) { + emitInheritedCall(site, invocation.getExecutable(), inherited.get()); + continue; + } emitCall(site, invocation.getExecutable(), provenance.get()); } } + /** + * A call with no declaring type, decided by {@link AncestorCallLookup}: the one + * library ancestor's stub, naming the method, {@code derived} — or, with two + * that could answer, dropped and counted apart. Only ever a drop turned into an + * edge: a call with no declaring type had no edge before. + */ + private void emitInheritedCall( + CtElement site, CtExecutableReference executable, AncestorCallLookup.Outcome outcome) { + if (outcome instanceof AncestorCallLookup.Outcome.Ambiguous) { + ambiguousAncestorCalls++; + return; + } + String typeId = ((AncestorCallLookup.Outcome.Attributed) outcome).typeId(); + Optional anchor = anchorOf(site); + Optional owner = invocableOwnerOf(site); + if (anchor.isEmpty() || owner.isEmpty()) { + return; + } + ancestorAttributedCalls++; + emitTypeLevelCall( + owner.get(), typeId, stubMember(typeId, executable.getSimpleName()), Provenance.DERIVED, anchor.get()); + } + /** * An unqualified call ECJ never bound, resolved by {@link UnboundCallLookup} to * the corpus method it names — under the id pass 2 declared for it. A lookup @@ -1045,6 +1095,8 @@ private void reset() { droppedSelfReferences = 0; droppedUnidentifiedTargets = 0; droppedUnanchoredFacts = 0; + ancestorAttributedCalls = 0; + ambiguousAncestorCalls = 0; } /** diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/Main.java b/extractors/java/src/main/java/dev/codegraph/spoon/Main.java index 4ab71913..c5925605 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/Main.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/Main.java @@ -138,7 +138,8 @@ private static void run(Options options, Progress progress) throws Exception { List declared = new EntityExtractor(whitelist, anchors).extract(spoonModel, progress); // Pass 3 — relations; self-edges are not representable in the metamodel. - List allEdges = new EdgeExtractor(whitelist, anchors).extract(spoonModel, progress); + EdgeExtractor edgeExtractor = new EdgeExtractor(whitelist, anchors); + List allEdges = edgeExtractor.extract(spoonModel, progress); List edges = new ArrayList<>(allEdges.size()); int droppedSelfEdges = 0; for (Edge edge : allEdges) { @@ -195,7 +196,10 @@ private static void run(Options options, Progress progress) throws Exception { } progress.log( - stats.withOutput(entities.size(), stubs.size(), edges.size(), droppedSelfEdges).summary()); + stats + .withOutput(entities.size(), stubs.size(), edges.size(), droppedSelfEdges) + .withAncestorCalls(edgeExtractor.ancestorAttributedCalls(), edgeExtractor.ambiguousAncestorCalls()) + .summary()); if (droppedDanglingEdges > 0) { progress.log( "warning: " + droppedDanglingEdges + " edge(s) dropped for an undeclarable endpoint"); diff --git a/extractors/java/src/main/java/dev/codegraph/spoon/ResolutionStats.java b/extractors/java/src/main/java/dev/codegraph/spoon/ResolutionStats.java index 280f8e69..70f9b7d5 100644 --- a/extractors/java/src/main/java/dev/codegraph/spoon/ResolutionStats.java +++ b/extractors/java/src/main/java/dev/codegraph/spoon/ResolutionStats.java @@ -24,6 +24,9 @@ * @param stubCount entities with {@code isStub: true} * @param edgeCount edges written * @param droppedSelfEdges edges dropped because {@code from == to} (METAMODEL.md §4) + * @param ancestorAttributedCalls call sites charged to the one library ancestor + * that could answer ({@code derived}; {@link AncestorCallLookup}) + * @param ambiguousAncestorCalls call sites dropped because two library ancestors could answer */ public record ResolutionStats( long totalTypeReferences, @@ -31,7 +34,9 @@ public record ResolutionStats( int entityCount, int stubCount, int edgeCount, - int droppedSelfEdges) { + int droppedSelfEdges, + int ancestorAttributedCalls, + int ambiguousAncestorCalls) { /** Spoon's static type for the {@code null} literal — a pseudo-type, not a type. */ private static final String NULL_TYPE = ""; @@ -62,7 +67,7 @@ public static ResolutionStats measure(CtModel model) { resolved++; } } - return new ResolutionStats(total, resolved, 0, 0, 0, 0); + return new ResolutionStats(total, resolved, 0, 0, 0, 0, 0, 0); } /** @@ -94,7 +99,26 @@ static boolean resolves(CtTypeReference reference) { public ResolutionStats withOutput(int entityCount, int stubCount, int edgeCount, int droppedSelfEdges) { return new ResolutionStats( - totalTypeReferences, resolvedTypeReferences, entityCount, stubCount, edgeCount, droppedSelfEdges); + totalTypeReferences, + resolvedTypeReferences, + entityCount, + stubCount, + edgeCount, + droppedSelfEdges, + ancestorAttributedCalls, + ambiguousAncestorCalls); + } + + public ResolutionStats withAncestorCalls(int attributed, int ambiguous) { + return new ResolutionStats( + totalTypeReferences, + resolvedTypeReferences, + entityCount, + stubCount, + edgeCount, + droppedSelfEdges, + attributed, + ambiguous); } public long unresolvedTypeReferences() { @@ -114,7 +138,9 @@ public String summary() { unresolved : %d resolution rate : %.1f%% entities : %d (stubs: %d) - edges : %d (self-edges dropped: %d)""" + edges : %d (self-edges dropped: %d) + ancestor-attributed : %d (derived) + ambiguous-ancestor : %d (dropped)""" .formatted( totalTypeReferences, resolvedTypeReferences, @@ -123,6 +149,8 @@ public String summary() { entityCount, stubCount, edgeCount, - droppedSelfEdges); + droppedSelfEdges, + ancestorAttributedCalls, + ambiguousAncestorCalls); } } diff --git a/extractors/java/src/test/java/dev/codegraph/spoon/AncestorAttributedCallTest.java b/extractors/java/src/test/java/dev/codegraph/spoon/AncestorAttributedCallTest.java new file mode 100644 index 00000000..3dc6c28a --- /dev/null +++ b/extractors/java/src/test/java/dev/codegraph/spoon/AncestorAttributedCallTest.java @@ -0,0 +1,771 @@ +package dev.codegraph.spoon; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +import dev.codegraph.spoon.model.Edge; +import dev.codegraph.spoon.model.EdgeKind; +import dev.codegraph.spoon.model.Provenance; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Path; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.io.TempDir; +import spoon.Launcher; +import spoon.reflect.CtModel; + +/** + * A call to a method a corpus type inherits from a library type has no declaring + * type Spoon can name without the library's jar: {@code owners.save(owner)} on an + * {@code OwnerRepository extends JpaRepository} left no edge at all + * (spring-petclinic: five write sites, while the reads the interface redeclares + * resolved). When nothing in the corpus declares the name and exactly ONE library + * type of the receiver's supertype closure could answer, the call is that type's — + * an inference by elimination, so {@code derived}, naming the member (MM-6). + * + *

The real pass 1 builds the whitelist here, so what is asserted is what the + * extractor would write. Every {@code com.nonexistent} type is on no classpath. + */ +class AncestorAttributedCallTest { + + private static final String PACKAGE = "java:com.acme.shop/"; + private static final String STORE = "java:com.nonexistent.store/CrudStore"; + private static final String BASE = "java:com.nonexistent.web/BaseController"; + + private static final Map SOURCES = new LinkedHashMap<>(); + + static { + SOURCES.put( + "com/acme/shop/Owner.java", + """ + package com.acme.shop; + + public class Owner {} + """); + SOURCES.put( + "com/acme/shop/OwnerStore.java", + """ + package com.acme.shop; + + import com.nonexistent.store.CrudStore; + + public interface OwnerStore extends CrudStore { + Owner findById(Integer id); + } + """); + SOURCES.put( + "com/acme/shop/OwnerController.java", + """ + package com.acme.shop; + + public class OwnerController { + + private final OwnerStore owners; + + private final Object initial = owners.count(); + + OwnerController(OwnerStore owners) { + this.owners = owners; + } + + void viaField(Owner owner) { + this.owners.save(owner); + } + + void viaBareField(Owner owner) { + owners.saveAndFlush(owner); + } + + void viaParameter(OwnerStore store, Owner owner) { + store.save(owner); + } + + void viaTypedLocal(Owner owner) { + OwnerStore local = owners; + local.delete(owner); + } + + void viaInferredLocal(Owner owner) { + var inferred = owners; + inferred.flush(); + } + + Owner read(Integer id) { + return this.owners.findById(id); + } + } + """); + } + + // ----------------------------------------------- condition 1: the receiver + + @Test + void aCallOnAFieldTypedByACorpusInterfaceReachesItsOneLibraryAncestor(@TempDir Path root) throws IOException { + Extraction run = extract(root); + Edge edge = single(run, PACKAGE + "OwnerController.viaField(com.acme.shop.Owner)", STORE, "save"); + assertEquals(EdgeKind.INVOCATION, edge.edge()); + assertEquals(Provenance.DERIVED, edge.provenance()); + assertEquals(lineOf("com/acme/shop/OwnerController.java", " this.owners.save(owner);"), edge.anchor().startLine()); + single(run, PACKAGE + "OwnerController.viaBareField(com.acme.shop.Owner)", STORE, "saveAndFlush"); + } + + @Test + void aParameterAndAnExplicitlyTypedLocalAreReceiversAsWell(@TempDir Path root) throws IOException { + Extraction run = extract(root); + single(run, PACKAGE + "OwnerController.viaParameter(com.acme.shop.OwnerStore,com.acme.shop.Owner)", STORE, "save"); + single(run, PACKAGE + "OwnerController.viaTypedLocal(com.acme.shop.Owner)", STORE, "delete"); + } + + /** Outside every invocable the fact degrades to a reference, as any call folded to a stub does. */ + @Test + void aCallInAFieldInitializerIsAReferenceNamingTheMember(@TempDir Path root) throws IOException { + Edge edge = single(extract(root), PACKAGE + "OwnerController.initial", STORE, "count"); + assertEquals(EdgeKind.REFERENCE, edge.edge()); + assertEquals(Provenance.DERIVED, edge.provenance()); + } + + /** {@code var} writes no type: the receiver's type is ECJ's inference, not the corpus's word. */ + @Test + void aReceiverWhoseTypeIsNotWrittenStaysDropped(@TempDir Path root) throws IOException { + Extraction run = extract(root); + assertTrue( + from(run, PACKAGE + "OwnerController.viaInferredLocal(com.acme.shop.Owner)").stream() + .noneMatch(e -> e.edge() == EdgeKind.INVOCATION), + () -> "a var receiver was attributed: " + run.edges()); + } + + /** The read the corpus interface redeclares resolved before and must stay byte-identical. */ + @Test + void aCallTheCorpusDeclaresIsUnchanged(@TempDir Path root) throws IOException { + List read = from(extract(root), PACKAGE + "OwnerController.read(java.lang.Integer)"); + List calls = read.stream().filter(e -> e.edge() == EdgeKind.INVOCATION).toList(); + assertEquals(1, calls.size(), () -> "invocations from read: " + read); + assertEquals(PACKAGE + "OwnerStore.findById(java.lang.Integer)", calls.get(0).to()); + assertEquals(Provenance.DECLARED, calls.get(0).provenance()); + assertEquals(null, calls.get(0).member()); + } + + // ------------------------------- condition 1: this, super, and no receiver + + private static final String CONTROLLER = PACKAGE + "PetController"; + + /** A corpus class with one library superclass: the enclosing class is the receiver's type. */ + private static final Map CONTROLLER_SOURCES = + Map.of( + "com/acme/shop/PetController.java", + """ + package com.acme.shop; + + import com.nonexistent.web.BaseController; + import com.nonexistent.web.Callback; + + public class PetController extends BaseController { + + void unqualified() { + redirect("/pets"); + } + + void explicitThis() { + this.render("pets"); + } + + @Override + public void handle(Object request) { + super.handle(request); + } + + Callback inALambdaEcjCouldNotType() { + return event -> refresh(); + } + + class Inner { + void outerAncestor() { + redirect("/inner"); + } + } + } + """, + "com/acme/shop/MockedController.java", + """ + package com.acme.shop; + + import static com.nonexistent.mock.Mocks.*; + + import com.nonexistent.web.BaseController; + + public class MockedController extends BaseController { + + void staticallyImported() { + mock(Owner.class); + } + + void qualified() { + this.render("mocked"); + } + } + """, + "com/acme/shop/Owner.java", + "package com.acme.shop;\n\npublic class Owner {}\n"); + + @Test + void anUnqualifiedCallAndAThisCallReachTheEnclosingClassesLibraryAncestor(@TempDir Path root) throws IOException { + Extraction run = extract(root, CONTROLLER_SOURCES); + Edge bare = single(run, CONTROLLER + ".unqualified()", BASE, "redirect"); + assertEquals(EdgeKind.INVOCATION, bare.edge()); + assertEquals(Provenance.DERIVED, bare.provenance()); + single(run, CONTROLLER + ".explicitThis()", BASE, "render"); + } + + /** {@code super.m()} skips the class itself: its own override of {@code handle} is no evidence against it. */ + @Test + void aSuperCallReachesTheLibrarySuperclassDespiteTheOverride(@TempDir Path root) throws IOException { + single(extract(root, CONTROLLER_SOURCES), CONTROLLER + ".handle(java.lang.Object)", BASE, "handle"); + } + + /** JLS §15.12.1 looks through the enclosing classes: the inner class has no ancestor of its own. */ + @Test + void anUnqualifiedCallInAnInnerClassReachesTheOuterClassesAncestor(@TempDir Path root) throws IOException { + single(extract(root, CONTROLLER_SOURCES), CONTROLLER + ".Inner.outerAncestor()", BASE, "redirect"); + } + + @Test + void anUnqualifiedCallInALambdaEcjCouldNotTypeIsAttributedToo(@TempDir Path root) throws IOException { + Extraction run = extract(root, CONTROLLER_SOURCES); + List fromLambda = + run.edges().stream() + .filter(e -> e.from().startsWith(CONTROLLER + "#com/acme/shop/PetController.java:")) + .filter(e -> e.to().equals(BASE) && "refresh".equals(e.member())) + .toList(); + assertEquals(1, fromLambda.size(), () -> "edges: " + run.edges().stream().map(AncestorAttributedCallTest::render).toList()); + assertEquals(Provenance.DERIVED, fromLambda.get(0).provenance()); + } + + /** + * A static on-demand import may bind the name ({@code mock} from Mockito + * arrives exactly like an inherited call): "nothing in the corpus declares it" + * no longer points at the ancestor, so an unqualified call there stays dropped. + * A qualified {@code this.m()} in the same file is unaffected. + */ + @Test + void aStaticOnDemandImportKeepsAnUnqualifiedCallDropped(@TempDir Path root) throws IOException { + Extraction run = extract(root, CONTROLLER_SOURCES); + assertTrue( + from(run, PACKAGE + "MockedController.staticallyImported()").stream() + .noneMatch(e -> e.edge() == EdgeKind.INVOCATION), + () -> "a statically importable name was attributed: " + from(run, PACKAGE + "MockedController.staticallyImported()")); + single(run, PACKAGE + "MockedController.qualified()", BASE, "render"); + } + + // --------------------- condition 2: nothing in the corpus declares the name + + private static final Map REDECLARED_SOURCES = + Map.of( + "com/acme/shop/Owner.java", + "package com.acme.shop;\n\npublic class Owner {}\n", + "com/acme/shop/Renamable.java", + """ + package com.acme.shop; + + public interface Renamable { + void rename(String name); + } + """, + "com/acme/shop/OwnerStore.java", + """ + package com.acme.shop; + + import com.nonexistent.store.CrudStore; + + public interface OwnerStore extends CrudStore, Renamable { + Owner findById(Integer id); + } + """, + "com/acme/shop/Redeclaring.java", + """ + package com.acme.shop; + + import com.nonexistent.web.BaseController; + import com.nonexistent.web.Callback; + + public class Redeclaring extends BaseController { + + private OwnerStore owners; + + void sameInterface() { + owners.findById(1, "two"); + } + + Callback sameInterfaceInALambda() { + return event -> owners.findById(7); + } + + Callback corpusSuperinterfaceInALambda() { + return event -> owners.rename("x"); + } + + Callback ownClassInALambda() { + return event -> redirect("a", "b"); + } + + void redirect(int code) {} + } + """); + + /** + * In a lambda ECJ could not type, a call the corpus declares arrives unbound + * too. A method of that name in a corpus type of the closure is evidence the + * call may be the corpus's, so the elimination is gone and the call stays + * dropped — wherever the name is: the type itself, a corpus superinterface, + * the enclosing class (an overload {@link UnboundCallLookup} found no arity for). + */ + @Test + void aNameACorpusTypeOfTheClosureDeclaresStaysDropped(@TempDir Path root) throws IOException { + Extraction run = extract(root, REDECLARED_SOURCES); + List toLibrary = + run.edges().stream() + .filter(e -> e.from().startsWith(PACKAGE + "Redeclaring")) + .filter(e -> e.to().equals(STORE) || e.to().equals(BASE)) + .filter(e -> e.edge() != EdgeKind.INHERITANCE) + .toList(); + assertTrue( + toLibrary.isEmpty(), + () -> "attributed: " + toLibrary.stream().map(AncestorAttributedCallTest::render).toList()); + assertEquals(0, run.ancestorAttributedCalls()); + // ECJ binds the wrong-arity call to the one corpus findById; that edge predates the rule and stays. + assertEquals( + List.of(PACKAGE + "OwnerStore.findById(java.lang.Integer)"), + from(run, PACKAGE + "Redeclaring.sameInterface()").stream() + .filter(e -> e.edge() == EdgeKind.INVOCATION) + .map(Edge::to) + .toList()); + } + + /** + * Lombok writes members no source declares ({@code @Getter} on a field is a + * {@code getX()}), so in a type that carries a Lombok annotation the corpus's + * silence about a name is no evidence. Found on apache/fineract: 2 319 calls + * like {@code product.getLoanProductRelatedDetail()} charged to + * {@code Persistable}, a library interface its entities implement. + */ + private static final Map LOMBOK_SOURCES = + Map.of( + "com/acme/shop/Entity.java", + """ + package com.acme.shop; + + import com.nonexistent.data.Persistable; + + public abstract class Entity implements Persistable {} + """, + "com/acme/shop/Product.java", + """ + package com.acme.shop; + + import lombok.Getter; + + public class Product extends Entity { + + @Getter + private String detail; + } + """, + "com/acme/shop/Account.java", + """ + package com.acme.shop; + + @lombok.Data + public class Account extends Entity { + + private String code; + } + """, + "com/acme/shop/Plan.java", + """ + package com.acme.shop; + + public class Plan extends Product {} + """, + "com/acme/shop/Pricing.java", + """ + package com.acme.shop; + + public class Pricing { + + void fieldGetter(Product product) { + product.getDetail(); + } + + void typeLevelData(Account account) { + account.getCode(); + } + + void inheritedFromALombokSuperclass(Plan plan) { + plan.getDetail(); + } + + void noLombokOnTheWay(Entity entity) { + entity.isNew(); + } + } + """); + + @Test + void aLombokAnnotatedTypeInTheClosureKeepsTheCallDropped(@TempDir Path root) throws IOException { + Extraction run = extract(root, LOMBOK_SOURCES); + String persistable = "java:com.nonexistent.data/Persistable"; + for (String method : + List.of( + "fieldGetter(com.acme.shop.Product)", + "typeLevelData(com.acme.shop.Account)", + "inheritedFromALombokSuperclass(com.acme.shop.Plan)")) { + List attributed = + from(run, PACKAGE + "Pricing." + method).stream().filter(e -> e.to().equals(persistable)).toList(); + assertTrue(attributed.isEmpty(), () -> method + " was attributed: " + attributed); + } + single(run, PACKAGE + "Pricing.noLombokOnTheWay(com.acme.shop.Entity)", persistable, "isNew"); + assertEquals(1, run.ancestorAttributedCalls()); + } + + // ------------------------------- condition 3: exactly one library candidate + + private static final Map CANDIDATE_SOURCES = + Map.of( + "com/acme/shop/Owner.java", + "package com.acme.shop;\n\npublic class Owner {}\n", + "com/acme/shop/AuditedStore.java", + """ + package com.acme.shop; + + import com.nonexistent.audit.Audited; + import com.nonexistent.store.CrudStore; + + public interface AuditedStore extends CrudStore, Audited {} + """, + "com/acme/shop/Ledger.java", + """ + package com.acme.shop; + + import com.nonexistent.audit.Audited; + import java.util.ArrayList; + + public class Ledger extends ArrayList implements Audited {} + """, + "com/acme/shop/Plain.java", + """ + package com.acme.shop; + + import java.util.ArrayList; + + public class Plain extends ArrayList {} + """, + "com/acme/shop/Callers.java", + """ + package com.acme.shop; + + public class Callers { + + void twoLibraryParents(AuditedStore store, Owner owner) { + store.save(owner); + } + + void aVisibleJdkTypeLacksTheName(Ledger ledger) { + ledger.audit("posted"); + } + + void onlyAVisibleJdkType(Plain plain) { + plain.audit("posted"); + } + } + """); + + /** Which of the two declares {@code save} only the jars could say: dropped, counted apart. */ + @Test + void twoLibraryTypesThatCouldAnswerAreAmbiguousAndCountedApart(@TempDir Path root) throws IOException { + Extraction run = extract(root, CANDIDATE_SOURCES); + List calls = + from(run, PACKAGE + "Callers.twoLibraryParents(com.acme.shop.AuditedStore,com.acme.shop.Owner)").stream() + .filter(e -> e.edge() == EdgeKind.INVOCATION) + .toList(); + assertTrue(calls.isEmpty(), () -> "an ambiguous call was attributed: " + calls); + assertEquals(1, run.ambiguousAncestorCalls()); + } + + /** Spoon sees what {@code ArrayList} declares, and {@code audit} is not among it: one candidate left. */ + @Test + void aLibraryTypeWhoseMembersAreVisibleAnswersOnlyForWhatItDeclares(@TempDir Path root) throws IOException { + Extraction run = extract(root, CANDIDATE_SOURCES); + single( + run, + PACKAGE + "Callers.aVisibleJdkTypeLacksTheName(com.acme.shop.Ledger)", + "java:com.nonexistent.audit/Audited", + "audit"); + } + + /** No library type could answer, so there is no one to charge it to — and it is no ambiguity either. */ + @Test + void aClosureOfVisibleTypesOnlyLeavesTheCallDroppedAsBefore(@TempDir Path root) throws IOException { + Extraction run = extract(root, CANDIDATE_SOURCES); + assertTrue( + from(run, PACKAGE + "Callers.onlyAVisibleJdkType(com.acme.shop.Plain)").stream() + .noneMatch(e -> e.edge() == EdgeKind.INVOCATION), + () -> "attributed: " + from(run, PACKAGE + "Callers.onlyAVisibleJdkType(com.acme.shop.Plain)")); + assertEquals(1, run.ambiguousAncestorCalls(), "only twoLibraryParents is ambiguous"); + assertEquals(1, run.ancestorAttributedCalls(), "only aVisibleJdkTypeLacksTheName is attributed"); + } + + // ------------------ types written in the corpus that are not named types + + private static final String LIB = "java:com.nonexistent.lib/"; + private static final String OUTER = PACKAGE + "Outer"; + + /** + * An anonymous class, a local class and an enum constant body are written in the + * corpus: each is walked as corpus (its own methods are evidence, its supertypes + * are visited), never taken for a library candidate. + */ + private static final Map NESTED_SOURCES = + Map.of( + "com/acme/shop/Outer.java", + """ + package com.acme.shop; + + import com.nonexistent.lib.Expectations; + import com.nonexistent.lib.LibBase; + import com.nonexistent.lib.LibCallback; + import com.nonexistent.lib.LibIface; + import com.nonexistent.web.Callback; + + public class Outer extends LibBase { + + void anonymousWithALibrarySupertype() { + new LibCallback() { + public void run() { + helper(); + } + }; + } + + void doubleBraceInitializer() { + new Expectations() {{ + oneOf(1); + }}; + } + + void anonymousThatDeclaresTheName() { + new LibCallback() { + void helper(int code) {} + + public void run() { + Callback later = event -> helper("a", "b"); + } + }; + } + + void anonymousWithAJdkSupertype() { + new Runnable() { + public void run() { + render(); + } + }; + } + + void localClass() { + class Local extends LibCallback { + void go() { + helper(); + } + } + } + + class Inner extends LibCallback { + void qualifiedThis() { + Outer.this.render(); + } + } + } + """, + "com/acme/shop/Kind.java", + """ + package com.acme.shop; + + import com.nonexistent.lib.LibIface; + + public enum Kind implements LibIface { + A { + void go() { + ping(); + } + }; + + void go() {} + } + """, + "com/acme/shop/TwoParents.java", + """ + package com.acme.shop; + + import com.nonexistent.lib.LibA; + import com.nonexistent.lib.LibB; + + public class TwoParents implements LibA, LibB { + + @Override + public void ping() { + LibA.super.ping(); + } + } + """); + + /** Case A: {@code helper} may be LibCallback's or LibBase's. */ + @Test + void anUnqualifiedCallInAnAnonymousClassWithALibrarySupertypeIsAmbiguous(@TempDir Path root) throws IOException { + Extraction run = extract(root, NESTED_SOURCES); + List attributed = toLibrary(run, "Outer.java", "helper();", 0); + assertTrue(attributed.isEmpty(), () -> "case A was attributed: " + attributed); + List local = toLibrary(run, "Outer.java", "helper();", 1); + assertTrue(local.isEmpty(), () -> "the local class's call was attributed: " + local); + // Ambiguous, not merely dropped: case A, the local class and the double-brace initializer. + assertEquals(3, run.ambiguousAncestorCalls()); + } + + /** jMock's shape: {@code oneOf} may be the Expectations' or the outer class's ancestor's. */ + @Test + void aDoubleBraceInitializerIsAmbiguousToo(@TempDir Path root) throws IOException { + Extraction run = extract(root, NESTED_SOURCES); + List attributed = toLibrary(run, "Outer.java", "oneOf(1);", 0); + assertTrue(attributed.isEmpty(), () -> "oneOf was attributed: " + attributed); + } + + /** Case B: the anonymous class declares {@code helper}; the call is never charged to a library, nor to a stub for the anonymous class. */ + @Test + void anAnonymousClassThatDeclaresTheNameKeepsTheCallDropped(@TempDir Path root) throws IOException { + Extraction run = extract(root, NESTED_SOURCES); + List derived = + run.edges().stream() + .filter(e -> e.anchor().file().equals("com/acme/shop/Outer.java") && e.anchor().startLine() == nestedLine("Outer.java", "helper(\"a\", \"b\")", 0)) + .filter(e -> e.provenance() == Provenance.DERIVED || "helper".equals(e.member())) + .toList(); + assertTrue(derived.isEmpty(), () -> "case B was attributed: " + derived.stream().map(AncestorAttributedCallTest::render).toList()); + } + + /** The control: a JDK supertype lacking the name leaves the outer class's one library ancestor. */ + @Test + void anAnonymousClassWithAJdkSupertypeLeavesTheOuterAncestor(@TempDir Path root) throws IOException { + Extraction run = extract(root, NESTED_SOURCES); + List attributed = toLibrary(run, "Outer.java", "render();", 0); + assertEquals(1, attributed.size(), () -> "edges: " + attributed); + assertEquals(LIB + "LibBase", attributed.get(0).to()); + assertEquals("render", attributed.get(0).member()); + } + + /** An enum constant body is an anonymous class: walked through, its enum's library interface answers. */ + @Test + void anEnumConstantBodyReachesItsEnumsLibraryInterface(@TempDir Path root) throws IOException { + Extraction run = extract(root, NESTED_SOURCES); + List attributed = toLibrary(run, "Kind.java", "ping();", 0); + assertEquals(1, attributed.size(), () -> "edges: " + attributed); + assertEquals(LIB + "LibIface", attributed.get(0).to()); + } + + /** {@code Outer.this.m()} looks in Outer alone: the inner class's own library supertype is not asked. */ + @Test + void aQualifiedThisLooksInTheNamedClassOnly(@TempDir Path root) throws IOException { + single(extract(root, NESTED_SOURCES), OUTER + ".Inner.qualifiedThis()", LIB + "LibBase", "render"); + } + + /** {@code LibA.super.ping()} names its interface: not ambiguous with LibB, and the override is no evidence. */ + @Test + void anInterfaceQualifiedSuperReachesThatInterface(@TempDir Path root) throws IOException { + Extraction run = extract(root, NESTED_SOURCES); + single(run, PACKAGE + "TwoParents.ping()", LIB + "LibA", "ping"); + assertTrue(from(run, PACKAGE + "TwoParents.ping()").stream().noneMatch(e -> e.to().equals(LIB + "LibB"))); + } + + /** Invocations of a {@code com.nonexistent.lib} stub on the {@code nth} line of {@code file} containing {@code text}. */ + private static List toLibrary(Extraction run, String file, String text, int nth) { + int line = nestedLine(file, text, nth); + return run.edges().stream() + .filter(e -> e.to().startsWith(LIB) && e.edge() == EdgeKind.INVOCATION) + .filter(e -> e.anchor().file().equals("com/acme/shop/" + file) && e.anchor().startLine() == line) + .toList(); + } + + private static int nestedLine(String file, String text, int nth) { + List lines = List.of(NESTED_SOURCES.get("com/acme/shop/" + file).split("\n", -1)); + int seen = 0; + for (int i = 0; i < lines.size(); i++) { + if (lines.get(i).contains(text) && seen++ == nth) { + return i + 1; + } + } + throw new AssertionError("no line " + nth + " containing [" + text + "] in " + file); + } + + // -------------------------------------------------------------- fixtures + + record Extraction( + List edges, int droppedUnidentifiedTargets, int ancestorAttributedCalls, int ambiguousAncestorCalls) {} + + static Extraction extract(Path root) throws IOException { + return extract(root, SOURCES); + } + + static Extraction extract(Path root, Map sources) throws IOException { + for (Map.Entry source : sources.entrySet()) { + Path file = root.resolve(source.getKey()); + Files.createDirectories(file.getParent()); + Files.writeString(file, source.getValue()); + } + Launcher launcher = new Launcher(); + launcher.getEnvironment().setNoClasspath(true); + launcher.getEnvironment().setComplianceLevel(17); + launcher.getEnvironment().setCommentEnabled(true); + launcher.addInputResource(root.toString()); + CtModel model = launcher.buildModel(); + Anchors anchors = new Anchors(root); + EdgeExtractor extractor = new EdgeExtractor(CorpusWhitelist.build(model, anchors), anchors); + List edges = extractor.extract(model); + return new Extraction( + edges, + extractor.droppedUnidentifiedTargets(), + extractor.ancestorAttributedCalls(), + extractor.ambiguousAncestorCalls()); + } + + static List from(Extraction run, String from) { + return run.edges().stream().filter(e -> e.from().equals(from)).toList(); + } + + /** The one edge {@code from} → {@code to} naming {@code member}. */ + static Edge single(Extraction run, String from, String to, String member) { + List matches = + run.edges().stream() + .filter(e -> e.from().equals(from) && e.to().equals(to) && member.equals(e.member())) + .toList(); + if (matches.size() != 1) { + throw new AssertionError( + "expected one edge " + from + " -> " + to + " naming " + member + ", got " + matches.size() + + "; edges from it:\n" + + String.join("\n", from(run, from).stream().map(AncestorAttributedCallTest::render).toList()) + + "\n(dropped unidentified targets: " + run.droppedUnidentifiedTargets() + ")"); + } + return matches.get(0); + } + + static String render(Edge e) { + return e.edge() + " " + e.from() + " -> " + e.to() + " member=" + e.member() + " [" + e.provenance().json() + "]"; + } + + private static int lineOf(String file, String text) { + List lines = List.of(SOURCES.get(file).split("\n", -1)); + for (int i = 0; i < lines.size(); i++) { + if (lines.get(i).equals(text)) { + return i + 1; + } + } + throw new AssertionError("no line [" + text + "] in " + file); + } +} diff --git a/extractors/java/src/test/java/dev/codegraph/spoon/AnchorsAndStatsTest.java b/extractors/java/src/test/java/dev/codegraph/spoon/AnchorsAndStatsTest.java index c4cfc402..767f9df8 100644 --- a/extractors/java/src/test/java/dev/codegraph/spoon/AnchorsAndStatsTest.java +++ b/extractors/java/src/test/java/dev/codegraph/spoon/AnchorsAndStatsTest.java @@ -79,6 +79,15 @@ void resolutionSummaryCountsUnresolvedReferences(@TempDir Path root) throws IOEx assertFalse(summary.contains("%d")); } + /** The two counts of the ancestor rule, named as the Python and Ruby extractors name them. */ + @Test + void resolutionSummaryCountsAncestorAttributedAndAmbiguousCalls(@TempDir Path root) throws IOException { + String summary = ResolutionStats.measure(build(root)).withOutput(12, 3, 20, 1).withAncestorCalls(5, 2).summary(); + assertTrue(summary.contains("\n ancestor-attributed : 5 (derived)"), summary); + assertTrue(summary.contains("\n ambiguous-ancestor : 2 (dropped)"), summary); + assertTrue(summary.contains("edges : 20 (self-edges dropped: 1)"), summary); + } + /** * The root a user types is not the root Spoon reports: Spoon resolves symlinks, * shells and build tools generally do not (on macOS {@code /tmp} and {@code /var} diff --git a/extractors/java/src/test/java/dev/codegraph/spoon/ResolutionRateTest.java b/extractors/java/src/test/java/dev/codegraph/spoon/ResolutionRateTest.java index 78d09cb0..8c9de417 100644 --- a/extractors/java/src/test/java/dev/codegraph/spoon/ResolutionRateTest.java +++ b/extractors/java/src/test/java/dev/codegraph/spoon/ResolutionRateTest.java @@ -97,6 +97,16 @@ void theSummaryAgreesWithTheEmittedModel() { assertEquals(run.edges().size(), Integer.parseInt(edges.group(1)), "edge count"); } + /** + * The ancestor rule's counts reach stderr from a real run: the fixture's one site + * is {@code super.post(document)} in LedgerAdapter, charged to LedgerClient. + */ + @Test + void theSummaryCountsTheFixturesOneAncestorAttributedCall() { + assertTrue(summary.contains("\n ancestor-attributed : 1 (derived)"), () -> "no ancestor count:\n" + summary); + assertTrue(summary.contains("\n ambiguous-ancestor : 0 (dropped)"), () -> "no ambiguity count:\n" + summary); + } + @Test void theFixtureCorpusResolvesAboveTheSmokeFloor() { double rate = (double) count("resolved") / count("type references"); diff --git a/fixtures/java/README.md b/fixtures/java/README.md index 482879e5..783e572a 100644 --- a/fixtures/java/README.md +++ b/fixtures/java/README.md @@ -38,7 +38,7 @@ other file compiles — if `javac` ever reports an error outside | `OrderService.java` | **The id scheme's parameter-type rule.** Two `archive` overloads whose parameter types are `java.util.List` and `com.acme.order.legacy.List` — identical simple names, different packages. | METAMODEL.md §10's illustrative id writes `bill(Order)`. Under simple names both overloads render `archive(List)`, collapse into one id, and one method silently disappears from the model. Ids use erased **FQNs**: `…/OrderService.archive(java.util.List)` vs `…/OrderService.archive(com.acme.order.legacy.List)`. | | `OrderService.java` | **Fabricated FQNs.** `Invoice` is used with no import and declared nowhere; Spoon reports the referenced type as `com.acme.order.Invoice` with `getTypeDeclaration() == null`. | A package-prefix membership filter (`startsWith("com.acme")`) classifies this fabrication as a corpus type and launders an invention into a fact. Membership is the pass-1 whitelist and nothing else. | | `OrderService.java` | **Member-level references into a stub type**: `ledger.post(...)`, `ledger.archive(...)` on an unresolvable `LedgerClient`. | Per the `EdgeExtractor` decision these retarget to the declaring type's stub id, so an `invocation` edge legitimately ends at a `TType`, not an Invocable. Anything that assumes invocation targets are invocable breaks here. | -| `LedgerAdapter.java` | **Inheritance from an unresolvable external type**, plus a second fabrication site (`AuditTrail`) in `com.acme.order.adapter`. | Proves the invented package tracks the *enclosing* file, not one hard-coded prefix. The `inheritance` edge to a stub must survive; dropping unresolvable supertypes silently truncates the hierarchy. | +| `LedgerAdapter.java` | **Inheritance from an unresolvable external type**, plus a second fabrication site (`AuditTrail`) in `com.acme.order.adapter`. | Proves the invented package tracks the *enclosing* file, not one hard-coded prefix. The `inheritance` edge to a stub must survive; dropping unresolvable supertypes silently truncates the hierarchy. `super.post(document)` is the ancestor rule's one fixture case: no declaring type without the jar, so a `derived` invocation of the `LedgerClient` stub naming `post`. | | `legacy/List.java` | **Recursion** (`length()` calls `tail.length()`) and the simple-name collision partner. | Recursion yields `from == to`. `Edge.selfReference()` exists and `Main` drops such edges; pass 3 should drop them at the source. A recursive method is also the cheapest way to produce a self-edge by accident. | | `Basket.java` | **The `getAllTypes()` blind spot**: a static nested class `Line`, a nested-inside-nested `Line.Discount`, and a non-static inner `Cursor`. Measured: `getAllTypes()` returns 13 types and **none of these three**. | The name says "all". Nested types are reachable only by recursing `CtType.getNestedTypes()`. An extractor that trusts the name drops every inner class from both the whitelist and the entity set — and then every reference to them becomes a spurious stub. Ids: `…/Basket.Line`, `…/Basket.Line.Discount`, `…/Basket.Cursor` (dots, never Spoon's `$`). | | `Basket.java` | **Implicit default constructor.** `Basket` declares none, so Spoon synthesises one with `isImplicit() == true` and **no valid source position**. | Anchors are required on every entity and edge, and spans are 1-based (a span starting at 0 is rejected by the schema). `Anchors.of` returns empty here by design; the extractor must anchor to the enclosing type or skip the member, never invent a line. Measured: **9** such constructors in this corpus (also `Money`'s canonical record ctor, `Channel`'s enum ctor, and the anonymous class's). | diff --git a/fixtures/java/expected/model.jsonl b/fixtures/java/expected/model.jsonl index b8fb7437..c6ef6b6a 100644 --- a/fixtures/java/expected/model.jsonl +++ b/fixtures/java/expected/model.jsonl @@ -371,6 +371,7 @@ {"t":"x","k":3,"f":140,"o":155,"p":0,"anchor":[14,6,6]} {"t":"x","k":5,"f":142,"o":139,"p":0,"member":"record","anchor":[14,12,12]} {"t":"x","k":0,"f":142,"o":144,"p":0,"isRead":true,"isWrite":false,"anchor":[14,12,12]} +{"t":"x","k":5,"f":142,"o":155,"p":1,"member":"post","anchor":[14,13,13]} {"t":"x","k":1,"f":142,"o":161,"p":0,"anchor":[14,10,10]} {"t":"x","k":6,"f":143,"o":160,"p":0,"anchor":[14,11,11]} {"t":"x","k":6,"f":144,"o":139,"p":0,"anchor":[14,8,8]} @@ -383,4 +384,4 @@ {"t":"x","k":6,"f":151,"o":164,"p":0,"anchor":[15,15,15]} {"t":"x","k":0,"f":152,"o":153,"p":0,"isRead":true,"isWrite":false,"anchor":[15,20,20]} {"t":"x","k":6,"f":153,"o":146,"p":0,"anchor":[15,8,8]} -{"t":"eof","counts":{"files":16,"entities":179,"edges":189}} +{"t":"eof","counts":{"files":16,"entities":179,"edges":190}} diff --git a/fixtures/java/expected/model.metrics.jsonl b/fixtures/java/expected/model.metrics.jsonl index 66c38f55..ad3915cd 100644 --- a/fixtures/java/expected/model.metrics.jsonl +++ b/fixtures/java/expected/model.metrics.jsonl @@ -371,6 +371,7 @@ {"t":"x","k":3,"f":140,"o":155,"p":0,"anchor":[14,6,6]} {"t":"x","k":5,"f":142,"o":139,"p":0,"member":"record","anchor":[14,12,12]} {"t":"x","k":0,"f":142,"o":144,"p":0,"isRead":true,"isWrite":false,"anchor":[14,12,12]} +{"t":"x","k":5,"f":142,"o":155,"p":1,"member":"post","anchor":[14,13,13]} {"t":"x","k":1,"f":142,"o":161,"p":0,"anchor":[14,10,10]} {"t":"x","k":6,"f":143,"o":160,"p":0,"anchor":[14,11,11]} {"t":"x","k":6,"f":144,"o":139,"p":0,"anchor":[14,8,8]} @@ -383,4 +384,4 @@ {"t":"x","k":6,"f":151,"o":164,"p":0,"anchor":[15,15,15]} {"t":"x","k":0,"f":152,"o":153,"p":0,"isRead":true,"isWrite":false,"anchor":[15,20,20]} {"t":"x","k":6,"f":153,"o":146,"p":0,"anchor":[15,8,8]} -{"t":"eof","counts":{"files":16,"entities":179,"edges":189}} +{"t":"eof","counts":{"files":16,"entities":179,"edges":190}} diff --git a/packages/analyzer/test/conformance.test.ts b/packages/analyzer/test/conformance.test.ts index 25313eed..4c859214 100644 --- a/packages/analyzer/test/conformance.test.ts +++ b/packages/analyzer/test/conformance.test.ts @@ -79,14 +79,15 @@ describe("checkConformance on the committed Spoon snapshot", () => { models: 1, entities: 179, stubs: 27, - edges: 189, + edges: 190, langs: ["java"], sources: ["fixtures/java"], unknownProfiles: [], - // MM-6 (M24a): the Java extractor names the member on 20 of its 61 edges to + // MM-6 (M24a): the Java extractor names the member on 21 of its 62 edges to // stubs; the other 41 are type uses and constructor calls, which name none. - edgesToStubs: 61, - membersNamed: 20, + // The 21st is LedgerAdapter's ancestor-attributed `super.post` (`post`). + edgesToStubs: 62, + membersNamed: 21, }); }); diff --git a/packages/analyzer/test/integration.test.ts b/packages/analyzer/test/integration.test.ts index fa5a2210..0bd0a8cb 100644 --- a/packages/analyzer/test/integration.test.ts +++ b/packages/analyzer/test/integration.test.ts @@ -42,12 +42,15 @@ import { edge, javaFixture, javaGraph, pkg, toyModel, type } from "./fixture.js" */ const ENTITIES = 179; -/** 189 since MM-6: `values.isEmpty() ? null : values.get(0)` (Reporting.first) is two invocations of the List stub, `get` and `isEmpty`, where it was one. */ -const EDGES = 189; +/** + * 189 since MM-6: `values.isEmpty() ? null : values.get(0)` (Reporting.first) is two invocations of the List stub, `get` and `isEmpty`, where it was one. + * 190 since the ancestor rule: `super.post(document)` (LedgerAdapter.java:13), dropped before, is an invocation of the LedgerClient stub naming `post`. + */ +const EDGES = 190; const STUBS = 27; -/** The edges that touch no stub (MM-6 split only an edge to a stub, so this does not move). */ +/** The edges that touch no stub (MM-6 and the ancestor rule add only edges to a stub, so this does not move). */ const INTERNAL_EDGES = 107; -/** Exactly three edges are the extractor's inference, all module→module imports. */ +/** Four edges are the extractor's inference: three module→module imports and the ancestor-attributed `super.post`. */ const DECLARED_EDGES = 186; const ORDER = "java:com.acme.order"; diff --git a/packages/analyzer/test/load.test.ts b/packages/analyzer/test/load.test.ts index 8bab060f..fa0ce18a 100644 --- a/packages/analyzer/test/load.test.ts +++ b/packages/analyzer/test/load.test.ts @@ -9,8 +9,9 @@ describe("loadModels", () => { expect(union.models).toHaveLength(1); expect(union.langs).toEqual(["java"]); expect(union.entities).toHaveLength(179); - // 189 since MM-6 split Reporting.first's two calls on the List stub (`get`, `isEmpty`). - expect(union.edges).toHaveLength(189); + // 189 since MM-6 split Reporting.first's two calls on the List stub (`get`, `isEmpty`); + // 190 since the ancestor rule kept LedgerAdapter's `super.post` (LedgerClient, `post`). + expect(union.edges).toHaveLength(190); expect(union.sources[0]).toEqual({ index: 0, label: "fixtures/java", lang: "java" }); expect(diagnostics.schemaErrors).toEqual([]); diff --git a/packages/analyzer/test/queries.test.ts b/packages/analyzer/test/queries.test.ts index 6cd0fbc4..d64d0875 100644 --- a/packages/analyzer/test/queries.test.ts +++ b/packages/analyzer/test/queries.test.ts @@ -181,14 +181,16 @@ describe("typeDependencyGraph over the committed Java snapshot", () => { expect(folded.view).toEqual({ name: "all", filters: [] }); }); - it("folds all 189 edges: 178 aggregate into 78 pairs, 11 have no type", () => { + it("folds all 190 edges: 179 aggregate into 78 pairs, 11 have no type", () => { const folded = typeDependencyGraph(graph); expect(folded.edges).toHaveLength(78); expect(folded.nodes).toHaveLength(39); const weight = folded.edges.reduce((sum, e) => sum + e.count, 0); // 178 since MM-6: Reporting.first calls `get` and `isEmpty` on one line, two - // edges that fold into one pair, Reporting → List, of weight 2. - expect(weight).toBe(178); + // edges that fold into one pair, Reporting → List, of weight 2. 179 since the + // ancestor rule: `super.post` adds weight to the existing LedgerAdapter → + // LedgerClient pair (the inheritance), no new pair. + expect(weight).toBe(179); expect(weight).toBe(folded.diagnostics.foldedEdges); // The 11 dropped edges are the module-level imports: a package has no // containing TYPE. Reported, never silently discarded. diff --git a/packages/analyzer/test/views.test.ts b/packages/analyzer/test/views.test.ts index c06edf50..bc61475b 100644 --- a/packages/analyzer/test/views.test.ts +++ b/packages/analyzer/test/views.test.ts @@ -12,8 +12,11 @@ import { } from "../src/views.js"; import { javaGraph } from "./fixture.js"; -/** The Java fixture's edges: 189 since MM-6 split Reporting.first's `get` and `isEmpty` calls on the List stub. */ -const EDGES = 189; +/** + * The Java fixture's edges: 189 since MM-6 split Reporting.first's `get` and `isEmpty` calls on the List stub; + * 190 since the ancestor rule made LedgerAdapter's `super.post(document)` a derived invocation of the LedgerClient stub. + */ +const EDGES = 190; describe("views", () => { const graph = javaGraph(); @@ -40,8 +43,9 @@ describe("views", () => { it("declaredOnly keeps facts and drops inferences", () => { const projection = projectView(graph, declaredOnly); expect(projection.edges.every((edge) => edge.provenance === "declared")).toBe(true); - // The Java module -> module import edges are the extractor's inference. - expect(projection.edges).toHaveLength(EDGES - 3); + // The Java module -> module import edges and the ancestor-attributed + // `super.post` are the extractor's inference. + expect(projection.edges).toHaveLength(EDGES - 4); expect( projection.edges.some( (edge) => edge.from === "java:com.acme.order" && edge.to === "java:com.megacorp.ledger", @@ -83,7 +87,7 @@ describe("views", () => { it("provenanceOnly generalizes the facts-only filter", () => { const derived = projectView(graph, provenanceOnly("derived")); - expect(derived.edges).toHaveLength(3); + expect(derived.edges).toHaveLength(4); expect(derived.view.name).toBe("provenance:derived"); const both = projectView(graph, provenanceOnly("declared", "derived")); expect(both.edges).toHaveLength(EDGES); @@ -132,8 +136,9 @@ describe("view arithmetic and purity", () => { it("internalOnly removes exactly the edges touching a stub", () => { const stubs = new Set(stubIds); const touching = graph.edges.filter((e) => stubs.has(e.from) || stubs.has(e.to)); - // 82 since MM-6 split one edge to the List stub in two. - expect(touching).toHaveLength(82); + // 82 since MM-6 split one edge to the List stub in two; 83 since the ancestor + // rule added LedgerAdapter.post → LedgerClient (`super.post`). + expect(touching).toHaveLength(83); const kept = projectView(graph, internalOnly).edges; expect(kept).toHaveLength(EDGES - touching.length); expect(kept.some((e) => touching.includes(e))).toBe(false); @@ -147,14 +152,21 @@ describe("view arithmetic and purity", () => { it("declaredOnly drops exactly the derived edges", () => { const derived = graph.edges.filter((e) => e.provenance !== "declared"); - expect(derived).toHaveLength(3); + expect(derived).toHaveLength(4); expect(derived.map((e) => [e.edge, e.from, e.to, e.provenance])).toEqual([ ["import", "java:com.acme.order", "java:com.megacorp.ledger", "derived"], ["import", "java:com.acme.order", "java:com.megacorp.ledger", "derived"], ["import", "java:com.acme.order.adapter", "java:com.megacorp.ledger", "derived"], + // `super.post(document)`: the one library ancestor that could answer. + [ + "invocation", + "java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)", + "java:com.megacorp.ledger/LedgerClient", + "derived", + ], ]); const kept = projectView(graph, declaredOnly).edges; - expect(kept).toHaveLength(EDGES - 3); + expect(kept).toHaveLength(EDGES - 4); for (const inferred of derived) expect(kept).not.toContain(inferred); // Entities are untouched: declaredOnly filters edges only. expect(projectView(graph, declaredOnly).entities).toHaveLength(179); diff --git a/packages/cli/test/analyze.test.ts b/packages/cli/test/analyze.test.ts index f7f1787c..3d0c8a2d 100644 --- a/packages/cli/test/analyze.test.ts +++ b/packages/cli/test/analyze.test.ts @@ -477,11 +477,13 @@ describe("--json carries the same information as the text form (decision 8)", () it("reports the fold diagnostics the stderr note states", () => { const payload = jsonOf({ report: "coupling", level: "type" }); // 177 → 178 and 183 → 184 since MM-6: Reporting.first's two calls on the List - // stub are two edges, which fold into the one pair they were before. - expect(payload["foldDiagnostics"]).toMatchObject({ droppedEdges: 11, foldedEdges: 178 }); + // stub are two edges, which fold into the one pair they were before. 178 → 179 and + // 184 → 185 since the ancestor rule: LedgerAdapter's `super.post` folds into the + // LedgerAdapter → LedgerClient pair (and adapter → ledger) its inheritance already made. + expect(payload["foldDiagnostics"]).toMatchObject({ droppedEdges: 11, foldedEdges: 179 }); expect(jsonOf({ report: "coupling", level: "module" })["foldDiagnostics"]).toMatchObject({ droppedEdges: 5, - foldedEdges: 184, + foldedEdges: 185, }); }); @@ -502,13 +504,13 @@ describe("stream discipline and exit codes (decisions 2 and 3)", () => { it("keeps the fold diagnostics on stderr, never in the artifact", () => { const result = analyze({ report: "deps", level: "type" }); expect(result.stderr).toContain("11 dropped (an endpoint has no type container in this view)"); - expect(result.stderr).toContain("178 base edges aggregated into 78"); + expect(result.stderr).toContain("179 base edges aggregated into 78"); expect(result.stdout).not.toContain("dropped ("); }); it("reports the module fold's 5 dropped edges — a smaller graph is never silent", () => { expect(analyze({ report: "coupling", level: "module" }).stderr).toContain( - "fold(module): 184 base edges aggregated into 14; 5 dropped", + "fold(module): 185 base edges aggregated into 14; 5 dropped", ); }); diff --git a/packages/cli/test/e2e-json-parity.test.ts b/packages/cli/test/e2e-json-parity.test.ts index 1dcb7cbc..31ad54a7 100644 --- a/packages/cli/test/e2e-json-parity.test.ts +++ b/packages/cli/test/e2e-json-parity.test.ts @@ -108,9 +108,9 @@ describe("validate says the same thing in both forms", () => { valuesUnderKey(parsed, /.*/).filter((value): value is number => typeof value === "number"), ); expect(numbers, "the JSON form must state how many entities were validated").toContain(179); - expect(numbers, "the JSON form must state how many edges were validated").toContain(189); + expect(numbers, "the JSON form must state how many edges were validated").toContain(190); expect(text.stdout).toContain("179"); - expect(text.stdout).toContain("189"); + expect(text.stdout).toContain("190"); }); }); diff --git a/packages/cli/test/golden/explain/java-max-scc-1/model.insights.sha256 b/packages/cli/test/golden/explain/java-max-scc-1/model.insights.sha256 index 1db62521..e83cc263 100644 --- a/packages/cli/test/golden/explain/java-max-scc-1/model.insights.sha256 +++ b/packages/cli/test/golden/explain/java-max-scc-1/model.insights.sha256 @@ -1,6 +1,6 @@ {"t":"header","kind":"codegraph.insights/1","generatedBy":"@codegraph/insights","promptVersion":"2","metamodel":"specy.domain/3","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"provider":"openrouter","depth":1,"source":{"paths":["fixtures/java/expected/model.jsonl"],"langs":["java"],"view":{"name":"all","filters":[]}}} i operation java:com.acme.order.adapter/LedgerAdapter.() sha256=07ed4c6b82a42a2b79aa605d9517336e652090101c5047262879fd787a39321b -i operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) sha256=2d7a40bc37cd006b5ddc2a99cb860fcca5f7dd1a95bee8a44a43225d2fb0acc4 +i operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) sha256=343cdb9b244f2be99da4ab968851f35a93b8a5944e7d113d144436e6fc0a24f2 i operation java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List) sha256=2b27036717a091d1878d790880af484f7e28c97fa6a29d4a895b92147edc5b85 i operation java:com.acme.order.legacy/List.head() sha256=19af8cc36c3afeaad4ff5ea6f74735882a84218e4453ef93a251eac4d70a9381 i operation java:com.acme.order.legacy/List.length() sha256=865f35ca351758e6aa8a636aa288715356f8496c96ba521458e00455a6e02583 @@ -56,7 +56,7 @@ i operation java:com.acme.order/Reporting.today() sha256=7afd491566300eb4c7f06e4 i operation java:com.acme.order/StockGuard.() sha256=b366a49b8142e00ac1d109fd9711c356801268362894a5b0efb98440dedaa27e i operation java:com.acme.order/StockGuard.check(int) sha256=b805486d1ac0a7b30202ebf235732d06ea3a65153c20338101b8a38a487610c8 i operation java:com.acme.order/StockGuard.ensure(int) sha256=a4a859bceb2dfc34dc230c59b1df670c531a85c21dae5a6ce6cbc24304203e80 -i type java:com.acme.order.adapter/LedgerAdapter sha256=ee764b41bc9af651e8bd4799d9bd7eb0767130815281ef88ddfacc73241b0cfc +i type java:com.acme.order.adapter/LedgerAdapter sha256=25c33c6fb03cb24ba83c41dba6d2a43de417e416260e6876a811dc5077b71676 i type java:com.acme.order.legacy/List sha256=d459df9624429226dbacffc8c0ec79cfc32abe8781bbcf85c2a11e4f169acb68 i type java:com.acme.order/AbstractOrder sha256=a8c7d1182dd26a4abeac2dd92b2de3524b654c7d04f4bdee7adae06de555bb99 i type java:com.acme.order/Audited sha256=5929f179e296d275a23accd8386caea27ee9ee5b44b40af4fe2820cb4089b604 @@ -76,6 +76,6 @@ i type java:com.acme.order/Priceable sha256=bcd3efb3273f9af691b075ec93e04793b030 i type java:com.acme.order/Reporting sha256=87cd68c3330f08e9096da5d58640fec492d4a5b74b6d86b14e02e727a3f60085 i type java:com.acme.order/StockGuard sha256=b641ff89201c63ed30531ded96ee11d17854a90c33600241df2d03f69b9f5f1e i module java:com.acme.order sha256=0b0839382c4167fe6f0e498c012dcdae692f35525e8c87ec7327173aff735f5f -i module java:com.acme.order.adapter sha256=2771897e09650d9e714f4fcb135f04be430438adc4d2a603a278c586c0f40ee3 +i module java:com.acme.order.adapter sha256=51602051a23022f9fbb76977b4b758a18ed654d1494c14830008ec4ecaa4be53 i module java:com.acme.order.legacy sha256=3a816b142c3d7b225694a9f2ef207659a2657c49bb48714bd9a155e39a5c873e {"t":"eof","counts":{"records":79,"llm":70,"template":9,"reused":0,"failed":0},"usage":{"promptTokens":70000,"completionTokens":4480,"cost":0.01708984375},"generatedAt":"2026-11-21T00:00:00.000Z"} diff --git a/packages/cli/test/golden/explain/java-max-scc-1/plan.jsonl b/packages/cli/test/golden/explain/java-max-scc-1/plan.jsonl index 457732fb..2b19dd03 100644 --- a/packages/cli/test/golden/explain/java-max-scc-1/plan.jsonl +++ b/packages/cli/test/golden/explain/java-max-scc-1/plan.jsonl @@ -1,6 +1,6 @@ -{"kind":"codegraph.explainPlan/1","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"depth":1,"estimates":{"calls":70,"promptTokens":117329,"completionTokens":52415,"byLevel":{"operation":{"calls":48,"promptTokens":78146,"completionTokens":30120,"units":57},"type":{"calls":19,"promptTokens":34193,"completionTokens":15470,"units":17},"module":{"calls":3,"promptTokens":4990,"completionTokens":6825,"units":3}},"byStatus":{"llm":68,"template":9,"reuse":0,"skip-scope":0,"skip-budget":0}},"steps":"77 steps, one per line below"} +{"kind":"codegraph.explainPlan/1","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"depth":1,"estimates":{"calls":70,"promptTokens":117342,"completionTokens":52415,"byLevel":{"operation":{"calls":48,"promptTokens":78159,"completionTokens":30120,"units":57},"type":{"calls":19,"promptTokens":34193,"completionTokens":15470,"units":17},"module":{"calls":3,"promptTokens":4990,"completionTokens":6825,"units":3}},"byStatus":{"llm":68,"template":9,"reuse":0,"skip-scope":0,"skip-budget":0}},"steps":"77 steps, one per line below"} {"id":"java:com.acme.order.adapter/LedgerAdapter.()","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.()"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1599} -{"id":"java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1634} +{"id":"java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1647} {"id":"java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)","level":"operation","members":["java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)"],"layer":0,"status":"template","model":"openai/gpt-5.6-luna","calls":0,"promptTokens":0} {"id":"java:com.acme.order.legacy/List.head()","level":"operation","members":["java:com.acme.order.legacy/List.head()"],"layer":0,"status":"template","model":"openai/gpt-5.6-luna","calls":0,"promptTokens":0} {"id":"java:com.acme.order.legacy/List.length()","level":"operation","members":["java:com.acme.order.legacy/List.length()"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1584} diff --git a/packages/cli/test/golden/explain/java-max-scc-1/prompts-planned.sha256 b/packages/cli/test/golden/explain/java-max-scc-1/prompts-planned.sha256 index 1b3c2d98..95885489 100644 --- a/packages/cli/test/golden/explain/java-max-scc-1/prompts-planned.sha256 +++ b/packages/cli/test/golden/explain/java-max-scc-1/prompts-planned.sha256 @@ -1,5 +1,5 @@ 1 operation java:com.acme.order.adapter/LedgerAdapter.() codegraph_operation system=dc45667c9ad4bd03 user=8732c876634573ebc4e7a0a87ad9e4529abda1ae8b0b795d46f4539c6dc296f6 -2 operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) codegraph_operation system=dc45667c9ad4bd03 user=ab4cec9757e684cfb1e430665c373ab47b2c95c2819999e8f9c0cd19b5a9199d +2 operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) codegraph_operation system=dc45667c9ad4bd03 user=febb011f7806f071e637f07f61cdb9fc4c083abad39630fa0c357089db7f5291 3 operation java:com.acme.order.legacy/List.length() codegraph_operation system=dc45667c9ad4bd03 user=9e009db9e2f27a33f6c311091e4eaa696b1710aadcf23b75977f2048f7d73438 4 operation java:com.acme.order/AbstractOrder.price() codegraph_operation system=dc45667c9ad4bd03 user=9bf9e11b550d5a8d6a29232bd19449b71a6a0d435a37d27af18501848400cd1d 5 operation java:com.acme.order/Audited.value() codegraph_operation system=dc45667c9ad4bd03 user=82ebfc707adc43dedd97d32e47b4d40aa02aa66bb765921a8886fa04f213af10 diff --git a/packages/cli/test/golden/explain/java-max-scc-1/prompts.sha256 b/packages/cli/test/golden/explain/java-max-scc-1/prompts.sha256 index 6d5f3c7c..2a38f5f3 100644 --- a/packages/cli/test/golden/explain/java-max-scc-1/prompts.sha256 +++ b/packages/cli/test/golden/explain/java-max-scc-1/prompts.sha256 @@ -1,5 +1,5 @@ 1 operation java:com.acme.order.adapter/LedgerAdapter.() codegraph_operation system=dc45667c9ad4bd03 user=8732c876634573ebc4e7a0a87ad9e4529abda1ae8b0b795d46f4539c6dc296f6 model=openai/gpt-5.6-luna -2 operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) codegraph_operation system=dc45667c9ad4bd03 user=ab4cec9757e684cfb1e430665c373ab47b2c95c2819999e8f9c0cd19b5a9199d model=openai/gpt-5.6-luna +2 operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) codegraph_operation system=dc45667c9ad4bd03 user=febb011f7806f071e637f07f61cdb9fc4c083abad39630fa0c357089db7f5291 model=openai/gpt-5.6-luna 3 operation java:com.acme.order.legacy/List.length() codegraph_operation system=dc45667c9ad4bd03 user=9e009db9e2f27a33f6c311091e4eaa696b1710aadcf23b75977f2048f7d73438 model=openai/gpt-5.6-luna 4 operation java:com.acme.order/AbstractOrder.price() codegraph_operation system=dc45667c9ad4bd03 user=9bf9e11b550d5a8d6a29232bd19449b71a6a0d435a37d27af18501848400cd1d model=openai/gpt-5.6-luna 5 operation java:com.acme.order/Audited.value() codegraph_operation system=dc45667c9ad4bd03 user=82ebfc707adc43dedd97d32e47b4d40aa02aa66bb765921a8886fa04f213af10 model=openai/gpt-5.6-luna diff --git a/packages/cli/test/golden/explain/java-max-scc-1/units.txt b/packages/cli/test/golden/explain/java-max-scc-1/units.txt index f598c1a5..5cfa5f84 100644 --- a/packages/cli/test/golden/explain/java-max-scc-1/units.txt +++ b/packages/cli/test/golden/explain/java-max-scc-1/units.txt @@ -1,5 +1,5 @@ operation java:com.acme.order.adapter/LedgerAdapter.() llm fingerprint=6302a188842d9edc128da6bc61a553414de1ae9ea87461a9022ea7f6b694db2d chain=a33628ab88428f027b455b3fc5ed8039c4ca2b2239bc9cddddc8c252c48709a5 -operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) llm fingerprint=d482fc2440b20f13edaa908642428095cb96da95739aef7f7214b1354500a3ab chain=32edb856f6591fa9eab56025fb3af8bb1848c7810db228ca68ddd677910a5dce +operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) llm fingerprint=e543cbd5cc0e3afc77fd5d1b9e297acb1e1dfff052bb9fd2f2022ffe039a5076 chain=d636fe5166825bb98d2ad46e1234c212984c771a145fb9b35887dd4fa891d95b operation java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List) template (trivialConstructor) fingerprint=d5fa5c347f7736585649e3e3d97bd901b5a904999e597398aeeec789777e4a85 chain=76552b6693c59a259c92cac02efce3c6e13e87a5742b68ea24bf2b2ae48ec988 operation java:com.acme.order.legacy/List.head() template (getter) fingerprint=4c10fcfbf329ec4699a5b727b9309fc96e449e1fb0927e388f0d681c83d333b5 chain=58e039e580bce8fe86e72d2e416e7b6bcb56437ef371b6173171833bba2881d9 operation java:com.acme.order.legacy/List.length() llm fingerprint=ede9d0077c5f8d5caee781a5cc81abd24c237713e547eb8bb2d34288ce57e25a chain=6588e25b050f8e2a29d9968c91535c3bd076d8c57f0c841062272b97dc8b8505 @@ -39,7 +39,7 @@ operation java:com.acme.order/Reporting.max(java.util.List) llm fingerprint=23e3 operation java:com.acme.order/Reporting.today() llm fingerprint=7cb499045ddeac3965d4db8bad638482e3af78376735d94a3ca1644ab8a45f45 chain=a1026703ea36dc2b8688675014a71f7965bff78d4c499596a4fc2855568025c3 operation java:com.acme.order/StockGuard.() llm fingerprint=4efe29199de9fd0320091f6ffbd5d0b59a456efffc2641ca55ee95d9ecfb5309 chain=16fce8e911f74ad78b890c1d370b1ce46d07b3c429e9df86392698c57f9e185f operation java:com.acme.order/StockGuard.check(int) llm fingerprint=946a83ff45648c4e23ec621230960733dc570493980958fbcb709a29aa1929d5 chain=8a49446a4e653cd95ca9e4ba842ae3704f5ef6d153f20c359e87ef53c29abffe -type java:com.acme.order.adapter/LedgerAdapter llm fingerprint=de6f642b25bea68047476a0c1ca175c6ac9d6523f50595c3f52bcb86993b80b4 chain=406b67473376c04f581e10511ec9cb17a396911c9343426009dd89326a2aa5f9 stamped=6308c19643d34fba7586c53018cb1b26efc35a801a2769c93e2a3e88ef8f37b9 +type java:com.acme.order.adapter/LedgerAdapter llm fingerprint=f0470a8ecf493b91d31618812ce56a914e4c597bc0a31331102fbd425582c4a2 chain=44497be4a3040bbe2fd172e5d48d8a3c918d035fca490f60bc1fd22b86550f17 stamped=970857c46079c66c6b453b0ec06cfb95ff7b6727aa9482f715cb85c5fda58d42 type java:com.acme.order.legacy/List llm fingerprint=39af6c37e0aaed403a8d56b303c6e6fa820eef4538dd81b8f2c35ce63766d2d2 chain=6e7c6b5ac71e58f751d71bd3eaeda9c9463743197aef5553bbb104bdb169a54a stamped=f7d9ef8d7b23e659b9de3a01da94fc4a682260e402db5fa5701693a53063c37b type java:com.acme.order/Audited llm fingerprint=27f0929bda9b960c7a7725e337a302d5869a1623cc0672f362ccffdcaf2adbae chain=d6a3407f72319e492e0e651663588fedc7659fe9cde7d0954664d9c92caee409 stamped=dcbf0bbd0798b8fa740ad5973e531534629d494f86d3de7a7d443311010e39fb type java:com.acme.order/Basket.Line.Discount llm fingerprint=357314b8d07565ed4e6d8da9457c772977501df93e59db75b18cbdc95fe813d0 chain=c8261d4d1759978ccd7dc41f69a4e1b7eb9adecdbc701eccb650569336a4086b stamped=b4307f557435f1048e9423a35dd767c478439220fddadec5d5d9cbf0ba588fd9 @@ -53,7 +53,7 @@ operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) l operation java:com.acme.order/OrderService.archive(java.util.List) llm fingerprint=5014c95fd755888907ec4b1f8148ba250f81792cc80046234f8efc6562489979 chain=de018c799d2b0031de3a25a2d444af86dc9365fa768e2f3bcccaa92f02efa147 stamped=22ec4347bac0df33543ed198bc351418e00c8a4fbb029dbf8ca0564e0cc6349c operation java:com.acme.order/OrderService.bill(com.acme.order.Order) llm fingerprint=c229926c94a504cfc95904666c6a13e450cb391710008f7d9f71070ad660dbbd chain=ae243cd612510f274a13ed96f983bacc0470236e7d57b0b6f5bfb0f826ac88ee stamped=c23efc407657d4bf30d8a526d82578f2295bb4a396962f6274eabfc8ee01d6e9 operation java:com.acme.order/StockGuard.ensure(int) llm fingerprint=4b670b6e7e7cd2270199477474ed04bda7ec1eea956f520921ab25af7e9c6787 chain=56372d54bdadac7dd6fc038fafddde2ba5f24f753ec0d220e362708aa6806fbc stamped=2d1c4136a0e310922e00980d8db38d9c43a6d242a44242e731ded007c0543176 -module java:com.acme.order.adapter llm fingerprint=10ee6e8539c02125d3c80dc3f02fe2bb19463f8a86058a8704ee7bd6fd71a547 chain=db08005858d5a99138b40dac475f0d7a50ed054d0fc55b26ad101a8752cdefe2 stamped=44b0273a83a6fd3cc0b3d13413e03bf38573883a4e75b417fdfac235c80e62ee +module java:com.acme.order.adapter llm fingerprint=cefb6fd8308187787e107595b7c9c371cabe8f28589d800396b0c69916f4496e chain=ff47c9fe75385ca90db5b32647424d2fad301757661a0f1453d311f1878b30a4 stamped=72f4ce44c00f52bf9383124dbdfc9359ce7924210e861f6e20c9d74483c36bf0 module java:com.acme.order.legacy llm fingerprint=35a959fc1c2d2ae9863563dced8e8aa22718ed45ce4af6b0f57140b45aeceb53 chain=5863e82396f5a658600bf4e2e3d51a627477bdc023150e78598159095eda23f0 stamped=95664a806624fdfdf835a7f18becc03dc8b718779c9247cde1608ae97a24266e operation java:com.acme.order/AbstractOrder.(java.lang.String) llm fingerprint=692ca8a5882ced05c3e6c90bfe8e0bb966d71916863533de50707801dcda677f chain=618580d4ac5ea6b6ef5da53b0a15a19dadf611e70aa187e73825b398ddd445a3 stamped=7ec9001d3e69e35ea44e4ece46667ee572ba3a7c6fa14419e4ba5227c29c2653 type java:com.acme.order/Basket.Line llm fingerprint=ef17220316e16357fc7588cffb1c903cb7d7693aee0ae3b0130accd38506a868 chain=aa00575901d5dfc540987c4aeb41a746a5d93c8aa00ba1f2a7f7126003d6552f stamped=5f4095eae126943b5a55fcc7a3d37c0a274bf4ca6aeb45e73411e7a9a5825730 diff --git a/packages/cli/test/golden/explain/java-scope-order/units.txt b/packages/cli/test/golden/explain/java-scope-order/units.txt index d73bd8cf..e84c11c2 100644 --- a/packages/cli/test/golden/explain/java-scope-order/units.txt +++ b/packages/cli/test/golden/explain/java-scope-order/units.txt @@ -1,5 +1,5 @@ operation java:com.acme.order.adapter/LedgerAdapter.() skip-scope fingerprint=6302a188842d9edc128da6bc61a553414de1ae9ea87461a9022ea7f6b694db2d chain=a33628ab88428f027b455b3fc5ed8039c4ca2b2239bc9cddddc8c252c48709a5 -operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) skip-scope fingerprint=d482fc2440b20f13edaa908642428095cb96da95739aef7f7214b1354500a3ab chain=32edb856f6591fa9eab56025fb3af8bb1848c7810db228ca68ddd677910a5dce +operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) skip-scope fingerprint=e543cbd5cc0e3afc77fd5d1b9e297acb1e1dfff052bb9fd2f2022ffe039a5076 chain=d636fe5166825bb98d2ad46e1234c212984c771a145fb9b35887dd4fa891d95b operation java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List) template (trivialConstructor) fingerprint=d5fa5c347f7736585649e3e3d97bd901b5a904999e597398aeeec789777e4a85 chain=76552b6693c59a259c92cac02efce3c6e13e87a5742b68ea24bf2b2ae48ec988 operation java:com.acme.order.legacy/List.head() template (getter) fingerprint=4c10fcfbf329ec4699a5b727b9309fc96e449e1fb0927e388f0d681c83d333b5 chain=58e039e580bce8fe86e72d2e416e7b6bcb56437ef371b6173171833bba2881d9 operation java:com.acme.order.legacy/List.length() skip-scope fingerprint=ede9d0077c5f8d5caee781a5cc81abd24c237713e547eb8bb2d34288ce57e25a chain=6588e25b050f8e2a29d9968c91535c3bd076d8c57f0c841062272b97dc8b8505 @@ -39,7 +39,7 @@ operation java:com.acme.order/Reporting.max(java.util.List) llm fingerprint=23e3 operation java:com.acme.order/Reporting.today() llm fingerprint=7cb499045ddeac3965d4db8bad638482e3af78376735d94a3ca1644ab8a45f45 chain=a1026703ea36dc2b8688675014a71f7965bff78d4c499596a4fc2855568025c3 operation java:com.acme.order/StockGuard.() llm fingerprint=4efe29199de9fd0320091f6ffbd5d0b59a456efffc2641ca55ee95d9ecfb5309 chain=16fce8e911f74ad78b890c1d370b1ce46d07b3c429e9df86392698c57f9e185f operation java:com.acme.order/StockGuard.check(int) llm fingerprint=946a83ff45648c4e23ec621230960733dc570493980958fbcb709a29aa1929d5 chain=8a49446a4e653cd95ca9e4ba842ae3704f5ef6d153f20c359e87ef53c29abffe -type java:com.acme.order.adapter/LedgerAdapter skip-scope fingerprint=59c162383f64841517f84ed1531c74594c1371b1e38375fe6d219f64c81de657 chain=7f77fa7a4168e9ac4f92497b03040e3ae49beac1c21ca5d25df90aa2604d93f5 stamped=24b1babf490b29bb18a09401be4ba92a501c8541d1198ed5771ce56c79736c12 +type java:com.acme.order.adapter/LedgerAdapter skip-scope fingerprint=b0a194bdb1533009ce568a090fd6abca565fce1a58685748b88704857c89ebe6 chain=48d42702b3f1e382099c90e764557702c63c3f5942cd3404be2aa1820c509506 stamped=1c622fd3c811e1dfd275b603db93e0845e07584b01285054c4fe887aac88dff2 type java:com.acme.order.legacy/List skip-scope fingerprint=77692d3ea7fd503b073c8c8a875b0a8dd710c40f21928d11125894cd71b51065 chain=55b0f5b03aa417d3a72f0e380763598d189829f260b750df52d787305491d997 stamped=638af1f80aec537cbf0ec798c8c07bfcca336f169d75fe8c1508d7ad7253f776 type java:com.acme.order/Audited llm fingerprint=27f0929bda9b960c7a7725e337a302d5869a1623cc0672f362ccffdcaf2adbae chain=d6a3407f72319e492e0e651663588fedc7659fe9cde7d0954664d9c92caee409 stamped=dcbf0bbd0798b8fa740ad5973e531534629d494f86d3de7a7d443311010e39fb type java:com.acme.order/Basket.Line.Discount llm fingerprint=357314b8d07565ed4e6d8da9457c772977501df93e59db75b18cbdc95fe813d0 chain=c8261d4d1759978ccd7dc41f69a4e1b7eb9adecdbc701eccb650569336a4086b stamped=b4307f557435f1048e9423a35dd767c478439220fddadec5d5d9cbf0ba588fd9 @@ -53,7 +53,7 @@ operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) l operation java:com.acme.order/OrderService.archive(java.util.List) llm fingerprint=5014c95fd755888907ec4b1f8148ba250f81792cc80046234f8efc6562489979 chain=de018c799d2b0031de3a25a2d444af86dc9365fa768e2f3bcccaa92f02efa147 stamped=22ec4347bac0df33543ed198bc351418e00c8a4fbb029dbf8ca0564e0cc6349c operation java:com.acme.order/OrderService.bill(com.acme.order.Order) llm fingerprint=c229926c94a504cfc95904666c6a13e450cb391710008f7d9f71070ad660dbbd chain=ae243cd612510f274a13ed96f983bacc0470236e7d57b0b6f5bfb0f826ac88ee stamped=c23efc407657d4bf30d8a526d82578f2295bb4a396962f6274eabfc8ee01d6e9 operation java:com.acme.order/StockGuard.ensure(int) llm fingerprint=4b670b6e7e7cd2270199477474ed04bda7ec1eea956f520921ab25af7e9c6787 chain=56372d54bdadac7dd6fc038fafddde2ba5f24f753ec0d220e362708aa6806fbc stamped=2d1c4136a0e310922e00980d8db38d9c43a6d242a44242e731ded007c0543176 -module java:com.acme.order.adapter skip-scope fingerprint=67d2af6d651b942fb0286f271fc5b2e114acc3bc8463d78263576501513d1982 chain=3fc1dbb915bb844b88b5fc1324e4c077612fafb909cca64666f5c6731c804342 stamped=c98074ddc5920b8aa6a10eeaead91823ff9784943634722e6e7f85477e66eb91 +module java:com.acme.order.adapter skip-scope fingerprint=d31d3351b5edb7aba06eba6da5ad31f61ff2d49cbdb16838d787c25550bb9b14 chain=af4d70e7ef47a0f1318b5b966307ae688158f5f20be10f8a223db86dbf61d6d1 stamped=94c96afc756576ce74d2a29c8d178ef13256df50ae06dae1a70f166f0c7582b1 module java:com.acme.order.legacy skip-scope fingerprint=3f28ea1d3083e343f9e47eed3b21072d0d52fdc7666cff698f44076d2386c7bc chain=30632755691dd75a662ca5c71b4b17078b481d7acf00a7f1b8316cd7b9b9aaa4 stamped=ab3ac3f6ded03452320b03791cf85a3e824b7eaaeb685dd9259de5a7e6a21c92 operation java:com.acme.order/AbstractOrder.(java.lang.String) llm fingerprint=692ca8a5882ced05c3e6c90bfe8e0bb966d71916863533de50707801dcda677f chain=618580d4ac5ea6b6ef5da53b0a15a19dadf611e70aa187e73825b398ddd445a3 stamped=7ec9001d3e69e35ea44e4ece46667ee572ba3a7c6fa14419e4ba5227c29c2653 type java:com.acme.order/Basket.Line llm fingerprint=ef17220316e16357fc7588cffb1c903cb7d7693aee0ae3b0130accd38506a868 chain=aa00575901d5dfc540987c4aeb41a746a5d93c8aa00ba1f2a7f7126003d6552f stamped=5f4095eae126943b5a55fcc7a3d37c0a274bf4ca6aeb45e73411e7a9a5825730 diff --git a/packages/cli/test/golden/explain/java/model.insights.jsonl b/packages/cli/test/golden/explain/java/model.insights.jsonl index ebe78a46..3539c8f5 100644 --- a/packages/cli/test/golden/explain/java/model.insights.jsonl +++ b/packages/cli/test/golden/explain/java/model.insights.jsonl @@ -1,6 +1,6 @@ {"t":"header","kind":"codegraph.insights/1","generatedBy":"@codegraph/insights","promptVersion":"2","metamodel":"specy.domain/3","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"provider":"openrouter","depth":1,"source":{"paths":["fixtures/java/expected/model.jsonl"],"langs":["java"],"view":{"name":"all","filters":[]}}} {"t":"i","id":"java:com.acme.order.adapter/LedgerAdapter.()","key":{"lang":"java","module":"com.acme.order.adapter","symbol":"LedgerAdapter.()"},"level":"operation","kind":"constructor","file":"com/acme/order/adapter/LedgerAdapter.java","origin":"llm","block":{"name":"LedgerAdapter.()","description":"Operation LedgerAdapter.().","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[],"confidence":0.5},"fingerprint":"6302a188842d9edc128da6bc61a553414de1ae9ea87461a9022ea7f6b694db2d","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} -{"t":"i","id":"java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)","key":{"lang":"java","module":"com.acme.order.adapter","symbol":"LedgerAdapter.post(java.lang.Object)"},"level":"operation","kind":"method","name":"post","file":"com/acme/order/adapter/LedgerAdapter.java","origin":"llm","block":{"name":"LedgerAdapter.post(java.lang.Object)","description":"Operation LedgerAdapter.post(java.lang.Object).","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"post","in":["post"],"concern":"domain","sense":"post","meaning":"post in LedgerAdapter.post(java.lang.Object).","confidence":0.5},{"word":"document","in":["document"],"concern":"domain","sense":"document","meaning":"document in LedgerAdapter.post(java.lang.Object).","confidence":0.5}],"confidence":0.5},"fingerprint":"d482fc2440b20f13edaa908642428095cb96da95739aef7f7214b1354500a3ab","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} +{"t":"i","id":"java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)","key":{"lang":"java","module":"com.acme.order.adapter","symbol":"LedgerAdapter.post(java.lang.Object)"},"level":"operation","kind":"method","name":"post","file":"com/acme/order/adapter/LedgerAdapter.java","origin":"llm","block":{"name":"LedgerAdapter.post(java.lang.Object)","description":"Operation LedgerAdapter.post(java.lang.Object).","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"post","in":["post"],"concern":"domain","sense":"post","meaning":"post in LedgerAdapter.post(java.lang.Object).","confidence":0.5},{"word":"document","in":["document"],"concern":"domain","sense":"document","meaning":"document in LedgerAdapter.post(java.lang.Object).","confidence":0.5}],"confidence":0.5},"fingerprint":"e543cbd5cc0e3afc77fd5d1b9e297acb1e1dfff052bb9fd2f2022ffe039a5076","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)","key":{"lang":"java","module":"com.acme.order.legacy","symbol":"List.(java.lang.String,com.acme.order.legacy.List)"},"level":"operation","kind":"constructor","file":"com/acme/order/legacy/List.java","origin":"template","block":{"name":"List","description":"Constructor: assigns the fields of `List` (`head`, `tail`).","safe":false,"idempotent":false,"owner":"unknown","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":["head","tail"],"confidence":1},"fingerprint":"d5fa5c347f7736585649e3e3d97bd901b5a904999e597398aeeec789777e4a85"} {"t":"i","id":"java:com.acme.order.legacy/List.head()","key":{"lang":"java","module":"com.acme.order.legacy","symbol":"List.head()"},"level":"operation","kind":"method","name":"head","file":"com/acme/order/legacy/List.java","origin":"template","block":{"name":"head","description":"Getter: returns the `head` field of `List`.","safe":true,"idempotent":true,"owner":"unknown","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":["head"],"confidence":1},"fingerprint":"4c10fcfbf329ec4699a5b727b9309fc96e449e1fb0927e388f0d681c83d333b5"} {"t":"i","id":"java:com.acme.order.legacy/List.length()","key":{"lang":"java","module":"com.acme.order.legacy","symbol":"List.length()"},"level":"operation","kind":"method","name":"length","file":"com/acme/order/legacy/List.java","origin":"llm","block":{"name":"List.length()","description":"Operation List.length().","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"length","in":["length"],"concern":"domain","sense":"length","meaning":"length in List.length().","confidence":0.5}],"confidence":0.5},"fingerprint":"ede9d0077c5f8d5caee781a5cc81abd24c237713e547eb8bb2d34288ce57e25a","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} @@ -56,7 +56,7 @@ {"t":"i","id":"java:com.acme.order/StockGuard.()","key":{"lang":"java","module":"com.acme.order","symbol":"StockGuard.()"},"level":"operation","kind":"constructor","file":"com/acme/order/StockGuard.java","origin":"llm","block":{"name":"StockGuard.()","description":"Operation StockGuard.().","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[],"confidence":0.5},"fingerprint":"4efe29199de9fd0320091f6ffbd5d0b59a456efffc2641ca55ee95d9ecfb5309","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/StockGuard.check(int)","key":{"lang":"java","module":"com.acme.order","symbol":"StockGuard.check(int)"},"level":"operation","kind":"method","name":"check","file":"com/acme/order/StockGuard.java","origin":"llm","block":{"name":"StockGuard.check(int)","description":"Operation StockGuard.check(int).","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"check","in":["check"],"concern":"domain","sense":"check","meaning":"check in StockGuard.check(int).","confidence":0.5},{"word":"quantity","in":["quantity"],"concern":"domain","sense":"quantity","meaning":"quantity in StockGuard.check(int).","confidence":0.5}],"confidence":0.5},"fingerprint":"946a83ff45648c4e23ec621230960733dc570493980958fbcb709a29aa1929d5","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/StockGuard.ensure(int)","key":{"lang":"java","module":"com.acme.order","symbol":"StockGuard.ensure(int)"},"level":"operation","kind":"method","name":"ensure","file":"com/acme/order/StockGuard.java","origin":"llm","block":{"name":"StockGuard.ensure(int)","description":"Operation StockGuard.ensure(int).","safe":true,"idempotent":null,"owner":"entity","handlesCommand":null,"emits":[],"preconditions":[],"postconditions":[],"invariantsEnforced":[],"usesSpi":[],"domainTerms":[],"words":[{"word":"ensure","in":["ensure"],"concern":"domain","sense":"ensure","meaning":"ensure in StockGuard.ensure(int).","confidence":0.5},{"word":"quantity","in":["quantity"],"concern":"domain","sense":"quantity","meaning":"quantity in StockGuard.ensure(int).","confidence":0.5}],"confidence":0.5},"fingerprint":"4b670b6e7e7cd2270199477474ed04bda7ec1eea956f520921ab25af7e9c6787","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} -{"t":"i","id":"java:com.acme.order.adapter/LedgerAdapter","key":{"lang":"java","module":"com.acme.order.adapter","symbol":"LedgerAdapter"},"level":"type","kind":"class","name":"LedgerAdapter","file":"com/acme/order/adapter/LedgerAdapter.java","origin":"llm","block":{"name":"LedgerAdapter","description":"Type LedgerAdapter.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"ledger","in":["LedgerAdapter"],"concern":"domain","sense":"ledger","meaning":"ledger in LedgerAdapter.","confidence":0.5},{"word":"adapter","in":["LedgerAdapter"],"concern":"domain","sense":"adapter","meaning":"adapter in LedgerAdapter.","confidence":0.5},{"word":"trail","in":["trail"],"concern":"domain","sense":"trail","meaning":"trail in LedgerAdapter.","confidence":0.5}],"confidence":0.5},"fingerprint":"de6f642b25bea68047476a0c1ca175c6ac9d6523f50595c3f52bcb86993b80b4","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} +{"t":"i","id":"java:com.acme.order.adapter/LedgerAdapter","key":{"lang":"java","module":"com.acme.order.adapter","symbol":"LedgerAdapter"},"level":"type","kind":"class","name":"LedgerAdapter","file":"com/acme/order/adapter/LedgerAdapter.java","origin":"llm","block":{"name":"LedgerAdapter","description":"Type LedgerAdapter.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"ledger","in":["LedgerAdapter"],"concern":"domain","sense":"ledger","meaning":"ledger in LedgerAdapter.","confidence":0.5},{"word":"adapter","in":["LedgerAdapter"],"concern":"domain","sense":"adapter","meaning":"adapter in LedgerAdapter.","confidence":0.5},{"word":"trail","in":["trail"],"concern":"domain","sense":"trail","meaning":"trail in LedgerAdapter.","confidence":0.5}],"confidence":0.5},"fingerprint":"f0470a8ecf493b91d31618812ce56a914e4c597bc0a31331102fbd425582c4a2","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order.legacy/List","key":{"lang":"java","module":"com.acme.order.legacy","symbol":"List"},"level":"type","kind":"class","name":"List","file":"com/acme/order/legacy/List.java","origin":"llm","block":{"name":"List","description":"Type List.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"list","in":["List"],"concern":"domain","sense":"list","meaning":"list in List.","confidence":0.5},{"word":"head","in":["head"],"concern":"domain","sense":"head","meaning":"head in List.","confidence":0.5},{"word":"tail","in":["tail"],"concern":"domain","sense":"tail","meaning":"tail in List.","confidence":0.5}],"confidence":0.5},"fingerprint":"39af6c37e0aaed403a8d56b303c6e6fa820eef4538dd81b8f2c35ce63766d2d2","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/AbstractOrder","key":{"lang":"java","module":"com.acme.order","symbol":"AbstractOrder"},"level":"type","kind":"class","name":"AbstractOrder","file":"com/acme/order/AbstractOrder.java","origin":"llm","block":{"name":"AbstractOrder","description":"Type AbstractOrder.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"order","in":["AbstractOrder"],"concern":"domain","sense":"order","meaning":"order in AbstractOrder.","confidence":0.5},{"word":"reference","in":["reference"],"concern":"domain","sense":"reference","meaning":"reference in AbstractOrder.","confidence":0.5},{"word":"total","in":["total"],"concern":"domain","sense":"total","meaning":"total in AbstractOrder.","confidence":0.5}],"confidence":0.5},"fingerprint":"207ca5d95fab853c713af0ac32a8a7702bdb68fea776448425d6d6759d4d04ba","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/Audited","key":{"lang":"java","module":"com.acme.order","symbol":"Audited"},"level":"type","kind":"annotation","name":"Audited","file":"com/acme/order/Audited.java","origin":"llm","block":{"name":"Audited","description":"Type Audited.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"audited","in":["Audited"],"concern":"domain","sense":"audited","meaning":"audited in Audited.","confidence":0.5}],"confidence":0.5},"fingerprint":"27f0929bda9b960c7a7725e337a302d5869a1623cc0672f362ccffdcaf2adbae","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} @@ -76,6 +76,6 @@ {"t":"i","id":"java:com.acme.order/Reporting","key":{"lang":"java","module":"com.acme.order","symbol":"Reporting"},"level":"type","kind":"class","name":"Reporting","file":"com/acme/order/Reporting.java","origin":"llm","block":{"name":"Reporting","description":"Type Reporting.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"reporting","in":["Reporting"],"concern":"domain","sense":"reporting","meaning":"reporting in Reporting.","confidence":0.5}],"confidence":0.5},"fingerprint":"59fccba95d1271f51f41a77609dc338697c72e76ecf6be77b7038e2b7bf2946d","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order/StockGuard","key":{"lang":"java","module":"com.acme.order","symbol":"StockGuard"},"level":"type","kind":"class","name":"StockGuard","file":"com/acme/order/StockGuard.java","origin":"llm","block":{"name":"StockGuard","description":"Type StockGuard.","concept":"entity","eventKind":null,"interfaceRole":null,"aggregateRoot":null,"containedIn":null,"syncPattern":null,"identity":null,"fields":[],"invariants":[],"stateMachine":null,"relatesTo":[],"exposes":[],"dependsOn":[],"domainTerms":[],"words":[{"word":"stock","in":["StockGuard"],"concern":"domain","sense":"stock","meaning":"stock in StockGuard.","confidence":0.5},{"word":"guard","in":["StockGuard"],"concern":"domain","sense":"guard","meaning":"guard in StockGuard.","confidence":0.5}],"confidence":0.5},"fingerprint":"0f066f5f08784d5f56ae32aa795c13d767d9f251c3512d72cb14b409e633b464","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order","key":{"lang":"java","module":"com.acme.order","symbol":""},"level":"module","kind":"package","name":"com.acme.order","origin":"llm","block":{"name":"java:com.acme.order","description":"Module java:com.acme.order.","apis":[],"spis":[],"dependsOn":[],"concepts":[],"boundedContextHint":null,"sharedKernelHint":null,"ubiquitousLanguage":[],"words":[{"word":"order","in":["com.acme.order"],"concern":"domain","sense":"order","meaning":"order in java:com.acme.order.","confidence":0.5}],"glossary":[{"word":"order","concern":"domain","sense":"order","meaning":"order in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"basket","concern":"domain","sense":"basket","meaning":"basket in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"channel","concern":"domain","sense":"channel","meaning":"channel in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"discount","concern":"domain","sense":"discount","meaning":"discount in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"cursor","concern":"domain","sense":"cursor","meaning":"cursor in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"lines","concern":"domain","sense":"lines","meaning":"lines in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"total","concern":"domain","sense":"total","meaning":"total in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"reference","concern":"domain","sense":"reference","meaning":"reference in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"amount","concern":"domain","sense":"amount","meaning":"amount in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"line","concern":"domain","sense":"line","meaning":"line in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"audited","concern":"domain","sense":"audited","meaning":"audited in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"batch","concern":"domain","sense":"batch","meaning":"batch in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"cents","concern":"domain","sense":"cents","meaning":"cents in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"discountable","concern":"domain","sense":"discountable","meaning":"discountable in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"empty","concern":"domain","sense":"empty","meaning":"empty in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"exception","concern":"domain","sense":"exception","meaning":"exception in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"guard","concern":"domain","sense":"guard","meaning":"guard in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"money","concern":"domain","sense":"money","meaning":"money in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"notifications","concern":"domain","sense":"notifications","meaning":"notifications in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"priceable","concern":"domain","sense":"priceable","meaning":"priceable in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"reporting","concern":"domain","sense":"reporting","meaning":"reporting in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"service","concern":"domain","sense":"service","meaning":"service in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"stock","concern":"domain","sense":"stock","meaning":"stock in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"max","concern":"domain","sense":"max","meaning":"max in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"shipped","concern":"domain","sense":"shipped","meaning":"shipped in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"counts","concern":"domain","sense":"counts","meaning":"counts in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"ledger","concern":"domain","sense":"ledger","meaning":"ledger in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"prices","concern":"domain","sense":"prices","meaning":"prices in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"index","concern":"domain","sense":"index","meaning":"index in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"phone","concern":"domain","sense":"phone","meaning":"phone in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"store","concern":"domain","sense":"store","meaning":"store in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"trail","concern":"domain","sense":"trail","meaning":"trail in java:com.acme.order.","polysemous":false,"senses":[]},{"word":"web","concern":"domain","sense":"web","meaning":"web in java:com.acme.order.","polysemous":false,"senses":[]}],"confidence":0.5},"fingerprint":"6687324da963a818b521bac404ffdd5252700b36ab84c9de9e93cd0dbf6582f5","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} -{"t":"i","id":"java:com.acme.order.adapter","key":{"lang":"java","module":"com.acme.order.adapter","symbol":""},"level":"module","kind":"package","name":"com.acme.order.adapter","origin":"llm","block":{"name":"java:com.acme.order.adapter","description":"Module java:com.acme.order.adapter.","apis":[],"spis":[],"dependsOn":[],"concepts":[],"boundedContextHint":null,"sharedKernelHint":null,"ubiquitousLanguage":[],"words":[{"word":"adapter","in":["com.acme.order.adapter"],"concern":"domain","sense":"adapter","meaning":"adapter in java:com.acme.order.adapter.","confidence":0.5}],"glossary":[{"word":"adapter","concern":"domain","sense":"adapter","meaning":"adapter in java:com.acme.order.adapter.","polysemous":false,"senses":[]},{"word":"ledger","concern":"domain","sense":"ledger","meaning":"ledger in java:com.acme.order.adapter.","polysemous":false,"senses":[]},{"word":"trail","concern":"domain","sense":"trail","meaning":"trail in java:com.acme.order.adapter.","polysemous":false,"senses":[]}],"confidence":0.5},"fingerprint":"10ee6e8539c02125d3c80dc3f02fe2bb19463f8a86058a8704ee7bd6fd71a547","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} +{"t":"i","id":"java:com.acme.order.adapter","key":{"lang":"java","module":"com.acme.order.adapter","symbol":""},"level":"module","kind":"package","name":"com.acme.order.adapter","origin":"llm","block":{"name":"java:com.acme.order.adapter","description":"Module java:com.acme.order.adapter.","apis":[],"spis":[],"dependsOn":[],"concepts":[],"boundedContextHint":null,"sharedKernelHint":null,"ubiquitousLanguage":[],"words":[{"word":"adapter","in":["com.acme.order.adapter"],"concern":"domain","sense":"adapter","meaning":"adapter in java:com.acme.order.adapter.","confidence":0.5}],"glossary":[{"word":"adapter","concern":"domain","sense":"adapter","meaning":"adapter in java:com.acme.order.adapter.","polysemous":false,"senses":[]},{"word":"ledger","concern":"domain","sense":"ledger","meaning":"ledger in java:com.acme.order.adapter.","polysemous":false,"senses":[]},{"word":"trail","concern":"domain","sense":"trail","meaning":"trail in java:com.acme.order.adapter.","polysemous":false,"senses":[]}],"confidence":0.5},"fingerprint":"cefb6fd8308187787e107595b7c9c371cabe8f28589d800396b0c69916f4496e","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"i","id":"java:com.acme.order.legacy","key":{"lang":"java","module":"com.acme.order.legacy","symbol":""},"level":"module","kind":"package","name":"com.acme.order.legacy","origin":"llm","block":{"name":"java:com.acme.order.legacy","description":"Module java:com.acme.order.legacy.","apis":[],"spis":[],"dependsOn":[],"concepts":[],"boundedContextHint":null,"sharedKernelHint":null,"ubiquitousLanguage":[],"words":[{"word":"legacy","in":["com.acme.order.legacy"],"concern":"domain","sense":"legacy","meaning":"legacy in java:com.acme.order.legacy.","confidence":0.5}],"glossary":[{"word":"head","concern":"domain","sense":"head","meaning":"head in java:com.acme.order.legacy.","polysemous":false,"senses":[]},{"word":"list","concern":"domain","sense":"list","meaning":"list in java:com.acme.order.legacy.","polysemous":false,"senses":[]},{"word":"tail","concern":"domain","sense":"tail","meaning":"tail in java:com.acme.order.legacy.","polysemous":false,"senses":[]}],"confidence":0.5},"fingerprint":"35a959fc1c2d2ae9863563dced8e8aa22718ed45ce4af6b0f57140b45aeceb53","model":"openai/gpt-5.6-luna","usage":{"promptTokens":1000,"completionTokens":64,"cost":0.000244140625}} {"t":"eof","counts":{"records":79,"llm":70,"template":9,"reused":0,"failed":0},"usage":{"promptTokens":68000,"completionTokens":4352,"cost":0.0166015625},"generatedAt":"2026-11-21T00:00:00.000Z"} diff --git a/packages/cli/test/golden/explain/java/plan.jsonl b/packages/cli/test/golden/explain/java/plan.jsonl index aa6f1a17..868bc11c 100644 --- a/packages/cli/test/golden/explain/java/plan.jsonl +++ b/packages/cli/test/golden/explain/java/plan.jsonl @@ -1,6 +1,6 @@ -{"kind":"codegraph.explainPlan/1","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"depth":1,"estimates":{"calls":68,"promptTokens":114136,"completionTokens":52415,"byLevel":{"operation":{"calls":48,"promptTokens":78146,"completionTokens":30120,"units":57},"type":{"calls":17,"promptTokens":31000,"completionTokens":15470,"units":17},"module":{"calls":3,"promptTokens":4990,"completionTokens":6825,"units":3}},"byStatus":{"llm":68,"template":9,"reuse":0,"skip-scope":0,"skip-budget":0}},"steps":"77 steps, one per line below"} +{"kind":"codegraph.explainPlan/1","models":{"leaf":"openai/gpt-5.6-luna","rollup":"openai/gpt-5.6-luna"},"depth":1,"estimates":{"calls":68,"promptTokens":114149,"completionTokens":52415,"byLevel":{"operation":{"calls":48,"promptTokens":78159,"completionTokens":30120,"units":57},"type":{"calls":17,"promptTokens":31000,"completionTokens":15470,"units":17},"module":{"calls":3,"promptTokens":4990,"completionTokens":6825,"units":3}},"byStatus":{"llm":68,"template":9,"reuse":0,"skip-scope":0,"skip-budget":0}},"steps":"77 steps, one per line below"} {"id":"java:com.acme.order.adapter/LedgerAdapter.()","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.()"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1599} -{"id":"java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1634} +{"id":"java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)","level":"operation","members":["java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1647} {"id":"java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)","level":"operation","members":["java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List)"],"layer":0,"status":"template","model":"openai/gpt-5.6-luna","calls":0,"promptTokens":0} {"id":"java:com.acme.order.legacy/List.head()","level":"operation","members":["java:com.acme.order.legacy/List.head()"],"layer":0,"status":"template","model":"openai/gpt-5.6-luna","calls":0,"promptTokens":0} {"id":"java:com.acme.order.legacy/List.length()","level":"operation","members":["java:com.acme.order.legacy/List.length()"],"layer":0,"status":"llm","model":"openai/gpt-5.6-luna","calls":1,"promptTokens":1584} diff --git a/packages/cli/test/golden/explain/java/prompts-planned.sha256 b/packages/cli/test/golden/explain/java/prompts-planned.sha256 index f13dce08..ff6f5a78 100644 --- a/packages/cli/test/golden/explain/java/prompts-planned.sha256 +++ b/packages/cli/test/golden/explain/java/prompts-planned.sha256 @@ -1,5 +1,5 @@ 1 operation java:com.acme.order.adapter/LedgerAdapter.() codegraph_operation system=dc45667c9ad4bd03 user=8732c876634573ebc4e7a0a87ad9e4529abda1ae8b0b795d46f4539c6dc296f6 -2 operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) codegraph_operation system=dc45667c9ad4bd03 user=ab4cec9757e684cfb1e430665c373ab47b2c95c2819999e8f9c0cd19b5a9199d +2 operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) codegraph_operation system=dc45667c9ad4bd03 user=febb011f7806f071e637f07f61cdb9fc4c083abad39630fa0c357089db7f5291 3 operation java:com.acme.order.legacy/List.length() codegraph_operation system=dc45667c9ad4bd03 user=9e009db9e2f27a33f6c311091e4eaa696b1710aadcf23b75977f2048f7d73438 4 operation java:com.acme.order/AbstractOrder.price() codegraph_operation system=dc45667c9ad4bd03 user=9bf9e11b550d5a8d6a29232bd19449b71a6a0d435a37d27af18501848400cd1d 5 operation java:com.acme.order/Audited.value() codegraph_operation system=dc45667c9ad4bd03 user=82ebfc707adc43dedd97d32e47b4d40aa02aa66bb765921a8886fa04f213af10 diff --git a/packages/cli/test/golden/explain/java/prompts.txt b/packages/cli/test/golden/explain/java/prompts.txt index 574402f0..2aff845b 100644 --- a/packages/cli/test/golden/explain/java/prompts.txt +++ b/packages/cli/test/golden/explain/java/prompts.txt @@ -43,6 +43,7 @@ Source (com/acme/order/adapter/LedgerAdapter.java:11-14): ```` Calls: - AuditTrail of AuditTrail (external) +- LedgerClient of LedgerClient (external, derived) Field accesses: - read LedgerAdapter.trail Words to define in `words` (each once, with every identifier it appears in): diff --git a/packages/cli/test/golden/explain/java/units.txt b/packages/cli/test/golden/explain/java/units.txt index f598c1a5..5cfa5f84 100644 --- a/packages/cli/test/golden/explain/java/units.txt +++ b/packages/cli/test/golden/explain/java/units.txt @@ -1,5 +1,5 @@ operation java:com.acme.order.adapter/LedgerAdapter.() llm fingerprint=6302a188842d9edc128da6bc61a553414de1ae9ea87461a9022ea7f6b694db2d chain=a33628ab88428f027b455b3fc5ed8039c4ca2b2239bc9cddddc8c252c48709a5 -operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) llm fingerprint=d482fc2440b20f13edaa908642428095cb96da95739aef7f7214b1354500a3ab chain=32edb856f6591fa9eab56025fb3af8bb1848c7810db228ca68ddd677910a5dce +operation java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object) llm fingerprint=e543cbd5cc0e3afc77fd5d1b9e297acb1e1dfff052bb9fd2f2022ffe039a5076 chain=d636fe5166825bb98d2ad46e1234c212984c771a145fb9b35887dd4fa891d95b operation java:com.acme.order.legacy/List.(java.lang.String,com.acme.order.legacy.List) template (trivialConstructor) fingerprint=d5fa5c347f7736585649e3e3d97bd901b5a904999e597398aeeec789777e4a85 chain=76552b6693c59a259c92cac02efce3c6e13e87a5742b68ea24bf2b2ae48ec988 operation java:com.acme.order.legacy/List.head() template (getter) fingerprint=4c10fcfbf329ec4699a5b727b9309fc96e449e1fb0927e388f0d681c83d333b5 chain=58e039e580bce8fe86e72d2e416e7b6bcb56437ef371b6173171833bba2881d9 operation java:com.acme.order.legacy/List.length() llm fingerprint=ede9d0077c5f8d5caee781a5cc81abd24c237713e547eb8bb2d34288ce57e25a chain=6588e25b050f8e2a29d9968c91535c3bd076d8c57f0c841062272b97dc8b8505 @@ -39,7 +39,7 @@ operation java:com.acme.order/Reporting.max(java.util.List) llm fingerprint=23e3 operation java:com.acme.order/Reporting.today() llm fingerprint=7cb499045ddeac3965d4db8bad638482e3af78376735d94a3ca1644ab8a45f45 chain=a1026703ea36dc2b8688675014a71f7965bff78d4c499596a4fc2855568025c3 operation java:com.acme.order/StockGuard.() llm fingerprint=4efe29199de9fd0320091f6ffbd5d0b59a456efffc2641ca55ee95d9ecfb5309 chain=16fce8e911f74ad78b890c1d370b1ce46d07b3c429e9df86392698c57f9e185f operation java:com.acme.order/StockGuard.check(int) llm fingerprint=946a83ff45648c4e23ec621230960733dc570493980958fbcb709a29aa1929d5 chain=8a49446a4e653cd95ca9e4ba842ae3704f5ef6d153f20c359e87ef53c29abffe -type java:com.acme.order.adapter/LedgerAdapter llm fingerprint=de6f642b25bea68047476a0c1ca175c6ac9d6523f50595c3f52bcb86993b80b4 chain=406b67473376c04f581e10511ec9cb17a396911c9343426009dd89326a2aa5f9 stamped=6308c19643d34fba7586c53018cb1b26efc35a801a2769c93e2a3e88ef8f37b9 +type java:com.acme.order.adapter/LedgerAdapter llm fingerprint=f0470a8ecf493b91d31618812ce56a914e4c597bc0a31331102fbd425582c4a2 chain=44497be4a3040bbe2fd172e5d48d8a3c918d035fca490f60bc1fd22b86550f17 stamped=970857c46079c66c6b453b0ec06cfb95ff7b6727aa9482f715cb85c5fda58d42 type java:com.acme.order.legacy/List llm fingerprint=39af6c37e0aaed403a8d56b303c6e6fa820eef4538dd81b8f2c35ce63766d2d2 chain=6e7c6b5ac71e58f751d71bd3eaeda9c9463743197aef5553bbb104bdb169a54a stamped=f7d9ef8d7b23e659b9de3a01da94fc4a682260e402db5fa5701693a53063c37b type java:com.acme.order/Audited llm fingerprint=27f0929bda9b960c7a7725e337a302d5869a1623cc0672f362ccffdcaf2adbae chain=d6a3407f72319e492e0e651663588fedc7659fe9cde7d0954664d9c92caee409 stamped=dcbf0bbd0798b8fa740ad5973e531534629d494f86d3de7a7d443311010e39fb type java:com.acme.order/Basket.Line.Discount llm fingerprint=357314b8d07565ed4e6d8da9457c772977501df93e59db75b18cbdc95fe813d0 chain=c8261d4d1759978ccd7dc41f69a4e1b7eb9adecdbc701eccb650569336a4086b stamped=b4307f557435f1048e9423a35dd767c478439220fddadec5d5d9cbf0ba588fd9 @@ -53,7 +53,7 @@ operation java:com.acme.order/OrderService.archive(com.acme.order.legacy.List) l operation java:com.acme.order/OrderService.archive(java.util.List) llm fingerprint=5014c95fd755888907ec4b1f8148ba250f81792cc80046234f8efc6562489979 chain=de018c799d2b0031de3a25a2d444af86dc9365fa768e2f3bcccaa92f02efa147 stamped=22ec4347bac0df33543ed198bc351418e00c8a4fbb029dbf8ca0564e0cc6349c operation java:com.acme.order/OrderService.bill(com.acme.order.Order) llm fingerprint=c229926c94a504cfc95904666c6a13e450cb391710008f7d9f71070ad660dbbd chain=ae243cd612510f274a13ed96f983bacc0470236e7d57b0b6f5bfb0f826ac88ee stamped=c23efc407657d4bf30d8a526d82578f2295bb4a396962f6274eabfc8ee01d6e9 operation java:com.acme.order/StockGuard.ensure(int) llm fingerprint=4b670b6e7e7cd2270199477474ed04bda7ec1eea956f520921ab25af7e9c6787 chain=56372d54bdadac7dd6fc038fafddde2ba5f24f753ec0d220e362708aa6806fbc stamped=2d1c4136a0e310922e00980d8db38d9c43a6d242a44242e731ded007c0543176 -module java:com.acme.order.adapter llm fingerprint=10ee6e8539c02125d3c80dc3f02fe2bb19463f8a86058a8704ee7bd6fd71a547 chain=db08005858d5a99138b40dac475f0d7a50ed054d0fc55b26ad101a8752cdefe2 stamped=44b0273a83a6fd3cc0b3d13413e03bf38573883a4e75b417fdfac235c80e62ee +module java:com.acme.order.adapter llm fingerprint=cefb6fd8308187787e107595b7c9c371cabe8f28589d800396b0c69916f4496e chain=ff47c9fe75385ca90db5b32647424d2fad301757661a0f1453d311f1878b30a4 stamped=72f4ce44c00f52bf9383124dbdfc9359ce7924210e861f6e20c9d74483c36bf0 module java:com.acme.order.legacy llm fingerprint=35a959fc1c2d2ae9863563dced8e8aa22718ed45ce4af6b0f57140b45aeceb53 chain=5863e82396f5a658600bf4e2e3d51a627477bdc023150e78598159095eda23f0 stamped=95664a806624fdfdf835a7f18becc03dc8b718779c9247cde1608ae97a24266e operation java:com.acme.order/AbstractOrder.(java.lang.String) llm fingerprint=692ca8a5882ced05c3e6c90bfe8e0bb966d71916863533de50707801dcda677f chain=618580d4ac5ea6b6ef5da53b0a15a19dadf611e70aa187e73825b398ddd445a3 stamped=7ec9001d3e69e35ea44e4ece46667ee572ba3a7c6fa14419e4ba5227c29c2653 type java:com.acme.order/Basket.Line llm fingerprint=ef17220316e16357fc7588cffb1c903cb7d7693aee0ae3b0130accd38506a868 chain=aa00575901d5dfc540987c4aeb41a746a5d93c8aa00ba1f2a7f7126003d6552f stamped=5f4095eae126943b5a55fcc7a3d37c0a274bf4ca6aeb45e73411e7a9a5825730 diff --git a/packages/cli/test/load.test.ts b/packages/cli/test/load.test.ts index 44b762c2..df7ee355 100644 --- a/packages/cli/test/load.test.ts +++ b/packages/cli/test/load.test.ts @@ -23,7 +23,8 @@ describe("loading model files", () => { expect(loaded.paths).toEqual([FIXTURE]); expect(loaded.union.entities.length).toBe(179); // 189 since MM-6 split Reporting.first's `get` and `isEmpty` calls on the List stub. - expect(loaded.union.edges.length).toBe(189); + // 190 since the ancestor rule kept LedgerAdapter's `super.post` (LedgerClient, `post`). + expect(loaded.union.edges.length).toBe(190); expect(loaded.union.langs).toEqual(["java"]); expect(loaded.clean).toBe(true); expect(loadExitCode(loaded)).toBe(EXIT.OK); diff --git a/packages/cli/test/validate.test.ts b/packages/cli/test/validate.test.ts index d80dab0e..adbea3c8 100644 --- a/packages/cli/test/validate.test.ts +++ b/packages/cli/test/validate.test.ts @@ -82,7 +82,7 @@ describe("codegraph validate on clean output", () => { expect(result.code).toBe(EXIT.OK); expect(result.stdout).toContain("OK — every model conforms"); expect(result.stdout).toContain("179 entities"); - expect(result.stdout).toContain("189 edges"); + expect(result.stdout).toContain("190 edges"); expect(result.stdout).not.toContain("FAILED"); }); @@ -92,9 +92,10 @@ describe("codegraph validate on clean output", () => { // [named, eligible]: Elixir names every member its sites write (M24a); its 5 // unnamed edges are 3 modules written as values (`{Registry, keys: :unique}`) and // 2 `%Ecto.Changeset{…}` struct references, whose fields are the named accesses. - // Java (M24a): 20 of 61 — the other 41 are type uses and constructor calls, + // Java (M24a): 21 of 62 — the other 41 are type uses and constructor calls, // which name no member; 61 was 60 before Reporting.first's `get` and `isEmpty` - // on one line became two edges. TypeScript (M24a): 14 of 18 — the other 4 are + // on one line became two edges, 62 since LedgerAdapter's `super.post` became an + // ancestor-attributed invocation naming `post`. TypeScript (M24a): 14 of 18 — the other 4 are // two `String(x)` call signatures, a `super` call and a type reference. // C# (M24a): 17 of 119 — the other 102 are type uses, constructor calls, // delegate calls and indexers, which name no member (the 17th is the unbound @@ -108,7 +109,7 @@ describe("codegraph validate on clean output", () => { const counts: Record = { csharp: [17, 119], elixir: [37, 42], - java: [20, 61], + java: [21, 62], python: [16, 25], ruby: [13, 24], typescript: [14, 18], @@ -132,7 +133,7 @@ describe("codegraph validate on clean output", () => { expect(result.code).toBe(EXIT.FINDINGS); expect(result.stdout).toContain("member-target-not-stub"); // Not counted: only an edge to a stub can name a member. - expect(result.stdout).toContain("members named: 20 of 61 edges to stubs"); + expect(result.stdout).toContain("members named: 21 of 62 edges to stubs"); }); it("exits 0 with a clean verdict on the committed Roslyn snapshot too", () => { @@ -207,7 +208,7 @@ describe("codegraph validate on clean output", () => { expect(report.ok).toBe(true); expect(report.findings).toEqual([]); expect(report.counts.errors).toBe(0); - expect(report.subject).toMatchObject({ entities: 179, stubs: 27, edges: 189 }); + expect(report.subject).toMatchObject({ entities: 179, stubs: 27, edges: 190 }); }); it("is deterministic — the same invocation twice is byte-identical (decision 6)", () => { diff --git a/packages/core/src/profiles/java.ts b/packages/core/src/profiles/java.ts index 7b152874..46970fd8 100644 --- a/packages/core/src/profiles/java.ts +++ b/packages/core/src/profiles/java.ts @@ -180,12 +180,13 @@ export const javaProfile: Profile = { "noClasspath resolution rate, measured (M2 audit): 100.0% on apache/commons-lang (263 files, 133478 type references, 0 unresolved) and 77.8% on spring-petclinic (30 files, 2189 references, 487 unresolved, all of them Spring and Jakarta types whose jars are absent). The rate is a property of the corpus's DEPENDENCY SURFACE, not of the extractor: commons-lang is self-contained and depends on nothing but the JDK, which resolves against the runner's own classpath. A jar that is not on the classpath cannot be resolved by any extractor, so a corpus with third-party dependencies has a structural ceiling well below 100% and a single cross-corpus target number is not meaningful. The stub discipline, not the resolution rate, is the property worth asserting.", "The resolution rate counts neither type variables nor ``: neither names anything that could have a declaration, so counting them measures the corpus's writing style. This is not cosmetic — ``, Spoon's static type for the `null` literal, was ALL 1466 of commons-lang's originally-reported unresolved references, making the headline number a function of how many `return null;` statements the corpus contains.", "In noClasspath Spoon promotes an unresolvable RECEIVER to a type in the enclosing package: `typeHint -> typeHint.with(...)` and `cm.setStatisticsEnabled(...)` produced stub classes named `typeHint` and `cm` inside the corpus's own package on spring-petclinic. They are correctly stubbed (membership is the declared-id whitelist), and they are why the whitelist exists — but the stub set of a real corpus therefore contains a tail of entities named after local variables, and a stub count is not a count of external types.", - "A lambda whose functional interface is not on the classpath is a body ECJ never resolves, nested lambdas included: every call in it reaches Spoon with no declaring type and no parameter types (and its receivers become the stubs of the note above). Such calls used to be dropped, so `cm -> cm.createCache(\"vets\", cacheConfiguration())` on spring-petclinic left `cacheConfiguration()` with no caller. An UNQUALIFIED call there is now resolved by the language's own lookup — the innermost enclosing type with a method of that name, declared or inherited from a corpus type, then the one method whose arity accepts the call — and is `declared` when every type the lookup consulted has all its supertypes in the corpus, `derived` when one does not (a supertype outside the corpus may declare a same-arity overload, or the name itself). Still dropped: two overloads of the same arity, a name `java.lang.Object` declares (`toString`, `equals`…), `this.m()`, `Outer.this.m()`, `super.m()` and method references; a type-qualified call with arguments (`Util.f(x)`) folds to its type.", + "A lambda whose functional interface is not on the classpath is a body ECJ never resolves, nested lambdas included: every call in it reaches Spoon with no declaring type and no parameter types (and its receivers become the stubs of the note above). Such calls used to be dropped, so `cm -> cm.createCache(\"vets\", cacheConfiguration())` on spring-petclinic left `cacheConfiguration()` with no caller. An UNQUALIFIED call there is now resolved by the language's own lookup — the innermost enclosing type with a method of that name, declared or inherited from a corpus type, then the one method whose arity accepts the call — and is `declared` when every type the lookup consulted has all its supertypes in the corpus, `derived` when one does not (a supertype outside the corpus may declare a same-arity overload, or the name itself). Still unresolved here: two overloads of the same arity, a name `java.lang.Object` declares (`toString`, `equals`…), `this.m()`, `Outer.this.m()`, `super.m()` and method references — the ancestor rule (the next note) may still charge such a call to a library type; a type-qualified call with arguments (`Util.f(x)`) folds to its type.", + "A call to a method a corpus type inherits from a LIBRARY type has no declaring type Spoon can name without the jar, so it was dropped: on spring-petclinic `owners.save(owner)` on `OwnerRepository extends JpaRepository` left no edge, while the reads the interface redeclares resolved. It is now an `invocation` (a `reference` outside every invocable) of the stub of the one library ancestor that could answer, naming the method, with provenance `derived` — an inference by elimination, counted `ancestor-attributed` in the run's summary — when: the receiver's type is WRITTEN in the corpus (a field, a parameter, a local not declared `var`), or is `this` (`Outer.this` looks in `Outer` alone), `super` (from the superclass, `Iface.super` from that interface: the class's own override is no evidence against it) or the implicit `this` of an unqualified call (every enclosing class looked through, JLS §15.12.1); a type written in the corpus — an anonymous class, a local class, an enum constant body — is walked like any corpus type, whatever its id, and is never a candidate, so `new LibCallback() { … helper(); }` in a class extending `LibBase` is ambiguous; no corpus type of that type's supertype closure declares a method of that name; no corpus type there carries a Lombok annotation (it has members no source writes: on apache/fineract 2 319 getters were charged to `Persistable` before this condition); and exactly ONE library type there could answer — one Spoon can see (the JDK) only for a name it has, `java.lang.Object` never. The target is the type the corpus WROTE, erased (`JpaRepository`, though `CrudRepository` really declares `save`: only the jar could tell). With two that could answer, the call stays dropped and is counted `ambiguous-ancestor`; with none, dropped as before. An unqualified call in a file with a static on-demand import (`import static org.mockito.Mockito.*`), or a single static import of that name, stays dropped: the import may bind it. Not covered: a read the corpus redeclares (already an edge to the corpus method), an interface with two library parents (ambiguous), a receiver whose type is not written (`var`, a call's result, an inferred lambda parameter, an array element), a method reference. A unit holding such a call has one fact more, so its explain prompt and fingerprint change and its stored insight is re-asked. Measured: spring-petclinic 891 → 896 edges (5 attributed, 0 ambiguous; with its tests 13, 0), BroadleafCommerce 383 attributed sites and 12 ambiguous, apache/fineract 313 and 1 103; no edge that existed before moved.", "An array type is not an entity, and neither is its component where a member is concerned. `xs.length` and `int[]::new` declare their member on `int[]` / `Money[]`; folding that up names the component and states a fact the source never wrote. Such facts are dropped, not degraded — the dependency on the component is already carried by the written type reference that mentions it.", "An anonymous class has exactly one id, the `#file:line:column` form pass 1 declared. Spoon names it `Outer$N`, which renders as a plausible nested-type id in the corpus's own package; a reference resolved through that name gives one declared class two ids and launders the second into a stub. Type references must be resolved to their declaration before being named.", "Spoon materializes the implicit constructor of an anonymous class with synthetic parameters named `$anonymousN`. They are emitted (implicit members are, deliberately, so that `new Foo()` does not dangle), so the model contains a handful of parameter entities nobody wrote, carrying no anchor of their own — 5 of 15338 entities on commons-lang.", "The metrics pass (`codegraph-metrics`, PLAN.md §18) joins big-code-analysis spaces to entities on their anchors. Spoon starts a declaration AFTER its annotations and tree-sitter AT them; the pass bridges the two when nothing but annotation lines lies between (a LEADING join — most of a Spring corpus). It measures nothing on a lambda (big-code-analysis opens no space for one and charges its cognitive, exits and ABC to the enclosing method), on an implicit constructor (anchored on its class) or on an annotation element (no body): those carry none of the pass's keys.", - "MM-6 (an edge's `member`, contract 1.1.0): an edge to a stub names the member the site wrote, by its SIMPLE name — no parameter types, since an external method's erased types need a classpath and the extractor runs noClasspath. A method call on a stub type is an `invocation` naming the method (`lines.add(x)` → `add`, a static call through a static import included: `asList`); a method reference `Integer::parseInt` names `parseInt`; a field read or written is an `access` naming the field (`System.out` → `out`), and a read and a write of one field at one site stay one access with both flags; written outside every invocable (a field initializer, an annotation argument) the call or the field read degrades to a `reference` that keeps the name (`Logger.getLogger(…)` → `getLogger`, `@Retention(RetentionPolicy.RUNTIME)` → `RUNTIME`). Named nowhere: a constructor call or reference (`new ArrayList<>()`, `super(…)`, `ArrayList::new` — the edge to the type says all the site wrote), a class literal (`Foo.class` is no member of Foo), a written type use, a supertype clause, and every edge to a corpus entity — its member is an entity, and the edge points at it. The member is part of the edge: `values.isEmpty() ? null : values.get(0)` is two invocations of `List`, where it was one. Measured on spring-petclinic: 723 of 1 164 edges to stubs named, 2 800 edges become 2 847 (42 sites split). A call to a member a corpus interface INHERITS from a library one (`owners.save(owner)` on a Spring Data `JpaRepository`) yields no edge in noClasspath, before as after, so it names nothing: the five repository writes of spring-petclinic have no edge.", + "MM-6 (an edge's `member`, contract 1.1.0): an edge to a stub names the member the site wrote, by its SIMPLE name — no parameter types, since an external method's erased types need a classpath and the extractor runs noClasspath. A method call on a stub type is an `invocation` naming the method (`lines.add(x)` → `add`, a static call through a static import included: `asList`); a method reference `Integer::parseInt` names `parseInt`; a field read or written is an `access` naming the field (`System.out` → `out`), and a read and a write of one field at one site stay one access with both flags; written outside every invocable (a field initializer, an annotation argument) the call or the field read degrades to a `reference` that keeps the name (`Logger.getLogger(…)` → `getLogger`, `@Retention(RetentionPolicy.RUNTIME)` → `RUNTIME`). Named nowhere: a constructor call or reference (`new ArrayList<>()`, `super(…)`, `ArrayList::new` — the edge to the type says all the site wrote), a class literal (`Foo.class` is no member of Foo), a written type use, a supertype clause, and every edge to a corpus entity — its member is an entity, and the edge points at it. The member is part of the edge: `values.isEmpty() ? null : values.get(0)` is two invocations of `List`, where it was one. Measured on spring-petclinic: 723 of 1 164 edges to stubs named, 2 800 edges become 2 847 (42 sites split). A call to a member a corpus type INHERITS from a library one (`owners.save(owner)` on a Spring Data `JpaRepository`) has no declaring type in noClasspath; where the ancestor rule (the `ancestor-attributed` note) charges it to the one library ancestor, the edge names the member like any other (`save`, `saveAndFlush`): the five repository writes of spring-petclinic.", ], lexicon: { diff --git a/packages/insights/test/propose-census.test.ts b/packages/insights/test/propose-census.test.ts index 0642ba06..659084c2 100644 --- a/packages/insights/test/propose-census.test.ts +++ b/packages/insights/test/propose-census.test.ts @@ -29,8 +29,9 @@ describe("the censuses on the Java fixture", () => { expect(names(census.annotations.shown)).toEqual(["Override 7", "Audited 2", "Retention 1"]); expect(census.supertypes.shown.every((entry) => entry.count > 0)).toBe(true); const ledger = census.stubs.shown.find((stub) => stub.name === "LedgerClient"); - expect(ledger).toMatchObject({ count: 4, modules: ["com.megacorp.ledger"] }); - expect(names(ledger!.members.shown)).toEqual(["archive 2", "AUDIT_TAG 1", "post 1"]); + // 5 since the ancestor rule: LedgerAdapter's `super.post` is an edge to the stub. + expect(ledger).toMatchObject({ count: 5, modules: ["com.megacorp.ledger"] }); + expect(names(ledger!.members.shown)).toEqual(["archive 2", "post 2", "AUDIT_TAG 1"]); expect(census.modules.shown.map((entry) => entry.name)).toContain("java.util"); }); diff --git a/website/content/docs/discover/boundaries.md b/website/content/docs/discover/boundaries.md index cfae9d94..8127ed74 100644 --- a/website/content/docs/discover/boundaries.md +++ b/website/content/docs/discover/boundaries.md @@ -103,7 +103,7 @@ SELECT m.symbol AS external_module, |---|---|---| | `java.lang` | 0 | 39 | | `java.util` | 0 | 16 | -| `com.megacorp.ledger` | 0 | 10 | +| `com.megacorp.ledger` | 0 | 11 | | `java.lang.annotation` | 0 | 4 | | `java.util.function` | 0 | 4 | | `com.acme.order` | 1 | 3 | diff --git a/website/content/docs/discover/domain.md b/website/content/docs/discover/domain.md index a93aace3..31b87ed9 100644 --- a/website/content/docs/discover/domain.md +++ b/website/content/docs/discover/domain.md @@ -66,7 +66,7 @@ codegraph query app.jsonl --file purity.sql --param stdlib='["java.*"]' |---|---|---|---| | `com.acme.order.legacy` | 6 | 0 | 100.0 | | `com.acme.order` | 111 | 11 | 90.1 | -| `com.acme.order.adapter` | 5 | 4 | 20.0 | +| `com.acme.order.adapter` | 6 | 5 | 16.7 | A pure module is the domain candidate. A module whose references are mostly stubs is plumbing: `adapter` above lives up to its name. The mixed ones are diff --git a/website/content/docs/discover/stimuli.md b/website/content/docs/discover/stimuli.md index fc23cd5e..33c70d6d 100644 --- a/website/content/docs/discover/stimuli.md +++ b/website/content/docs/discover/stimuli.md @@ -154,7 +154,7 @@ codegraph query app.jsonl --file entry-points.sql --param-file stack=stack.json |---|---|---|---|---|---|---| | `java:com.acme.order/Order.discount(int)` | method | annotation | Audited | inbound command | 1 | `[{"name":"value","value":{"k":"unevaluated","source":"LedgerClient.AUDIT_TAG"}}]` | | `java:com.acme.order/Reporting.max(java.util.List)` | method | annotation | Audited | inbound command | 1 | `[{"name":"value","value":{"k":"string","v":"monthly"}}]` | -| `java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)` | method | supertype | LedgerClient | external event | 1 | NULL | +| `java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)` | method | supertype | LedgerClient | external event | 2 | NULL | | `java:com.acme.order/Notifications.notifyShipped(com.acme.order.Order)` | method | by hand | NULL | internal event | 1 | NULL | | `java:com.acme.order/OrderService.bill(com.acme.order.Order)` | method | type name | `*Service` | inbound command | 3 | NULL | | `java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)` | method | type name | `*Service` | inbound command | 2 | NULL | diff --git a/website/content/docs/discover/structure.md b/website/content/docs/discover/structure.md index 70138303..cf0e7636 100644 --- a/website/content/docs/discover/structure.md +++ b/website/content/docs/discover/structure.md @@ -43,7 +43,9 @@ RESOLUTION SUMMARY unresolved : 35 resolution rate : 94.5% entities : 179 (stubs: 27) - edges : 189 (self-edges dropped: 0) + edges : 190 (self-edges dropped: 0) + ancestor-attributed : 1 (derived) + ambiguous-ancestor : 0 (dropped) ``` Two lines matter. The **resolution rate** is the share of type references the diff --git a/website/content/docs/how-to/extract-java.md b/website/content/docs/how-to/extract-java.md index 4c26a067..b9fcc5a3 100644 --- a/website/content/docs/how-to/extract-java.md +++ b/website/content/docs/how-to/extract-java.md @@ -32,7 +32,9 @@ repository forces on you. unresolved : 35 resolution rate : 94.5% entities : 179 (stubs: 27) - edges : 189 (self-edges dropped: 0) + edges : 190 (self-edges dropped: 0) + ancestor-attributed : 1 (derived) + ambiguous-ancestor : 0 (dropped) ``` Progress is a bar on a terminal and silent when piped. Use `--progress plain` @@ -47,8 +49,8 @@ repository forces on you. ``` ```text - checked 1 model — 179 entities (27 stubs), 189 edges, lang java - members named: 20 of 61 edges to stubs + checked 1 model — 179 entities (27 stubs), 190 edges, lang java + members named: 21 of 62 edges to stubs OK — every model conforms: closure, no self-reference, provenance, candidates, profile, anchors, ids, members. ``` diff --git a/website/content/docs/how-to/query-model-db.md b/website/content/docs/how-to/query-model-db.md index d67eb059..bb1f3d3b 100644 --- a/website/content/docs/how-to/query-model-db.md +++ b/website/content/docs/how-to/query-model-db.md @@ -134,7 +134,7 @@ SELECT (SELECT value FROM meta WHERE key = 'lang') AS lang, | lang | entities | stubs | edges | files | |---|---|---|---|---| -| java | 179 | 27 | 189 | 16 | +| java | 179 | 27 | 190 | 16 | Fan-in — what everything depends on. `edge_to` is an *index* over the stored outgoing facts, so this is a `GROUP BY` and it can never disagree with the @@ -152,9 +152,9 @@ SELECT n.id, count(*) AS fan_in |---|---| | `java:com.acme.order/Money` | 16 | | `java:java.lang/String` | 16 | +| `java:com.megacorp.ledger/LedgerClient` | 8 | +| `java:java.util/List` | 8 | | `java:com.acme.order/Order` | 7 | -| `java:com.acme.order/Priceable` | 7 | -| `java:com.megacorp.ledger/LedgerClient` | 7 | How much of the graph is inference — worth running once on any corpus: @@ -169,9 +169,11 @@ SELECT d.provenance, d.kind, count(*) AS n | provenance | kind | n | |---|---|---| | derived | import | 3 | +| derived | invocation | 1 | -Three derived imports out of 189 edges: on this corpus almost everything is a -fact the extractor read. +Three derived imports and one derived call (`super.post` in `LedgerAdapter`, +charged to the one library ancestor that could answer) out of 190 edges: on this +corpus almost everything is a fact the extractor read. The most complex invocables: diff --git a/website/content/docs/reference/boundaries.md b/website/content/docs/reference/boundaries.md index f691c43e..351b0a50 100644 --- a/website/content/docs/reference/boundaries.md +++ b/website/content/docs/reference/boundaries.md @@ -92,7 +92,7 @@ A row is an `invocation` or an `access` edge to a stub a rule names. A `referenc "name": "petclinic", "lang": "java", "inbound": { "concepts": { "applicationService": "inbound request" } }, - "outbound": { "concepts": { "repository": { "kind": "database", "why": "a Spring Data interface: its save is inherited, so no edge says so" } } } + "outbound": { "concepts": { "repository": { "kind": "database", "why": "a Spring Data interface: the reads it declares are calls into the code, not into a stub" } } } } ``` @@ -309,12 +309,14 @@ The shipped `spring.json` on [spring-petclinic](https://github.com/spring-projec "outbound": { "modules": { "org.springframework.data.repository.*": "database", + "org.springframework.data.jpa.repository": "database", "org.springframework.kafka.*": "broker", "org.springframework.mail.*": "mail", "javax.cache.*": "cache" }, "types": { "JdbcTemplate": "database", "RestTemplate": "http api" }, "effects": { + "org.springframework.data.jpa.repository": { "save*": "write", "delete*": "write", "find*": "read" }, "JdbcTemplate": { "query*": "read", "update": "write", "batchUpdate": "write" }, "RestTemplate": { "get*": "read", "post*": "write", "put": "write", "delete": "write" } } @@ -322,9 +324,10 @@ The shipped `spring.json` on [spring-petclinic](https://github.com/spring-projec } ``` -On PetClinic it files one row, the cache: `CacheConfiguration.cacheConfiguration()` building a `javax.cache` `MutableConfiguration`. Two things the run shows: +On PetClinic it files six rows: the cache, `CacheConfiguration.cacheConfiguration()` building a `javax.cache` `MutableConfiguration`, and five `database` writes, `save` and `saveAndFlush` on `JpaRepository`. Three things the run shows: -- **A Spring Data repository is not a stub.** `OwnerRepository` is an interface of the code that extends `JpaRepository`: `owners.findById(ownerId)` reaches the `findById` that interface declares, an entity of the code, so no outbound row is written for it. And `owners.save(owner)` (`OwnerController.java:84`), a method inherited from the stub, is no invocation edge at all in this model: the line holds only the read of the field `owners`. The database behind a repository is not visible from the calls. +- **A Spring Data repository is not a stub, but its library parent is.** `OwnerRepository` is an interface of the code that extends `JpaRepository`: `owners.findById(ownerId)` reaches the `findById` that interface declares, an entity of the code, so no outbound row is written for it. `owners.save(owner)` (`OwnerController.java:84`) calls a method inherited from the stub; the extractor charges it to `JpaRepository`, the one library ancestor that could answer, as a `derived` invocation naming `save` ([the Java extractor's ancestor rule](/docs/reference/java-extractor/#calls-to-a-method-inherited-from-a-library-type)), so the effect rule reads `write`. The reads the repository declares itself stay calls into the code: a `find*` effect on the stub finds nothing on PetClinic. +- **Name the package the stub is in.** `JpaRepository` lives in `org.springframework.data.jpa.repository`, which `org.springframework.data.repository.*` does not cover: without the second line the five writes file no row. - **A `modules` pattern names a whole package.** `org.springframework.data.*` would file the 13 calls into `Page` and `PageRequest`, which are values a query returns, as database calls. Name the package that talks to the system, or the type. ## See also diff --git a/website/content/docs/reference/cli/import.md b/website/content/docs/reference/cli/import.md index 942432a7..6d7e699f 100644 --- a/website/content/docs/reference/cli/import.md +++ b/website/content/docs/reference/cli/import.md @@ -39,7 +39,7 @@ codegraph import [--out FILE] [--at SHA] [--time T] [--json] $ codegraph import fixtures/java/expected/model.jsonl fixtures/java/expected/model.jsonl: 0.03 s, 0.0 MB jsonl -> 0.2 MB db imported fixtures/java/expected/model.jsonl -> fixtures/java/expected/model.db - 179 entities (27 stubs), 189 edges, 16 files, lang java + 179 entities (27 stubs), 190 edges, 16 files, lang java OK — the store is ready. Run `codegraph analyze` against the model as usual. ``` diff --git a/website/content/docs/reference/cli/validate.md b/website/content/docs/reference/cli/validate.md index 15a230ab..49c8c3c7 100644 --- a/website/content/docs/reference/cli/validate.md +++ b/website/content/docs/reference/cli/validate.md @@ -34,9 +34,9 @@ codegraph validate [--json] ```console $ codegraph validate fixtures/java/expected/model.jsonl -checked 1 model — 179 entities (27 stubs), 189 edges, lang java +checked 1 model — 179 entities (27 stubs), 190 edges, lang java fixtures/java/expected/model.jsonl -members named: 20 of 61 edges to stubs +members named: 21 of 62 edges to stubs OK — every model conforms: closure, no self-reference, provenance, candidates, profile, anchors, ids, members. ``` diff --git a/website/content/docs/reference/java-extractor.md b/website/content/docs/reference/java-extractor.md index e850e4d9..9b77b11a 100644 --- a/website/content/docs/reference/java-extractor.md +++ b/website/content/docs/reference/java-extractor.md @@ -53,7 +53,7 @@ Copied verbatim into the header; the extractor runs no git — whoever invokes i ## Streams -stdout carries one thing: the finished run's `source:` roots and `model:` file, absolute. Progress and the **resolution summary** — how many type references Spoon resolved in noClasspath mode, how many entities and stubs were emitted, and how many edges — go to stderr, and progress never reaches a stream that is not a terminal unless asked for. +stdout carries one thing: the finished run's `source:` roots and `model:` file, absolute. Progress and the **resolution summary** — how many type references Spoon resolved in noClasspath mode, how many entities and stubs were emitted, how many edges, and the two counts of [the ancestor rule](#calls-to-a-method-inherited-from-a-library-type) — go to stderr, and progress never reaches a stream that is not a terminal unless asked for. ## The Java profile @@ -120,9 +120,9 @@ A stub has no members, so the edge names the one the site wrote: the optional `m | a written type use, a supertype clause, an import, an annotation use, a `throw` | `reference`, `inheritance`, … | none | | anything whose target is a corpus entity | any | none — the member is an entity there, and the edge points at it | -The member is part of the edge. `values.isEmpty() ? null : values.get(0)` is two invocations of the `List` stub (`get`, `isEmpty`) where it used to be one, and in the canonical order the member is the last tiebreak, the absent one first. A read and a write of ONE member at one site (`Counter.total = Counter.total + 1`, `Counter.hits++`) stay one `access` with both flags. `codegraph validate` prints the coverage: `members named: 20 of 61 edges to stubs` on the reference corpus, 723 of 1 164 on spring-petclinic. +The member is part of the edge. `values.isEmpty() ? null : values.get(0)` is two invocations of the `List` stub (`get`, `isEmpty`) where it used to be one, and in the canonical order the member is the last tiebreak, the absent one first. A read and a write of ONE member at one site (`Counter.total = Counter.total + 1`, `Counter.hits++`) stay one `access` with both flags. `codegraph validate` prints the coverage: `members named: 21 of 62 edges to stubs` on the reference corpus, 723 of 1 164 on spring-petclinic before the ancestor rule. -A call to a method a corpus interface inherits from a library one — `owners.save(owner)` on a Spring Data `JpaRepository` — yields no edge in noClasspath (measured on spring-petclinic: none of its five repository writes has one, before or after MM-6), and so names nothing. +A call to a method a corpus type inherits from a library one — `owners.save(owner)` on a Spring Data `JpaRepository` — has no declaring type in noClasspath. Where [the ancestor rule](#calls-to-a-method-inherited-from-a-library-type) charges it to the one library ancestor, the edge names the member like any other: `save`, `saveAndFlush`. **Primitives, `void` and `` are not entities.** `declaredType` is omitted for them rather than letting `java:/int` be fabricated into a stub class named `int`. `TTypedEntity`'s value is optional even when the trait is declared, so omitting is legal and lossless. @@ -143,7 +143,36 @@ Up to and including 0.3.0 such calls were dropped as unidentifiable targets, so | exactly one method fits, but a type consulted extends or implements a type outside the corpus | `invocation`, `derived` — that supertype may declare a same-arity overload, or the name itself | | two overloads of the same arity; a name `java.lang.Object` declares; no enclosing type has the name | dropped, never guessed | -`this.m()`, `Outer.this.m()`, `super.m()` and method references in such a body stay dropped; a type-qualified call with arguments (`Util.f(x)`) folds to an edge on its type; a call on a receiver (`cm.createCache(…)`) targets the receiver-named stub described in the profile notes. +`this.m()`, `Outer.this.m()`, `super.m()` and method references in such a body are not resolved by this lookup (the ancestor rule below may still charge one to a library type); a type-qualified call with arguments (`Util.f(x)`) folds to an edge on its type; a call on a receiver (`cm.createCache(…)`) targets the receiver-named stub described in the profile notes. + +## Calls to a method inherited from a library type + +`OwnerRepository extends JpaRepository` is a corpus interface; `JpaRepository` is a library type, a stub. Without its jar, ECJ cannot see what `JpaRepository` declares, so `this.owners.save(owner)` reaches Spoon with **no declaring type**. Before this rule such a call was dropped as an unidentifiable target: on spring-petclinic the five repository writes (`save`, `saveAndFlush`) had no edge, while the ten reads the interfaces redeclare (`findById`, `findPetTypes`…) resolved to the corpus methods. + +Such a call is now charged to the library type by elimination, when **all** of these hold: + +1. **The receiver's static type is a corpus type, and it is written.** A field, a parameter, or a local with an explicit type; `this.m()` (`Outer.this.m()` in `Outer` alone); `super.m()`, looked up from the superclass (`Iface.super.m()` from that interface), so the class's own override is no evidence against it; an unqualified `m()`, looked up through every enclosing class (JLS §15.12.1), the enclosing classes being the receiver. A type written in the corpus — an anonymous class, a local class, an enum constant body — is walked as corpus whatever its id, never taken for a library candidate: jMock's `new Expectations() {{ oneOf(x); }}` in a class that extends `TestCase` is ambiguous, not `TestCase`'s. +2. **Nothing in the corpus declares the name.** No corpus type of the receiver's supertype closure, itself included, declares a method of that name (an overload counts: the call may be the corpus's), and none carries a Lombok annotation, since it has members no source writes. +3. **Exactly one library type could answer.** A library type Spoon cannot see could declare anything. One it can see, the JDK, answers only for the names it has; `java.lang.Object` never answers. + +| Outcome | Edge | Counted | +|---|---|---| +| one library type could answer | `invocation` (a `reference` outside every invocable) of its stub, `derived`, naming the method (`member: "save"`) | `ancestor-attributed` | +| two could answer (an interface with two library parents) | dropped | `ambiguous-ancestor` | +| none, a corpus type declares the name, a Lombok type in the closure, or the receiver is out of reach | dropped, as before | — | + +The target is the type the corpus **wrote**, erased: `JpaRepository`, although `CrudRepository`, its own ancestor, really declares `save`. Only the jar could tell. An unqualified call in a file with a static on-demand import (`import static org.mockito.Mockito.*`), or with a single static import of that name, stays dropped: the import may bind the name, and it arrives exactly as an inherited call does. The rule only ever turns a drop into an edge: no edge that existed before changes. + +```text + ancestor-attributed : 5 (derived) + ambiguous-ancestor : 0 (dropped) +``` + +The two counts close the resolution summary on stderr. On spring-petclinic: 891 → 896 edges, 5 attributed, 0 ambiguous, and the ten reads byte-identical (13 and 0 with its tests). BroadleafCommerce: 383 attributed sites, mostly JUnit 3's `assertTrue` on `TestCase`, and 12 ambiguous. apache/fineract: 313 attributed and 1 103 ambiguous, after the Lombok condition, without which 2 319 generated getters (`getLoanProductRelatedDetail()`) were charged to Spring's `Persistable`. + +**Not covered:** a read the corpus redeclares (it is already an edge to the corpus method); an interface with two library parents (ambiguous); a receiver whose type is not written (`var`, a call's result, an inferred lambda parameter, an array element); a method reference (`owners::save` already folds to the corpus interface). + +**Explain re-asks these units.** A unit holding such a call has one fact more (`- JpaRepository of JpaRepository (external, derived)` in its prompt), so its prompt, its fingerprint and those of the type and module above it change, and their stored insights are asked again on the next `codegraph explain`. ## Measures emitted @@ -186,12 +215,13 @@ The documented blind spots, verbatim from the profile. - noClasspath resolution rate, measured (M2 audit): 100.0% on apache/commons-lang (263 files, 133478 type references, 0 unresolved) and 77.8% on spring-petclinic (30 files, 2189 references, 487 unresolved, all of them Spring and Jakarta types whose jars are absent). The rate is a property of the corpus's DEPENDENCY SURFACE, not of the extractor: commons-lang is self-contained and depends on nothing but the JDK, which resolves against the runner's own classpath. A jar that is not on the classpath cannot be resolved by any extractor, so a corpus with third-party dependencies has a structural ceiling well below 100% and a single cross-corpus target number is not meaningful. The stub discipline, not the resolution rate, is the property worth asserting. - The resolution rate counts neither type variables nor ``: neither names anything that could have a declaration, so counting them measures the corpus's writing style. This is not cosmetic — ``, Spoon's static type for the `null` literal, was ALL 1466 of commons-lang's originally-reported unresolved references, making the headline number a function of how many `return null;` statements the corpus contains. - In noClasspath Spoon promotes an unresolvable RECEIVER to a type in the enclosing package: `typeHint -> typeHint.with(...)` and `cm.setStatisticsEnabled(...)` produced stub classes named `typeHint` and `cm` inside the corpus's own package on spring-petclinic. They are correctly stubbed (membership is the declared-id whitelist), and they are why the whitelist exists — but the stub set of a real corpus therefore contains a tail of entities named after local variables, and a stub count is not a count of external types. -- A lambda whose functional interface is not on the classpath is a body ECJ never resolves, nested lambdas included: every call in it reaches Spoon with no declaring type and no parameter types (and its receivers become the stubs of the note above). Such calls used to be dropped, so `cm -> cm.createCache("vets", cacheConfiguration())` on spring-petclinic left `cacheConfiguration()` with no caller. An UNQUALIFIED call there is now resolved by the language's own lookup — the innermost enclosing type with a method of that name, declared or inherited from a corpus type, then the one method whose arity accepts the call — and is `declared` when every type the lookup consulted has all its supertypes in the corpus, `derived` when one does not (a supertype outside the corpus may declare a same-arity overload, or the name itself). Still dropped: two overloads of the same arity, a name `java.lang.Object` declares (`toString`, `equals`…), `this.m()`, `Outer.this.m()`, `super.m()` and method references; a type-qualified call with arguments (`Util.f(x)`) folds to its type. +- A lambda whose functional interface is not on the classpath is a body ECJ never resolves, nested lambdas included: every call in it reaches Spoon with no declaring type and no parameter types (and its receivers become the stubs of the note above). Such calls used to be dropped, so `cm -> cm.createCache("vets", cacheConfiguration())` on spring-petclinic left `cacheConfiguration()` with no caller. An UNQUALIFIED call there is now resolved by the language's own lookup — the innermost enclosing type with a method of that name, declared or inherited from a corpus type, then the one method whose arity accepts the call — and is `declared` when every type the lookup consulted has all its supertypes in the corpus, `derived` when one does not (a supertype outside the corpus may declare a same-arity overload, or the name itself). Still unresolved here: two overloads of the same arity, a name `java.lang.Object` declares (`toString`, `equals`…), `this.m()`, `Outer.this.m()`, `super.m()` and method references — the ancestor rule (the next note) may still charge such a call to a library type; a type-qualified call with arguments (`Util.f(x)`) folds to its type. +- A call to a method a corpus type inherits from a LIBRARY type has no declaring type Spoon can name without the jar, so it was dropped: on spring-petclinic `owners.save(owner)` on `OwnerRepository extends JpaRepository` left no edge, while the reads the interface redeclares resolved. It is now an `invocation` (a `reference` outside every invocable) of the stub of the one library ancestor that could answer, naming the method, with provenance `derived` — an inference by elimination, counted `ancestor-attributed` in the run's summary — when: the receiver's type is WRITTEN in the corpus (a field, a parameter, a local not declared `var`), or is `this` (`Outer.this` looks in `Outer` alone), `super` (from the superclass, `Iface.super` from that interface: the class's own override is no evidence against it) or the implicit `this` of an unqualified call (every enclosing class looked through, JLS §15.12.1); a type written in the corpus — an anonymous class, a local class, an enum constant body — is walked like any corpus type, whatever its id, and is never a candidate, so `new LibCallback() { … helper(); }` in a class extending `LibBase` is ambiguous; no corpus type of that type's supertype closure declares a method of that name; no corpus type there carries a Lombok annotation (it has members no source writes: on apache/fineract 2 319 getters were charged to `Persistable` before this condition); and exactly ONE library type there could answer — one Spoon can see (the JDK) only for a name it has, `java.lang.Object` never. The target is the type the corpus WROTE, erased (`JpaRepository`, though `CrudRepository` really declares `save`: only the jar could tell). With two that could answer, the call stays dropped and is counted `ambiguous-ancestor`; with none, dropped as before. An unqualified call in a file with a static on-demand import (`import static org.mockito.Mockito.*`), or a single static import of that name, stays dropped: the import may bind it. Not covered: a read the corpus redeclares (already an edge to the corpus method), an interface with two library parents (ambiguous), a receiver whose type is not written (`var`, a call's result, an inferred lambda parameter, an array element), a method reference. A unit holding such a call has one fact more, so its explain prompt and fingerprint change and its stored insight is re-asked. Measured: spring-petclinic 891 → 896 edges (5 attributed, 0 ambiguous; with its tests 13, 0), BroadleafCommerce 383 attributed sites and 12 ambiguous, apache/fineract 313 and 1 103; no edge that existed before moved. - An array type is not an entity, and neither is its component where a member is concerned. `xs.length` and `int[]::new` declare their member on `int[]` / `Money[]`; folding that up names the component and states a fact the source never wrote. Such facts are dropped, not degraded — the dependency on the component is already carried by the written type reference that mentions it. - An anonymous class has exactly one id, the `#file:line:column` form pass 1 declared. Spoon names it `Outer$N`, which renders as a plausible nested-type id in the corpus's own package; a reference resolved through that name gives one declared class two ids and launders the second into a stub. Type references must be resolved to their declaration before being named. - Spoon materializes the implicit constructor of an anonymous class with synthetic parameters named `$anonymousN`. They are emitted (implicit members are, deliberately, so that `new Foo()` does not dangle), so the model contains a handful of parameter entities nobody wrote, carrying no anchor of their own — 5 of 15338 entities on commons-lang. - The metrics pass (`codegraph-metrics`, PLAN.md §18) joins big-code-analysis spaces to entities on their anchors. Spoon starts a declaration AFTER its annotations and tree-sitter AT them; the pass bridges the two when nothing but annotation lines lies between (a LEADING join — most of a Spring corpus). It measures nothing on a lambda (big-code-analysis opens no space for one and charges its cognitive, exits and ABC to the enclosing method), on an implicit constructor (anchored on its class) or on an annotation element (no body): those carry none of the pass's keys. -- MM-6 (an edge's `member`, contract 1.1.0): an edge to a stub names the member the site wrote, by its SIMPLE name — no parameter types, since an external method's erased types need a classpath and the extractor runs noClasspath. A method call on a stub type is an `invocation` naming the method (`lines.add(x)` → `add`, a static call through a static import included: `asList`); a method reference `Integer::parseInt` names `parseInt`; a field read or written is an `access` naming the field (`System.out` → `out`), and a read and a write of one field at one site stay one access with both flags; written outside every invocable (a field initializer, an annotation argument) the call or the field read degrades to a `reference` that keeps the name (`Logger.getLogger(…)` → `getLogger`, `@Retention(RetentionPolicy.RUNTIME)` → `RUNTIME`). Named nowhere: a constructor call or reference (`new ArrayList<>()`, `super(…)`, `ArrayList::new` — the edge to the type says all the site wrote), a class literal (`Foo.class` is no member of Foo), a written type use, a supertype clause, and every edge to a corpus entity — its member is an entity, and the edge points at it. The member is part of the edge: `values.isEmpty() ? null : values.get(0)` is two invocations of `List`, where it was one. Measured on spring-petclinic: 723 of 1 164 edges to stubs named, 2 800 edges become 2 847 (42 sites split). A call to a member a corpus interface INHERITS from a library one (`owners.save(owner)` on a Spring Data `JpaRepository`) yields no edge in noClasspath, before as after, so it names nothing: the five repository writes of spring-petclinic have no edge. +- MM-6 (an edge's `member`, contract 1.1.0): an edge to a stub names the member the site wrote, by its SIMPLE name — no parameter types, since an external method's erased types need a classpath and the extractor runs noClasspath. A method call on a stub type is an `invocation` naming the method (`lines.add(x)` → `add`, a static call through a static import included: `asList`); a method reference `Integer::parseInt` names `parseInt`; a field read or written is an `access` naming the field (`System.out` → `out`), and a read and a write of one field at one site stay one access with both flags; written outside every invocable (a field initializer, an annotation argument) the call or the field read degrades to a `reference` that keeps the name (`Logger.getLogger(…)` → `getLogger`, `@Retention(RetentionPolicy.RUNTIME)` → `RUNTIME`). Named nowhere: a constructor call or reference (`new ArrayList<>()`, `super(…)`, `ArrayList::new` — the edge to the type says all the site wrote), a class literal (`Foo.class` is no member of Foo), a written type use, a supertype clause, and every edge to a corpus entity — its member is an entity, and the edge points at it. The member is part of the edge: `values.isEmpty() ? null : values.get(0)` is two invocations of `List`, where it was one. Measured on spring-petclinic: 723 of 1 164 edges to stubs named, 2 800 edges become 2 847 (42 sites split). A call to a member a corpus type INHERITS from a library one (`owners.save(owner)` on a Spring Data `JpaRepository`) has no declaring type in noClasspath; where the ancestor rule (the `ancestor-attributed` note) charges it to the one library ancestor, the edge names the member like any other (`save`, `saveAndFlush`): the five repository writes of spring-petclinic. ## The reference corpus diff --git a/website/content/docs/reference/model-jsonl.md b/website/content/docs/reference/model-jsonl.md index 533c2f8d..db64268d 100644 --- a/website/content/docs/reference/model-jsonl.md +++ b/website/content/docs/reference/model-jsonl.md @@ -225,7 +225,7 @@ From `fixtures/java/expected/model.jsonl`, five lines out of 200: {"t":"f","i":0,"path":"com/acme/order/AbstractOrder.java"} {"t":"e","i":2,"k":3,"tr":[6,11,0,2,16,15,14,10,3],"m":0,"s":"AbstractOrder.(java.lang.String)","signature":"(java.lang.String)","parent":1,"parameters":[3],"localVariables":[],"metrics":{"cyclomatic":1,"sloc":4},"anchor":[0,10,13]} {"t":"x","k":1,"f":8,"o":168,"p":0,"arguments":[{"name":"value","value":{"k":"enum","type":169,"name":"RUNTIME"}}],"anchor":[1,7,7]} -{"t":"eof","counts":{"files":16,"entities":179,"edges":189}} +{"t":"eof","counts":{"files":16,"entities":179,"edges":190}} ``` ## Why JSONL diff --git a/website/content/docs/reference/profiles.md b/website/content/docs/reference/profiles.md index 87bccf17..7af835a8 100644 --- a/website/content/docs/reference/profiles.md +++ b/website/content/docs/reference/profiles.md @@ -25,7 +25,7 @@ A profile licenses an entity by the rule `required(kind) ⊆ traits ⊆ required | `csharp` | C# | 15 | 8 | 22 | | `ex` | Elixir | 9 | 6 | 22 | | `go` | Go | 10 | 6 | 9 | -| `java` | Java | 12 | 8 | 19 | +| `java` | Java | 12 | 8 | 20 | | `js` | JavaScript | 8 | 5 | 13 | | `php` | PHP | 12 | 8 | 10 | | `python` | Python | 7 | 8 | 21 | @@ -261,12 +261,13 @@ A profile that is specified but has no shipped extractor is complete, not defici - noClasspath resolution rate, measured (M2 audit): 100.0% on apache/commons-lang (263 files, 133478 type references, 0 unresolved) and 77.8% on spring-petclinic (30 files, 2189 references, 487 unresolved, all of them Spring and Jakarta types whose jars are absent). The rate is a property of the corpus's DEPENDENCY SURFACE, not of the extractor: commons-lang is self-contained and depends on nothing but the JDK, which resolves against the runner's own classpath. A jar that is not on the classpath cannot be resolved by any extractor, so a corpus with third-party dependencies has a structural ceiling well below 100% and a single cross-corpus target number is not meaningful. The stub discipline, not the resolution rate, is the property worth asserting. - The resolution rate counts neither type variables nor ``: neither names anything that could have a declaration, so counting them measures the corpus's writing style. This is not cosmetic — ``, Spoon's static type for the `null` literal, was ALL 1466 of commons-lang's originally-reported unresolved references, making the headline number a function of how many `return null;` statements the corpus contains. - In noClasspath Spoon promotes an unresolvable RECEIVER to a type in the enclosing package: `typeHint -> typeHint.with(...)` and `cm.setStatisticsEnabled(...)` produced stub classes named `typeHint` and `cm` inside the corpus's own package on spring-petclinic. They are correctly stubbed (membership is the declared-id whitelist), and they are why the whitelist exists — but the stub set of a real corpus therefore contains a tail of entities named after local variables, and a stub count is not a count of external types. -- A lambda whose functional interface is not on the classpath is a body ECJ never resolves, nested lambdas included: every call in it reaches Spoon with no declaring type and no parameter types (and its receivers become the stubs of the note above). Such calls used to be dropped, so `cm -> cm.createCache("vets", cacheConfiguration())` on spring-petclinic left `cacheConfiguration()` with no caller. An UNQUALIFIED call there is now resolved by the language's own lookup — the innermost enclosing type with a method of that name, declared or inherited from a corpus type, then the one method whose arity accepts the call — and is `declared` when every type the lookup consulted has all its supertypes in the corpus, `derived` when one does not (a supertype outside the corpus may declare a same-arity overload, or the name itself). Still dropped: two overloads of the same arity, a name `java.lang.Object` declares (`toString`, `equals`…), `this.m()`, `Outer.this.m()`, `super.m()` and method references; a type-qualified call with arguments (`Util.f(x)`) folds to its type. +- A lambda whose functional interface is not on the classpath is a body ECJ never resolves, nested lambdas included: every call in it reaches Spoon with no declaring type and no parameter types (and its receivers become the stubs of the note above). Such calls used to be dropped, so `cm -> cm.createCache("vets", cacheConfiguration())` on spring-petclinic left `cacheConfiguration()` with no caller. An UNQUALIFIED call there is now resolved by the language's own lookup — the innermost enclosing type with a method of that name, declared or inherited from a corpus type, then the one method whose arity accepts the call — and is `declared` when every type the lookup consulted has all its supertypes in the corpus, `derived` when one does not (a supertype outside the corpus may declare a same-arity overload, or the name itself). Still unresolved here: two overloads of the same arity, a name `java.lang.Object` declares (`toString`, `equals`…), `this.m()`, `Outer.this.m()`, `super.m()` and method references — the ancestor rule (the next note) may still charge such a call to a library type; a type-qualified call with arguments (`Util.f(x)`) folds to its type. +- A call to a method a corpus type inherits from a LIBRARY type has no declaring type Spoon can name without the jar, so it was dropped: on spring-petclinic `owners.save(owner)` on `OwnerRepository extends JpaRepository` left no edge, while the reads the interface redeclares resolved. It is now an `invocation` (a `reference` outside every invocable) of the stub of the one library ancestor that could answer, naming the method, with provenance `derived` — an inference by elimination, counted `ancestor-attributed` in the run's summary — when: the receiver's type is WRITTEN in the corpus (a field, a parameter, a local not declared `var`), or is `this` (`Outer.this` looks in `Outer` alone), `super` (from the superclass, `Iface.super` from that interface: the class's own override is no evidence against it) or the implicit `this` of an unqualified call (every enclosing class looked through, JLS §15.12.1); a type written in the corpus — an anonymous class, a local class, an enum constant body — is walked like any corpus type, whatever its id, and is never a candidate, so `new LibCallback() { … helper(); }` in a class extending `LibBase` is ambiguous; no corpus type of that type's supertype closure declares a method of that name; no corpus type there carries a Lombok annotation (it has members no source writes: on apache/fineract 2 319 getters were charged to `Persistable` before this condition); and exactly ONE library type there could answer — one Spoon can see (the JDK) only for a name it has, `java.lang.Object` never. The target is the type the corpus WROTE, erased (`JpaRepository`, though `CrudRepository` really declares `save`: only the jar could tell). With two that could answer, the call stays dropped and is counted `ambiguous-ancestor`; with none, dropped as before. An unqualified call in a file with a static on-demand import (`import static org.mockito.Mockito.*`), or a single static import of that name, stays dropped: the import may bind it. Not covered: a read the corpus redeclares (already an edge to the corpus method), an interface with two library parents (ambiguous), a receiver whose type is not written (`var`, a call's result, an inferred lambda parameter, an array element), a method reference. A unit holding such a call has one fact more, so its explain prompt and fingerprint change and its stored insight is re-asked. Measured: spring-petclinic 891 → 896 edges (5 attributed, 0 ambiguous; with its tests 13, 0), BroadleafCommerce 383 attributed sites and 12 ambiguous, apache/fineract 313 and 1 103; no edge that existed before moved. - An array type is not an entity, and neither is its component where a member is concerned. `xs.length` and `int[]::new` declare their member on `int[]` / `Money[]`; folding that up names the component and states a fact the source never wrote. Such facts are dropped, not degraded — the dependency on the component is already carried by the written type reference that mentions it. - An anonymous class has exactly one id, the `#file:line:column` form pass 1 declared. Spoon names it `Outer$N`, which renders as a plausible nested-type id in the corpus's own package; a reference resolved through that name gives one declared class two ids and launders the second into a stub. Type references must be resolved to their declaration before being named. - Spoon materializes the implicit constructor of an anonymous class with synthetic parameters named `$anonymousN`. They are emitted (implicit members are, deliberately, so that `new Foo()` does not dangle), so the model contains a handful of parameter entities nobody wrote, carrying no anchor of their own — 5 of 15338 entities on commons-lang. - The metrics pass (`codegraph-metrics`, PLAN.md §18) joins big-code-analysis spaces to entities on their anchors. Spoon starts a declaration AFTER its annotations and tree-sitter AT them; the pass bridges the two when nothing but annotation lines lies between (a LEADING join — most of a Spring corpus). It measures nothing on a lambda (big-code-analysis opens no space for one and charges its cognitive, exits and ABC to the enclosing method), on an implicit constructor (anchored on its class) or on an annotation element (no body): those carry none of the pass's keys. -- MM-6 (an edge's `member`, contract 1.1.0): an edge to a stub names the member the site wrote, by its SIMPLE name — no parameter types, since an external method's erased types need a classpath and the extractor runs noClasspath. A method call on a stub type is an `invocation` naming the method (`lines.add(x)` → `add`, a static call through a static import included: `asList`); a method reference `Integer::parseInt` names `parseInt`; a field read or written is an `access` naming the field (`System.out` → `out`), and a read and a write of one field at one site stay one access with both flags; written outside every invocable (a field initializer, an annotation argument) the call or the field read degrades to a `reference` that keeps the name (`Logger.getLogger(…)` → `getLogger`, `@Retention(RetentionPolicy.RUNTIME)` → `RUNTIME`). Named nowhere: a constructor call or reference (`new ArrayList<>()`, `super(…)`, `ArrayList::new` — the edge to the type says all the site wrote), a class literal (`Foo.class` is no member of Foo), a written type use, a supertype clause, and every edge to a corpus entity — its member is an entity, and the edge points at it. The member is part of the edge: `values.isEmpty() ? null : values.get(0)` is two invocations of `List`, where it was one. Measured on spring-petclinic: 723 of 1 164 edges to stubs named, 2 800 edges become 2 847 (42 sites split). A call to a member a corpus interface INHERITS from a library one (`owners.save(owner)` on a Spring Data `JpaRepository`) yields no edge in noClasspath, before as after, so it names nothing: the five repository writes of spring-petclinic have no edge. +- MM-6 (an edge's `member`, contract 1.1.0): an edge to a stub names the member the site wrote, by its SIMPLE name — no parameter types, since an external method's erased types need a classpath and the extractor runs noClasspath. A method call on a stub type is an `invocation` naming the method (`lines.add(x)` → `add`, a static call through a static import included: `asList`); a method reference `Integer::parseInt` names `parseInt`; a field read or written is an `access` naming the field (`System.out` → `out`), and a read and a write of one field at one site stay one access with both flags; written outside every invocable (a field initializer, an annotation argument) the call or the field read degrades to a `reference` that keeps the name (`Logger.getLogger(…)` → `getLogger`, `@Retention(RetentionPolicy.RUNTIME)` → `RUNTIME`). Named nowhere: a constructor call or reference (`new ArrayList<>()`, `super(…)`, `ArrayList::new` — the edge to the type says all the site wrote), a class literal (`Foo.class` is no member of Foo), a written type use, a supertype clause, and every edge to a corpus entity — its member is an entity, and the edge points at it. The member is part of the edge: `values.isEmpty() ? null : values.get(0)` is two invocations of `List`, where it was one. Measured on spring-petclinic: 723 of 1 164 edges to stubs named, 2 800 edges become 2 847 (42 sites split). A call to a member a corpus type INHERITS from a library one (`owners.save(owner)` on a Spring Data `JpaRepository`) has no declaring type in noClasspath; where the ancestor rule (the `ancestor-attributed` note) charges it to the one library ancestor, the edge names the member like any other (`save`, `saveAndFlush`): the five repository writes of spring-petclinic. ## JavaScript — `js` diff --git a/website/content/docs/tutorials/explain.md b/website/content/docs/tutorials/explain.md index 62505666..b5fbe8ca 100644 --- a/website/content/docs/tutorials/explain.md +++ b/website/content/docs/tutorials/explain.md @@ -46,7 +46,9 @@ RESOLUTION SUMMARY unresolved : 35 resolution rate : 94.5% entities : 179 (stubs: 27) - edges : 189 (self-edges dropped: 0) + edges : 190 (self-edges dropped: 0) + ancestor-attributed : 1 (derived) + ambiguous-ancestor : 0 (dropped) ``` {{< callout type="info" >}}