From c8a1afc40999521d2682903d93c43d3d17595d19 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 07:17:32 -0500 Subject: [PATCH 01/19] docs(design): schema v2 id format for Go callables and types Spec from the design loop: types /, methods //, functions /, closures keep closure_N, external ids /@external///, Neo4j signature from the JSON field. Follows codeanalyzer-typescript idFromSig and codeanalyzer-python child_id. --- docs/design/specs/v2-go-ids.md | 117 +++++++++++++++++++++++++++++++++ 1 file changed, 117 insertions(+) create mode 100644 docs/design/specs/v2-go-ids.md diff --git a/docs/design/specs/v2-go-ids.md b/docs/design/specs/v2-go-ids.md new file mode 100644 index 0000000..9ec996e --- /dev/null +++ b/docs/design/specs/v2-go-ids.md @@ -0,0 +1,117 @@ +# Spec: schema v2 id format for Go callables and types (codeanalyzer-go) + +> **Cross-repo spec.** The python-sdk Go backend keys types and fields by the last id segment, +> so the canonical home is `codellm-devkit/.github → docs/design/specs/`, beside the +> coordinating record. Staged locally on `feat/v2-go-ids` until that repo is available (same +> precedent as `v2-l1-emission.md` and `v2-artifacts.md`). This is the design transcript of the +> datamodel loop, linked from the tracking issue, not pasted into it. + +## Contract-Impact Triage + +**Does this change schema v2 output?** Yes. It changes the id shape of `type`, method, and +function nodes, and of `external_symbols` keys. It does not change the module, field, +artifact, or ordinal-id shapes, and it adds no field. + +| Change type | Analyzers | SDKs | Docs | +| --- | --- | --- | --- | +| Schema v2 id-format change | **codeanalyzer-go** (`internal/schema/v2/ids.go`, `v2emit`, Neo4j projector) | **python-sdk** Go backend (`cldk/analysis/go/neo4j/neo4j_backend.py` keys types and fields by last id segment; verify methods at the SDK rung) | `CLAUDE.md` § Schema decisions, `canonical-schema.md` references, this spec | + +Convention anchor: `codeanalyzer-typescript/src/schema/ids.ts` (`idFromSig`: strip the module +prefix from the dotted signature, split the tail on `.`) and `codeanalyzer-python/codeanalyzer/schema/ids.py` +(`child_id`, `ordinal_id`, `external_id`, `artifact_id`). + +## Problem + +Go ids embed the full import-qualified signature as one segment. For a method this repeats the +package path twice: + +``` +can://boutique/frontend/go/middleware.go/github.com/GoogleCloudPlatform/microservices-demo/src/frontend.logHandler/github.com/GoogleCloudPlatform/microservices-demo/src/frontend.logHandler.ServeHTTP/github.com/GoogleCloudPlatform/microservices-demo/src/frontend.logHandler.ServeHTTP.closure_1@82:3/2/actual_out:2 +``` + +The segment is not a path segment. A parser that splits on `/` (the Neo4j projector's +`lastSegment`) cannot recover a Go callable's name from its id, and the id is long and +unreadable. + +## Design-loop decisions (the transcript) + +Each decision was made with the user, one per question, in spine order. + +### Module (unchanged) +`can:////go/`. Already the convention. No question was needed. + +### Type +- **Tail = ``** (user decision, recommended). The Go package path is stripped from the + signature, then the type name is appended to the module: `/logHandler`. Precedent: + TypeScript `idFromSig`, Python `child_id`. The package path is not repeated, since the module + already names the scope. +- The package path that is stripped is the `pkgPath` of the symbol's signature, which equals + the package's import path. It is the same for every symbol in one file. + +### Callable +- **Function: `/`**, e.g. `middleware.go/ensureSessionID`. No receiver. +- **Method: `//`** (user decision, recommended). A method nests under its + receiver type, matching containment (`type.callables`). Precedent: TypeScript split-on-dots, + Python `child_id`. Example: `middleware.go/logHandler/ServeHTTP`. +- **Closure: `/closure_N`** (user decision, recommended). N is the source-order index + within the enclosing callable, as the analyzer numbers them today. Example: + `middleware.go/logHandler/ServeHTTP/closure_1`. Position is not used, because the body + ordinal key already carries it. +- **Ordinal and synthetic keys are unchanged**: `@`, `@entry`, `@exit`, + `@formal_in:`, `@actual_in:` / `@actual_out`, and the `/N` disambiguator for nested + calls at one position. Nothing in those changes. + +### Field +`/`, already in this shape. No change. + +### External symbols (decided earlier with the user) +`/@external///`, the TypeScript `/` form. The +import path stays whole, since it contains dots and slashes. A package-level function is +`/@external//`. + +### Call body node and call-graph edge +Unchanged in shape. A call node's `callee` and a call-graph edge's endpoints take the new +callable and external ids. No new field. + +### Projector: signature property (user decision) +The Neo4j `signature` property on `:GoCallable` and `:GoType` is copied from the node's JSON +`signature` field, not derived from the id. Today the projector takes the last `/` or `@` +segment of the id (`lastSegment`), which yields `Type.Method` and loses the import-qualified +name the JSON carries. The id no longer needs to carry it. + +## Consequences + +- **Parsing**: a Go id splits cleanly on `/`: module, then type, then method. The `@` ordinal + suffix is unchanged. +- **Uniqueness**: ids are unique within a file. Go forbids duplicate package-scope identifiers, + and forbids a duplicate method name on one type. Two files in one package have distinct + module ids, so the stripped package path never causes a collision. +- **Cross-file methods**: a method declared in another file nests under its receiver type's + module, as today (`source_file` handles its text). Its id is `//`. +- **python-sdk**: `cldk/analysis/go/neo4j/neo4j_backend.py` keys types by `ty.id.split("/")[-1]`, + which still returns the type name, and fields by `fld.id.split("/")[-1]`, which is unchanged. + Callables keyed by a dotted sig will change meaning: the last segment is now the bare method + name. The SDK rung must verify this. + +## Open items (flagged for review) + +1. **Name collision inside a file**: a type `X` and a function `X` cannot share a file's package + scope, so the ids cannot collide. Confirm no other Go construct gives two nodes the same + `//` (a type's method set is unique by name). Expected: none. +2. **Generic types**: a generic type's signature includes type parameters. The `[...]` part is + not part of the segment name. Decide at implementation: strip the type parameters (default) + or keep them. +3. **Dot-free function names in `external_symbols` keys**: keys become `//`. + Confirm the key is still unique when two packages share a last path element. + +## Tracking + +One issue in `codeanalyzer-go`, rungs as checklist items (user decision). Base branch +`feat/artifacts`, since the artifact code is the base for this work (user decision). Analyzer +ships first; the python-sdk Go backend follows once the id shape is released. + +## Out of scope + +- Module, field, artifact, and ordinal-id shapes. +- Any new node kind, edge kind, or field. +- Renaming the `signature` field (kept as-is). From 8b08451fc5be3bc2dba39fd04b8e95256df03901 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 07:28:50 -0500 Subject: [PATCH 02/19] feat(ids): Go callable and type ids use the bare member name (TS/Python convention) Type /, method //, function /, closure /closure_N; the package import path is dropped (the member is the signature part after its last dot). External ids /@external///. Type nodes gain a signature field (full import-qualified name) so the Neo4j :GoType signature no longer depends on the id. Projector copies signature from the JSON field. Refs codellm-devkit/codeanalyzer-go#46 --- CLAUDE.md | 22 ++++-- docs/design/specs/v2-go-ids.md | 13 ++++ internal/neo4j/project.go | 2 +- internal/neo4j/signature_test.go | 75 ++++++++++++++++++ internal/schema/v2/ids.go | 55 ++++++++++---- internal/schema/v2/ids_member_test.go | 76 +++++++++++++++++++ internal/schema/v2/ids_test.go | 2 +- internal/schema/v2/schema.go | 6 +- .../v2emit/determinism_freshbuild_test.go | 4 +- internal/syntactic_analysis/v2emit/emit.go | 1 + .../syntactic_analysis/v2emit/gate_l2_test.go | 8 +- .../syntactic_analysis/v2emit/gate_l3_test.go | 4 +- .../v2emit/gate_l4_done_test.go | 2 +- .../syntactic_analysis/v2emit/gate_test.go | 2 +- 14 files changed, 239 insertions(+), 33 deletions(-) create mode 100644 internal/neo4j/signature_test.go create mode 100644 internal/schema/v2/ids_member_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 9091930..36b310e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -15,10 +15,21 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. - **`application.id`** = `can://` (app outermost, so a polyglot app shares one prefix), where `` is the **`--app-name`** value, defaulting to the input directory's base name (per the CLI contract; the SDK's Neo4j backend must use the same anchor). Module ids are - `can:///go/`; externals are language-neutral `can:///@external//`. + `can:///go/`; externals are language-neutral `can:///@external///` (see § Id member segments). L3/L4 build ids on this unchanged. -- **Callable signature** = existing `signatureOf()` output as the last `can://` path - segment; receiver folded in for methods. One canonicalizer, unchanged from v1. +- **Id member segments (spec `docs/design/specs/v2-go-ids.md`, issue #46)**: a type is + `/`; a method is `//`; a package-level function is + `/`; a closure is `/closure_N`. The package import path is dropped: + the member segment is the signature's part after its last dot (Go names contain no dots). + Follows `codeanalyzer-typescript` `idFromSig` and `codeanalyzer-python` `child_id` + [user, 2026-11-20]. Externals: `/@external///` (import path + whole) [user, 2026-11-20]. +- **Callable and type `signature`** = the full `signatureOf()` output (import-qualified), a + JSON field on both (types gained it, additive, for the Neo4j `:GoType.signature`) [user, + 2026-11-20]. The id carries only the bare member name, so this field is where the package + path lives. One canonicalizer, unchanged from v1. +- **Generic types**: `signatureOf()` carries no type parameters, so a generic type or method + ids as `//`, with no `[T]` in the id. - **`span.bytes`** = **UTF-8 byte offsets** into `module.source` (Go strings are natively UTF-8; avoids the UTF-16/rune slicing mismatch TS hit in cants#179). @@ -64,8 +75,9 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. `(*strings.Builder).WriteString`) is no longer dropped: the call node's `callee` and the `call_graph` edge `dst` are the callee's `@external` id. Builtins, type conversions (no longer minted as `.__new__`) and calls through function values stay `null`. -- **Id** = `can:///@external//` where `` is the callee signature - minus the `.` prefix (`Println`, `Builder.WriteString`); it may also name a +- **Id** = `can:///@external///` where `` is the callee signature + minus the `.` prefix; its dots become segments (`Println` → `…/fmt/Println`, + `Builder.WriteString` → `…/strings/Builder/WriteString`); it may also name a library *interface* method (`@external/io/Writer.Write`). Methods on generic library types record the declared (origin) signature, not the instance. `@external` is language-neutral (not `go/`), so a polyglot app shares one external namespace. diff --git a/docs/design/specs/v2-go-ids.md b/docs/design/specs/v2-go-ids.md index 9ec996e..4ed8d62 100644 --- a/docs/design/specs/v2-go-ids.md +++ b/docs/design/specs/v2-go-ids.md @@ -110,6 +110,19 @@ One issue in `codeanalyzer-go`, rungs as checklist items (user decision). Base b `feat/artifacts`, since the artifact code is the base for this work (user decision). Analyzer ships first; the python-sdk Go backend follows once the id shape is released. +## Implementation notes (2026-11-20) + +- **Type signature field (amended)**: the spec said this change adds no field. The Neo4j + `:GoType.signature` needs the full name, which the type id no longer carries, so `Type` + gained a `signature` JSON field (the full `signatureOf()`), mirroring `Callable`. The + projector copies it. Decided with the user. +- **Member name rule**: implemented as "the part after the last dot of the signature". This + is the same as stripping the import path, since Go identifiers contain no dots. +- **Open item 2 (generics) resolved**: `signatureOf()` has no type parameters, so a generic + type `Set[T]` ids as `set/set.go/Set` and its method as `set/set.go/Set/Add`. +- **Open item 1 (collisions) resolved**: the generics fixture and the chi/init fixtures + produce distinct ids. `init` functions are distinct per file by module. + ## Out of scope - Module, field, artifact, and ordinal-id shapes. diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index 7df42af..455e365 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -167,7 +167,7 @@ func (p *projector) projectType(modRef NodeRef, module string, t v2.Type) { "id", t.ID, Props{ "kind": t.Kind, // struct|interface|alias|defined (decision T1) - "signature": lastSegment(t.ID), + "signature": t.Signature, "span_json": spanJSON(t.Span), }, module, diff --git a/internal/neo4j/signature_test.go b/internal/neo4j/signature_test.go new file mode 100644 index 0000000..1df9ffc --- /dev/null +++ b/internal/neo4j/signature_test.go @@ -0,0 +1,75 @@ +package neo4j + +import ( + "testing" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// The :GoCallable signature property is the JSON signature field, the full +// import-qualified name, not a segment parsed out of the id (the id now carries +// only the bare member name). +func TestProject_CallableSignatureFromJSONField(t *testing.T) { + const ( + sig = "github.com/acme/app/worker.Worker.Run" + mod = "can://ns/app/go/worker.go" + ) + a := &v2.Analysis{ + IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, + Application: v2.Application{ + IdentityVersion: 2, ID: "can://ns/app", Kind: "application", + SymbolTable: map[string]v2.Module{ + "worker.go": { + ID: mod, Kind: "module", + Types: map[string]v2.Type{ + "Worker": { + ID: mod + "/Worker", Kind: "struct", Signature: "github.com/acme/app/worker.Worker", + Callables: map[string]v2.Callable{ + "Run": {ID: mod + "/Worker/Run", Kind: "method", Signature: sig}, + }, + }, + }, + }, + }, + }, + } + rows := Project(a) + for _, n := range rows.Nodes { + if hasLabel(n, LabelCallable) && n.Value == mod+"/Worker/Run" { + if got := n.Props["signature"]; got != sig { + t.Errorf("signature property = %v, want %q", got, sig) + } + return + } + } + t.Fatalf("no :GoCallable row for %s", mod+"/Worker/Run") +} + +// The :GoType signature is the type JSON's signature field (full name), not the +// bare type name the id ends with. +func TestProject_TypeSignatureFromJSONField(t *testing.T) { + const ( + sig = "github.com/acme/app/worker.Worker" + mod = "can://ns/app/go/worker.go" + ) + a := &v2.Analysis{ + IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, + Application: v2.Application{ + IdentityVersion: 2, ID: "can://ns/app", Kind: "application", + SymbolTable: map[string]v2.Module{ + "worker.go": {ID: mod, Kind: "module", Types: map[string]v2.Type{ + "Worker": {ID: mod + "/Worker", Kind: "struct", Signature: sig}, + }}, + }, + }, + } + for _, n := range Project(a).Nodes { + if hasLabel(n, LabelType) && n.Value == mod+"/Worker" { + if got := n.Props["signature"]; got != sig { + t.Errorf("type signature property = %v, want %q", got, sig) + } + return + } + } + t.Fatalf("no :GoType row for %s", mod+"/Worker") +} diff --git a/internal/schema/v2/ids.go b/internal/schema/v2/ids.go index e2e0788..2b2cf5f 100644 --- a/internal/schema/v2/ids.go +++ b/internal/schema/v2/ids.go @@ -15,18 +15,26 @@ import ( // Durable id grammar (the app segment is outermost so a polyglot app shares one // `can:///` prefix across languages; the language follows it): // -// can://///// -// can://myapp/myapp/go/src/util.go/Hasher/Hash(string)uint64 +// can:///// module +// can:////// type +// can://///// method +// can:////// package-level function +// can://myapp/myapp/go/util.go/Hasher/Hash e.g. a method +// +// Each member segment is the bare name: the package import path is dropped (it is +// always before the last dot of the signature, and Go names contain no dots). +// Closures nest under their enclosing callable as closure_N. // // External (out-of-project) symbols are language-neutral: // -// can:////@external// +// can:////@external/// +// can://myapp/myapp/@external/strings/Builder/WriteString // // Ordinal id grammar (statements and synthetic vertices, addressed WITHIN their // callable): // -// @: e.g. …/Hash(string)uint64@15:2 -// @ e.g. …/Hash(string)uint64@entry +// @: e.g. …/Hasher/Hash@15:2 +// @ e.g. …/Hasher/Hash@entry // // The delimiters `/`, `@`, `:` are fixed by the keystone; do not substitute. const ( @@ -91,13 +99,29 @@ func ModuleID(appID, relPath string) string { } // ExternalID builds the id of an out-of-project symbol: -// /@external//. It is language-neutral. An empty sig -// (an import-level ghost, no symbol) yields /@external/. +// /@external/// (or .../ for a +// package-level function). sig is the callee signature without the import-path +// prefix ("Client.Zone"); its dots become path segments, matching the in-project +// form. It is language-neutral. An empty sig (an import-level ghost, no symbol) +// yields /@external/. func ExternalID(appID, importPath, sig string) string { if sig == "" { return appID + idSep + "@external" + idSep + importPath } - return appID + idSep + "@external" + idSep + importPath + idSep + sig + return appID + idSep + "@external" + idSep + importPath + idSep + strings.ReplaceAll(sig, ".", idSep) +} + +// memberName is the member segment a symbol contributes under its parent: the +// part of its signature after the last dot. The package import path is always +// before that dot and Go identifiers contain no dots, so this strips the path +// and keeps the bare name (a function or type name, a method name, or a closure +// name such as closure_1). Precedent: codeanalyzer-typescript idFromSig and +// codeanalyzer-python child_id. +func memberName(sig string) string { + if i := strings.LastIndex(sig, "."); i >= 0 { + return sig[i+1:] + } + return sig } // GlobalOrdinal joins a callable id and a local ordinal: callableID + local @@ -110,17 +134,18 @@ func GlobalOrdinal(callableID, local string) string { return callableID + ordinalSep + local } -// TypeID builds a type id under its module. sig is the type's signatureOf() -// output — the last (and only) segment the type contributes. +// TypeID builds a type id under its module: /. sig is the type's +// signatureOf() output; the package path is dropped (see memberName). func TypeID(moduleID, sig string) string { - return moduleID + idSep + sig + return moduleID + idSep + memberName(sig) } -// CallableID builds a callable id under its parent. For a method the parent is -// its receiver Type id; for a module-level function the parent is the Module -// id. sig is the callable's signatureOf() output — the last path segment. +// CallableID builds a callable id under its parent: / for a +// method (parent is the receiver Type id), / for a package-level +// function (parent is the Module id), /closure_N for a closure. sig is +// the callable's signatureOf() output; the package path is dropped (see memberName). func CallableID(parentID, sig string) string { - return parentID + idSep + sig + return parentID + idSep + memberName(sig) } // OrdinalID addresses a real body node (statement / call) within its callable diff --git a/internal/schema/v2/ids_member_test.go b/internal/schema/v2/ids_member_test.go new file mode 100644 index 0000000..4cb931a --- /dev/null +++ b/internal/schema/v2/ids_member_test.go @@ -0,0 +1,76 @@ +package v2 + +import "testing" + +// The member segment is the signature's last dot-separated part, so the package +// import path (which may itself contain dots) never reaches the id. +func TestMemberIDs_DropPackagePath(t *testing.T) { + mod := ModuleID("can://ns/app", "go/w.go") + cases := []struct { + name string + got string + want string + }{ + {"type", TypeID(mod, "github.com/acme/app/worker.Worker"), mod + "/Worker"}, + {"function", CallableID(mod, "github.com/acme/app/worker.Run"), mod + "/Run"}, + {"method", CallableID(TypeID(mod, "github.com/acme/app/worker.Worker"), "github.com/acme/app/worker.Worker.Run"), mod + "/Worker/Run"}, + {"closure", CallableID(mod+"/Run", "github.com/acme/app/worker.Run.closure_2"), mod + "/Run/closure_2"}, + {"dotted import path", CallableID(mod, "gopkg.in/yaml.v2.Marshal"), mod + "/Marshal"}, + {"init", CallableID(mod, "github.com/acme/app/worker.init"), mod + "/init"}, + } + for _, c := range cases { + if c.got != c.want { + t.Errorf("%s: got %q, want %q", c.name, c.got, c.want) + } + } +} + +// Library callees: the import path stays whole, and the member's dots become +// segments, so Type and Member are separate segments. +func TestExternalID_PathForm(t *testing.T) { + const app = "can://ns/app" + cases := []struct { + importPath, sig, want string + }{ + {"strings", "Builder.WriteString", app + "/@external/strings/Builder/WriteString"}, + {"fmt", "Println", app + "/@external/fmt/Println"}, + {"database/sql", "DB.Query", app + "/@external/database/sql/DB/Query"}, + {"cloud.google.com/go/compute/metadata", "Client.Zone", app + "/@external/cloud.google.com/go/compute/metadata/Client/Zone"}, + {"net/http", "", app + "/@external/net/http"}, + } + for _, c := range cases { + if got := ExternalID(app, c.importPath, c.sig); got != c.want { + t.Errorf("ExternalID(%q, %q) = %q, want %q", c.importPath, c.sig, got, c.want) + } + } +} + +// Two library symbols with the same member name in different packages must keep +// distinct ids: the import path is the disambiguator. +func TestExternalID_SameMemberDifferentPackagesDistinct(t *testing.T) { + const app = "can://ns/app" + a := ExternalID(app, "encoding/json", "Decoder.Decode") + b := ExternalID(app, "encoding/xml", "Decoder.Decode") + if a == b { + t.Fatalf("encoding/json and encoding/xml Decoder.Decode collide at %s", a) + } +} + +// Within one module, every member name is unique: Go forbids duplicate package- +// scope identifiers and duplicate method names per type, so the bare names are +// safe as keys under their parent. +func TestMemberIDs_UniqueWithinModule(t *testing.T) { + mod := ModuleID("can://ns/app", "go/a.go") + ids := map[string]bool{} + for _, id := range []string{ + TypeID(mod, "pkg.T"), + CallableID(mod, "pkg.F"), + CallableID(TypeID(mod, "pkg.T"), "pkg.T.M"), + CallableID(TypeID(mod, "pkg.T"), "pkg.T.N"), + } { + if ids[id] { + t.Errorf("duplicate id %s", id) + } + ids[id] = true + } +} diff --git a/internal/schema/v2/ids_test.go b/internal/schema/v2/ids_test.go index 72e4ee3..7361348 100644 --- a/internal/schema/v2/ids_test.go +++ b/internal/schema/v2/ids_test.go @@ -97,7 +97,7 @@ func TestIDs_AppOutermost(t *testing.T) { cases := []struct{ got, want string }{ {app, "can://shop/shop"}, {ModuleID(app, "pkg/a.go"), "can://shop/shop/go/pkg/a.go"}, - {ExternalID(app, "database/sql", "DB.Query"), "can://shop/shop/@external/database/sql/DB.Query"}, + {ExternalID(app, "database/sql", "DB.Query"), "can://shop/shop/@external/database/sql/DB/Query"}, {GlobalOrdinal("X/F", "@entry"), "X/F@entry"}, {GlobalOrdinal("X/F", "12:3"), "X/F@12:3"}, } diff --git a/internal/schema/v2/schema.go b/internal/schema/v2/schema.go index ce3eefa..3c5ca1a 100644 --- a/internal/schema/v2/schema.go +++ b/internal/schema/v2/schema.go @@ -185,6 +185,9 @@ type Type struct { ID string `json:"id"` Kind string `json:"kind"` // struct | interface | alias | defined Span Span `json:"span"` + // Signature is the type's full import-qualified name (one signatureOf()). The + // id carries only the bare type name, so this is where the package path lives. + Signature string `json:"signature"` // BaseTypes are embedded type ids (struct/interface embedding — the explicit // spine). BaseTypes []string `json:"base_types,omitempty"` @@ -214,7 +217,8 @@ type Callable struct { ID string `json:"id"` Kind string `json:"kind"` // function | method | lambda Span Span `json:"span"` - // Signature is the human-readable last path segment of ID (one signatureOf()). + // Signature is the full import-qualified name (one signatureOf()). The id + // carries only the bare member name, so this field is where the package path lives. Signature string `json:"signature"` // SourceFile names the callable's declaring file (a symbol_table key) when it // differs from the module this callable is nested under — the Go case where a diff --git a/internal/syntactic_analysis/v2emit/determinism_freshbuild_test.go b/internal/syntactic_analysis/v2emit/determinism_freshbuild_test.go index b4b7d6a..f0d73ac 100644 --- a/internal/syntactic_analysis/v2emit/determinism_freshbuild_test.go +++ b/internal/syntactic_analysis/v2emit/determinism_freshbuild_test.go @@ -116,7 +116,7 @@ func TestInitCollision_DistinctNodesAndEdges(t *testing.T) { continue } for _, fn := range mod.Functions { - if strings.HasSuffix(fn.ID, "middleware.init") { + if strings.HasSuffix(fn.ID, "/init") { initNodeIDs[fn.ID] = true } } @@ -131,7 +131,7 @@ func TestInitCollision_DistinctNodesAndEdges(t *testing.T) { // edge resolved to ITS OWN file's init, so the id is self-consistent). sawInitEdge := false for _, e := range out.Application.CallGraph { - if !strings.HasSuffix(e.Src, "middleware.init") { + if !strings.HasSuffix(e.Src, "/init") { continue } sawInitEdge = true diff --git a/internal/syntactic_analysis/v2emit/emit.go b/internal/syntactic_analysis/v2emit/emit.go index 1371aa4..55e81a4 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/v2emit/emit.go @@ -310,6 +310,7 @@ func emitType(modID, modRel string, t schema.GoType, idx sigIndex, srcs *sourceC out := v2.Type{ ID: typeID, Kind: typeKind(t), + Signature: t.Signature, Span: lineSpan(li, t.StartLine, t.EndLine), BaseTypes: nonEmpty(t.BaseTypes), Callables: make(map[string]v2.Callable, len(t.Methods)), diff --git a/internal/syntactic_analysis/v2emit/gate_l2_test.go b/internal/syntactic_analysis/v2emit/gate_l2_test.go index d402ed6..412d424 100644 --- a/internal/syntactic_analysis/v2emit/gate_l2_test.go +++ b/internal/syntactic_analysis/v2emit/gate_l2_test.go @@ -110,8 +110,8 @@ func TestGateL2_NamedEdgePresent(t *testing.T) { out := buildMultipackageL2(t) const ( - src = "can://multipackage/multipackage/go/worker/worker.go/example.com/multipackage/worker.Worker/example.com/multipackage/worker.Worker.Run" - dst = "can://multipackage/multipackage/go/worker/worker.go/example.com/multipackage/worker.Worker/example.com/multipackage/worker.Worker.execute" + src = "can://multipackage/multipackage/go/worker/worker.go/Worker/Run" + dst = "can://multipackage/multipackage/go/worker/worker.go/Worker/execute" ) found := false for _, e := range out.Application.CallGraph { @@ -133,8 +133,8 @@ func TestGateL2_CrossPackageEdge(t *testing.T) { out := buildMultipackageL2(t) const ( - src = "can://multipackage/multipackage/go/main.go/example.com/multipackage.main" - dst = "can://multipackage/multipackage/go/server/server.go/example.com/multipackage/server.New" + src = "can://multipackage/multipackage/go/main.go/main" + dst = "can://multipackage/multipackage/go/server/server.go/New" ) found := false for _, e := range out.Application.CallGraph { diff --git a/internal/syntactic_analysis/v2emit/gate_l3_test.go b/internal/syntactic_analysis/v2emit/gate_l3_test.go index a9f17fc..ddec91a 100644 --- a/internal/syntactic_analysis/v2emit/gate_l3_test.go +++ b/internal/syntactic_analysis/v2emit/gate_l3_test.go @@ -508,7 +508,7 @@ func TestSymbolTable_MethodDeclaredAboveItsType(t *testing.T) { for _, mod := range out.Application.SymbolTable { for _, ty := range mod.Types { for _, m := range ty.Callables { - if strings.HasSuffix(m.ID, "/"+sig) { + if strings.HasSuffix(m.ID, "/early/Bump") { return m, true } } @@ -531,7 +531,7 @@ func TestSymbolTable_MethodDeclaredAboveItsType(t *testing.T) { if call == nil { t.Fatalf("%s has no call site", sig) } - if call.Callee == nil || !strings.HasSuffix(*call.Callee, "/"+fID) { + if call.Callee == nil || !strings.HasSuffix(*call.Callee, "/f") { t.Fatalf("call to f not resolved at -a 2: callee = %v", call.Callee) } sawEdge := false diff --git a/internal/syntactic_analysis/v2emit/gate_l4_done_test.go b/internal/syntactic_analysis/v2emit/gate_l4_done_test.go index 6803719..c22142b 100644 --- a/internal/syntactic_analysis/v2emit/gate_l4_done_test.go +++ b/internal/syntactic_analysis/v2emit/gate_l4_done_test.go @@ -144,7 +144,7 @@ func TestGateL4_HTTPToSQLPath(t *testing.T) { method := func(typ, m string) string { return v2.CallableID(v2.TypeID(mod, pkg+typ), pkg+typ+"."+m) } sink := vertex(v2.ExternalID(app, "database/sql", "DB.Query"), "formal_in", "query") - if sink != "can://httpsql/httpsql/@external/database/sql/DB.Query@formal_in:1" { + if sink != "can://httpsql/httpsql/@external/database/sql/DB/Query@formal_in:1" { t.Fatalf("sink vertex %s", sink) } find := method("sqlRepo", "Find") diff --git a/internal/syntactic_analysis/v2emit/gate_test.go b/internal/syntactic_analysis/v2emit/gate_test.go index 41822be..321cdaf 100644 --- a/internal/syntactic_analysis/v2emit/gate_test.go +++ b/internal/syntactic_analysis/v2emit/gate_test.go @@ -599,7 +599,7 @@ func TestGateL2_GoStatementArgumentCalls(t *testing.T) { if w.callee == "" { continue } - want := "can://dataflow/dataflow/go/flow/flow.go/" + pkg + w.callee + want := "can://dataflow/dataflow/go/flow/flow.go/" + w.callee if n.Callee == nil || *n.Callee != want { t.Errorf("GoArgs %s callee = %v, want %s", w.key, n.Callee, want) } From 60f5fdd598b6e61d38a6a929180dc53c3502a34c Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 07:56:57 -0500 Subject: [PATCH 03/19] test(v2emit): drop unused constants after the id-format change Remove the fID and pkg constants left unused by the bare-member id expectations; golangci-lint's unused check failed CI on them. Refs codellm-devkit/codeanalyzer-go#46 --- internal/syntactic_analysis/v2emit/gate_l3_test.go | 1 - internal/syntactic_analysis/v2emit/gate_test.go | 1 - 2 files changed, 2 deletions(-) diff --git a/internal/syntactic_analysis/v2emit/gate_l3_test.go b/internal/syntactic_analysis/v2emit/gate_l3_test.go index ddec91a..3b98d89 100644 --- a/internal/syntactic_analysis/v2emit/gate_l3_test.go +++ b/internal/syntactic_analysis/v2emit/gate_l3_test.go @@ -502,7 +502,6 @@ func TestGateL3_LineDirectiveRealPositions(t *testing.T) { func TestSymbolTable_MethodDeclaredAboveItsType(t *testing.T) { fx := buildL3(t, "dataflow") const sig = "example.com/dataflow/flow.early.Bump" - const fID = "example.com/dataflow/flow.f" find := func(out *v2.Analysis) (v2.Callable, bool) { for _, mod := range out.Application.SymbolTable { diff --git a/internal/syntactic_analysis/v2emit/gate_test.go b/internal/syntactic_analysis/v2emit/gate_test.go index 321cdaf..86382da 100644 --- a/internal/syntactic_analysis/v2emit/gate_test.go +++ b/internal/syntactic_analysis/v2emit/gate_test.go @@ -578,7 +578,6 @@ func TestGateL1_BodyNodeIDs(t *testing.T) { func TestGateL2_GoStatementArgumentCalls(t *testing.T) { out := buildDataflowL2V2(t) fn := functionByName(t, mustModule(t, out, "flow/flow.go"), "GoArgs") - const pkg = "example.com/dataflow/flow." for _, w := range []struct { key, callee string goroutine bool From 349fb840c7c516fde1860660a38e46c9dde3ba56 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 07:59:07 -0500 Subject: [PATCH 04/19] scripts: add end-to-end eval (analysis.json -> Neo4j projection -> load) eval_e2e.sh runs cango -a 2 on an app, pushes the Neo4j projection live, and checks analysis.json and the loaded graph (app-scoped GoCanNode rows plus :Package nodes). EAGER=1 reloads: the push runs with --eager, purging the application's subgraph first. --- scripts/eval_e2e.sh | 166 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 166 insertions(+) create mode 100755 scripts/eval_e2e.sh diff --git a/scripts/eval_e2e.sh b/scripts/eval_e2e.sh new file mode 100755 index 0000000..84d1558 --- /dev/null +++ b/scripts/eval_e2e.sh @@ -0,0 +1,166 @@ +#!/usr/bin/env bash +# eval_e2e.sh - end-to-end check: Go app -> analysis.json -> Neo4j projection -> loaded graph. +# +# Usage (from the repository root): +# scripts/eval_e2e.sh APP_DIR [OUT_DIR] +# +# APP_DIR a Go module root (must contain go.mod). +# OUT_DIR where analysis.json and the run log go (default: APP_DIR). +# +# Example: +# NEO4J_PASSWORD='...' scripts/eval_e2e.sh /path/to/microservices-demo/src/frontend +# +# Environment: +# LEVEL analysis level for analysis.json (default 2; 1..4) +# APP_NAME --app-name anchor (default: APP_DIR base name, as cango does) +# CANGO analyzer binary. When unset, it is built from this checkout into +# OUT_DIR/cango with `go build ./cmd/codeanalyzer`. +# NEO4J_URI Bolt URI (default bolt://localhost:7687) +# NEO4J_USER username (default neo4j) +# NEO4J_PASSWORD password (default neo4j). Passed to cango through its env var; never echoed. +# EAGER 1 = reload: the push runs with --eager, purging this application's +# subgraph (its can:// prefix only) first. Default 0 (additive upsert). +# CYPHER_SHELL cypher-shell binary for verification (auto-detected when unset). When it +# cannot be found or connected, the count check is reported as skipped. +# +# Steps: +# 1. Validate APP_DIR and the requested level. +# 2. Build the analyzer (unless CANGO is set). +# 3. cango -a LEVEL -i APP_DIR -o OUT_DIR -> OUT_DIR/analysis.json +# 4. cango --emit neo4j --neo4j-uri URI ... -> live push (MERGE, idempotent) +# 5. Verify analysis.json (schema, level, app id) and that the database holds the +# pushed node count under this application's can:// prefix. +# +# Exit status: 0 when every check passes (or is skipped with a reason), non-zero otherwise. +set -euo pipefail + +if [ $# -lt 1 ]; then + sed -n '2,/^set -euo/p' "$0" | sed '$d' >&2 + exit 2 +fi + +REPO=$(cd "$(dirname "$0")/.." && pwd) +APP=$(cd "$1" && pwd) +OUT=${2:-$APP} +mkdir -p "$OUT" +OUT=$(cd "$OUT" && pwd) + +LEVEL=${LEVEL:-2} +URI=${NEO4J_URI:-bolt://localhost:7687} +USER=${NEO4J_USER:-neo4j} +PASS=${NEO4J_PASSWORD:-neo4j} +APP_NAME=${APP_NAME:-$(basename "$APP")} +# The run log lives outside OUT: a log inside the project would be captured as an artifact. +LOG=${E2E_LOG:-${TMPDIR:-/tmp}/cldk-e2e-${APP_NAME}.log} + +fail=0 +step() { echo; echo "== $1"; } +pass() { echo " PASS: $1"; } +bad() { echo " FAIL: $1" >&2; fail=1; } +skip() { echo " SKIP: $1"; } + +# Strings that become id segments or Cypher literals must be plain names. +case "$APP_NAME" in + *[!A-Za-z0-9._-]*|"") echo "APP_NAME '$APP_NAME' must contain only letters, digits, '.', '_' or '-'" >&2; exit 2 ;; +esac +case "$LEVEL" in 1|2|3|4) ;; *) echo "LEVEL must be 1..4 (got '$LEVEL')" >&2; exit 2 ;; esac +[ -f "$APP/go.mod" ] || { echo "APP_DIR '$APP' has no go.mod; not a Go module root" >&2; exit 2; } + +: >"$LOG" + +step "1/5 analyzer binary" +if [ -n "${CANGO:-}" ]; then + [ -x "$CANGO" ] || { echo "CANGO '$CANGO' is not executable" >&2; exit 2; } + echo " using $CANGO" +else + CANGO="$OUT/cango" + (cd "$REPO" && go build -o "$CANGO" ./cmd/codeanalyzer) >>"$LOG" 2>&1 + echo " built $CANGO from $REPO" +fi + +step "2/5 analysis.json (-a $LEVEL)" +"$CANGO" -a "$LEVEL" --app-name "$APP_NAME" -i "$APP" -o "$OUT" >>"$LOG" 2>&1 +[ -s "$OUT/analysis.json" ] && pass "wrote $OUT/analysis.json ($(wc -c <"$OUT/analysis.json" | tr -d ' ') bytes)" \ + || { bad "analysis.json missing or empty (see $LOG)"; exit 1; } + +step "3/5 Neo4j projection (live push to $URI as $USER)" +# EAGER=1 reloads: --eager purges this application's subgraph (its can://// +# prefix only) before the push, so nodes from an earlier id format do not linger. +EAGER_FLAG=() +[ "${EAGER:-0}" = "1" ] && EAGER_FLAG=(--eager) +push_out=$(NEO4J_PASSWORD="$PASS" "$CANGO" --emit neo4j --neo4j-uri "$URI" --neo4j-user "$USER" \ + --app-name "$APP_NAME" "${EAGER_FLAG[@]}" -i "$APP" -o "$OUT" 2>&1) && push_rc=0 || push_rc=$? +printf '%s\n' "$push_out" >>"$LOG" +if [ "$push_rc" -ne 0 ]; then + bad "projection push failed (exit $push_rc): $(printf '%s' "$push_out" | tail -1)" + exit 1 +fi +pushed=$(printf '%s\n' "$push_out" | sed -n 's/^pushed \([0-9]*\) nodes, \([0-9]*\) relationships.*/\1 \2/p' | tail -1) +[ -n "$pushed" ] && pass "pushed $(printf '%s' "$pushed" | cut -d' ' -f1) nodes, $(printf '%s' "$pushed" | cut -d' ' -f2) relationships" \ + || bad "push output had no 'pushed N nodes' line" + +step "4/5 verify analysis.json" +if command -v python3 >/dev/null 2>&1; then + if python3 -I - "$OUT/analysis.json" "$LEVEL" "$APP_NAME" <<'PY' +import json, sys +path, level, app = sys.argv[1], int(sys.argv[2]), sys.argv[3] +d = json.load(open(path, encoding="utf-8")) +errs = [] +if d.get("language") != "go": errs.append(f"language is {d.get('language')!r}") +if d.get("max_level") != level: errs.append(f"max_level is {d.get('max_level')!r}, expected {level}") +app_id = d.get("application", {}).get("id", "") +if not app_id.startswith(f"can://"): errs.append(f"application.id {app_id!r} is not a can:// id") +if app not in app_id: errs.append(f"application.id {app_id!r} lacks the app name {app!r}") +st = d.get("application", {}).get("symbol_table", {}) +if not st: errs.append("symbol_table is empty") +if errs: + print("\n".join(" FAIL: " + e for e in errs)); sys.exit(1) +print(f" PASS: schema {d.get('schema_version')}, level {level}, {len(st)} files, " + f"{len(d['application'].get('call_graph', []))} call edges, id {app_id}") +PY + then :; else fail=1; fi +else + skip "python3 not found; analysis.json not inspected" +fi + +step "5/5 verify loaded graph" +CS=${CYPHER_SHELL:-} +if [ -z "$CS" ]; then + CS=$(command -v cypher-shell || true) + [ -n "$CS" ] || for c in /opt/homebrew/bin/cypher-shell /usr/local/bin/cypher-shell; do + [ -x "$c" ] && { CS=$c; break; } + done +fi +if [ -z "$CS" ]; then + skip "cypher-shell not found; set CYPHER_SHELL to enable the count check" +else + shell() { "$CS" -a "$URI" -u "$USER" -p "$PASS" --format plain "$@" 2>/dev/null; } + if ! shell "RETURN 1" >/dev/null; then + skip "cannot authenticate to $URI with cypher-shell; the count check was not run" + else + # Nodes keyed by this application's id root, the same prefix the projector scopes on. + prefix="can://${APP_NAME}/" + db_nodes=$(shell "MATCH (n:GoCanNode) WHERE n.id STARTS WITH '$prefix' RETURN count(n) AS c" | tail -1 | tr -d '"[:space:]') + want_nodes=$(printf '%s' "$pushed" | cut -d' ' -f1) + # Dependency :Package nodes are neutral (pkg: purls, shared across apps), so they are + # not under the prefix. They are part of the push count and checked separately. + db_pkgs=$(shell "MATCH (n:Package) WHERE n.id STARTS WITH 'pkg:' RETURN count(n) AS c" | tail -1 | tr -d '"[:space:]') + echo " info: $db_pkgs :Package nodes in the database" + # Pushed nodes are app-scoped (GoCanNode under the prefix) plus neutral :Package nodes. + if [ -n "$db_nodes" ] && [ "$db_nodes" -gt 0 ] && [ "$((db_nodes + ${db_pkgs:-0}))" -ge "$want_nodes" ]; then + pass "database holds $db_nodes GoCanNode rows under $prefix and ${db_pkgs:-0} :Package nodes (pushed $want_nodes nodes)" + else + bad "database has ${db_nodes:-no} GoCanNode rows under $prefix plus ${db_pkgs:-0} :Package; expected at least $want_nodes" + fi + labels=$(shell "MATCH (n:GoCallable) WHERE n.id STARTS WITH '$prefix' RETURN count(n) AS c" | tail -1 | tr -d '"[:space:]') + echo " info: $labels GoCallable nodes under $prefix" + fi +fi + +echo +if [ "$fail" -eq 0 ]; then + echo "E2E OK: $APP_NAME -> $OUT/analysis.json -> Neo4j at $URI" +else + echo "E2E FAILED for $APP_NAME (log: $LOG)" >&2 +fi +exit "$fail" From c52a7c01d4e927700a6204a584256b97fe0d68f9 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 08:39:11 -0500 Subject: [PATCH 05/19] scripts(eval_e2e): fix bash 3.2 unbound array and build outside the project EAGER_FLAG is a plain string, since an empty array trips set -u on macOS bash 3.2. The default cango build goes to the temp dir, not the project, so the binary is not captured as an artifact. --- scripts/eval_e2e.sh | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/scripts/eval_e2e.sh b/scripts/eval_e2e.sh index 84d1558..27de8cb 100755 --- a/scripts/eval_e2e.sh +++ b/scripts/eval_e2e.sh @@ -73,7 +73,8 @@ if [ -n "${CANGO:-}" ]; then [ -x "$CANGO" ] || { echo "CANGO '$CANGO' is not executable" >&2; exit 2; } echo " using $CANGO" else - CANGO="$OUT/cango" + # Build outside the project: a binary inside it would be captured as an artifact. + CANGO="${E2E_BUILD_DIR:-${TMPDIR:-/tmp}}/cldk-e2e-cango-${APP_NAME}" (cd "$REPO" && go build -o "$CANGO" ./cmd/codeanalyzer) >>"$LOG" 2>&1 echo " built $CANGO from $REPO" fi @@ -86,10 +87,11 @@ step "2/5 analysis.json (-a $LEVEL)" step "3/5 Neo4j projection (live push to $URI as $USER)" # EAGER=1 reloads: --eager purges this application's subgraph (its can://// # prefix only) before the push, so nodes from an earlier id format do not linger. -EAGER_FLAG=() -[ "${EAGER:-0}" = "1" ] && EAGER_FLAG=(--eager) +# A plain string, not an array: an empty array trips `set -u` on bash 3.2 (macOS). +EAGER_FLAG="" +[ "${EAGER:-0}" = "1" ] && EAGER_FLAG="--eager" push_out=$(NEO4J_PASSWORD="$PASS" "$CANGO" --emit neo4j --neo4j-uri "$URI" --neo4j-user "$USER" \ - --app-name "$APP_NAME" "${EAGER_FLAG[@]}" -i "$APP" -o "$OUT" 2>&1) && push_rc=0 || push_rc=$? + --app-name "$APP_NAME" $EAGER_FLAG -i "$APP" -o "$OUT" 2>&1) && push_rc=0 || push_rc=$? printf '%s\n' "$push_out" >>"$LOG" if [ "$push_rc" -ne 0 ]; then bad "projection push failed (exit $push_rc): $(printf '%s' "$push_out" | tail -1)" From ed17de5d838293602a4e472d6d996fe616636dc0 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 09:18:38 -0500 Subject: [PATCH 06/19] scripts(eval_e2e): add --json-only to write and check analysis.json only Skips the Neo4j push and the graph check, so no password or running database is needed. The build and the analysis.json check still run. --- scripts/eval_e2e.sh | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/scripts/eval_e2e.sh b/scripts/eval_e2e.sh index 27de8cb..34188ec 100755 --- a/scripts/eval_e2e.sh +++ b/scripts/eval_e2e.sh @@ -2,13 +2,16 @@ # eval_e2e.sh - end-to-end check: Go app -> analysis.json -> Neo4j projection -> loaded graph. # # Usage (from the repository root): -# scripts/eval_e2e.sh APP_DIR [OUT_DIR] +# scripts/eval_e2e.sh [--json-only] APP_DIR [OUT_DIR] # -# APP_DIR a Go module root (must contain go.mod). -# OUT_DIR where analysis.json and the run log go (default: APP_DIR). +# APP_DIR a Go module root (must contain go.mod). +# OUT_DIR where analysis.json and the run log go (default: APP_DIR). +# --json-only write and check analysis.json only: no Neo4j push, no graph check, +# no password or running database needed. # # Example: # NEO4J_PASSWORD='...' scripts/eval_e2e.sh /path/to/microservices-demo/src/frontend +# scripts/eval_e2e.sh --json-only /path/to/microservices-demo/src/frontend # # Environment: # LEVEL analysis level for analysis.json (default 2; 1..4) @@ -34,6 +37,9 @@ # Exit status: 0 when every check passes (or is skipped with a reason), non-zero otherwise. set -euo pipefail +JSON_ONLY=0 +if [ "${1:-}" = "--json-only" ]; then JSON_ONLY=1; shift; fi + if [ $# -lt 1 ]; then sed -n '2,/^set -euo/p' "$0" | sed '$d' >&2 exit 2 @@ -84,6 +90,9 @@ step "2/5 analysis.json (-a $LEVEL)" [ -s "$OUT/analysis.json" ] && pass "wrote $OUT/analysis.json ($(wc -c <"$OUT/analysis.json" | tr -d ' ') bytes)" \ || { bad "analysis.json missing or empty (see $LOG)"; exit 1; } +if [ "$JSON_ONLY" = "1" ]; then + step "3/5 Neo4j projection"; skip "--json-only: no push" +else step "3/5 Neo4j projection (live push to $URI as $USER)" # EAGER=1 reloads: --eager purges this application's subgraph (its can://// # prefix only) before the push, so nodes from an earlier id format do not linger. @@ -100,6 +109,7 @@ fi pushed=$(printf '%s\n' "$push_out" | sed -n 's/^pushed \([0-9]*\) nodes, \([0-9]*\) relationships.*/\1 \2/p' | tail -1) [ -n "$pushed" ] && pass "pushed $(printf '%s' "$pushed" | cut -d' ' -f1) nodes, $(printf '%s' "$pushed" | cut -d' ' -f2) relationships" \ || bad "push output had no 'pushed N nodes' line" +fi step "4/5 verify analysis.json" if command -v python3 >/dev/null 2>&1; then @@ -125,6 +135,9 @@ else skip "python3 not found; analysis.json not inspected" fi +if [ "$JSON_ONLY" = "1" ]; then + step "5/5 verify loaded graph"; skip "--json-only: graph not checked" +else step "5/5 verify loaded graph" CS=${CYPHER_SHELL:-} if [ -z "$CS" ]; then @@ -159,9 +172,15 @@ else fi fi +fi + echo if [ "$fail" -eq 0 ]; then - echo "E2E OK: $APP_NAME -> $OUT/analysis.json -> Neo4j at $URI" + if [ "$JSON_ONLY" = "1" ]; then + echo "E2E OK (json-only): $APP_NAME -> $OUT/analysis.json" + else + echo "E2E OK: $APP_NAME -> $OUT/analysis.json -> Neo4j at $URI" + fi else echo "E2E FAILED for $APP_NAME (log: $LOG)" >&2 fi From 728748ef8f42c7e5a9b28e3ba38fc531626a443a Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 10:47:17 -0500 Subject: [PATCH 07/19] docs(design): cross-file method ids use the declaring file A method declared in another file than its receiver type now gets an id under the declaring module: //. The node stays in the receiver's callables{}; source_file is kept; Neo4j adds GO_DECLARES from the declaring module. Refs codellm-devkit/codeanalyzer-go#46 --- CLAUDE.md | 8 +++++++- docs/design/specs/v2-go-ids.md | 32 ++++++++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 3 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 36b310e..769a9cf 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -19,7 +19,8 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. L3/L4 build ids on this unchanged. - **Id member segments (spec `docs/design/specs/v2-go-ids.md`, issue #46)**: a type is `/`; a method is `//`; a package-level function is - `/`; a closure is `/closure_N`. The package import path is dropped: + `/` (a method declared in another file uses that file as ``, see + § Cross-file method ids below); a closure is `/closure_N`. The package import path is dropped: the member segment is the signature's part after its last dot (Go names contain no dots). Follows `codeanalyzer-typescript` `idFromSig` and `codeanalyzer-python` `child_id` [user, 2026-11-20]. Externals: `/@external///` (import path @@ -28,6 +29,11 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. JSON field on both (types gained it, additive, for the Neo4j `:GoType.signature`) [user, 2026-11-20]. The id carries only the bare member name, so this field is where the package path lives. One canonicalizer, unchanged from v1. +- **Cross-file method ids** [user, 2026-11-20]: a method declared in another file than its receiver + type gets `//`, e.g. `…/handlers.go/frontendServer/logoutHandler`. + The node stays in the receiver type's `callables{}`. `source_file` is kept for text recovery. + Neo4j adds `GO_DECLARES` from the declaring `:GoModule` to the method, beside `GO_HAS_METHOD`. + Spec: `docs/design/specs/v2-go-ids.md` § Amendment. - **Generic types**: `signatureOf()` carries no type parameters, so a generic type or method ids as `//`, with no `[T]` in the id. - **`span.bytes`** = **UTF-8 byte offsets** into `module.source` (Go strings are diff --git a/docs/design/specs/v2-go-ids.md b/docs/design/specs/v2-go-ids.md index 4ed8d62..b35ba2d 100644 --- a/docs/design/specs/v2-go-ids.md +++ b/docs/design/specs/v2-go-ids.md @@ -86,8 +86,10 @@ name the JSON carries. The id no longer needs to carry it. - **Uniqueness**: ids are unique within a file. Go forbids duplicate package-scope identifiers, and forbids a duplicate method name on one type. Two files in one package have distinct module ids, so the stripped package path never causes a collision. -- **Cross-file methods**: a method declared in another file nests under its receiver type's - module, as today (`source_file` handles its text). Its id is `//`. +- **Cross-file methods** (amended 2026-11-20, see Amendment below): a method declared in another + file gets an id under the file that declares it, `//`. The + method node stays in its receiver type's `callables{}`, and `source_file` names the declaring + file for text recovery. - **python-sdk**: `cldk/analysis/go/neo4j/neo4j_backend.py` keys types by `ty.id.split("/")[-1]`, which still returns the type name, and fields by `fld.id.split("/")[-1]`, which is unchanged. Callables keyed by a dotted sig will change meaning: the last segment is now the bare method @@ -123,6 +125,32 @@ ships first; the python-sdk Go backend follows once the id shape is released. - **Open item 1 (collisions) resolved**: the generics fixture and the chi/init fixtures produce distinct ids. `init` functions are distinct per file by module. +## Amendment (2026-11-20): cross-file method ids + +Decided with the user in the design loop, after the id change landed. + +**Problem.** A method is nested under its receiver type's module, so its id names the file +where the receiver lives, not the file where the method is declared. Example: `frontendServer.logoutHandler` +is declared in `handlers.go` but its id was `…/main.go/frontendServer/logoutHandler`. 22 methods in the +frontend app are affected (those with `source_file` set). + +**Decisions.** + +1. **Id.** A callable's id contains the file where it is declared: + `//`, e.g. `…/handlers.go/frontendServer/logoutHandler`. The type + segment stays. Rejected: `/`, because a method and a package-level + function of the same name in one file would collide. +2. **JSON containment.** The node stays in its receiver type's `callables{}` (containment by + receiver is unchanged). Only its id changes. Moving it under the declaring module was rejected + because it changes containment for every consumer and hides which type the method belongs to. +3. **Text recovery.** `source_file` is kept. The id's module now equals `source_file`, but the + node still nests under the receiver's module, so its span still needs `source_file` to resolve. +4. **Neo4j.** `GO_HAS_METHOD` from the receiver `:GoType` is kept. A `GO_DECLARES` edge is added from + the declaring `:GoModule` to the method, so "which file declares this method" is one query. No + new relationship kind. + +**Release.** Same PR and release as the id format (feat/v2-go-ids). Tracked in #46. + ## Out of scope - Module, field, artifact, and ordinal-id shapes. From d9af418849dba459ff361c17e83a0bee8960e8b5 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 10:50:51 -0500 Subject: [PATCH 08/19] feat(ids): cross-file methods get ids under their declaring file A method declared in a file other than its receiver type now nests under that file's module: //. The JSON node stays in the receiver type's callables{}, and source_file is kept. The Neo4j projector adds GO_DECLARES from the declaring module to the method, beside GO_HAS_METHOD. 22 frontend methods change, e.g. handlers.go/frontendServer/logoutHandler (was main.go/frontendServer/logoutHandler). Refs codellm-devkit/codeanalyzer-go#46 --- internal/core/crossfile_method_test.go | 161 ++++++++++++++++++ internal/neo4j/crossfile_test.go | 54 ++++++ internal/neo4j/project.go | 6 + internal/syntactic_analysis/v2emit/emit.go | 8 +- .../syntactic_analysis/v2emit/sigindex.go | 17 +- 5 files changed, 240 insertions(+), 6 deletions(-) create mode 100644 internal/core/crossfile_method_test.go create mode 100644 internal/neo4j/crossfile_test.go diff --git a/internal/core/crossfile_method_test.go b/internal/core/crossfile_method_test.go new file mode 100644 index 0000000..aa3060a --- /dev/null +++ b/internal/core/crossfile_method_test.go @@ -0,0 +1,161 @@ +package core_test + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/core" + "github.com/codellm-devkit/codeanalyzer-go/internal/options" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" +) + +// crossFileProject: T is declared in a.go, its method M in b.go, a package-level +// function M in b.go too (same name, different id), and Use in c.go calls both. +func crossFileProject(t *testing.T) string { + t.Helper() + dir := t.TempDir() + files := map[string]string{ + "go.mod": "module example.com/xf\n\ngo 1.25.0\n", + "a.go": "package xf\n\ntype T struct{ n int }\n", + "b.go": "package xf\n\nfunc (t T) M() int { return t.n }\n\nfunc M() int { return 2 }\n", + "c.go": "package xf\n\nfunc Use() int {\n\tvar t T\n\treturn t.M() + M()\n}\n", + } + for rel, content := range files { + if err := os.WriteFile(filepath.Join(dir, rel), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + return dir +} + +// analyzeL2 runs the real pipeline at -a 2 and returns the analysis.json tree as +// generic maps (the v2 Go structs are not needed for these checks). +func analyzeL2(t *testing.T, dir string) map[string]any { + t.Helper() + opts := options.AnalysisOptions{ + InputPath: dir, AppName: "xf", Level: options.LevelCallGraph, + SkipTests: true, CacheDir: t.TempDir(), OutputDir: t.TempDir(), + } + app, err := core.New(opts).Analyze() + if err != nil { + t.Fatal(err) + } + identity, err := v2.ResolveIdentity("xf", nil) + if err != nil { + t.Fatal(err) + } + payload := v2emit.Emit(app, identity, dir, int(opts.Level), "test", 0, nil, nil) + raw, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + var doc map[string]any + if err := json.Unmarshal(raw, &doc); err != nil { + t.Fatal(err) + } + return doc +} + +func asMap(v any) map[string]any { m, _ := v.(map[string]any); return m } + +// methodNode finds the method whose signature ends in suffix, under any type. +func methodNode(st map[string]any, suffix string) map[string]any { + for _, mod := range st { + for _, ty := range asMap(asMap(mod)["types"]) { + for _, c := range asMap(asMap(ty)["callables"]) { + if strings.HasSuffix(asMap(c)["signature"].(string), suffix) { + return asMap(c) + } + } + } + } + return nil +} + +func TestCrossFileMethod_IDNamesDeclaringFile(t *testing.T) { + doc := analyzeL2(t, crossFileProject(t)) + st := asMap(asMap(doc["application"])["symbol_table"]) + + m := methodNode(st, ".T.M") + if m == nil { + t.Fatal("method T.M not found") + } + const wantID = "can://xf/xf/go/b.go/T/M" + if got := m["id"]; got != wantID { + t.Errorf("method id = %v, want %s (declaring file b.go, not the receiver's a.go)", got, wantID) + } + if got := m["source_file"]; got != "b.go" { + t.Errorf("source_file = %v, want b.go", got) + } +} + +func TestCrossFileMethod_SameNameFunctionDistinct(t *testing.T) { + doc := analyzeL2(t, crossFileProject(t)) + st := asMap(asMap(doc["application"])["symbol_table"]) + fn := asMap(asMap(asMap(st["b.go"])["functions"])) + var fnID string + for _, f := range fn { + if asMap(f)["signature"] == "example.com/xf.M" { + fnID = asMap(f)["id"].(string) + } + } + const wantFn = "can://xf/xf/go/b.go/M" + if fnID != wantFn { + t.Errorf("function M id = %q, want %s", fnID, wantFn) + } + if m := methodNode(st, ".T.M"); m != nil && m["id"] == fnID { + t.Errorf("method and function named M collide at %s", fnID) + } +} + +// The call in Use (c.go) to the cross-file method resolves to the declaring-file +// id: the call-graph edge and the body call node both name b.go. +func TestCrossFileMethod_CallsResolveToDeclaringFile(t *testing.T) { + doc := analyzeL2(t, crossFileProject(t)) + app := asMap(doc["application"]) + const method = "can://xf/xf/go/b.go/T/M" + + var caller string + for _, mod := range asMap(app["symbol_table"]) { + for _, f := range asMap(asMap(mod)["functions"]) { + if asMap(f)["signature"] == "example.com/xf.Use" { + caller = asMap(f)["id"].(string) + } + } + } + if caller == "" { + t.Fatal("Use not found") + } + + edge := false + for _, e := range app["call_graph"].([]any) { + em := asMap(e) + if em["src"] == caller && em["dst"] == method { + edge = true + } + } + if !edge { + t.Errorf("no call_graph edge %s -> %s", caller, method) + } + + resolved := false + for _, mod := range asMap(app["symbol_table"]) { + for _, f := range asMap(asMap(mod)["functions"]) { + if asMap(f)["id"] != caller { + continue + } + for _, bn := range asMap(asMap(f)["body"]) { + if c, ok := asMap(bn)["callee"].(string); ok && c == method { + resolved = true + } + } + } + } + if !resolved { + t.Errorf("no body call node in Use has callee %s", method) + } +} diff --git a/internal/neo4j/crossfile_test.go b/internal/neo4j/crossfile_test.go new file mode 100644 index 0000000..1c7132d --- /dev/null +++ b/internal/neo4j/crossfile_test.go @@ -0,0 +1,54 @@ +package neo4j + +import ( + "testing" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// A method declared in b.go but whose receiver type lives in a.go: GO_HAS_METHOD +// from the type, and GO_DECLARES from the declaring module b.go. +func TestProject_CrossFileMethodDeclaredByItsModule(t *testing.T) { + const ( + app = "can://xf/xf" + typeMod = app + "/go/a.go" + declMod = app + "/go/b.go" + typeID = typeMod + "/T" + methodID = declMod + "/T/M" + ) + a := &v2.Analysis{ + IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, + Application: v2.Application{ + IdentityVersion: 2, ID: app, Kind: "application", + SymbolTable: map[string]v2.Module{ + "a.go": {ID: typeMod, Kind: "module", Types: map[string]v2.Type{ + "T": {ID: typeID, Kind: "struct", Signature: "example.com/xf.T", + Callables: map[string]v2.Callable{ + "example.com/xf.T.M": {ID: methodID, Kind: "method", Signature: "example.com/xf.T.M", SourceFile: "b.go"}, + }}, + }}, + "b.go": {ID: declMod, Kind: "module"}, + }, + }, + } + rows := Project(a) + + hasMethod, declares := false, false + for _, e := range rows.Edges { + if e.To.Value != methodID { + continue + } + switch e.Type { + case RelHasMethod: + hasMethod = e.From.Value == typeID + case RelDeclares: + declares = e.From.Label == LabelModule && e.From.Value == declMod + } + } + if !hasMethod { + t.Errorf("no GO_HAS_METHOD from receiver type %s to %s", typeID, methodID) + } + if !declares { + t.Errorf("no GO_DECLARES from declaring module %s to %s", declMod, methodID) + } +} diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index 455e365..1e3c4d0 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -200,6 +200,12 @@ func (p *projector) projectType(modRef NodeRef, module string, t v2.Type) { for _, m := range t.Callables { mRef := p.projectCallable(tRef, module, m) p.b.Edge(RelHasMethod, tRef, mRef, nil, "") + // A method declared in another file is also declared by that file's module, + // so "which file declares this method" is one query (spec v2-go-ids § Amendment). + if m.SourceFile != "" { + declaring := NodeRef{Label: LabelModule, KeyProp: "id", Value: v2.ModuleID(p.analysis.Application.ID, m.SourceFile)} + p.b.Edge(RelDeclares, declaring, mRef, nil, "") + } } } diff --git a/internal/syntactic_analysis/v2emit/emit.go b/internal/syntactic_analysis/v2emit/emit.go index 55e81a4..5268552 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/v2emit/emit.go @@ -292,7 +292,7 @@ func emitModule(appID, modRel string, file schema.GoFile, idx sigIndex, srcs *so } for name, t := range file.Types { - mod.Types[name] = emitType(modID, modRel, t, idx, srcs, flow, l4) + mod.Types[name] = emitType(appID, modRel, t, idx, srcs, flow, l4) } for sig, fn := range file.Functions { mod.Functions[sig] = emitCallable(modID, modRel, modRel, li, fn, idx, srcs, flow, l4) @@ -304,9 +304,9 @@ func emitModule(appID, modRel string, file schema.GoFile, idx sigIndex, srcs *so // kind and splitting embedding (base_types) from computed satisfaction. Methods // resolve into the type's callables{}. modRel is the module the type lives in; // its methods may be declared in other files (handled in emitCallable). -func emitType(modID, modRel string, t schema.GoType, idx sigIndex, srcs *sourceCache, flow l3Overlay, l4 *l4Overlay) v2.Type { +func emitType(appID, modRel string, t schema.GoType, idx sigIndex, srcs *sourceCache, flow l3Overlay, l4 *l4Overlay) v2.Type { li := srcs.index(modRel) - typeID := v2.TypeID(modID, t.Signature) + typeID := v2.TypeID(v2.ModuleID(appID, modRel), t.Signature) out := v2.Type{ ID: typeID, Kind: typeKind(t), @@ -327,7 +327,7 @@ func emitType(modID, modRel string, t schema.GoType, idx sigIndex, srcs *sourceC } } for sig, m := range t.Methods { - out.Callables[sig] = emitCallable(typeID, modRel, modRel, li, m, idx, srcs, flow, l4) + out.Callables[sig] = emitCallable(methodParentID(appID, modRel, t, m), modRel, modRel, li, m, idx, srcs, flow, l4) } return out } diff --git a/internal/syntactic_analysis/v2emit/sigindex.go b/internal/syntactic_analysis/v2emit/sigindex.go index 00ed238..83a3f07 100644 --- a/internal/syntactic_analysis/v2emit/sigindex.go +++ b/internal/syntactic_analysis/v2emit/sigindex.go @@ -55,15 +55,28 @@ func buildSigIndex(appID string, symbolTable map[string]schema.GoFile) sigIndex idx.addCallable(modID, relPath, fn) } for _, t := range file.Types { - typeID := v2.TypeID(modID, t.Signature) for _, m := range t.Methods { - idx.addCallable(typeID, relPath, m) + idx.addCallable(methodParentID(appID, relPath, t, m), relPath, m) } } } return idx } +// methodParentID is the id a method nests under. A method declared in its +// receiver type's file nests under that type's id. A method declared in another +// file nests under the same type in the DECLARING file's module, so its id names +// where the method is written (spec v2-go-ids § Amendment). The JSON node itself +// stays in the receiver type's callables{}; only its id moves. modRel is the +// receiver's module (the file the type lives in). +func methodParentID(appID, modRel string, t schema.GoType, c schema.GoCallable) string { + mod := modRel + if c.Path != "" { + mod = c.Path + } + return v2.TypeID(v2.ModuleID(appID, mod), t.Signature) +} + // addCallable records one callable and recurses into its closures, matching the // id nesting emitCallable produces. relPath is the module file this callable is // reached through; it keys the disambiguating (signature,path) entry. From 73f986e97a7b0e2a48ec807d41812f9435eb5c98 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 14:50:52 -0500 Subject: [PATCH 09/19] docs(design): add application.name alongside application_name Additive v2 field with the same value as application_name, which is kept (renaming a shared field is forbidden). Neo4j :GoApplication gets the same name property. Spec: docs/design/specs/v2-application-name-field.md --- CLAUDE.md | 3 ++ .../design/specs/v2-application-name-field.md | 29 +++++++++++++++++++ 2 files changed, 32 insertions(+) create mode 100644 docs/design/specs/v2-application-name-field.md diff --git a/CLAUDE.md b/CLAUDE.md index 769a9cf..3e4ddd1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,6 +12,9 @@ v2 vocabulary (parity clause: add at the leaves, never rename shared names). The committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. ### Identity & positioning (Group A — reused verbatim by L3/L4) +- **`application.name`** [user, 2026-11-20; spec `docs/design/specs/v2-application-name-field.md`]: an additive + field with the same value as `application_name`. `application_name` is kept unchanged (renaming a shared + field is forbidden), and `:GoApplication.name` carries the same value in Neo4j. - **`application.id`** = `can://` (app outermost, so a polyglot app shares one prefix), where `` is the **`--app-name`** value, defaulting to the input directory's base name (per the CLI contract; the SDK's Neo4j backend must use the same anchor). Module ids are diff --git a/docs/design/specs/v2-application-name-field.md b/docs/design/specs/v2-application-name-field.md new file mode 100644 index 0000000..f7983b7 --- /dev/null +++ b/docs/design/specs/v2-application-name-field.md @@ -0,0 +1,29 @@ +# Spec: `application.name` alongside `application_name` (codeanalyzer-go) + +## Contract-Impact Triage + +**Does this change schema v2 output?** Yes, additively. The v2 `application` node gains a +`name` field. No existing field is renamed or removed. + +| Change type | Analyzers | SDKs | Docs | +| --- | --- | --- | --- | +| Additive schema field | **codeanalyzer-go** (schema, emit, Neo4j projector) | none now (python-sdk and codeanalyzer-python keep reading `application_name`) | `CLAUDE.md` § Schema decisions, this spec | + +## Design-loop decisions + +Made with the user on 2026-11-20. + +1. **Field.** `application.name` is added to the v2 application node in `analysis.json`. Its + value is the same as `application_name`. +2. **Keep `application_name`.** Renaming it was rejected. The parity rule forbids renaming shared + fields, and `codeanalyzer-python` and `python-sdk` read `application_name`. +3. **Neo4j.** The `:GoApplication` node gets a `name` property with the same value as + `application_name`, so the two projections keep matching. +4. **Tracking.** One issue in `codeanalyzer-go`, one checklist. A PR on `fix-app-name`. +5. **Release.** One PR, one release. The python-sdk can read `name` later; nothing is required + of it now. + +## Out of scope + +- Removing or deprecating `application_name`. That is a later, separate schema change. +- Changing the python-sdk or codeanalyzer-python readers. From f9f28a10f482734b79bafea587801eac08cdf1d3 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 14:53:36 -0500 Subject: [PATCH 10/19] feat(schema): add application.name alongside application_name Additive v2 field with the same value as application_name, which is kept. The Neo4j :GoApplication node carries the same name property. Spec: docs/design/specs/v2-application-name-field.md Refs codellm-devkit/codeanalyzer-go#50 --- internal/core/application_name_test.go | 29 ++++++++++++++++++++++ internal/neo4j/application_name_test.go | 23 +++++++++++++++++ internal/neo4j/project.go | 2 +- internal/neo4j/schema.go | 2 +- internal/schema/v2/schema.go | 7 ++++-- internal/syntactic_analysis/v2emit/emit.go | 3 ++- 6 files changed, 61 insertions(+), 5 deletions(-) create mode 100644 internal/core/application_name_test.go create mode 100644 internal/neo4j/application_name_test.go diff --git a/internal/core/application_name_test.go b/internal/core/application_name_test.go new file mode 100644 index 0000000..215515a --- /dev/null +++ b/internal/core/application_name_test.go @@ -0,0 +1,29 @@ +package core_test + +import ( + "encoding/json" + "testing" +) + +// application.name is additive and carries the same value as application_name. +func TestAnalyze_ApplicationNameFieldMatchesLegacyField(t *testing.T) { + dir := repoProject(t) + var doc struct { + Application struct { + ApplicationName string `json:"application_name"` + Name string `json:"name"` + } `json:"application"` + } + if err := json.Unmarshal(emitJSON(t, dir, false), &doc); err != nil { + t.Fatal(err) + } + if doc.Application.Name == "" { + t.Fatal("application.name missing") + } + if doc.Application.Name != doc.Application.ApplicationName { + t.Errorf("name = %q, application_name = %q; want equal", doc.Application.Name, doc.Application.ApplicationName) + } + if doc.Application.Name != "repoapp" { + t.Errorf("name = %q, want repoapp", doc.Application.Name) + } +} diff --git a/internal/neo4j/application_name_test.go b/internal/neo4j/application_name_test.go new file mode 100644 index 0000000..92bcea4 --- /dev/null +++ b/internal/neo4j/application_name_test.go @@ -0,0 +1,23 @@ +package neo4j + +import "testing" + +// The :GoApplication node carries name alongside application_name, with the same value. +func TestProject_ApplicationNodeWritesName(t *testing.T) { + a := repoAnalysis() + a.Application.ApplicationName = "frontend" + a.Application.Name = "frontend" + + var app *NodeRow + for _, n := range Project(a).Nodes { + if hasLabel(n, LabelApplication) { + app = &n + } + } + if app == nil { + t.Fatal("no :GoApplication row") + } + if app.Props["name"] != "frontend" || app.Props["application_name"] != "frontend" { + t.Errorf("props name=%v application_name=%v, want both frontend", app.Props["name"], app.Props["application_name"]) + } +} diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index 1e3c4d0..b3d10cd 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -63,7 +63,7 @@ func (p *projector) projectApplication(degraded []v2.Degraded) { []string{LabelApplication, MarkerLabel}, "id", a.Application.ID, Props{ - "identity_version": a.IdentityVersion, "application_name": a.Application.ApplicationName, "identity_namespace": a.Application.IdentityNamespace, "schema_version": a.SchemaVersion, + "identity_version": a.IdentityVersion, "application_name": a.Application.ApplicationName, "name": a.Application.Name, "identity_namespace": a.Application.IdentityNamespace, "schema_version": a.SchemaVersion, "language": a.Language, "max_level": a.MaxLevel, "analyzer_name": a.Analyzer.Name, diff --git a/internal/neo4j/schema.go b/internal/neo4j/schema.go index 274d39d..4c767bd 100644 --- a/internal/neo4j/schema.go +++ b/internal/neo4j/schema.go @@ -190,7 +190,7 @@ type RelSpec struct { var Nodes = []NodeSpec{ { Label: LabelApplication, MergeLabel: LabelApplication, Key: "id", CanNode: true, - Props: []string{"identity_version", "application_name", "identity_namespace", "schema_version", "language", "max_level", "analyzer_name", "analyzer_version", "degraded_json"}, + Props: []string{"identity_version", "application_name", "name", "identity_namespace", "schema_version", "language", "max_level", "analyzer_name", "analyzer_version", "degraded_json"}, }, { Label: LabelModule, MergeLabel: LabelModule, Key: "id", CanNode: true, diff --git a/internal/schema/v2/schema.go b/internal/schema/v2/schema.go index 3c5ca1a..6ea806d 100644 --- a/internal/schema/v2/schema.go +++ b/internal/schema/v2/schema.go @@ -81,8 +81,11 @@ type AnalyzerTag struct { // Application is the root node of the containment tree. type Application struct { - IdentityVersion int `json:"identity_version"` - ApplicationName string `json:"application_name"` + IdentityVersion int `json:"identity_version"` + ApplicationName string `json:"application_name"` + // Name is the application's name: the same value as ApplicationName (additive, + // spec v2-application-name-field). ApplicationName is kept unchanged. + Name string `json:"name"` IdentityNamespace string `json:"identity_namespace"` // ID is `can:///` — the app segment is outermost, so a polyglot // app shares one prefix across languages. is the --app-name value (default: input dir base name). diff --git a/internal/syntactic_analysis/v2emit/emit.go b/internal/syntactic_analysis/v2emit/emit.go index 5268552..e9766af 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/v2emit/emit.go @@ -248,7 +248,8 @@ func (e *emitter) envelope(app *schema.GoApplication, maxLevel int, analyzerVers MaxLevel: maxLevel, Analyzer: v2.AnalyzerTag{Name: "codeanalyzer-go", Version: analyzerVersion}, Application: v2.Application{ - IdentityVersion: 2, ApplicationName: e.identity.ApplicationName, IdentityNamespace: e.identity.Namespace, ID: e.appID, + IdentityVersion: 2, ApplicationName: e.identity.ApplicationName, Name: e.identity.ApplicationName, + IdentityNamespace: e.identity.Namespace, ID: e.appID, Kind: "application", CallGraph: emitCallGraph(app.CallGraph, e.idx), }, From a8b4b09bbc8652212d4bd3ef12b11f62736f3aaf Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sat, 21 Nov 2026 08:29:54 -0500 Subject: [PATCH 11/19] docs(design): start_line and end_line on Go span-bearing models Additive top-level keys next to span on Import, Parameter, Callable, Type, Field and BodyNode, for parity with codeanalyzer-python. No code_start_line. Neo4j nodes carry the same properties beside span_json. Spec: docs/design/specs/v2-span-lines.md --- CLAUDE.md | 3 +++ docs/design/specs/v2-span-lines.md | 34 ++++++++++++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 docs/design/specs/v2-span-lines.md diff --git a/CLAUDE.md b/CLAUDE.md index 3e4ddd1..e98ad4a 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -39,6 +39,9 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. Spec: `docs/design/specs/v2-go-ids.md` § Amendment. - **Generic types**: `signatureOf()` carries no type parameters, so a generic type or method ids as `//`, with no `[T]` in the id. +- **`start_line` / `end_line`** [user, 2026-11-21; spec `docs/design/specs/v2-span-lines.md`]: top-level keys next + to `span` on `Import`, `Parameter`, `Callable`, `Type`, `Field` and `BodyNode`, equal to `span.start[0]` and + `span.end[0]`. No `code_start_line`. Neo4j nodes carry the same two properties beside `span_json`. - **`span.bytes`** = **UTF-8 byte offsets** into `module.source` (Go strings are natively UTF-8; avoids the UTF-16/rune slicing mismatch TS hit in cants#179). diff --git a/docs/design/specs/v2-span-lines.md b/docs/design/specs/v2-span-lines.md new file mode 100644 index 0000000..5c2846d --- /dev/null +++ b/docs/design/specs/v2-span-lines.md @@ -0,0 +1,34 @@ +# Spec: start_line and end_line on Go span-bearing models + +## Contract-Impact Triage + +**Does this change schema v2 output?** Yes, additively. Six Go model types gain two integer +fields. No existing field changes. + +| Change type | Analyzers | SDKs | Docs | +| --- | --- | --- | --- | +| Additive schema fields | **codeanalyzer-go** (schema, emit, Neo4j projector) | none now; python-sdk can read the keys later | `CLAUDE.md` § Schema decisions, this spec | + +Anchor: `codeanalyzer-python/codeanalyzer/schema/py_schema.py`. Python puts `start_line` and +`end_line` next to `span` on imports, parameters, callables, classes, call sites and others. + +## Design-loop decisions + +Made with the user on 2026-11-21. + +1. **Placement.** Top-level keys on each model, next to `span` (Python style), not inside `span`. + The values equal `span.start[0]` and `span.end[0]`. +2. **Scope.** All span-bearing Go models: `Import`, `Parameter`, `Callable`, `Type`, `Field`, + and `BodyNode`. +3. **`code_start_line`.** Not added. For Go the signature and the opening brace share a line in + practice, so the field would carry no information. +4. **Neo4j.** `start_line` and `end_line` are node properties beside `span_json`, on every + span-bearing node the projector writes. `Import` is an edge in Neo4j, not a node, so it gets + no property; its lines appear in the JSON only. +5. **Tracking.** One issue in codeanalyzer-go, one checklist. One PR on `add_startline_endline`. +6. **Release.** One PR, one release. The keys are additive, so existing consumers keep working. + +## Out of scope + +- `code_start_line` (decision 3). +- Comments and variable declarations, which Python emits and v2 Go does not carry. From ba30e09afea353349c2fb75ec385352d648f1c91 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sat, 21 Nov 2026 08:34:33 -0500 Subject: [PATCH 12/19] feat(schema): start_line and end_line on Go span-bearing models Top-level start_line and end_line next to span on Import, Parameter, Callable, Type, Field and BodyNode (equal to span.start[0] and span.end[0]). Neo4j nodes carry the same properties beside span_json; the synthetic body nodes omit them. Spec: docs/design/specs/v2-span-lines.md Refs codellm-devkit/codeanalyzer-go#51 --- internal/core/span_lines_test.go | 101 ++++++++++++++++++ internal/neo4j/project.go | 28 +++-- internal/neo4j/schema.go | 10 +- internal/neo4j/span_lines_test.go | 70 ++++++++++++ internal/schema/v2/schema.go | 41 ++++--- internal/syntactic_analysis/v2emit/emit.go | 42 +++++--- internal/syntactic_analysis/v2emit/emit_l3.go | 1 + 7 files changed, 256 insertions(+), 37 deletions(-) create mode 100644 internal/core/span_lines_test.go create mode 100644 internal/neo4j/span_lines_test.go diff --git a/internal/core/span_lines_test.go b/internal/core/span_lines_test.go new file mode 100644 index 0000000..b916654 --- /dev/null +++ b/internal/core/span_lines_test.go @@ -0,0 +1,101 @@ +package core_test + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +// spanLinesProject declares one of each span-bearing model: an import, a type +// with a field, a method with a parameter, and a call in the method's body. +func spanLinesProject(t *testing.T) string { + t.Helper() + dir := t.TempDir() + files := map[string]string{ + "go.mod": "module example.com/sl\n\ngo 1.25.0\n", + "main.go": "package sl\n\nimport \"fmt\"\n\ntype T struct {\n\tn int\n}\n\n" + + "func (t T) M(x int) int {\n\tfmt.Println(x)\n\treturn t.n\n}\n", + } + for rel, content := range files { + if err := os.WriteFile(filepath.Join(dir, rel), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + return dir +} + +// checkSpanLines walks the JSON tree and asserts that every node carrying both a +// span and start_line/end_line has them equal to span.start[0] and span.end[0]. +// seen counts those nodes by the innermost container they sit under. +func checkSpanLines(t *testing.T, v any, path string, seen map[string]int) { + t.Helper() + containers := []string{"imports", "types", "fields", "callables", "parameters", "body"} + switch x := v.(type) { + case map[string]any: + if sp, ok := x["span"].(map[string]any); ok { + start, _ := sp["start"].([]any) + end, _ := sp["end"].([]any) + if len(start) == 2 && len(end) == 2 { + if sl, has := x["start_line"]; has { + if sl != start[0] || x["end_line"] != end[0] { + t.Errorf("%s: start_line/end_line = %v/%v, span = %v/%v", path, sl, x["end_line"], start[0], end[0]) + } + if c := innermostContainer(path, containers); c != "" { + seen[c]++ + } + } + } + } + for k, child := range x { + checkSpanLines(t, child, path+"/"+k, seen) + } + case []any: + for _, child := range x { + checkSpanLines(t, child, path+"/[]", seen) + } + } +} + +// innermostContainer is the deepest container segment on the path (a method's +// fields and parameters sit under its type, so the type is not the innermost). +func innermostContainer(path string, containers []string) string { + segs := splitPath(path) + for i := len(segs) - 1; i >= 0; i-- { + for _, c := range containers { + if segs[i] == c { + return c + } + } + } + return "" +} + +func splitPath(path string) []string { + var out []string + cur := "" + for _, r := range path { + if r == '/' { + out = append(out, cur) + cur = "" + continue + } + cur += string(r) + } + return append(out, cur) +} + +func TestSpanLines_KeysEqualSpanLines(t *testing.T) { + dir := spanLinesProject(t) + var doc map[string]any + if err := json.Unmarshal(emitJSON(t, dir, false), &doc); err != nil { + t.Fatal(err) + } + seen := map[string]int{} + checkSpanLines(t, doc, "", seen) + for _, container := range []string{"imports", "types", "fields", "callables", "parameters", "body"} { + if seen[container] == 0 { + t.Errorf("no %s node carried start_line/end_line; saw %v", container, seen) + } + } +} diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index b3d10cd..f6d87a5 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -144,6 +144,7 @@ func (p *projector) projectModule(m v2.Module) { "source": m.Source, "content_hash": emptyToNil(m.ContentHash), "span_json": spanJSON(m.Span), + "start_line": spanLine(m.Span, true), "end_line": spanLine(m.Span, false), }, m.ID, ) @@ -166,9 +167,10 @@ func (p *projector) projectType(modRef NodeRef, module string, t v2.Type) { []string{SymbolLabel, LabelType, MarkerLabel}, "id", t.ID, Props{ - "kind": t.Kind, // struct|interface|alias|defined (decision T1) - "signature": t.Signature, - "span_json": spanJSON(t.Span), + "kind": t.Kind, // struct|interface|alias|defined (decision T1) + "signature": t.Signature, + "span_json": spanJSON(t.Span), + "start_line": spanLine(t.Span, true), "end_line": spanLine(t.Span, false), }, module, ) @@ -190,7 +192,7 @@ func (p *projector) projectType(modRef NodeRef, module string, t v2.Type) { fRef := p.b.Node( []string{LabelField, MarkerLabel}, "id", f.ID, - Props{"kind": f.Kind, "type": f.Type, "span_json": spanJSON(f.Span)}, + Props{"kind": f.Kind, "type": f.Type, "span_json": spanJSON(f.Span), "start_line": spanLine(f.Span, true), "end_line": spanLine(f.Span, false)}, module, ) p.b.Edge(RelHasField, tRef, fRef, nil, "") @@ -225,7 +227,8 @@ func (p *projector) projectCallable(parentRef NodeRef, module string, c v2.Calla "error_channel": stringsOrNil(c.ErrorChannel), "source_file": emptyToNil(c.SourceFile), // only when ≠ nesting module (D8) "span_json": spanJSON(c.Span), - "metrics_json": metricsJSON(c.Metrics), + "start_line": spanLine(c.Span, true), "end_line": spanLine(c.Span, false), + "metrics_json": metricsJSON(c.Metrics), }, module, ) @@ -268,7 +271,8 @@ func (p *projector) projectBodyNode(callableRef NodeRef, module, callableID, loc "is_goroutine": boolOrNil(bn.IsGoroutine), "is_deferred": boolOrNil(bn.IsDeferred), "span_json": bodySpanJSON(bn.Span), - "call_node": callNode, + "start_line": spanLine(bn.Span, true), "end_line": spanLine(bn.Span, false), + "call_node": callNode, // var is JSON `of`: set on L4 vertices only (pruned when empty). "var": emptyToNil(bn.Of), }, @@ -463,6 +467,18 @@ func moduleDeclared(m v2.Module, into map[string]bool) { // ─── flattening helpers ────────────────────────────────────────────────────── +// spanLine is a span's start or end line as a node property, nil (pruned) for the +// span-less synthetic nodes. Lines are 1-based, so a zero span is the absent one. +func spanLine(s v2.Span, start bool) Value { + if s.Start[0] == 0 && s.End[0] == 0 { + return nil + } + if start { + return s.Start[0] + } + return s.End[0] +} + // spanJSON flattens a span to a compact JSON string property. (A span is a // nested map, which Neo4j cannot store as a property, so it rides as *_json — // the same approach the siblings use for variant-shaped fields.) diff --git a/internal/neo4j/schema.go b/internal/neo4j/schema.go index 4c767bd..2ba98e8 100644 --- a/internal/neo4j/schema.go +++ b/internal/neo4j/schema.go @@ -194,22 +194,22 @@ var Nodes = []NodeSpec{ }, { Label: LabelModule, MergeLabel: LabelModule, Key: "id", CanNode: true, - Props: []string{"package", "source", "content_hash", "span_json"}, + Props: []string{"package", "source", "content_hash", "span_json", "start_line", "end_line"}, }, { Label: LabelType, MergeLabel: SymbolLabel, Key: "id", CanNode: true, // kind ∈ struct|interface|alias|defined (property, decision T1). - Props: []string{"kind", "signature", "span_json"}, + Props: []string{"kind", "signature", "span_json", "start_line", "end_line"}, }, { Label: LabelCallable, MergeLabel: SymbolLabel, Key: "id", CanNode: true, // source_file present only when it differs from the nesting module (D8); // error_channel is a homogeneous string array; is_* only on body nodes. - Props: []string{"kind", "signature", "return_type", "error_channel", "source_file", "span_json", "metrics_json"}, + Props: []string{"kind", "signature", "return_type", "error_channel", "source_file", "span_json", "metrics_json", "start_line", "end_line"}, }, { Label: LabelField, MergeLabel: LabelField, Key: "id", CanNode: true, - Props: []string{"kind", "type", "span_json"}, + Props: []string{"kind", "type", "span_json", "start_line", "end_line"}, }, { Label: LabelBodyNode, MergeLabel: LabelBodyNode, Key: "id", CanNode: true, @@ -220,7 +220,7 @@ var Nodes = []NodeSpec{ // resolved against the owning callable or stand-in; Python parity. // var = JSON `of` (L4 vertices only). span_json absent on the // synthetic entry/exit nodes and on vertices. - Props: []string{"kind", "is_goroutine", "is_deferred", "span_json", "call_node", "var"}, + Props: []string{"kind", "is_goroutine", "is_deferred", "span_json", "start_line", "end_line", "call_node", "var"}, }, { Label: LabelExternal, MergeLabel: SymbolLabel, Key: "id", CanNode: true, diff --git a/internal/neo4j/span_lines_test.go b/internal/neo4j/span_lines_test.go new file mode 100644 index 0000000..2bd3af5 --- /dev/null +++ b/internal/neo4j/span_lines_test.go @@ -0,0 +1,70 @@ +package neo4j + +import ( + "testing" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// The projector writes start_line and end_line beside span_json on every span-bearing +// node, and omits them on a span-less synthetic body node. +func TestProject_SpanLineProperties(t *testing.T) { + const ( + app = "can://ns/app" + mod = app + "/go/a.go" + typ = mod + "/T" + fld = typ + "/n" + fn = mod + "/T/M" + bod = fn + "@12:3" + syn = fn + "@entry" + ) + span := func(sl, el int) v2.Span { return v2.Span{Start: [2]int{sl, 1}, End: [2]int{el, 2}} } + a := &v2.Analysis{ + IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, + Application: v2.Application{ + IdentityVersion: 2, ID: app, Kind: "application", + SymbolTable: map[string]v2.Module{ + "a.go": {ID: mod, Kind: "module", Span: span(1, 20), Types: map[string]v2.Type{ + "T": {ID: typ, Kind: "struct", Span: span(5, 9), StartLine: 5, EndLine: 9, + Fields: map[string]v2.Field{"n": {ID: fld, Kind: "field", Span: span(6, 6), StartLine: 6, EndLine: 6}}, + Callables: map[string]v2.Callable{ + "M": {ID: fn, Kind: "method", Signature: "example.com/a.T.M", Span: span(11, 14), StartLine: 11, EndLine: 14, + Body: map[string]v2.BodyNode{ + "12:3": {ID: bod, Kind: "call", Span: span(12, 12), StartLine: 12, EndLine: 12}, + "@entry": {ID: syn, Kind: "entry"}, + }}, + }}, + }}, + }, + }, + } + props := map[string]Props{} + for _, n := range Project(a).Nodes { + props[n.Value] = n.Props + } + cases := []struct { + id string + start, end any + }{ + {mod, 1, 20}, + {typ, 5, 9}, + {fld, 6, 6}, + {fn, 11, 14}, + {bod, 12, 12}, + } + for _, c := range cases { + p, ok := props[c.id] + if !ok { + t.Errorf("no row for %s", c.id) + continue + } + if p["start_line"] != c.start || p["end_line"] != c.end { + t.Errorf("%s: start_line/end_line = %v/%v, want %v/%v", c.id, p["start_line"], p["end_line"], c.start, c.end) + } + } + if p, ok := props[syn]; ok { + if _, has := p["start_line"]; has { + t.Errorf("synthetic body node %s carries start_line %v; want absent", syn, p["start_line"]) + } + } +} diff --git a/internal/schema/v2/schema.go b/internal/schema/v2/schema.go index 6ea806d..4f259ba 100644 --- a/internal/schema/v2/schema.go +++ b/internal/schema/v2/schema.go @@ -174,10 +174,12 @@ type Module struct { // Import is a single import declaration. type Import struct { - Name string `json:"name"` // imported package name - Path string `json:"path"` // import path, e.g. "hash/fnv" - Alias string `json:"alias,omitempty"` // present only when aliased - Span Span `json:"span"` + Name string `json:"name"` // imported package name + Path string `json:"path"` // import path, e.g. "hash/fnv" + Alias string `json:"alias,omitempty"` // present only when aliased + Span Span `json:"span"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` } // ─── type ───────────────────────────────────────────────────────────────────── @@ -185,9 +187,11 @@ type Import struct { // Type is a named Go type. Kind is the specific type-declaration shape, not a // pile of is_* booleans. type Type struct { - ID string `json:"id"` - Kind string `json:"kind"` // struct | interface | alias | defined - Span Span `json:"span"` + ID string `json:"id"` + Kind string `json:"kind"` // struct | interface | alias | defined + Span Span `json:"span"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` // Signature is the type's full import-qualified name (one signatureOf()). The // id carries only the bare type name, so this is where the package path lives. Signature string `json:"signature"` @@ -206,10 +210,12 @@ type Type struct { // Field is a struct field. type Field struct { - ID string `json:"id"` - Kind string `json:"kind"` // always "field" - Type string `json:"type"` - Span Span `json:"span"` + ID string `json:"id"` + Kind string `json:"kind"` // always "field" + Type string `json:"type"` + Span Span `json:"span"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` } // ─── callable ───────────────────────────────────────────────────────────────── @@ -217,9 +223,11 @@ type Field struct { // Callable is a function, method, or closure. span.bytes → get_method_body = // module.source[bytes]. type Callable struct { - ID string `json:"id"` - Kind string `json:"kind"` // function | method | lambda - Span Span `json:"span"` + ID string `json:"id"` + Kind string `json:"kind"` // function | method | lambda + Span Span `json:"span"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` // Signature is the full import-qualified name (one signatureOf()). The id // carries only the bare member name, so this field is where the package path lives. Signature string `json:"signature"` @@ -261,6 +269,8 @@ type Parameter struct { Name string `json:"name"` Type string `json:"type"` Span Span `json:"span"` + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` IsVariadic bool `json:"is_variadic,omitempty"` } @@ -279,6 +289,9 @@ type BodyNode struct { // Span is the node's source range. Absent (zero) only on the synthetic // entry/exit nodes, which have no source. Span Span `json:"span,omitzero"` + // StartLine and EndLine equal span.start[0] and span.end[0]; absent with the span. + StartLine int `json:"start_line,omitempty"` + EndLine int `json:"end_line,omitempty"` // Parent is, at L3+, the local key of the statement a satellite call // node is nested in (the sanctioned parent refinement). Absent on CFG // nodes. diff --git a/internal/syntactic_analysis/v2emit/emit.go b/internal/syntactic_analysis/v2emit/emit.go index e9766af..d26a339 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/v2emit/emit.go @@ -308,22 +308,28 @@ func emitModule(appID, modRel string, file schema.GoFile, idx sigIndex, srcs *so func emitType(appID, modRel string, t schema.GoType, idx sigIndex, srcs *sourceCache, flow l3Overlay, l4 *l4Overlay) v2.Type { li := srcs.index(modRel) typeID := v2.TypeID(v2.ModuleID(appID, modRel), t.Signature) + tsp := lineSpan(li, t.StartLine, t.EndLine) out := v2.Type{ ID: typeID, Kind: typeKind(t), Signature: t.Signature, - Span: lineSpan(li, t.StartLine, t.EndLine), + Span: tsp, + StartLine: tsp.Start[0], + EndLine: tsp.End[0], BaseTypes: nonEmpty(t.BaseTypes), Callables: make(map[string]v2.Callable, len(t.Methods)), } if len(t.Fields) > 0 { out.Fields = make(map[string]v2.Field, len(t.Fields)) for _, f := range t.Fields { + fsp := lineSpan(li, f.StartLine, f.EndLine) out.Fields[f.Name] = v2.Field{ - ID: typeID + "/" + f.Name, - Kind: "field", - Type: f.Type, - Span: lineSpan(li, f.StartLine, f.EndLine), + ID: typeID + "/" + f.Name, + Kind: "field", + Type: f.Type, + Span: fsp, + StartLine: fsp.Start[0], + EndLine: fsp.End[0], } } } @@ -372,10 +378,13 @@ func emitCallable(parentID, modRel, declRel string, declLI *lineIndex, c schema. sourceFile = declRel } + csp := lineSpan(li, c.StartLine, c.EndLine) out := v2.Callable{ ID: callID, Kind: callableKind(c), - Span: lineSpan(li, c.StartLine, c.EndLine), + Span: csp, + StartLine: csp.Start[0], + EndLine: csp.End[0], Signature: c.Signature, SourceFile: sourceFile, Parameters: emitParams(li, c.Parameters), @@ -419,10 +428,13 @@ func emitBody(callableID string, li *lineIndex, sites []schema.GoCallsite, idx s body := make(map[string]v2.BodyNode, len(sites)) for i, cs := range sites { local := keys[i] + bsp := colSpan(li, cs.StartLine, cs.StartColumn, cs.EndLine, cs.EndColumn) body[local] = v2.BodyNode{ Kind: "call", ID: v2.GlobalOrdinal(callableID, local), - Span: colSpan(li, cs.StartLine, cs.StartColumn, cs.EndLine, cs.EndColumn), + Span: bsp, + StartLine: bsp.Start[0], + EndLine: bsp.End[0], Callee: calleeID(cs.CalleeSignature, idx), IsGoroutine: cs.IsGoroutine, IsDeferred: cs.IsDeferred, @@ -507,10 +519,13 @@ func emitExternalSymbols(appID string, externals map[string]schema.GoExternalCal func emitParams(li *lineIndex, params []schema.GoParameter) []v2.Parameter { out := make([]v2.Parameter, 0, len(params)) for _, p := range params { + psp := lineSpan(li, p.StartLine, p.EndLine) out = append(out, v2.Parameter{ Name: p.Name, Type: p.Type, - Span: lineSpan(li, p.StartLine, p.EndLine), + Span: psp, + StartLine: psp.Start[0], + EndLine: psp.End[0], IsVariadic: p.IsVariadic, }) } @@ -520,11 +535,14 @@ func emitParams(li *lineIndex, params []schema.GoParameter) []v2.Parameter { func emitImports(li *lineIndex, imports []schema.GoImport) []v2.Import { out := make([]v2.Import, 0, len(imports)) for _, imp := range imports { + isp := lineSpan(li, imp.StartLine, imp.EndLine) out = append(out, v2.Import{ - Name: packageBase(imp.Module), - Path: imp.Module, - Alias: imp.Alias, - Span: lineSpan(li, imp.StartLine, imp.EndLine), + Name: packageBase(imp.Module), + Path: imp.Module, + Alias: imp.Alias, + Span: isp, + StartLine: isp.Start[0], + EndLine: isp.End[0], }) } return out diff --git a/internal/syntactic_analysis/v2emit/emit_l3.go b/internal/syntactic_analysis/v2emit/emit_l3.go index bc43c28..ad6f1cb 100644 --- a/internal/syntactic_analysis/v2emit/emit_l3.go +++ b/internal/syntactic_analysis/v2emit/emit_l3.go @@ -70,6 +70,7 @@ func l3BodyNode(n dataflow.Node, li *lineIndex) v2.BodyNode { bn := v2.BodyNode{Kind: string(n.Kind), Parent: n.Parent} if n.Kind != dataflow.KindEntry && n.Kind != dataflow.KindExit { bn.Span = colSpan(li, n.StartLC[0], n.StartLC[1], n.EndLC[0], n.EndLC[1]) + bn.StartLine, bn.EndLine = bn.Span.Start[0], bn.Span.End[0] } return bn } From 49dbbe4eaaaf210651762947abbf1335abd33df6 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sat, 21 Nov 2026 08:43:25 -0500 Subject: [PATCH 13/19] feat(schema): start_line and end_line on the JSON module The module gains the two keys, equal to its whole-file span, so the JSON and Neo4j modules match. Spec amended: docs/design/specs/v2-span-lines.md. Refs codellm-devkit/codeanalyzer-go#51 --- CLAUDE.md | 2 +- docs/design/specs/v2-span-lines.md | 6 ++++++ internal/core/span_lines_test.go | 9 +++++++++ internal/schema/v2/schema.go | 3 +++ internal/syntactic_analysis/v2emit/emit.go | 5 ++++- 5 files changed, 23 insertions(+), 2 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index e98ad4a..73b599f 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -40,7 +40,7 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. - **Generic types**: `signatureOf()` carries no type parameters, so a generic type or method ids as `//`, with no `[T]` in the id. - **`start_line` / `end_line`** [user, 2026-11-21; spec `docs/design/specs/v2-span-lines.md`]: top-level keys next - to `span` on `Import`, `Parameter`, `Callable`, `Type`, `Field` and `BodyNode`, equal to `span.start[0]` and + to `span` on `Module` (added 2026-11-21 so the JSON and Neo4j modules match), `Import`, `Parameter`, `Callable`, `Type`, `Field` and `BodyNode`, equal to `span.start[0]` and `span.end[0]`. No `code_start_line`. Neo4j nodes carry the same two properties beside `span_json`. - **`span.bytes`** = **UTF-8 byte offsets** into `module.source` (Go strings are natively UTF-8; avoids the UTF-16/rune slicing mismatch TS hit in cants#179). diff --git a/docs/design/specs/v2-span-lines.md b/docs/design/specs/v2-span-lines.md index 5c2846d..70edc4e 100644 --- a/docs/design/specs/v2-span-lines.md +++ b/docs/design/specs/v2-span-lines.md @@ -28,6 +28,12 @@ Made with the user on 2026-11-21. 5. **Tracking.** One issue in codeanalyzer-go, one checklist. One PR on `add_startline_endline`. 6. **Release.** One PR, one release. The keys are additive, so existing consumers keep working. +## Amendment (2026-11-21): module + +The Neo4j module node carries `start_line` and `end_line`, so the JSON module must too, or the +two projections differ. Decided with the user: the JSON `module` gains the keys, equal to its +whole-file `span.start[0]` and `span.end[0]`. The module is therefore a seventh model. + ## Out of scope - `code_start_line` (decision 3). diff --git a/internal/core/span_lines_test.go b/internal/core/span_lines_test.go index b916654..8d97983 100644 --- a/internal/core/span_lines_test.go +++ b/internal/core/span_lines_test.go @@ -93,6 +93,15 @@ func TestSpanLines_KeysEqualSpanLines(t *testing.T) { } seen := map[string]int{} checkSpanLines(t, doc, "", seen) + mods := asMap(asMap(asMap(doc["application"])["symbol_table"])) + if len(mods) == 0 { + t.Fatal("no modules in symbol_table") + } + for path, m := range mods { + if _, ok := asMap(m)["start_line"]; !ok { + t.Errorf("module %s has no start_line", path) + } + } for _, container := range []string{"imports", "types", "fields", "callables", "parameters", "body"} { if seen[container] == 0 { t.Errorf("no %s node carried start_line/end_line; saw %v", container, seen) diff --git a/internal/schema/v2/schema.go b/internal/schema/v2/schema.go index 4f259ba..0f331e5 100644 --- a/internal/schema/v2/schema.go +++ b/internal/schema/v2/schema.go @@ -157,6 +157,9 @@ type Module struct { ID string `json:"id"` Kind string `json:"kind"` // always "module" Span Span `json:"span"` + // StartLine and EndLine equal span.start[0] and span.end[0] (the whole file). + StartLine int `json:"start_line"` + EndLine int `json:"end_line"` // Package is the Go package the file belongs to. Package string `json:"package"` // Source is the WHOLE file's text, stored once. Every node's text slices diff --git a/internal/syntactic_analysis/v2emit/emit.go b/internal/syntactic_analysis/v2emit/emit.go index d26a339..bad9fda 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/v2emit/emit.go @@ -278,10 +278,13 @@ func emitModule(appID, modRel string, file schema.GoFile, idx sigIndex, srcs *so source := li.source modID := v2.ModuleID(appID, modRel) + msp := wholeFileSpan(li, source) mod := v2.Module{ ID: modID, Kind: "module", - Span: wholeFileSpan(li, source), + Span: msp, + StartLine: msp.Start[0], + EndLine: msp.End[0], Package: file.PackageName, Source: source, Imports: emitImports(li, file.Imports), From 07b5cdc22ef3223b36d353e3414507ca6f5d531d Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sun, 22 Nov 2026 15:28:23 -0500 Subject: [PATCH 14/19] fix(symbol-table): keep every func init() in a file A file may declare any number of func init(), and all share the signature ".init". The symbol table keyed functions by signature, so the second init overwrote the first. The first init's body, its call sites and its call-graph edges were then missing from the analysis, with no warning. The second and later same-signature functions in a file now get a ":N" suffix (N = 2, 3, ...). That gives each init its own map key, its own can:// id (init, init:2, ...), and its own call-graph source. The first init keeps the bare name, so the ids of every file with one init are unchanged. A colon cannot appear in a Go identifier and no call site can name an init, so the suffix collides with nothing. Signature is therefore no longer exactly signatureOf() for the duplicate inits. That is a visible schema change and is recorded in CLAUDE.md. Adds TestInit_EveryInitSurvivesWithDistinctID, which fails on the old code (2 init callables instead of 3) and passes on the fix. Co-Authored-By: Claude Haiku 5.5 --- CLAUDE.md | 7 + internal/core/init_collision_test.go | 120 ++++++++++++++++++ internal/syntactic_analysis/symbol_table.go | 20 +++ .../syntactic_analysis/v2emit/sigindex.go | 22 ++-- 4 files changed, 158 insertions(+), 11 deletions(-) create mode 100644 internal/core/init_collision_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 73b599f..34f24ba 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,6 +32,13 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. JSON field on both (types gained it, additive, for the Neo4j `:GoType.signature`) [user, 2026-11-20]. The id carries only the bare member name, so this field is where the package path lives. One canonicalizer, unchanged from v1. + **Exception: duplicate `func init()`** (fix/init-collision, 2026-11-22). Go allows many + inits per file, all with signatureOf() `.init`. The second and later ones in a + file carry `:N` (N = 2, 3, ...), e.g. `.init:2`, in `signature`, in the callable's + id member (`init:2`), and as the call-graph source. The first keeps the bare name, so the + ids of files with one init are unchanged. The suffix is the only way to keep their ids and + edges distinct; a colon is not a Go identifier character, so it cannot collide with a + real function. - **Cross-file method ids** [user, 2026-11-20]: a method declared in another file than its receiver type gets `//`, e.g. `…/handlers.go/frontendServer/logoutHandler`. The node stays in the receiver type's `callables{}`. `source_file` is kept for text recovery. diff --git a/internal/core/init_collision_test.go b/internal/core/init_collision_test.go new file mode 100644 index 0000000..7cdaf8d --- /dev/null +++ b/internal/core/init_collision_test.go @@ -0,0 +1,120 @@ +package core_test + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/core" + "github.com/codellm-devkit/codeanalyzer-go/internal/options" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" +) + +// initProject declares two func init() in one file (Go allows any number per +// file), one in another file, and each calls a helper. +func initProject(t *testing.T) string { + t.Helper() + dir := t.TempDir() + files := map[string]string{ + "go.mod": "module example.com/ini\n\ngo 1.25.0\n", + "main.go": "package ini\n\nvar registry = map[string]int{}\n\n" + + "func a() { registry[\"a\"] = 1 }\nfunc b() { registry[\"b\"] = 2 }\n\n" + + "func init() {\n\ta()\n}\n\n" + + "func init() {\n\tb()\n}\n", + "other.go": "package ini\n\nfunc init() {\n\ta()\n}\n", + } + for rel, content := range files { + if err := os.WriteFile(filepath.Join(dir, rel), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + return dir +} + +// emitCallGraphJSON runs the analyzer at L2, where call_graph is emitted. The +// shared emitJSON helper runs at L1 and so has no edges to check. +func emitCallGraphJSON(t *testing.T, dir string) []byte { + t.Helper() + opts := options.AnalysisOptions{ + InputPath: dir, AppName: "repoapp", Level: options.LevelCallGraph, + SkipTests: true, CacheDir: t.TempDir(), OutputDir: t.TempDir(), + } + app, err := core.New(opts).Analyze() + if err != nil { + t.Fatal(err) + } + identity, err := v2.ResolveIdentity("repoapp", nil) + if err != nil { + t.Fatal(err) + } + out, err := json.Marshal(v2emit.Emit(app, identity, dir, int(opts.Level), "test", 0, nil, nil)) + if err != nil { + t.Fatal(err) + } + return out +} + +// TestInit_EveryInitSurvivesWithDistinctID guards the regression where a file +// with several func init() kept only the last one. Each init must appear in +// functions{} under its own id, and each must contribute its own call edge. +func TestInit_EveryInitSurvivesWithDistinctID(t *testing.T) { + dir := initProject(t) + var doc map[string]any + if err := json.Unmarshal(emitCallGraphJSON(t, dir), &doc); err != nil { + t.Fatal(err) + } + app := asMap(doc["application"]) + st := asMap(app["symbol_table"]) + + var initIDs []string + for _, mod := range st { + for _, fn := range asMap(asMap(mod)["functions"]) { + id, _ := asMap(fn)["id"].(string) + if strings.HasSuffix(id, "/init") || strings.Contains(id, "/init:") { + initIDs = append(initIDs, id) + } + } + } + if len(initIDs) != 3 { + t.Fatalf("want 3 init callables (two in main.go, one in other.go), got %d: %v", len(initIDs), initIDs) + } + ids := map[string]bool{} + for _, id := range initIDs { + if ids[id] { + t.Errorf("duplicate init id %s", id) + } + ids[id] = true + } + const base = "can://repoapp/repoapp/go/" + for _, want := range []string{"main.go/init", "main.go/init:2", "other.go/init"} { + if !ids[base+want] { + t.Errorf("missing init id %s%s; have %v", base, want, initIDs) + } + } + + // Each init's own call is an edge from that init's id to its callee. The + // two main.go inits must not merge into one edge set. + wantEdges := map[string]bool{ + base + "main.go/init -> " + base + "main.go/a": false, + base + "main.go/init:2 -> " + base + "main.go/b": false, + base + "other.go/init -> " + base + "main.go/a": false, + } + cg, _ := app["call_graph"].([]any) + for _, e := range cg { + edge := asMap(e) + key, _ := edge["src"].(string) + dst, _ := edge["dst"].(string) + key += " -> " + dst + if _, ok := wantEdges[key]; ok { + wantEdges[key] = true + } + } + for edge, found := range wantEdges { + if !found { + t.Errorf("missing call-graph edge %s", edge) + } + } +} diff --git a/internal/syntactic_analysis/symbol_table.go b/internal/syntactic_analysis/symbol_table.go index 9ada56b..ed10e09 100644 --- a/internal/syntactic_analysis/symbol_table.go +++ b/internal/syntactic_analysis/symbol_table.go @@ -270,6 +270,7 @@ func (b *SymbolTableBuilder) buildGoFile( methods = append(methods, pendingMethod{typeName, callable}) } } else { + callable.Signature = uniqueFuncSignature(gf.Functions, callable.Signature) gf.Functions[callable.Signature] = *callable } } @@ -286,6 +287,25 @@ func (b *SymbolTableBuilder) buildGoFile( return gf } +// uniqueFuncSignature returns sig for the first package-level function of that +// signature in a file, and sig:N (N = 2, 3, ...) for each later one. Go permits +// any number of func init() per file, and every one of them has the signature +// ".init". Without the suffix they collapse into one map entry, and +// their call-graph edges (keyed on Source = Signature) merge too. The suffix is +// safe: a colon cannot appear in a Go identifier, and no call site can name an +// init, so no edge ever needs to resolve to a suffixed signature. +func uniqueFuncSignature(fns map[string]schema.GoCallable, sig string) string { + if _, taken := fns[sig]; !taken { + return sig + } + for n := 2; ; n++ { + candidate := fmt.Sprintf("%s:%d", sig, n) + if _, taken := fns[candidate]; !taken { + return candidate + } + } +} + // ─── Imports ────────────────────────────────────────────────────────────────── func (b *SymbolTableBuilder) buildImports(astFile *ast.File) []schema.GoImport { diff --git a/internal/syntactic_analysis/v2emit/sigindex.go b/internal/syntactic_analysis/v2emit/sigindex.go index 83a3f07..da37467 100644 --- a/internal/syntactic_analysis/v2emit/sigindex.go +++ b/internal/syntactic_analysis/v2emit/sigindex.go @@ -18,17 +18,17 @@ import ( // // Signatures are ALMOST globally unique (a method signature embeds its receiver // type), with one exception: package-level `func init()`. Go permits many init -// functions per package (one per file), and they all share the signature -// ".init". They are nonetheless distinct callables with distinct -// can:// ids — the id embeds the declaring file via its parent module — so a -// flat signature→id map collapses them, and since it is populated by ranging a -// Go map (random order) the surviving id is nondeterministic run to run. That -// nondeterminism propagated into the call_graph edge set. +// functions per file, and they all share the signature ".init". The +// symbol table gives the second and later ones a ":N" suffix (see +// uniqueFuncSignature), so each init has its own signature and therefore its +// own can:// id, call-graph endpoint and map key. A signature is then unique +// per declaring file, and the flat map below is unambiguous except across files +// that each declare an init. // -// The index therefore keeps two maps: a flat signature→id (deterministic on -// collision — smallest id wins) for the unique common case, and a -// (signature,path)→id map that disambiguates the init collision by the source -// callable's declaring file. See idFor / idForWithPath. +// The index keeps two maps: a flat signature→id (deterministic on collision — +// smallest id wins) for the unique common case, and a (signature,path)→id map +// that resolves a signature declared in a specific file. See idFor / +// idForWithPath. type sigIndex struct { bySig map[string]string bySigPath map[sigPathKey]string @@ -93,7 +93,7 @@ func (idx sigIndex) addCallable(parentID, relPath string, c schema.GoCallable) { } // Precise entry: a callable's declaring file plus its signature is unique - // even for init, because at most one init exists per file. Call-graph + // (inits within one file carry distinct :N suffixes). Call-graph // edges carry the declaring file (c.Path), which differs from relPath for // a method declared apart from its receiver type, and for the closures in // one; index both so either resolves. From 35e2cf2cca2180759d011289e52df3df785308d4 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sun, 22 Nov 2026 15:33:15 -0500 Subject: [PATCH 15/19] fix(repository): resolve a symlinked project root before artifact discovery filepath.WalkDir does not follow a symlink at its root. It lstats the root and sees one non-directory entry, so a project reached through a symlink (a checkout under ~/work linked into a workspace, for example) produced an empty application.artifacts. The dependencies were still parsed through the link, so every dependency's declared_in named an artifact that was never emitted, and the Neo4j DECLARES_DEPENDENCY and LOCKS edges that MATCH on those ids were dropped without a warning. The same bug disabled the self-exclusion. A symlinked --output or --cache path was compared against walked paths that used the real location, so a previous run's analysis.json inside the project was captured as an artifact. Discover now resolves the root, OutputDir and CacheDir through symlinks before the walk. resolveDir handles a path that does not exist yet (an output directory created later) by resolving its longest existing ancestor. Any resolution error other than "does not exist" is now returned, where absOrEmpty used to return "" and silently disable the exclusion. That is the fail-closed choice. Symlinks inside the tree are still not followed, so discovery cannot leave the project root. A probe with an in-tree link to a file outside the project confirms the outside file is not captured. Tests: TestDiscover_SymlinkedRootMatchesRealRoot fails on the old code (no artifacts), TestDiscover_SymlinkedOutputDirIsExcluded fails on the old code (analysis.json captured), and TestResolveDir_MissingTailIsKept covers the not-yet-created output path. Co-Authored-By: Claude Haiku 5.5 --- internal/repository/repository.go | 54 ++++++++++-- internal/repository/symlink_root_test.go | 100 +++++++++++++++++++++++ 2 files changed, 146 insertions(+), 8 deletions(-) create mode 100644 internal/repository/symlink_root_test.go diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 45906d1..c8d5981 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -10,6 +10,7 @@ import ( "bytes" "crypto/sha256" "encoding/hex" + "errors" "fmt" "io/fs" "os" @@ -45,13 +46,25 @@ var outputFileNames = map[string]bool{"analysis.json": true, "graph.cypher": tru // Discover returns every non-.go regular file under root as an artifact, keyed by // its repo-relative POSIX path. Files are visited in lexical order. +// +// The root, OutputDir and CacheDir are resolved through symlinks before the walk. +// filepath.WalkDir does not follow a symlink at the root, so a project reached +// through one would otherwise yield no artifacts at all. Symlinks found inside the +// tree are still not followed (they are skipped, as before), so discovery never +// leaves the project root. func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { - absRoot, err := filepath.Abs(root) + absRoot, err := resolveDir(root) if err != nil { - return nil, err + return nil, fmt.Errorf("resolving project root: %w", err) + } + outDir, err := optionalDir(opts.OutputDir) + if err != nil { + return nil, fmt.Errorf("resolving output directory: %w", err) + } + cacheDir, err := optionalDir(opts.CacheDir) + if err != nil { + return nil, fmt.Errorf("resolving cache directory: %w", err) } - outDir := absOrEmpty(opts.OutputDir) - cacheDir := absOrEmpty(opts.CacheDir) out := map[string]schema.GoArtifact{} err = filepath.WalkDir(absRoot, func(p string, d fs.DirEntry, werr error) error { if werr != nil { @@ -86,15 +99,40 @@ func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { return out, nil } -func absOrEmpty(p string) string { +// optionalDir resolves an optional directory setting; "" means unset. +func optionalDir(p string) (string, error) { if p == "" { - return "" + return "", nil } + return resolveDir(p) +} + +// resolveDir returns the absolute, symlink-free form of p. p need not exist yet +// (an output directory may be created later): the longest existing ancestor is +// resolved and the missing tail is re-appended. Any error other than "does not +// exist" (a symlink loop, a permission failure) is returned rather than ignored, +// so the self-exclusion comparisons never silently turn off. +func resolveDir(p string) (string, error) { abs, err := filepath.Abs(p) if err != nil { - return "" + return "", err + } + cur, tail := abs, "" + for { + resolved, err := filepath.EvalSymlinks(cur) + if err == nil { + return filepath.Join(resolved, tail), nil + } + if !errors.Is(err, fs.ErrNotExist) { + return "", err + } + parent := filepath.Dir(cur) + if parent == cur { + return abs, nil + } + tail = filepath.Join(filepath.Base(cur), tail) + cur = parent } - return abs } // readArtifact hashes the whole file and classifies it. Text source is kept only diff --git a/internal/repository/symlink_root_test.go b/internal/repository/symlink_root_test.go new file mode 100644 index 0000000..5c08909 --- /dev/null +++ b/internal/repository/symlink_root_test.go @@ -0,0 +1,100 @@ +package repository + +import ( + "os" + "path/filepath" + "reflect" + "runtime" + "sort" + "testing" +) + +// symlinkTree makes a project at /real and a symlink /linked to it. +func symlinkTree(t *testing.T) (real, linked string) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("directory symlinks need privileges on Windows") + } + base := t.TempDir() + real = filepath.Join(base, "real") + writeTree(t, real, map[string]string{ + "go.mod": "module example.com/app\n\ngo 1.22\n\nrequire example.com/dep v1.0.0\n", + "go.sum": "example.com/dep v1.0.0 h1:AAAA=\n", + "README.md": "# readme\n", + "main.go": "package main\n", + }) + linked = filepath.Join(base, "linked") + if err := os.Symlink(real, linked); err != nil { + t.Fatal(err) + } + return real, linked +} + +// A project reached through a symlinked root must produce the same artifacts as +// the real path. Before the fix, WalkDir saw the root as one non-directory entry +// and returned no artifacts at all. +func TestDiscover_SymlinkedRootMatchesRealRoot(t *testing.T) { + real, linked := symlinkTree(t) + want, err := Discover(real, Options{}) + if err != nil { + t.Fatal(err) + } + got, err := Discover(linked, Options{}) + if err != nil { + t.Fatal(err) + } + if len(want) == 0 { + t.Fatal("real root produced no artifacts; the fixture is wrong") + } + if !reflect.DeepEqual(sortedKeysOf(got), sortedKeysOf(want)) { + t.Fatalf("symlinked root artifacts = %v, want %v", keys(got), keys(want)) + } +} + +// An output directory given through a symlink must still be excluded, or the +// previous run's analysis.json is captured as an artifact. +func TestDiscover_SymlinkedOutputDirIsExcluded(t *testing.T) { + real, _ := symlinkTree(t) + outReal := filepath.Join(real, "out") + if err := os.MkdirAll(outReal, 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(filepath.Join(outReal, "analysis.json"), []byte("{}"), 0o644); err != nil { + t.Fatal(err) + } + outLink := filepath.Join(t.TempDir(), "out-link") + if err := os.Symlink(outReal, outLink); err != nil { + t.Fatal(err) + } + // Walk the real root, so analysis.json is reachable; only the output dir is a symlink. + got, err := Discover(real, Options{OutputDir: outLink}) + if err != nil { + t.Fatal(err) + } + if _, ok := got["out/analysis.json"]; ok { + t.Fatalf("previous analysis.json was captured through a symlinked output dir: %v", keys(got)) + } +} + +func sortedKeysOf[V any](m map[string]V) []string { + ks := keys(m) + sort.Strings(ks) + return ks +} + +// resolveDir accepts a path that does not exist yet (an output directory created +// later), resolving its existing ancestor and keeping the missing tail. +func TestResolveDir_MissingTailIsKept(t *testing.T) { + real, linked := symlinkTree(t) + got, err := resolveDir(filepath.Join(linked, "not-yet", "deeper")) + if err != nil { + t.Fatal(err) + } + want := filepath.Join(real, "not-yet", "deeper") + if evalReal, err := filepath.EvalSymlinks(real); err == nil { + want = filepath.Join(evalReal, "not-yet", "deeper") + } + if got != want { + t.Fatalf("resolveDir = %q, want %q", got, want) + } +} From 00ad4a63d2c89dc29790e08b6108442dba6e57cd Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sun, 22 Nov 2026 15:56:23 -0500 Subject: [PATCH 16/19] fix(neo4j): a cross-file method belongs to the module that declares it A method declared in b.go on a type in a.go was projected as owned by a.go: its node and body rows took the receiver module's owner. The lazy push upserts a module's rows only when that module's content_hash changes, and the hash is the file's own content. So editing only b.go left a.go's hash alone, the method was never re-upserted, and the graph kept the old span and body. A method added to b.go was never upserted at all. Its GO_HAS_METHOD and GO_DECLARES MERGEs then matched no node and were dropped silently. The owner is now the declaring file, which matches the method's id prefix. The node id is unchanged, and so are the JSON and the edges. Only the owning module moves, so the purge-by-prefix and the content-hash diff now agree about every row. The change-detection comparison moved out of changedModules into the pure changedAgainst, so the lazy-push selection is testable without a database. Tests run the real symbol-table builder and emitter on real source and project each version. They fail on the old projector and pass on the fix: - TestLazyPush_EditingDeclaringFileUpsertsCrossFileMethod - TestLazyPush_NewCrossFileMethodIsUpserted (also checks both edge endpoints) - TestLazyPush_OwnerIsIdPrefixForEveryRow (the invariant the fix relies on) Not verified against a live Neo4j: the local instance has a password I do not have, so the integration test (neo4j_it tag) was not run. Co-Authored-By: Claude Haiku 5.5 --- internal/neo4j/bolt.go | 24 ++- internal/neo4j/crossfile_lazy_push_test.go | 172 +++++++++++++++++++++ internal/neo4j/project.go | 13 +- 3 files changed, 204 insertions(+), 5 deletions(-) create mode 100644 internal/neo4j/crossfile_lazy_push_test.go diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index 50b57e4..36f5dc7 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -453,9 +453,27 @@ func (w *boltWriter) moduleChanged(id, localHash string) (bool, error) { if err != nil { return false, err } - // Changed when the hash differs or the module is new, or when either side - // has no hash (can't prove unchanged → upsert). - return localHash == "" || dbHash == "" || localHash != dbHash, nil + return hashChanged(localHash, dbHash), nil +} + +// hashChanged reports whether a module must be upserted: its content_hash +// differs from the database's, the module is new, or either side has no hash +// (we cannot prove it unchanged). +func hashChanged(local, db string) bool { + return local == "" || db == "" || local != db +} + +// changedAgainst applies hashChanged to every module of byModule. dbHash is the +// stored hash of a module, "" when the module is absent. It is pure, so the +// lazy-push selection can be tested without a database. +func changedAgainst(byModule map[string][]NodeRow, dbHash func(string) string) map[string]bool { + changed := map[string]bool{} + for m, nodes := range byModule { + if hashChanged(moduleHash(nodes), dbHash(m)) { + changed[m] = true + } + } + return changed } // ─── upserts ────────────────────────────────────────────────────────────────── diff --git a/internal/neo4j/crossfile_lazy_push_test.go b/internal/neo4j/crossfile_lazy_push_test.go new file mode 100644 index 0000000..1f25de5 --- /dev/null +++ b/internal/neo4j/crossfile_lazy_push_test.go @@ -0,0 +1,172 @@ +package neo4j + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" +) + +// The lazy push upserts a module's rows only when that module's content_hash +// changed. A cross-file method is declared in b.go but its receiver type lives in +// a.go, so before the fix its node and body rows were owned by a.go. Editing +// b.go left a.go's hash alone, so the method was never re-upserted and the graph +// kept its old body. These tests use real source on disk, analyzed by the real +// symbol-table builder and emitter, and project each version with Project. + +// analyzeXF writes the files to a fresh project and returns its L1 analysis. +func analyzeXF(t *testing.T, files map[string]string) *v2.Analysis { + t.Helper() + dir := t.TempDir() + for rel, content := range files { + if err := os.WriteFile(filepath.Join(dir, rel), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + b := syntactic_analysis.NewSymbolTableBuilder(dir) + st, err := b.Build(nil, true) + if err != nil { + t.Fatalf("symbol table build: %v", err) + } + app := &schema.GoApplication{SymbolTable: st} + id, err := v2.ResolveIdentity("xf", nil) + if err != nil { + t.Fatal(err) + } + return v2emit.Emit(app, id, dir, 1, "lazy-push-test", 0, nil, nil) +} + +// lazyUpsertIDs is the set of node ids a lazy (non-eager) push would upsert when +// the database holds the module hashes of the previous push. It mirrors the +// writer: shared and L4 nodes always, plus every node of a changed module. +func lazyUpsertIDs(rows GraphRows, prev GraphRows) map[string]bool { + prevByModule, _, _ := partitionNodes(prev.Nodes) + dbHash := map[string]string{} + for m, nodes := range prevByModule { + dbHash[m] = moduleHash(nodes) + } + byModule, shared, l4 := partitionNodes(rows.Nodes) + changed := changedAgainst(byModule, func(m string) string { return dbHash[m] }) + up := map[string]bool{} + for _, n := range shared { + up[n.Value] = true + } + for _, n := range l4 { + up[n.Value] = true + } + for m, nodes := range byModule { + if !changed[m] { + continue + } + for _, n := range nodes { + up[n.Value] = true + } + } + return up +} + +// nodesUnder returns the ids of every node whose id is prefix or sits beneath it. +func nodesUnder(rows GraphRows, prefix string) []string { + var out []string + for _, n := range rows.Nodes { + if n.Value == prefix || strings.HasPrefix(n.Value, prefix+"/") || strings.HasPrefix(n.Value, prefix+"@") { + out = append(out, n.Value) + } + } + return out +} + +const xfA = "package xf\n\ntype T struct {\n\tn int\n}\n" + +// Scenario 1: the method body changes in b.go; a.go is byte-identical. +// +// a.go b.go (before) b.go (after) +// type T struct{ n int } func (t *T) M() int { func (t *T) M() int { +// return helper(t.n) return helper(t.n) + helper(2) +// } } +func TestLazyPush_EditingDeclaringFileUpsertsCrossFileMethod(t *testing.T) { + before := analyzeXF(t, map[string]string{ + "go.mod": "module example.com/xf\n\ngo 1.25.0\n", + "a.go": xfA, + "b.go": "package xf\n\nfunc (t *T) M() int {\n\treturn helper(t.n)\n}\n\nfunc helper(n int) int { return n }\n", + }) + after := analyzeXF(t, map[string]string{ + "go.mod": "module example.com/xf\n\ngo 1.25.0\n", + "a.go": xfA, + "b.go": "package xf\n\nfunc (t *T) M() int {\n\treturn helper(t.n) + helper(2)\n}\n\nfunc helper(n int) int { return n }\n", + }) + rPrev, rNow := Project(before), Project(after) + + methodID := "can://xf/xf/go/b.go/T/M" + up := lazyUpsertIDs(rNow, rPrev) + missed := []string{} + for _, id := range nodesUnder(rNow, methodID) { + if !up[id] { + missed = append(missed, id) + } + } + if len(missed) > 0 { + t.Errorf("lazy push skips rows of %s although b.go changed: %v", methodID, missed) + } +} + +// Scenario 2: a new method is added to b.go for T, which is declared in a.go. +// a.go is unchanged, so before the fix the new method's node and both edges that +// reference it were dropped: the MERGE edges MATCH the missing node and vanish. +// +// b.go (after): func (t *T) Reset() { t.n = 0 } // T is declared in a.go +func TestLazyPush_NewCrossFileMethodIsUpserted(t *testing.T) { + before := analyzeXF(t, map[string]string{ + "go.mod": "module example.com/xf\n\ngo 1.25.0\n", + "a.go": xfA, + "b.go": "package xf\n\nfunc (t *T) M() int { return t.n }\n", + }) + after := analyzeXF(t, map[string]string{ + "go.mod": "module example.com/xf\n\ngo 1.25.0\n", + "a.go": xfA, + "b.go": "package xf\n\nfunc (t *T) M() int { return t.n }\n\nfunc (t *T) Reset() { t.n = 0 }\n", + }) + rPrev, rNow := Project(before), Project(after) + + resetID := "can://xf/xf/go/b.go/T/Reset" + up := lazyUpsertIDs(rNow, rPrev) + if !up[resetID] { + t.Errorf("lazy push drops new cross-file method %s (a.go unchanged, b.go changed)", resetID) + } + // Each edge that names the method must have its endpoint upserted, or the + // MERGE in upsertEdges matches nothing and the edge is silently lost. + for _, e := range rNow.Edges { + if e.To.Value != resetID && e.From.Value != resetID { + continue + } + for _, end := range []string{e.From.Value, e.To.Value} { + if end == resetID && !up[end] { + t.Errorf("edge %s %s -> %s has an un-upserted endpoint", e.Type, e.From.Value, e.To.Value) + } + } + } +} + +// The invariant the lazy push depends on: a module-owned row's id carries that +// module's id as a prefix, so the module that owns a row is the module whose +// content hash governs it. A cross-file method violated this before the fix. +func TestLazyPush_OwnerIsIdPrefixForEveryRow(t *testing.T) { + a := analyzeXF(t, map[string]string{ + "go.mod": "module example.com/xf\n\ngo 1.25.0\n", + "a.go": xfA, + "b.go": "package xf\n\nfunc (t *T) M() int { return helper(t.n) }\n\nfunc (t *T) Reset() { t.n = 0 }\n\nfunc helper(n int) int { return n }\n", + }) + for _, n := range Project(a).Nodes { + if n.Module == "" || isL4Node(n) { + continue + } + if !strings.HasPrefix(n.Value, n.Module) { + t.Errorf("row %s %s is owned by %s, which is not its id prefix", n.Labels[0], n.Value, n.Module) + } + } +} diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index f6d87a5..716ed1f 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -200,12 +200,21 @@ func (p *projector) projectType(modRef NodeRef, module string, t v2.Type) { // Methods nest under their receiver type (containment-by-receiver). for _, m := range t.Callables { - mRef := p.projectCallable(tRef, module, m) + // A method declared in another file is owned by that file's module: its text + // (span, body) lives there, and its id carries that file's prefix. Owning it + // by the receiver's module instead leaves a lazy push blind to edits in the + // declaring file, since only the receiver's content hash decides what is + // upserted. The node id is unchanged; only the row's owner moves. + owner := module + if m.SourceFile != "" { + owner = v2.ModuleID(p.analysis.Application.ID, m.SourceFile) + } + mRef := p.projectCallable(tRef, owner, m) p.b.Edge(RelHasMethod, tRef, mRef, nil, "") // A method declared in another file is also declared by that file's module, // so "which file declares this method" is one query (spec v2-go-ids § Amendment). if m.SourceFile != "" { - declaring := NodeRef{Label: LabelModule, KeyProp: "id", Value: v2.ModuleID(p.analysis.Application.ID, m.SourceFile)} + declaring := NodeRef{Label: LabelModule, KeyProp: "id", Value: owner} p.b.Edge(RelDeclares, declaring, mRef, nil, "") } } From d8234abbd0cb1d70155ff744a1b7047bf2da3dd7 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sun, 22 Nov 2026 16:09:28 -0500 Subject: [PATCH 17/19] fix(repository): keep artifact discovery running past unreadable files; hash in constant memory Item 3. One unreadable directory or file aborted the whole analysis. WalkDir's error and readArtifact's ReadFile error were both returned, so Analyze failed with "repository layer: artifact discovery: ...", and no analysis.json was written, although the Go analysis had succeeded. A file that vanished between the walk and the read had the same effect. Now an entry that cannot be listed, stat'ed, opened or read is skipped with a warning that names it. The root stays fatal: without it there is nothing to analyze. go.mod and go.sum failures other than "does not exist" also warn, where they used to drop the dependencies or the locked versions silently. Item 5. Every non-Go file was read whole with os.ReadFile, only to hash it and sniff it for binary. A 1 GB binary in the tree peaked at 1.09 GB resident; the same tree without it peaked at 27 MB. Discovery now streams each file once through sniff, which hashes it and decides binary-ness in constant memory. Its answers equal the whole-file ones: binary means a NUL byte or invalid UTF-8 anywhere, and a rune split across two chunks is validated correctly. The 1 GB tree now peaks at 27.8 MB. Text is read a second time, and only with --artifact-text. That second read must hash to the first pass's hash, or the file is skipped with a warning, so captured source always matches the recorded hash. Security. readArtifact opens the file and checks that it is the file the walk recorded (os.SameFile, and a regular file). A path swapped for a symlink or a device after the walk is refused, not read. The walk still never follows a symlink inside the tree. Behavior change. The name rules (Dockerfile*, requirements*.txt) used to run before the binary check, so a binary with such a name was classified as text and, with --artifact-text, its raw bytes were captured. Binary now wins over the name rules, so binary bytes are never captured as text. Tests reproduce both items against the old code. They fail there (abort on an unreadable directory and on an unreadable file; 64 MiB allocated for a 64 MiB file; a Dockerfile-named binary captured as text) and pass now. A chunk-boundary test checks sniff against the whole-file answer for every chunk size. Co-Authored-By: Claude Haiku 5.5 --- internal/repository/repository.go | 116 +++++++++++---- internal/repository/robustness_test.go | 192 +++++++++++++++++++++++++ internal/repository/sniff.go | 105 ++++++++++++++ internal/repository/sniff_test.go | 42 ++++++ 4 files changed, 428 insertions(+), 27 deletions(-) create mode 100644 internal/repository/robustness_test.go create mode 100644 internal/repository/sniff.go create mode 100644 internal/repository/sniff_test.go diff --git a/internal/repository/repository.go b/internal/repository/repository.go index c8d5981..18a518f 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -12,12 +12,12 @@ import ( "encoding/hex" "errors" "fmt" + "io" "io/fs" "os" "path/filepath" "sort" "strings" - "unicode/utf8" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" @@ -67,8 +67,20 @@ func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { } out := map[string]schema.GoArtifact{} err = filepath.WalkDir(absRoot, func(p string, d fs.DirEntry, werr error) error { + rel, err := filepath.Rel(absRoot, p) + if err != nil { + return err + } + rel = filepath.ToSlash(rel) if werr != nil { - return werr + if p == absRoot { + return werr + } + // An entry that cannot be listed or stat'ed is skipped, not fatal: one + // unreadable directory must not cost the whole analysis. The warning names + // it, so the omission is visible rather than silent. + utils.Warn("repository: skipping %s: %v", rel, werr) + return nil } if d.IsDir() { if p != absRoot && (skipDirNames[d.Name()] || (cacheDir != "" && p == cacheDir)) { @@ -82,13 +94,17 @@ func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { if outDir != "" && filepath.Dir(p) == outDir && outputFileNames[d.Name()] { return nil } - rel, err := filepath.Rel(absRoot, p) + info, err := d.Info() if err != nil { - return err + utils.Warn("repository: skipping %s: %v", rel, err) + return nil } - art, err := readArtifact(p, filepath.ToSlash(rel), opts.CaptureText) + art, err := readArtifact(p, info, rel, opts.CaptureText) if err != nil { - return err + // A file that vanished, became unreadable, or changed while it was read + // mid-walk. None of these is a project-level failure. + utils.Warn("repository: skipping %s: %v", rel, err) + return nil } out[art.Path] = art return nil @@ -135,19 +151,38 @@ func resolveDir(p string) (string, error) { } } -// readArtifact hashes the whole file and classifies it. Text source is kept only -// when captureText is set; binaries are never captured. -func readArtifact(abs, rel string, captureText bool) (schema.GoArtifact, error) { - data, err := os.ReadFile(abs) +// readArtifact classifies one file the walk reported as a regular file. It reads +// the file in constant memory: one streaming pass hashes it and decides whether it +// is binary. Text source is read a second time, and only with captureText. Binary +// bytes are never captured. +// +// info is the walk's view of the entry. The opened file must be that same file, +// so a path swapped for a symlink or a device between the walk and the open is +// refused rather than read. +func readArtifact(abs string, info fs.FileInfo, rel string, captureText bool) (schema.GoArtifact, error) { + f, err := os.Open(abs) + if err != nil { + return schema.GoArtifact{}, err + } + defer f.Close() + st, err := f.Stat() if err != nil { return schema.GoArtifact{}, err } - sum := sha256.Sum256(data) + if !st.Mode().IsRegular() || !os.SameFile(info, st) { + return schema.GoArtifact{}, fmt.Errorf("replaced during analysis; not the file the walk saw") + } + + s := newSniff() + if _, err := io.Copy(s, f); err != nil { + return schema.GoArtifact{}, err + } + s.finish() art := schema.GoArtifact{ Path: rel, - Format: formatOf(rel, data), - SizeBytes: int64(len(data)), - SHA256: hex.EncodeToString(sum[:]), + Format: formatOf(rel, s.binary()), + SizeBytes: s.size, + SHA256: hex.EncodeToString(s.sum()), Extraction: "none", } switch rel { @@ -156,30 +191,50 @@ func readArtifact(abs, rel string, captureText bool) (schema.GoArtifact, error) case "go.sum": art.Roles = []string{"lockfile"} } - if captureText && art.Format != "binary" { - art.Source = string(data) - art.Extraction = "full" + if !captureText || s.binary() { + return art, nil } + + // Second read, for the text only. The bytes must hash to what the first pass + // hashed; otherwise the file changed in between, and its source would not match + // its recorded hash, so it is skipped with an error instead. + if _, err := f.Seek(0, io.SeekStart); err != nil { + return schema.GoArtifact{}, err + } + h := sha256.New() + var text bytes.Buffer + if _, err := io.Copy(io.MultiWriter(h, &text), f); err != nil { + return schema.GoArtifact{}, err + } + if !bytes.Equal(h.Sum(nil), s.sum()) { + return schema.GoArtifact{}, fmt.Errorf("changed while it was read; not captured") + } + art.Source = text.String() + art.Extraction = "full" return art, nil } -// formatOf names the file's format. go.mod and go.sum have their own names; the -// rest follow the Python analyzer's enum. Binary is a NUL byte or invalid UTF-8. -func formatOf(rel string, data []byte) string { +// formatOf names the file's format. go.mod and go.sum are named by their file name. +// A binary is never a Dockerfile or a requirements file, whatever its name: the +// name rules apply to text only, so binary bytes can never be captured as text. +// The rest follow the Python analyzer's enum. +func formatOf(rel string, binary bool) string { base := filepath.Base(rel) - switch { - case base == "go.mod": + switch base { + case "go.mod": return "gomod" - case base == "go.sum": + case "go.sum": return "gosum" + } + if binary { + return "binary" + } + switch { case base == "Dockerfile" || strings.HasPrefix(base, "Dockerfile.") || strings.HasSuffix(base, ".dockerfile"): return "dockerfile" case strings.HasPrefix(base, "requirements") && strings.HasSuffix(base, ".txt"): return "requirements" } - if bytes.IndexByte(data, 0) >= 0 || !utf8.Valid(data) { - return "binary" - } switch strings.ToLower(filepath.Ext(base)) { case ".toml": return "toml" @@ -207,7 +262,11 @@ func Facts(root string, app *schema.GoApplication, opts Options) (*schema.Reposi modPath := filepath.Join(root, "go.mod") modData, err := os.ReadFile(modPath) if err != nil { - // No root go.mod: artifacts only, no dependencies. + // No root go.mod: artifacts only, no dependencies. Any other failure (a + // permission error, say) also drops the dependencies, so it must be said. + if !errors.Is(err, fs.ErrNotExist) { + utils.Warn("repository: go.mod unreadable, dependencies skipped: %v", err) + } return facts, nil } f, err := modfile.Parse("go.mod", modData, nil) @@ -249,6 +308,9 @@ func parseGoSum(path string) map[string]map[string]bool { entries := map[string]map[string]*seen{} data, err := os.ReadFile(path) if err != nil { + if !errors.Is(err, fs.ErrNotExist) { + utils.Warn("repository: go.sum unreadable, no versions locked: %v", err) + } return map[string]map[string]bool{} } for _, line := range strings.Split(string(data), "\n") { diff --git a/internal/repository/robustness_test.go b/internal/repository/robustness_test.go new file mode 100644 index 0000000..fc6d67f --- /dev/null +++ b/internal/repository/robustness_test.go @@ -0,0 +1,192 @@ +package repository + +import ( + "os" + "path/filepath" + "runtime" + "testing" +) + +// skipIfCannotDenyRead skips where a permission-denied read cannot be produced: +// Windows has no mode bits, and root reads everything regardless of mode. +func skipIfCannotDenyRead(t *testing.T) { + t.Helper() + if runtime.GOOS == "windows" { + t.Skip("mode bits do not deny reads on Windows") + } + if os.Geteuid() == 0 { + t.Skip("root bypasses mode bits") + } +} + +// Item 3: one unreadable directory must not abort discovery. Before the fix, +// Discover returned "artifact discovery: open .../locked: permission denied" and +// the whole analysis failed, though only that directory's contents were lost. +func TestDiscover_UnreadableDirectoryIsSkippedNotFatal(t *testing.T) { + skipIfCannotDenyRead(t) + root := t.TempDir() + writeTree(t, root, map[string]string{ + "go.mod": "module example.com/x\n", + "README.md": "# readme\n", + "locked/a.txt": "secret\n", + }) + locked := filepath.Join(root, "locked") + if err := os.Chmod(locked, 0o000); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(locked, 0o755) }) + + got, err := Discover(root, Options{}) + if err != nil { + t.Fatalf("one unreadable directory aborted discovery: %v", err) + } + if _, ok := got["README.md"]; !ok { + t.Errorf("readable sibling README.md was lost: %v", keys(got)) + } + if _, ok := got["locked/a.txt"]; ok { + t.Errorf("file inside an unreadable directory was captured") + } +} + +// Item 3, file level: an unreadable file is skipped; the rest is still discovered. +func TestDiscover_UnreadableFileIsSkippedNotFatal(t *testing.T) { + skipIfCannotDenyRead(t) + root := t.TempDir() + writeTree(t, root, map[string]string{ + "go.mod": "module example.com/x\n", + "README.md": "# readme\n", + "noread.md": "hidden\n", + }) + noread := filepath.Join(root, "noread.md") + if err := os.Chmod(noread, 0o000); err != nil { + t.Fatal(err) + } + t.Cleanup(func() { _ = os.Chmod(noread, 0o644) }) + + got, err := Discover(root, Options{}) + if err != nil { + t.Fatalf("one unreadable file aborted discovery: %v", err) + } + if _, ok := got["README.md"]; !ok { + t.Errorf("readable sibling README.md was lost: %v", keys(got)) + } +} + +// The root itself stays fatal: without it there is nothing to analyze, and an +// empty artifact list would look like a clean run. +func TestDiscover_MissingRootIsFatal(t *testing.T) { + if _, err := Discover(filepath.Join(t.TempDir(), "absent"), Options{}); err == nil { + t.Fatal("a missing project root must be an error, not an empty artifact list") + } +} + +// Item 5: hashing must not load the file. A 64 MiB sparse file is hashed while the +// heap allocates far less than its size; os.ReadFile would allocate all 64 MiB. +func TestDiscover_LargeBinaryIsNotLoadedWhole(t *testing.T) { + const size = 64 << 20 + root := t.TempDir() + writeTree(t, root, map[string]string{"go.mod": "module example.com/x\n"}) + f, err := os.Create(filepath.Join(root, "model.bin")) + if err != nil { + t.Fatal(err) + } + if err := f.Truncate(size); err != nil { + t.Fatal(err) + } + if err := f.Close(); err != nil { + t.Fatal(err) + } + + var before, after runtime.MemStats + runtime.GC() + runtime.ReadMemStats(&before) + got, err := Discover(root, Options{}) + if err != nil { + t.Fatal(err) + } + runtime.ReadMemStats(&after) + if a := got["model.bin"]; a.SizeBytes != size { + t.Fatalf("size = %d, want %d", a.SizeBytes, size) + } + if allocated := after.TotalAlloc - before.TotalAlloc; allocated > 8<<20 { + t.Errorf("discovery allocated %d MiB for a %d MiB file: the file is read whole", + allocated>>20, size>>20) + } +} + +// A binary named like a Dockerfile must still be binary. Before the fix the name +// check ran first, so the file was classified "dockerfile" and, with +// --artifact-text, its raw bytes were captured as text. +func TestDiscover_BinaryNamedLikeDockerfileStaysBinary(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{"go.mod": "module example.com/x\n"}) + if err := os.WriteFile(filepath.Join(root, "Dockerfile.bin"), []byte("\x7fELF\x00\x01\x02"), 0o644); err != nil { + t.Fatal(err) + } + got, err := Discover(root, Options{CaptureText: true}) + if err != nil { + t.Fatal(err) + } + a := got["Dockerfile.bin"] + if a.Format != "binary" { + t.Errorf("format = %q, want binary", a.Format) + } + if a.Source != "" { + t.Errorf("binary file's bytes were captured as text: %q", a.Source) + } +} + +// Security: a path the walk saw as a regular file must still be that file when it +// is opened. A file swapped for a symlink (to, say, a secret outside the project) +// after the walk must be refused, not followed. +func TestReadArtifact_RefusesPathSwappedForSymlinkAfterWalk(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("symlink creation needs privileges on Windows") + } + dir := t.TempDir() + outside := filepath.Join(t.TempDir(), "secret.txt") + if err := os.WriteFile(outside, []byte("TOP SECRET\n"), 0o644); err != nil { + t.Fatal(err) + } + target := filepath.Join(dir, "notes.txt") + if err := os.WriteFile(target, []byte("ordinary\n"), 0o644); err != nil { + t.Fatal(err) + } + walked, err := os.Lstat(target) // what the walk recorded + if err != nil { + t.Fatal(err) + } + // The swap happens between the walk and the open. + if err := os.Remove(target); err != nil { + t.Fatal(err) + } + if err := os.Symlink(outside, target); err != nil { + t.Fatal(err) + } + art, err := readArtifact(target, walked, "notes.txt", true) + if err == nil { + t.Fatalf("symlink swapped in after the walk was read: %+v", art) + } + if art.Source != "" { + t.Errorf("secret captured through the swapped symlink: %q", art.Source) + } +} + +// A path that now names a different regular file than the walk recorded is refused. +func TestReadArtifact_RefusesDifferentFileAtSamePath(t *testing.T) { + dir := t.TempDir() + a := filepath.Join(dir, "a.txt") + b := filepath.Join(dir, "b.txt") + for _, p := range []string{a, b} { + if err := os.WriteFile(p, []byte("x\n"), 0o644); err != nil { + t.Fatal(err) + } + } + infoB, err := os.Lstat(b) + if err != nil { + t.Fatal(err) + } + if _, err := readArtifact(a, infoB, "a.txt", false); err == nil { + t.Fatal("a file other than the walked one was read") + } +} diff --git a/internal/repository/sniff.go b/internal/repository/sniff.go new file mode 100644 index 0000000..d8d8464 --- /dev/null +++ b/internal/repository/sniff.go @@ -0,0 +1,105 @@ +package repository + +import ( + "bytes" + "crypto/sha256" + "hash" + "unicode/utf8" +) + +// sniff hashes a file and decides whether it is binary in one streaming pass. It +// is an io.Writer, so io.Copy feeds it in fixed-size chunks and it never holds +// the file. Its answers equal the whole-file ones: binary means a NUL byte +// anywhere, or invalid UTF-8 anywhere, the rule formatOf has always applied. +// +// Validation is chunk-safe. A rune split across two Writes is completed from the +// carry, and at most utf8.UTFMax-1 bytes are ever carried, so the sniffer makes no +// allocation per chunk. +type sniff struct { + hash hash.Hash + size int64 + hasNUL bool + badUTF8 bool + // carry holds the incomplete UTF-8 sequence at the end of the last chunk. + carry []byte +} + +func newSniff() *sniff { + return &sniff{hash: sha256.New()} +} + +// Write consumes one chunk. It never fails; io.Writer requires the error result. +func (s *sniff) Write(p []byte) (int, error) { + n := len(p) + s.size += int64(n) + s.hash.Write(p) + if !s.hasNUL && bytes.IndexByte(p, 0) >= 0 { + s.hasNUL = true + } + if s.badUTF8 { + return n, nil + } + + // Finish a rune that started in the previous chunk. The completed rune is + // decoded from a fixed-size array, not from p, so a split rune costs no + // allocation. + if len(s.carry) > 0 { + var tmp [utf8.UTFMax]byte + m := copy(tmp[:], s.carry) + k := 0 + for m < utf8.UTFMax && k < len(p) && !utf8.FullRune(tmp[:m]) { + tmp[m] = p[k] + m++ + k++ + } + if !utf8.FullRune(tmp[:m]) { + // Still incomplete, and the chunk is used up: keep carrying. + s.carry = append(s.carry[:0], tmp[:m]...) + return n, nil + } + if r, sz := utf8.DecodeRune(tmp[:m]); r == utf8.RuneError && sz == 1 { + s.badUTF8 = true + return n, nil + } + s.carry = s.carry[:0] + p = p[k:] + } + + // p now starts on a rune boundary. Validate whole runes; an incomplete tail + // becomes the new carry. + i := 0 + for i < len(p) { + if p[i] < utf8.RuneSelf { + i++ + continue + } + if !utf8.FullRune(p[i:]) { + break + } + r, sz := utf8.DecodeRune(p[i:]) + if r == utf8.RuneError && sz == 1 { + s.badUTF8 = true + return n, nil + } + i += sz + } + s.carry = append(s.carry[:0], p[i:]...) + return n, nil +} + +// finish closes the stream. A sequence still incomplete at EOF is invalid UTF-8. +func (s *sniff) finish() { + if len(s.carry) > 0 { + s.badUTF8 = true + } +} + +// binary reports the classification. Valid after finish. +func (s *sniff) binary() bool { + return s.hasNUL || s.badUTF8 +} + +// sum is the SHA-256 of everything written. +func (s *sniff) sum() []byte { + return s.hash.Sum(nil) +} diff --git a/internal/repository/sniff_test.go b/internal/repository/sniff_test.go new file mode 100644 index 0000000..b2fc84c --- /dev/null +++ b/internal/repository/sniff_test.go @@ -0,0 +1,42 @@ +package repository + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "testing" + "unicode/utf8" +) + +// Item 5: the streamed hash and binary sniff must equal the whole-file answer for +// every chunking, including a multi-byte rune split across a chunk boundary. +func TestSniff_MatchesWholeFileForEveryChunking(t *testing.T) { + inputs := [][]byte{ + []byte("plain ascii\n"), + []byte("héllo wörld ✓ 世界 🙂\n"), // multi-byte runes + []byte("nul\x00inside\n"), + []byte("bad utf8 \xff\xfe here\n"), + []byte("truncated rune at end \xe4\xb8"), // incomplete sequence at EOF + {}, + } + for _, in := range inputs { + wantBinary := bytes.IndexByte(in, 0) >= 0 || !utf8.Valid(in) + wantSum := sha256.Sum256(in) + for chunk := 1; chunk <= len(in)+1; chunk++ { + s := newSniff() + for off := 0; off < len(in); off += chunk { + end := min(off+chunk, len(in)) + if _, err := s.Write(in[off:end]); err != nil { + t.Fatal(err) + } + } + s.finish() + if s.binary() != wantBinary { + t.Errorf("chunk=%d input=%q: binary=%v, want %v", chunk, in, s.binary(), wantBinary) + } + if got := hex.EncodeToString(s.sum()); got != hex.EncodeToString(wantSum[:]) { + t.Errorf("chunk=%d input=%q: sha256 mismatch", chunk, in) + } + } + } +} From c001e1dff60438cb1e8276519ffd85cb30b3c70d Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Sun, 29 Nov 2026 14:39:34 -0500 Subject: [PATCH 18/19] fix(neo4j): stream each node row with the module that owns it (#46) The streaming push staged every row of a module with the module that was projected. After the cross-file id change (dd9349b, 355b567), a cross-file method has its declaring file's id prefix and owner, but it was still staged with its receiver's module. An eager push then wrote the method and deleted it again in the declaring module's purge (TestBolt_StreamPushOrder/eager), and a lazy push checked the receiver's hash instead of the declaring file's. Pass 1 now holds the rows of a module that has no stage yet and adds them to that module's stage. Rows of a module that already has a stage go to the new stager step owned, which uses that module's change decision. The bolt writer records the decision per module; the snapshot writer writes the rows. This replaces 19c862a (purge every changed module before any upsert), which the rebase onto the streaming push dropped: the streaming push stages one module at a time, so it cannot purge every changed module first. Tests: TestStreamPush_EagerKeepsCrossFileMethod and TestStreamPush_LazyFollowsDeclaringFile, for both file orders. Co-Authored-By: Claude Opus 5.5 --- .../specs/2026-11-24-neo4j-streaming-push.md | 11 +++ internal/neo4j/bolt.go | 20 ++++ internal/neo4j/crossfile_stream_test.go | 95 +++++++++++++++++++ internal/neo4j/cypher.go | 1 + internal/neo4j/stream.go | 40 +++++++- internal/neo4j/stream_test.go | 6 ++ 6 files changed, 168 insertions(+), 5 deletions(-) create mode 100644 internal/neo4j/crossfile_stream_test.go diff --git a/docs/design/specs/2026-11-24-neo4j-streaming-push.md b/docs/design/specs/2026-11-24-neo4j-streaming-push.md index 3b0b22e..dfa2ac9 100644 --- a/docs/design/specs/2026-11-24-neo4j-streaming-push.md +++ b/docs/design/specs/2026-11-24-neo4j-streaming-push.md @@ -117,6 +117,17 @@ At the end of each phase it flushes every buffer. | 4 | Pass 2, for each module: push every edge. Then push `GO_CALLS`, the stand-in `GO_HAS_BODY_NODE` edges, `GO_PARAM_IN` and `GO_PARAM_OUT`. | Every node is in the DB before the first edge, so no edge `MATCH` fails. | | 5 | `pruneVanishedModules` (full + eager only), with the module ids from the symbol table keys. | Same as today. | +Step 2 stages each node row with the module that owns it (`NodeRow.Module`), not with the module that is projected. +These are different for a cross-file method: it nests under its receiver's type, but its declaring file owns it and its id has that file's prefix. +If the writer staged the method with the receiver's module, two things would go wrong: + +- An `--eager` push would write the method, and then the purge of the declaring module would delete it (#46). +- A lazy push would check the hash of the wrong module, so an edit to the declaring file would not upsert the method. + +So pass 1 holds the rows of a module that has no stage yet, and adds them to that module's stage. +It sends the rows of a module that already has a stage to `owned`. +`owned` uses that module's change decision, and the purge of that module is already done. + A lazy push still upserts every edge, as it does today. The push message reports the number of node rows and edge rows sent. diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index 36f5dc7..0fd144e 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -136,6 +136,9 @@ type boltWriter struct { level int // max_level of the begin row forced bool // forceFull || cfg.Eager: every module counts as changed scoped bool + // changed records, per staged module, whether its L1–L3 rows are upserted, + // so owned applies the same decision to the rows that arrive later. + changed map[string]bool nodeBuf map[string][]NodeRow edgeBuf map[string][]EdgeRow // hashes are the content_hash values of the modules whose nodes were @@ -203,6 +206,10 @@ func (w *boltWriter) module(id string, nodes []NodeRow) error { return err } } + if w.changed == nil { + w.changed = map[string]bool{} + } + w.changed[id] = changed if changed { if w.cfg.Eager && w.scoped { // Flushed first so the DB order matches the statement order; @@ -221,6 +228,19 @@ func (w *boltWriter) module(id string, nodes []NodeRow) error { return w.bufferNodes(l4) } +// owned buffers more rows of a module that module has already staged: its L1–L3 +// rows when that module changed, its L4 vertex rows always. The module's purge +// ran in its stage, so it cannot delete them. +func (w *boltWriter) owned(id string, nodes []NodeRow) error { + var rows []NodeRow + for _, n := range nodes { + if isL4Node(n) || w.changed[id] { + rows = append(rows, n) + } + } + return w.bufferNodes(rows) +} + // deferHashes returns core with each :GoModule row's content_hash replaced by // an explicit null (SET += removes a stored hash) and records the hash for // stampHashes. The rows passed in are not modified: the caller may reuse them. diff --git a/internal/neo4j/crossfile_stream_test.go b/internal/neo4j/crossfile_stream_test.go new file mode 100644 index 0000000..7329116 --- /dev/null +++ b/internal/neo4j/crossfile_stream_test.go @@ -0,0 +1,95 @@ +package neo4j + +import ( + "testing" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// The streaming push stages a row with the module that owns it. A cross-file +// method is projected while its receiver's module is projected, but its declaring +// file owns it. These tests cover both orders: the declaring file staged after +// the receiver's file (the rows wait for its stage) and before it (the rows go +// to owned). + +const xfMod = "module example.com/xf\n\ngo 1.25.0\n" + +// xfLayouts are the two file orders. The method M on T is declared in b.go in both. +var xfLayouts = []struct { + name, typeFile string +}{ + {"declaring file after receiver", "a.go"}, + {"declaring file before receiver", "z.go"}, +} + +func xfAnalysis(t *testing.T, typeFile, method string) *v2.Analysis { + t.Helper() + return analyzeXF(t, map[string]string{ + "go.mod": xfMod, + typeFile: "package xf\n\ntype T struct{ n int }\n", + "b.go": "package xf\n\n" + method + "\n\nfunc helper(n int) int { return n }\n", + }) +} + +// TestStreamPush_EagerKeepsCrossFileMethod (#46): on an eager push, no module +// purge runs after the cross-file method's rows are written. +func TestStreamPush_EagerKeepsCrossFileMethod(t *testing.T) { + for _, l := range xfLayouts { + t.Run(l.name, func(t *testing.T) { + a := xfAnalysis(t, l.typeFile, "func (t *T) M() int { return helper(t.n) }") + streamPushOrder(t, a, BoltConfig{Eager: true, FullRun: true}) + }) + } +} + +// TestStreamPush_LazyFollowsDeclaringFile: on a lazy push, the cross-file +// method's rows are upserted when its declaring file changed, and skipped when +// only its receiver's file changed. +func TestStreamPush_LazyFollowsDeclaringFile(t *testing.T) { + const methodID = "can://xf/xf/go/b.go/T/M" + for _, l := range xfLayouts { + t.Run(l.name, func(t *testing.T) { + before := xfAnalysis(t, l.typeFile, "func (t *T) M() int { return helper(t.n) }") + byModule, _, _ := partitionNodes(Project(before).Nodes) + stored := map[string]string{} + for m, ns := range byModule { + stored[m] = moduleHash(ns) + } + push := func(t *testing.T, a *v2.Analysis) map[string]bool { + t.Helper() + hashes := map[string]string{} + for m, h := range stored { + hashes[m] = h + } + db := &fakeDB{hashes: hashes} + pushStream(t, db, a, BoltConfig{}) + nodes, _ := db.pushed() + return nodes + } + + edited := xfAnalysis(t, l.typeFile, "func (t *T) M() int { return helper(t.n) + helper(2) }") + nodes := push(t, edited) + for _, id := range nodesUnder(Project(edited), methodID) { + if !nodes[id] { + t.Errorf("b.go changed, but %s was not upserted", id) + } + } + + receiverEdited := analyzeXF(t, map[string]string{ + "go.mod": xfMod, + l.typeFile: "package xf\n\n// T counts.\ntype T struct{ n int }\n", + "b.go": "package xf\n\nfunc (t *T) M() int { return helper(t.n) }\n\nfunc helper(n int) int { return n }\n", + }) + if nodes := push(t, receiverEdited); nodes[methodID] { + t.Errorf("only %s changed, but %s was upserted", l.typeFile, methodID) + } + }) + } +} + +func pushStream(t *testing.T, db *fakeDB, a *v2.Analysis, cfg BoltConfig) { + t.Helper() + if _, _, err := streamGraph(treeSource(a), newBoltWriter(t.Context(), db, a.Application.ID, cfg)); err != nil { + t.Fatal(err) + } +} diff --git a/internal/neo4j/cypher.go b/internal/neo4j/cypher.go index 48af592..0d1b02d 100644 --- a/internal/neo4j/cypher.go +++ b/internal/neo4j/cypher.go @@ -261,6 +261,7 @@ func (c *cypherWriter) begin(NodeRow) error { func (c *cypherWriter) shared(nodes []NodeRow) error { c.bufferNodes(nodes); return nil } func (c *cypherWriter) module(_ string, nodes []NodeRow) error { c.bufferNodes(nodes); return nil } +func (c *cypherWriter) owned(_ string, nodes []NodeRow) error { c.bufferNodes(nodes); return nil } // late buffers the last node rows and flushes every node group in key order. func (c *cypherWriter) late(nodes []NodeRow) error { diff --git a/internal/neo4j/stream.go b/internal/neo4j/stream.go index 18585c9..27ff599 100644 --- a/internal/neo4j/stream.go +++ b/internal/neo4j/stream.go @@ -18,6 +18,7 @@ type stager interface { begin(app NodeRow) error // step 0: identity, stale check, DDL, eager purge shared(nodes []NodeRow) error // step 1: repository nodes module(id string, nodes []NodeRow) error // step 2: every node row of one module + owned(id string, nodes []NodeRow) error // step 2: more rows of a module already staged late(nodes []NodeRow) error // step 3: ghosts, stand-ins, application row edges(edges []EdgeRow) error // step 4: called many times end(moduleIDs []string) error // step 5: flush, prune @@ -51,25 +52,54 @@ func streamGraph(src Source, st stager) (nodes, edges int, err error) { return } nodes += len(shared) - // Step 2, pass 1: module nodes. Ghost nodes (Module == "") move to the late builder. + // Step 2, pass 1: module nodes. Ghost nodes (Module == "") move to the late + // builder. A row goes to the stage of the module that owns it, which is not + // always the module being projected: a cross-file method nests under its + // receiver's type but is owned by its declaring file, whose id prefix it + // carries. Staged with the receiver's module, an eager push would write it and + // then delete it in the declaring module's purge (#46). Rows of a module not + // staged yet wait for its stage; rows of a module already staged go to owned. declared := map[string]bool{} late := mk(nodeOnly(), declared) + pending := map[string][]NodeRow{} + staged := map[string]bool{} for _, m := range src.Modules() { moduleDeclared(m, declared) p := mk(nodeOnly(), declared) p.projectModule(m) - var own []NodeRow + own := pending[m.ID] + delete(pending, m.ID) + other := map[string][]NodeRow{} for _, n := range p.b.Finish().Nodes { - if n.Module == "" { + switch { + case n.Module == "": late.b.Node(n.Labels, n.KeyProp, n.Value, n.Props, "") - continue + case n.Module == m.ID: + own = append(own, n) + case staged[n.Module]: + other[n.Module] = append(other[n.Module], n) + default: + pending[n.Module] = append(pending[n.Module], n) } - own = append(own, n) } if err = st.module(m.ID, own); err != nil { return } + staged[m.ID] = true nodes += len(own) + for _, id := range slices.Sorted(maps.Keys(other)) { + if err = st.owned(id, other[id]); err != nil { + return + } + nodes += len(other[id]) + } + } + // An owner that is not a module of the stream has no stage of its own. + for _, id := range slices.Sorted(maps.Keys(pending)) { + if err = st.module(id, pending[id]); err != nil { + return + } + nodes += len(pending[id]) } // Step 3: against the complete declared set, the body-callee ghosts, the // call-graph ghosts, the stand-in vertices, and the application row, which diff --git a/internal/neo4j/stream_test.go b/internal/neo4j/stream_test.go index 20b87e3..01b0ad4 100644 --- a/internal/neo4j/stream_test.go +++ b/internal/neo4j/stream_test.go @@ -39,6 +39,12 @@ func (c *collectStager) module(id string, n []NodeRow) error { return nil } +func (c *collectStager) owned(id string, n []NodeRow) error { + c.stages = append(c.stages, "owned") + c.nodes = append(c.nodes, n...) + return nil +} + func (c *collectStager) late(n []NodeRow) error { c.stages = append(c.stages, "late") c.nodes = append(c.nodes, n...) From c679b765902349cf9115ac5a42d51763be1d0d55 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Sun, 29 Nov 2026 15:05:21 -0500 Subject: [PATCH 19/19] fix(symbol-table): give a repeated init or _ its suffix before its closures and L3 unit (#75, #76) 205b7cd gave the second and later func init() in a file a ":N" suffix, but only after buildCallable had named its closures and only in the symbol table: - #75: the closures of init:2 kept ".init.closure_N", the signature of the first init's closures. Their L3 units, call-graph edges and signature index entries merged: init:2/closure_1 got the first closure's cfg and a body node outside its span, and init's call to its own closure resolved to init:2/closure_1. - #76: L3Units keyed the second init as ".init", found the first init's callable, failed the start-line check and skipped it. init:2 had no L3 or L4 output, and only an unmapped_ssa degraded entry hinted at it. func _() has the same problem: Go permits any number of them per file, and generated code (stringer) uses them. fileDeclSignature now computes the suffix from the FuncDecl's position in its file. buildCallable names the callable and its closures with it, and L3Units keys the unit with it, so all three agree. It replaces uniqueFuncSignature. Test: TestRepeatedFunc_ClosuresAndL3AreTheirOwn (two init, two _, each with a closure, at -a 4). It fails on the old code and passes on the fix. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 10 +- internal/core/init_l3_test.go | 124 ++++++++++++++++++ internal/syntactic_analysis/l3units.go | 2 +- internal/syntactic_analysis/symbol_table.go | 54 +++++--- .../syntactic_analysis/v2emit/sigindex.go | 8 +- 5 files changed, 168 insertions(+), 30 deletions(-) create mode 100644 internal/core/init_l3_test.go diff --git a/CLAUDE.md b/CLAUDE.md index 34f24ba..5c9573c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -32,10 +32,12 @@ committed spec is the full transcript: `docs/design/specs/v2-l1-emission.md`. JSON field on both (types gained it, additive, for the Neo4j `:GoType.signature`) [user, 2026-11-20]. The id carries only the bare member name, so this field is where the package path lives. One canonicalizer, unchanged from v1. - **Exception: duplicate `func init()`** (fix/init-collision, 2026-11-22). Go allows many - inits per file, all with signatureOf() `.init`. The second and later ones in a - file carry `:N` (N = 2, 3, ...), e.g. `.init:2`, in `signature`, in the callable's - id member (`init:2`), and as the call-graph source. The first keeps the bare name, so the + **Exception: duplicate `func init()` and `func _()`** (fix/init-collision, 2026-11-22; `_` + and closures #75/#76). Go allows many of each per file, all with signatureOf() + `.init` or `._`. The second and later ones in a file carry `:N` (N = 2, + 3, ...), e.g. `.init:2`, in `signature`, in the callable's id member (`init:2`), + as the call-graph source, in their closures' signatures (`.init:2.closure_1`) and + in their L3 unit key. One function computes it (`fileDeclSignature`). The first keeps the bare name, so the ids of files with one init are unchanged. The suffix is the only way to keep their ids and edges distinct; a colon is not a Go identifier character, so it cannot collide with a real function. diff --git a/internal/core/init_l3_test.go b/internal/core/init_l3_test.go new file mode 100644 index 0000000..139ae46 --- /dev/null +++ b/internal/core/init_l3_test.go @@ -0,0 +1,124 @@ +package core_test + +import ( + "encoding/json" + "os" + "path/filepath" + "strings" + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/core" + "github.com/codellm-devkit/codeanalyzer-go/internal/options" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" + "github.com/codellm-devkit/codeanalyzer-go/internal/syntactic_analysis/v2emit" +) + +// repeatedFuncProject declares two func init() and two func _() in one file, +// each with a closure that calls a helper of its own. Go permits any number of +// both per file; the symbol table gives the second one a ":2" suffix. +func repeatedFuncProject(t *testing.T) string { + t.Helper() + dir := t.TempDir() + files := map[string]string{ + "go.mod": "module example.com/rep\n\ngo 1.25.0\n", + "main.go": "package rep\n\n" + + "func a() {}\nfunc b() {}\nfunc c() {}\nfunc d() {}\n\n" + + "func init() {\n\tf := func() { a() }\n\tf()\n}\n\n" + + "func init() {\n\tg := func() { b() }\n\tg()\n}\n\n" + + "func _() {\n\tf := func() { c() }\n\tf()\n}\n\n" + + "func _() {\n\tg := func() { d() }\n\tg()\n}\n", + } + for rel, content := range files { + if err := os.WriteFile(filepath.Join(dir, rel), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + return dir +} + +// TestRepeatedFunc_ClosuresAndL3AreTheirOwn (#75, #76): the second init and the +// second _ get their own L3 body and cfg, and their closures are their own, not +// a copy of the first function's closure. No row is degraded. +func TestRepeatedFunc_ClosuresAndL3AreTheirOwn(t *testing.T) { + dir := repeatedFuncProject(t) + opts := options.AnalysisOptions{ + InputPath: dir, AppName: "rep", Level: options.LevelSDG, + SkipTests: true, CacheDir: t.TempDir(), OutputDir: t.TempDir(), + } + an := core.New(opts) + app, err := an.Analyze() + if err != nil { + t.Fatal(err) + } + identity, err := v2.ResolveIdentity("rep", nil) + if err != nil { + t.Fatal(err) + } + out, err := json.Marshal(v2emit.Emit(app, identity, dir, int(opts.Level), "test", core.KLimit(opts), an.L3(), an.L4())) + if err != nil { + t.Fatal(err) + } + var doc map[string]any + if err := json.Unmarshal(out, &doc); err != nil { + t.Fatal(err) + } + if deg, ok := doc["degraded"]; ok { + t.Errorf("degraded: %v", deg) + } + application := asMap(doc["application"]) + fns := asMap(asMap(asMap(application["symbol_table"])["main.go"])["functions"]) + + const base = "can://rep/rep/go/main.go/" + byID := map[string]map[string]any{} + for _, f := range fns { + byID[asMap(f)["id"].(string)] = asMap(f) + } + for _, name := range []string{"init", "init:2", "_", "_:2"} { + fn, ok := byID[base+name] + if !ok { + t.Errorf("no function %s", name) + continue + } + body := asMap(fn["body"]) + if _, ok := body["@entry"]; !ok { + t.Errorf("%s: no @entry body node (no L3)", name) + } + if cfg, _ := fn["cfg"].([]any); len(cfg) == 0 { + t.Errorf("%s: empty cfg", name) + } + cl := asMap(asMap(fn["callables"])["closure_1"]) + start, end := int(fn["start_line"].(float64)), int(fn["end_line"].(float64)) + for key, n := range asMap(cl["body"]) { + if l, ok := asMap(n)["start_line"].(float64); ok && (int(l) < start || int(l) > end) { + t.Errorf("%s/closure_1: body node %s at line %d is outside %s (lines %d-%d)", name, key, int(l), name, start, end) + } + } + } + + // The init -> closure edges are VTA edges (f() is a call through a function + // value). VTA gives no such edge for a func _(), on main as well, so the _ + // functions are checked through their closures' edges only. + want := map[string]bool{ + base + "init/closure_1 -> " + base + "a": false, + base + "init:2/closure_1 -> " + base + "b": false, + base + "_/closure_1 -> " + base + "c": false, + base + "_:2/closure_1 -> " + base + "d": false, + base + "init -> " + base + "init/closure_1": false, + base + "init:2 -> " + base + "init:2/closure_1": false, + } + cg, _ := application["call_graph"].([]any) + for _, e := range cg { + edge := asMap(e) + key := edge["src"].(string) + " -> " + edge["dst"].(string) + if _, ok := want[key]; ok { + want[key] = true + } else if strings.Contains(key, "closure_1") { + t.Errorf("unexpected closure edge %s", key) + } + } + for edge, found := range want { + if !found { + t.Errorf("missing call-graph edge %s", edge) + } + } +} diff --git a/internal/syntactic_analysis/l3units.go b/internal/syntactic_analysis/l3units.go index 07772d3..c4ada70 100644 --- a/internal/syntactic_analysis/l3units.go +++ b/internal/syntactic_analysis/l3units.go @@ -69,7 +69,7 @@ func (b *SymbolTableBuilder) L3Units(symbolTable map[string]schema.GoFile) []dat } key := dataflow.L3Key{ Path: utils.RelativePath(b.projectDir, tf.Name()), - Signature: b.declSignature(pkg, fd), + Signature: b.fileDeclSignature(pkg, file, fd), } c, ok := byKey[key] if !ok || seen[key] || c.StartLine != b.position(fd.Pos()).Line { diff --git a/internal/syntactic_analysis/symbol_table.go b/internal/syntactic_analysis/symbol_table.go index ed10e09..2cbf58f 100644 --- a/internal/syntactic_analysis/symbol_table.go +++ b/internal/syntactic_analysis/symbol_table.go @@ -270,7 +270,6 @@ func (b *SymbolTableBuilder) buildGoFile( methods = append(methods, pendingMethod{typeName, callable}) } } else { - callable.Signature = uniqueFuncSignature(gf.Functions, callable.Signature) gf.Functions[callable.Signature] = *callable } } @@ -287,25 +286,6 @@ func (b *SymbolTableBuilder) buildGoFile( return gf } -// uniqueFuncSignature returns sig for the first package-level function of that -// signature in a file, and sig:N (N = 2, 3, ...) for each later one. Go permits -// any number of func init() per file, and every one of them has the signature -// ".init". Without the suffix they collapse into one map entry, and -// their call-graph edges (keyed on Source = Signature) merge too. The suffix is -// safe: a colon cannot appear in a Go identifier, and no call site can name an -// init, so no edge ever needs to resolve to a suffixed signature. -func uniqueFuncSignature(fns map[string]schema.GoCallable, sig string) string { - if _, taken := fns[sig]; !taken { - return sig - } - for n := 2; ; n++ { - candidate := fmt.Sprintf("%s:%d", sig, n) - if _, taken := fns[candidate]; !taken { - return candidate - } - } -} - // ─── Imports ────────────────────────────────────────────────────────────────── func (b *SymbolTableBuilder) buildImports(astFile *ast.File) []schema.GoImport { @@ -595,7 +575,7 @@ func (b *SymbolTableBuilder) buildCallable( pos := b.position(decl.Pos()) end := b.position(decl.End()) - sig := b.declSignature(pkg, decl) + sig := b.fileDeclSignature(pkg, astFile, decl) var recvType, recvName string if decl.Recv != nil && len(decl.Recv.List) > 0 { @@ -643,6 +623,38 @@ func (b *SymbolTableBuilder) buildCallable( return callable } +// fileDeclSignature is decl's signature in the symbol table: declSignature, plus +// ":N" for the Nth package-level function of that signature in file (N = 2, 3, +// ...). Go permits any number of func init() and func _() per file, and each has +// the signature ".init" or "._". Without the suffix they would +// collapse into one map entry and their call-graph edges (keyed on Source = +// Signature) would merge. The suffix is safe: a colon cannot appear in a Go +// identifier, and no call site can name an init or a _, so no edge ever needs to +// resolve to a suffixed signature. +// +// It is the one place the suffix is computed. The callable, its closures (named +// under it) and its L3 unit (L3Units) all take it from here, so they agree. +func (b *SymbolTableBuilder) fileDeclSignature(pkg *packages.Package, file *ast.File, decl *ast.FuncDecl) string { + sig := b.declSignature(pkg, decl) + // Any other repeated package-level name is a compile error. + if decl.Recv != nil || (decl.Name.Name != "init" && decl.Name.Name != "_") { + return sig + } + n := 1 + for _, d := range file.Decls { + if d == decl { + break + } + if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv == nil && fd.Name.Name == decl.Name.Name { + n++ + } + } + if n == 1 { + return sig + } + return fmt.Sprintf("%s:%d", sig, n) +} + // declSignature is a FuncDecl's callable signature: SignatureOf its object, // or, without type info, [.].. func (b *SymbolTableBuilder) declSignature(pkg *packages.Package, decl *ast.FuncDecl) string { diff --git a/internal/syntactic_analysis/v2emit/sigindex.go b/internal/syntactic_analysis/v2emit/sigindex.go index da37467..e808349 100644 --- a/internal/syntactic_analysis/v2emit/sigindex.go +++ b/internal/syntactic_analysis/v2emit/sigindex.go @@ -17,10 +17,10 @@ import ( // real node id. // // Signatures are ALMOST globally unique (a method signature embeds its receiver -// type), with one exception: package-level `func init()`. Go permits many init -// functions per file, and they all share the signature ".init". The -// symbol table gives the second and later ones a ":N" suffix (see -// uniqueFuncSignature), so each init has its own signature and therefore its +// type), with one exception: package-level `func init()` and `func _()`. Go +// permits many of them per file, and they share the signature ".init" +// or "._". The symbol table gives the second and later ones a ":N" +// suffix (see fileDeclSignature), so each one has its own signature and therefore its // own can:// id, call-graph endpoint and map key. A signature is then unique // per declaring file, and the flat map below is unambiguous except across files // that each declare an init.