diff --git a/CLAUDE.md b/CLAUDE.md index 4531c94..13b02d5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -169,8 +169,8 @@ Made with the user in the 2026-11-19 design loop, anchored on `codeanalyzer-pyth - **Artifact id:** `can:///artifact/`, app-scoped (Python parity) [user]. The Go projector's `:Artifact` flips to `CanNode=true`. - **Package id:** version-less `pkg:golang/` [user]; version lives on the dependency edge. - **Source text:** `--artifact-text`, on by default; `--no-artifact-text` drops it (Python and TypeScript parity) [user]. `config_keys` deferred [user]. -- **Dependencies:** every `go.mod` require; `direct=false` on `// indirect`; `kind:"runtime"`; `go.sum` supplies `locked_version` only, `go.sum`-only entries excluded [user]. `locked_in` names the `go.sum` artifact that locked it; the projector reads it, and `v2.PackageID` is the one package-id builder. -- **`provides_imports`:** longest-prefix match against `go.mod` module paths [user]. +- **Dependencies:** every `go.mod` require; `direct=false` on `// indirect`; `kind:"runtime"`; `go.sum` supplies `locked_version` only, `go.sum`-only entries excluded [user]. `locked_in` names the `go.sum` artifact that locked it; the projector reads it, and `v2.PackageID` is the one package-id builder. A `replace` keeps the dependency's `name` and `spec`, records `replaced_by` (`@` or a local directory, which also adds `"replace"` to `prov`), and takes `locked_version` from the replacement, by Go's replace rule. +- **`provides_imports`:** longest-prefix match against `go.mod` module paths [user]. A `-t` run reads every project package's imports with a light package load, so it matches a full run. - **Level:** L1, every level, not gated [user]. ## Neo4j-projection decisions diff --git a/cmd/codeanalyzer/main_test.go b/cmd/codeanalyzer/main_test.go index b126669..d233e3b 100644 --- a/cmd/codeanalyzer/main_test.go +++ b/cmd/codeanalyzer/main_test.go @@ -10,6 +10,7 @@ import ( "os" "path/filepath" "runtime" + "slices" "strings" "testing" ) @@ -911,3 +912,59 @@ func TestRootCmd_EmitNeo4jTwiceInProjectIsStable(t *testing.T) { t.Error("two runs on an unchanged project wrote different snapshots") } } + +// TestRootCmd_TargetFilesKeepFullProvidesImports (#71): under -t the symbol +// table holds only the target packages, but provides_imports must be the same +// as on a full run. The library is a local module (replace => ./lib), so the +// package load needs no network. +func TestRootCmd_TargetFilesKeepFullProvidesImports(t *testing.T) { + dir := t.TempDir() + for name, body := range map[string]string{ + "go.mod": "module example.com/app\n\ngo 1.25.0\n\nrequire example.com/lib v0.0.0\n\nreplace example.com/lib => ./lib\n", + "cmd/main.go": "package main\n\nimport \"example.com/lib/a\"\n\nfunc main() { a.A() }\n", + "pkg/p.go": "package pkg\n\nimport \"example.com/lib/b\"\n\nfunc P() { b.B() }\n", + "lib/go.mod": "module example.com/lib\n\ngo 1.25.0\n", + "lib/a/a.go": "package a\n\nfunc A() {}\n", + "lib/b/b.go": "package b\n\nfunc B() {}\n", + } { + p := filepath.Join(dir, filepath.FromSlash(name)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + provides := func(t *testing.T, flags ...string) []string { + t.Helper() + out, _, err := runCmd(append([]string{"--input", dir, "--cache-dir", t.TempDir()}, flags...)...) + if err != nil { + t.Fatalf("%v: %v", flags, err) + } + var doc struct { + Application struct { + Dependencies []struct { + Name string `json:"name"` + ProvidesImports []string `json:"provides_imports"` + } `json:"dependencies"` + } `json:"application"` + } + if err := json.Unmarshal([]byte(out), &doc); err != nil { + t.Fatal(err) + } + for _, d := range doc.Application.Dependencies { + if d.Name == "example.com/lib" { + return d.ProvidesImports + } + } + t.Fatalf("%v: no example.com/lib dependency", flags) + return nil + } + full := provides(t) + if want := []string{"example.com/lib/a", "example.com/lib/b"}; !slices.Equal(full, want) { + t.Fatalf("full run: provides_imports %v, want %v", full, want) + } + if got := provides(t, "-t", "cmd/main.go"); !slices.Equal(got, full) { + t.Errorf("-t cmd/main.go: provides_imports %v, want the full run's %v", got, full) + } +} diff --git a/docs/design/specs/v2-artifacts.md b/docs/design/specs/v2-artifacts.md index d02787c..874c61e 100644 --- a/docs/design/specs/v2-artifacts.md +++ b/docs/design/specs/v2-artifacts.md @@ -85,15 +85,26 @@ Each decision was made with the user, one question per decision, in the order be | `direct` | `false` when the line carries `// indirect`, else `true` | | `locked_version` | version pinned in `go.sum` for that module, when present | | `locked_in` | the `go.sum` artifact id that gave `locked_version`, when present (#72) | + | `replaced_by` | the `go.mod` `replace` target, when one applies: `@`, or a local directory (#68) | | `declared_in` | the `go.mod` artifact id | | `provides_imports` | import paths in the project that resolve to this module (see below) | - | `prov` | `["declared"]`, plus `"lockfile"` when `go.sum` supplies `locked_version` | + | `prov` | `["declared"]`, plus `"lockfile"` when `go.sum` supplies `locked_version`, plus `"replace"` when a local directory replaces it | - **`go.sum`-only entries are not dependencies** (user decision, the non-recommended option would have included them; the recommended default is not to, because `go.sum` retains entries for pruned modules). `go.sum` contributes only `locked_version` and `prov`. - **`provides_imports`**: populated by longest-prefix match of each project import path against the `go.mod` module paths (user decision, Python parity). Import paths that match - no requirement are **not** recorded in this change (see Open items). + no requirement are **not** recorded in this change (see Open items). A `-t` run reads the + import paths of every project package with a light package load (names and imports, no + types; the full run's build tags and test setting), so it gets the same `provides_imports` + as a full run (#71) [user, 2026-11-30]. +- **`replace` directives** (#68) [user, 2026-11-30]: `go.sum` records what the build uses, + which is the replacement. A replace applies by Go's rule: one for the required version wins + over a version-less one. With `replace x => y v1.2.0`, the dependency keeps `name` `x` and + `spec` (so the code's imports of `x` still match it, and its package is `pkg:golang/x`), gets + `replaced_by` `y@v1.2.0`, and takes `locked_version` from `y v1.2.0` in `go.sum`. With + `replace x => ../x`, the build uses a local directory: the dependency is kept, with + `replaced_by` `../x`, `"replace"` in `prov`, and no `locked_version`. ### Analysis level - **L1, every level** (user decision). Parse-only facts, identical at `-a 1` through `-a 4`. @@ -107,7 +118,7 @@ Each decision was made with the user, one question per decision, in the order be - `:Package {id, ecosystem, name}` keyed by `id`. The id comes from `v2.PackageID`, the one place a package id is built (#72). - `DECLARES_DEPENDENCY` `(:Artifact)→(:Package)`, `_k = kind` (`runtime`), carrying `spec`, - `direct`, `prov` as properties. + `direct`, `prov` and, when a replace applies, `replaced_by` as properties. - `LOCKS` `(:Artifact)→(:Package)` from the dependency's `locked_in` artifact, carrying `version` (the sibling analyzers' name; it was `locked_version` before #72). - No `:ConfigKey` rows and no `DEFINES_CONFIG` rows in this change. diff --git a/internal/core/analyzer.go b/internal/core/analyzer.go index 1d90f0f..c6c704a 100644 --- a/internal/core/analyzer.go +++ b/internal/core/analyzer.go @@ -112,11 +112,23 @@ func (a *Analyzer) Analyze() (*schema.GoApplication, error) { if a.opts.Emit == options.EmitNeo4j && a.opts.OutputDir == "" { graphFile = "graph.cypher" // neo4j.GraphFileName } + // Under -t the symbol table has only the target packages; provides_imports + // must still cover the whole project (#71). If the light load fails, the + // symbol table's imports are used, and the warning says they are partial. + var imports []string + if len(a.opts.TargetFiles) > 0 { + var err error + if imports, err = repository.LoadImports(a.opts.InputPath, !a.opts.SkipTests); err != nil { + utils.Warn("repository: project imports not loaded, provides_imports covers only the target files: %v", err) + imports = nil + } + } facts, err := repository.Facts(a.opts.InputPath, app, repository.Options{ CaptureText: a.opts.ArtifactText, OutputDir: a.opts.OutputDir, CacheDir: a.cacheRoot, GraphFile: graphFile, + Imports: imports, }) if err != nil { return nil, fmt.Errorf("repository layer: %w", err) diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index ff1b0ea..6365893 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -130,7 +130,7 @@ func (p *projector) projectRepository() { ) declaredBy := NodeRef{Label: LabelArtifact, KeyProp: "id", Value: dep.DeclaredIn} p.b.Edge(RelDeclaresDependency, declaredBy, pkgRef, - Props{"spec": dep.Spec, "direct": dep.Direct, "prov": dep.Prov}, dep.Kind) + Props{"spec": dep.Spec, "direct": dep.Direct, "prov": dep.Prov, "replaced_by": emptyToNil(dep.ReplacedBy)}, dep.Kind) // The go.sum that locked it, by the id the JSON carries (#72). if dep.LockedVersion != "" && dep.LockedIn != "" { p.b.Edge(RelLocks, NodeRef{Label: LabelArtifact, KeyProp: "id", Value: dep.LockedIn}, pkgRef, diff --git a/internal/neo4j/repository_test.go b/internal/neo4j/repository_test.go index 4939dc1..cb548b2 100644 --- a/internal/neo4j/repository_test.go +++ b/internal/neo4j/repository_test.go @@ -34,6 +34,9 @@ func repoAnalysis() *v2.Analysis { DeclaredIn: goMod, Prov: []string{"declared"}}, {Name: "golang.org/x/tools", Ecosystem: "golang", Spec: "v0.52.0", Kind: "runtime", Direct: true, LockedVersion: "v0.52.0", LockedIn: toolsSum, DeclaredIn: toolsMod, Prov: []string{"declared", "lockfile"}}, + {Name: "example.com/x", Ecosystem: "golang", Spec: "v1.0.0", Kind: "runtime", Direct: true, + LockedVersion: "v1.2.0", LockedIn: goSum, ReplacedBy: "example.com/y@v1.2.0", DeclaredIn: goMod, + Prov: []string{"declared", "lockfile"}}, }, }, } @@ -65,10 +68,14 @@ func TestProject_RepositoryLayerRows(t *testing.T) { } decl := edges[RelDeclaresDependency] - if len(decl) != 3 { - t.Fatalf("DECLARES_DEPENDENCY edges = %d, want 3", len(decl)) + if len(decl) != 4 { + t.Fatalf("DECLARES_DEPENDENCY edges = %d, want 4", len(decl)) } for _, e := range decl { + // #68: replaced_by rides the edge, only on a replaced dependency. + if want := map[string]any{"pkg:golang/example.com/x": "example.com/y@v1.2.0"}[e.To.Value]; e.Props["replaced_by"] != want { + t.Errorf("DECLARES_DEPENDENCY -> %s replaced_by = %v, want %v", e.To.Value, e.Props["replaced_by"], want) + } if e.To.Label != LabelPackage || e.Key != "runtime" { t.Errorf("DECLARES_DEPENDENCY %s -> %s:%s _k=%q, want an artifact -> Package with _k runtime", e.From.Value, e.To.Label, e.To.Value, e.Key) } @@ -80,6 +87,7 @@ func TestProject_RepositoryLayerRows(t *testing.T) { want := map[string]string{ "pkg:golang/github.com/gorilla/mux": base + "go.sum", "pkg:golang/golang.org/x/tools": base + "tools/go.sum", + "pkg:golang/example.com/x": base + "go.sum", } locks := edges[RelLocks] if len(locks) != len(want) { diff --git a/internal/neo4j/schema.go b/internal/neo4j/schema.go index 86da832..1c5ab48 100644 --- a/internal/neo4j/schema.go +++ b/internal/neo4j/schema.go @@ -268,7 +268,7 @@ var Rels = []RelSpec{ // Repository layer. {Type: RelHasArtifact, From: []string{LabelApplication}, To: []string{LabelArtifact}}, - {Type: RelDeclaresDependency, From: []string{LabelArtifact}, To: []string{LabelPackage}, Props: []string{"spec", "direct", "prov"}, Discriminant: "kind"}, + {Type: RelDeclaresDependency, From: []string{LabelArtifact}, To: []string{LabelPackage}, Props: []string{"spec", "direct", "prov", "replaced_by"}, Discriminant: "kind"}, {Type: RelLocks, From: []string{LabelArtifact}, To: []string{LabelPackage}, Props: []string{"version"}}, {Type: RelDefinesConfig, From: []string{LabelArtifact}, To: []string{LabelConfigKey}}, {Type: RelProvides, From: []string{LabelPackage}, To: []string{LabelExternal}}, diff --git a/internal/repository/replace_test.go b/internal/repository/replace_test.go new file mode 100644 index 0000000..e7991e2 --- /dev/null +++ b/internal/repository/replace_test.go @@ -0,0 +1,96 @@ +package repository + +import ( + "reflect" + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" +) + +// replaceFacts runs Facts on a project with the given go.mod and go.sum, whose +// code imports the given paths. +func replaceFacts(t *testing.T, mod, sum string, imports ...string) map[string]schema.GoDependency { + t.Helper() + root := t.TempDir() + writeTree(t, root, map[string]string{"go.mod": mod, "go.sum": sum, "main.go": "package main\n"}) + facts, err := Facts(root, appWithImports(imports...), Options{}) + if err != nil { + t.Fatal(err) + } + out := map[string]schema.GoDependency{} + for _, d := range facts.Dependencies { + out[d.Name] = d + } + return out +} + +// TestFacts_ModuleReplace (#68): with replace x => y v1.2.0, go.sum has only the +// replacement's lines. locked_version comes from them, replaced_by names the +// replacement, and name stays x, so the code's imports of x still match. +func TestFacts_ModuleReplace(t *testing.T) { + deps := replaceFacts(t, `module example.com/app + +go 1.25.0 + +require example.com/x v1.0.0 + +replace example.com/x => example.com/y v1.2.0 +`, "example.com/y v1.2.0 h1:AAA=\nexample.com/y v1.2.0/go.mod h1:BBB=\n", "example.com/x/sub") + + want := schema.GoDependency{ + Name: "example.com/x", Ecosystem: "golang", Spec: "v1.0.0", Kind: "runtime", Direct: true, + LockedVersion: "v1.2.0", LockedIn: "go.sum", ReplacedBy: "example.com/y@v1.2.0", DeclaredIn: "go.mod", + ProvidesImports: []string{"example.com/x/sub"}, Prov: []string{"declared", "lockfile"}, + } + if got := deps["example.com/x"]; !reflect.DeepEqual(got, want) { + t.Errorf("dependency:\n got %+v\n want %+v", got, want) + } +} + +// TestFacts_LocalReplace (#68): a dependency replaced by a local directory is +// kept, marked local: replaced_by is the path, prov has "replace", and it has +// no locked_version (there is no version and no go.sum line). +func TestFacts_LocalReplace(t *testing.T) { + deps := replaceFacts(t, `module example.com/app + +go 1.25.0 + +require example.com/x v1.0.0 + +replace example.com/x => ../x +`, "example.com/x v1.0.0 h1:AAA=\nexample.com/x v1.0.0/go.mod h1:BBB=\n") + + got := deps["example.com/x"] + if got.ReplacedBy != "../x" || got.LockedVersion != "" || got.LockedIn != "" || + !reflect.DeepEqual(got.Prov, []string{"declared", "replace"}) { + t.Errorf("local replace: got replaced_by %q, locked %q in %q, prov %v; want ../x, none, [declared replace]", + got.ReplacedBy, got.LockedVersion, got.LockedIn, got.Prov) + } +} + +// TestFacts_TwoReplaces (#68): Go's rule. A version-specific replace applies +// only to that version and wins over a version-less one. +func TestFacts_TwoReplaces(t *testing.T) { + deps := replaceFacts(t, `module example.com/app + +go 1.25.0 + +require ( + example.com/a v1.0.0 + example.com/b v1.2.0 +) + +replace ( + example.com/a v1.0.0 => example.com/a v1.0.1 + example.com/a => example.com/a v9.0.0 + example.com/b v1.5.0 => example.com/b v1.6.0 +) +`, "") + + if got := deps["example.com/a"].ReplacedBy; got != "example.com/a@v1.0.1" { + t.Errorf("a: replaced_by %q, want the version-specific example.com/a@v1.0.1", got) + } + if got := deps["example.com/b"].ReplacedBy; got != "" { + t.Errorf("b: replaced_by %q, want none (the replace is for v1.5.0, b requires v1.2.0)", got) + } +} diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 12cfcb4..0414f29 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -14,14 +14,18 @@ import ( "fmt" "io" "io/fs" + "maps" "os" "path/filepath" + "slices" "sort" "strings" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/utils" "golang.org/x/mod/modfile" + "golang.org/x/mod/module" + "golang.org/x/tools/go/packages" ) // Ecosystem is the purl type used for Go modules (pkg:golang/). @@ -41,6 +45,10 @@ type Options struct { // GraphFile is the graph.cypher that --emit neo4j writes when no OutputDir is // set (in the current directory). It is skipped too. GraphFile string + // Imports, when non-nil, are the project's import paths for provides_imports. + // A -t run sets it (LoadImports), because its symbol table holds only the + // target packages. Nil means: read them from the symbol table. + Imports []string } // outputFileNames are the files this tool writes into OutputDir. @@ -354,8 +362,12 @@ func Facts(root string, app *schema.GoApplication, opts Options) (*schema.Reposi return facts, nil } locked := parseGoSum(filepath.Join(root, "go.sum")) - imports := projectImports(app) + imports := opts.Imports + if imports == nil { + imports = projectImports(app) + } + replaces := replaceIndex(f.Replace) deps := make([]schema.GoDependency, 0, len(f.Require)) for _, r := range f.Require { dep := schema.GoDependency{ @@ -367,8 +379,20 @@ func Facts(root string, app *schema.GoApplication, opts Options) (*schema.Reposi DeclaredIn: "go.mod", Prov: []string{"declared"}, } - if locked[r.Mod.Path][r.Mod.Version] { - dep.LockedVersion = r.Mod.Version + // go.sum records what the build uses: the replacement, when a replace + // applies (#68). A local directory has no version and no go.sum line. + used := r.Mod + if rep, ok := replaces.lookup(r.Mod); ok { + if rep.Version == "" { + dep.ReplacedBy = rep.Path + dep.Prov = append(dep.Prov, "replace") + } else { + dep.ReplacedBy = rep.Path + "@" + rep.Version + } + used = rep + } + if used.Version != "" && locked[used.Path][used.Version] { + dep.LockedVersion = used.Version dep.LockedIn = "go.sum" dep.Prov = append(dep.Prov, "lockfile") } @@ -380,6 +404,35 @@ func Facts(root string, app *schema.GoApplication, opts Options) (*schema.Reposi return facts, nil } +// replaceSet holds a go.mod's replace directives by module path. +type replaceSet struct { + exact map[module.Version]module.Version // replace x v1 => ... + any map[string]module.Version // replace x => ... +} + +func replaceIndex(rs []*modfile.Replace) replaceSet { + s := replaceSet{exact: map[module.Version]module.Version{}, any: map[string]module.Version{}} + for _, r := range rs { + if r.Old.Version != "" { + s.exact[r.Old] = r.New + } else { + s.any[r.Old.Path] = r.New + } + } + return s +} + +// lookup returns the replacement of m, by Go's rule: a replace for m's exact +// version wins over a version-less replace of its path. A replacement with no +// version is a local directory. +func (s replaceSet) lookup(m module.Version) (module.Version, bool) { + if r, ok := s.exact[m]; ok { + return r, true + } + r, ok := s.any[m.Path] + return r, ok +} + // parseGoSum returns, per module path and version, whether go.sum carries both // the module's h1 line and its /go.mod line. Only such a version is a locked // version. A missing or unreadable go.sum locks nothing. @@ -425,6 +478,33 @@ func parseGoSum(path string) map[string]map[string]bool { // projectImports is the sorted, deduplicated set of import paths the project's // (non-test, when the symbol table was built with --skip-tests) Go files use. +// LoadImports returns the import paths of every package of the project at +// root, with a light package load: names, files and imports, no types. It +// uses the symbol table's load settings (./..., Tests: tests), so a -t run gets +// the same provides_imports as a full run. The generated test-main packages +// (*.test) are not project code and are left out. +func LoadImports(root string, tests bool) ([]string, error) { + cfg := &packages.Config{ + Mode: packages.NeedName | packages.NeedFiles | packages.NeedImports, + Dir: root, + Tests: tests, + } + pkgs, err := packages.Load(cfg, "./...") + if err != nil { + return nil, err + } + seen := map[string]bool{} + for _, p := range pkgs { + if strings.HasSuffix(p.ID, ".test") { + continue + } + for imp := range p.Imports { + seen[imp] = true + } + } + return slices.Sorted(maps.Keys(seen)), nil +} + func projectImports(app *schema.GoApplication) []string { seen := map[string]bool{} for _, f := range app.SymbolTable { diff --git a/internal/schema/schema.go b/internal/schema/schema.go index e95f749..f03fea5 100644 --- a/internal/schema/schema.go +++ b/internal/schema/schema.go @@ -250,6 +250,7 @@ type GoDependency struct { Direct bool LockedVersion string // go.sum version of Spec, when both its h1 and /go.mod lines exist LockedIn string // path of the go.sum artifact that gave LockedVersion + ReplacedBy string // go.mod replace target: "@", or a local directory DeclaredIn string // path of the go.mod artifact ProvidesImports []string // project import paths that resolve to this module Prov []string // declared | lockfile diff --git a/internal/schema/v2/schema.go b/internal/schema/v2/schema.go index 90edc57..27d0468 100644 --- a/internal/schema/v2/schema.go +++ b/internal/schema/v2/schema.go @@ -394,8 +394,9 @@ type Dependency struct { Kind string `json:"kind"` // always "runtime" (go.mod has no dev/optional split) Direct bool `json:"direct"` // false for `// indirect` LockedVersion string `json:"locked_version,omitempty"` - LockedIn string `json:"locked_in,omitempty"` // the go.sum artifact id that gave locked_version - DeclaredIn string `json:"declared_in"` // the go.mod artifact id + LockedIn string `json:"locked_in,omitempty"` // the go.sum artifact id that gave locked_version + ReplacedBy string `json:"replaced_by,omitempty"` // go.mod replace target: "@", or a local directory + DeclaredIn string `json:"declared_in"` // the go.mod artifact id ProvidesImports []string `json:"provides_imports,omitempty"` Prov []string `json:"prov"` // declared | lockfile } diff --git a/internal/syntactic_analysis/v2emit/repository.go b/internal/syntactic_analysis/v2emit/repository.go index 819f422..473c8e8 100644 --- a/internal/syntactic_analysis/v2emit/repository.go +++ b/internal/syntactic_analysis/v2emit/repository.go @@ -52,6 +52,7 @@ func emitRepository(appID string, facts *schema.RepositoryFacts) (map[string]v2. Direct: d.Direct, LockedVersion: d.LockedVersion, LockedIn: lockedIn, + ReplacedBy: d.ReplacedBy, DeclaredIn: declared, ProvidesImports: d.ProvidesImports, Prov: d.Prov,