From 0f79345873661cc9e61140ea8a52d8fd236a7a38 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Sun, 29 Nov 2026 17:08:58 -0500 Subject: [PATCH 1/4] feat(schema): record the go.sum that locked a dependency (locked_in) (#72) A dependency's locked_version came from a go.sum, but the JSON did not say which one. The Neo4j projector then used the root go.sum for every LOCKS edge. A dependency of a nested go.mod would get a LOCKS edge from a go.sum that did not lock it. The dependency now carries locked_in, the id of the go.sum artifact that gave locked_version, in the same way declared_in names its go.mod. It is additive and omitted when the dependency is not locked. v2.PackageID is now the one function that builds a package id (pkg:/), as the sibling analyzers use one purl helper. Co-Authored-By: Claude Opus 5.5 --- internal/repository/repository.go | 1 + internal/repository/repository_test.go | 4 +-- internal/schema/schema.go | 1 + internal/schema/v2/ids.go | 8 ++++++ internal/schema/v2/ids_test.go | 8 ++++++ internal/schema/v2/schema.go | 3 ++- .../syntactic_analysis/v2emit/repository.go | 8 ++++-- .../v2emit/repository_test.go | 27 +++++++++++++++++++ 8 files changed, 55 insertions(+), 5 deletions(-) create mode 100644 internal/syntactic_analysis/v2emit/repository_test.go diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 18a518f..8763858 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -290,6 +290,7 @@ func Facts(root string, app *schema.GoApplication, opts Options) (*schema.Reposi } if locked[r.Mod.Path][r.Mod.Version] { dep.LockedVersion = r.Mod.Version + dep.LockedIn = "go.sum" dep.Prov = append(dep.Prov, "lockfile") } deps = append(deps, dep) diff --git a/internal/repository/repository_test.go b/internal/repository/repository_test.go index 0c048ef..80426ca 100644 --- a/internal/repository/repository_test.go +++ b/internal/repository/repository_test.go @@ -73,10 +73,10 @@ func TestFacts_DependenciesLocksAndImports(t *testing.T) { {Name: "cloud.google.com/go", Ecosystem: "golang", Spec: "v0.1.0", Kind: "runtime", Direct: true, DeclaredIn: "go.mod", ProvidesImports: []string{"cloud.google.com/go/storage"}, Prov: []string{"declared"}}, {Name: "cloud.google.com/go/auth", Ecosystem: "golang", Spec: "v0.2.0", Kind: "runtime", Direct: true, - LockedVersion: "v0.2.0", DeclaredIn: "go.mod", ProvidesImports: []string{"cloud.google.com/go/auth/credentials"}, + LockedVersion: "v0.2.0", LockedIn: "go.sum", DeclaredIn: "go.mod", ProvidesImports: []string{"cloud.google.com/go/auth/credentials"}, Prov: []string{"declared", "lockfile"}}, {Name: "github.com/gorilla/mux", Ecosystem: "golang", Spec: "v1.8.0", Kind: "runtime", Direct: true, - LockedVersion: "v1.8.0", DeclaredIn: "go.mod", ProvidesImports: []string{"github.com/gorilla/mux"}, + LockedVersion: "v1.8.0", LockedIn: "go.sum", DeclaredIn: "go.mod", ProvidesImports: []string{"github.com/gorilla/mux"}, Prov: []string{"declared", "lockfile"}}, {Name: "golang.org/x/text", Ecosystem: "golang", Spec: "v0.14.0", Kind: "runtime", Direct: false, DeclaredIn: "go.mod", Prov: []string{"declared"}}, diff --git a/internal/schema/schema.go b/internal/schema/schema.go index 99bf2c2..e95f749 100644 --- a/internal/schema/schema.go +++ b/internal/schema/schema.go @@ -249,6 +249,7 @@ type GoDependency struct { Kind string 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 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/ids.go b/internal/schema/v2/ids.go index fefc9f2..817f3dd 100644 --- a/internal/schema/v2/ids.go +++ b/internal/schema/v2/ids.go @@ -100,6 +100,14 @@ func ModuleID(appID, relPath string) string { return appID + idSep + Language + idSep + normalizePath(relPath) } +// PackageID builds the id of a :Package node: the version-less purl +// pkg:/ (spec v2-artifacts). The sibling analyzers use the same +// form (pkg:pypi/, pkg:npm/), so every analyzer of one repository +// converges on one package node. It is the one place a package id is built. +func PackageID(ecosystem, name string) string { + return "pkg:" + ecosystem + "/" + name +} + // ExternalID builds the id of an out-of-project symbol: // /@external/// (or .../ for a // package-level function). sig is the callee signature without the import-path diff --git a/internal/schema/v2/ids_test.go b/internal/schema/v2/ids_test.go index 7361348..8ad5a74 100644 --- a/internal/schema/v2/ids_test.go +++ b/internal/schema/v2/ids_test.go @@ -123,3 +123,11 @@ func TestCallBodyKeys(t *testing.T) { t.Fatal("nil input must yield no keys") } } + +// TestPackageID (#72): the one place a package id is built. It is the +// version-less purl the sibling analyzers use (pkg:pypi/…, pkg:npm/…). +func TestPackageID(t *testing.T) { + if got, want := PackageID("golang", "github.com/gorilla/mux"), "pkg:golang/github.com/gorilla/mux"; got != want { + t.Errorf("PackageID = %q, want %q", got, want) + } +} diff --git a/internal/schema/v2/schema.go b/internal/schema/v2/schema.go index 0f331e5..90edc57 100644 --- a/internal/schema/v2/schema.go +++ b/internal/schema/v2/schema.go @@ -394,7 +394,8 @@ 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"` - 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 + 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 b68924f..819f422 100644 --- a/internal/syntactic_analysis/v2emit/repository.go +++ b/internal/syntactic_analysis/v2emit/repository.go @@ -13,7 +13,7 @@ func artifactID(appID, relPath string) string { // emitRepository maps the repository facts onto the v2 layer. Artifacts are // keyed by path; dependencies keep the facts' order (sorted by module path) and -// point at their go.mod artifact by id. A nil facts set emits nothing. +// point at their go.mod artifact, and a locked one at its go.sum artifact, by id. A nil facts set emits nothing. func emitRepository(appID string, facts *schema.RepositoryFacts) (map[string]v2.Artifact, []v2.Dependency) { if facts == nil { return nil, nil @@ -37,10 +37,13 @@ func emitRepository(appID string, facts *schema.RepositoryFacts) (map[string]v2. } var deps []v2.Dependency for _, d := range facts.Dependencies { - declared := "" + declared, lockedIn := "", "" if d.DeclaredIn != "" { declared = artifactID(appID, d.DeclaredIn) } + if d.LockedIn != "" { + lockedIn = artifactID(appID, d.LockedIn) + } deps = append(deps, v2.Dependency{ Name: d.Name, Ecosystem: d.Ecosystem, @@ -48,6 +51,7 @@ func emitRepository(appID string, facts *schema.RepositoryFacts) (map[string]v2. Kind: d.Kind, Direct: d.Direct, LockedVersion: d.LockedVersion, + LockedIn: lockedIn, DeclaredIn: declared, ProvidesImports: d.ProvidesImports, Prov: d.Prov, diff --git a/internal/syntactic_analysis/v2emit/repository_test.go b/internal/syntactic_analysis/v2emit/repository_test.go new file mode 100644 index 0000000..e4ff1cd --- /dev/null +++ b/internal/syntactic_analysis/v2emit/repository_test.go @@ -0,0 +1,27 @@ +package v2emit + +import ( + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" +) + +// TestEmitRepository_LockedInIsTheLockfileArtifactID (#72): a locked +// dependency points at the go.sum artifact that locked it, by artifact id, as +// declared_in points at its go.mod. An unlocked one has no locked_in. +func TestEmitRepository_LockedInIsTheLockfileArtifactID(t *testing.T) { + const app = "can://app/app" + _, deps := emitRepository(app, &schema.RepositoryFacts{Dependencies: []schema.GoDependency{ + {Name: "github.com/gorilla/mux", LockedVersion: "v1.8.0", LockedIn: "go.sum", DeclaredIn: "go.mod"}, + {Name: "golang.org/x/text", DeclaredIn: "go.mod"}, + }}) + if len(deps) != 2 { + t.Fatalf("%d dependencies, want 2", len(deps)) + } + if got, want := deps[0].LockedIn, app+"/artifact/go.sum"; got != want { + t.Errorf("locked dependency: locked_in = %q, want %q", got, want) + } + if deps[1].LockedIn != "" { + t.Errorf("unlocked dependency: locked_in = %q, want empty", deps[1].LockedIn) + } +} From f24799ac25611b69259d4e372c8fd1849fdfeb9b Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Sun, 29 Nov 2026 17:08:59 -0500 Subject: [PATCH 2/4] fix(neo4j): write the artifact facts and LOCKS version as the siblings do (#81, #72) - :Artifact now carries kind, path, format, roles, size_bytes, sha256, source and extraction: the JSON artifact's fields. Before, it had only path and format, so a consumer of the shared node got the text and hash from a Python or TypeScript push and nothing from a Go push. Empty values are left out. (#81) - LOCKS comes from the dependency's locked_in artifact, not the root go.sum, and the package id comes from v2.PackageID. (#72) - The LOCKS property is now version, the name Python and TypeScript use, not locked_version. The SDK Go backend does not read it. The artifacts spec and CLAUDE.md record the decisions. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 5 +- docs/design/specs/v2-artifacts.md | 13 +++-- internal/neo4j/project.go | 18 ++++--- internal/neo4j/repository_test.go | 80 +++++++++++++++++++++++-------- internal/neo4j/schema.go | 4 +- 5 files changed, 88 insertions(+), 32 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5c9573c..cdc96a8 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -169,7 +169,7 @@ 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:** only with `--artifact-text`, default off [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]. +- **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 (#72) [user, 2026-11-29]. - **`provides_imports`:** longest-prefix match against `go.mod` module paths [user]. - **Level:** L1, every level, not gated [user]. @@ -238,6 +238,9 @@ shared neutral vocabulary verbatim; never rename a sibling's shared name). Spec: - Declare `:Artifact` / `:Package` / `:ConfigKey` and `HAS_ARTIFACT` / `DECLARES_DEPENDENCY` (`_k=kind`) / `LOCKS` / `DEFINES_CONFIG` **un-prefixed**, identical to the siblings, so a sibling analyzer over the same repo converges on the same node. + `:Artifact` carries the JSON artifact's fields (`kind`, `path`, `format`, `roles`, + `size_bytes`, `sha256`, `source`, `extraction`) and `LOCKS` carries `version`, as Python and + TypeScript write them (#81, #72) [user, 2026-11-29]. The projector emits rows **only for facts the Go analyzer produces** (go.mod deps → `:Package` `pkg:golang/…`); absent facts emit **zero rows** (declared contract, empty projection). `GO_PROVIDES` / `GO_UNRESOLVED_IMPORT` stay `GO_`-prefixed (this analyzer's diff --git a/docs/design/specs/v2-artifacts.md b/docs/design/specs/v2-artifacts.md index 6d8ed76..4e89ffb 100644 --- a/docs/design/specs/v2-artifacts.md +++ b/docs/design/specs/v2-artifacts.md @@ -79,6 +79,7 @@ Each decision was made with the user, one question per decision, in the order be | `kind` | `"runtime"` for every entry (`go.mod` has no dev/optional split) | | `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) | | `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` | @@ -94,12 +95,16 @@ Each decision was made with the user, one question per decision, in the order be Not gated. ### Neo4j projection (the neutral layer, unchanged labels) -- `:Artifact {id, path, format}` (keyed by `id`, `CanNode=true`), under `HAS_ARTIFACT` - from `:GoApplication`. -- `:Package {id, ecosystem, name}` keyed by `id`. +- `:Artifact {id, kind, path, format, roles, size_bytes, sha256, source, extraction}` (keyed + by `id`, `CanNode=true`), under `HAS_ARTIFACT` from `:GoApplication`. These are the JSON + artifact's fields; empty values are left out. Python writes the same set, TypeScript the + same set plus `kind` (#81; the original `{id, path, format}` left the text and hash out). +- `: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. -- `LOCKS` `(:Artifact)→(:Package)` from `go.sum`, carrying `locked_version`. +- `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. ## Open items (flagged for review, not asked) diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index 716ed1f..ff1b0ea 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -106,29 +106,35 @@ func (p *projector) projectRepository() { sort.Strings(paths) for _, path := range paths { art := arts[path] + // The JSON artifact's facts, as the Python and TypeScript projectors + // write them on the shared node (#81); kind as TypeScript does. ref := p.b.Node( []string{LabelArtifact, MarkerLabel}, "id", art.ID, - Props{"path": art.Path, "format": art.Format}, + Props{ + "kind": art.Kind, "path": art.Path, "format": art.Format, "roles": art.Roles, + "size_bytes": art.SizeBytes, "sha256": emptyToNil(art.SHA256), + "source": emptyToNil(art.Source), "extraction": emptyToNil(art.Extraction), + }, "", // an artifact belongs to no single module ) p.b.Edge(RelHasArtifact, p.appRef(), ref, nil, "") } - goSum, hasGoSum := arts["go.sum"] for _, dep := range p.analysis.Application.Dependencies { pkgRef := p.b.Node( []string{LabelPackage}, - "id", "pkg:"+dep.Ecosystem+"/"+dep.Name, + "id", v2.PackageID(dep.Ecosystem, dep.Name), Props{"ecosystem": dep.Ecosystem, "name": dep.Name}, "", ) 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) - if dep.LockedVersion != "" && hasGoSum { - p.b.Edge(RelLocks, NodeRef{Label: LabelArtifact, KeyProp: "id", Value: goSum.ID}, pkgRef, - Props{"locked_version": dep.LockedVersion}, "") + // 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, + Props{"version": dep.LockedVersion}, "") } } } diff --git a/internal/neo4j/repository_test.go b/internal/neo4j/repository_test.go index b2554f6..4939dc1 100644 --- a/internal/neo4j/repository_test.go +++ b/internal/neo4j/repository_test.go @@ -1,30 +1,39 @@ package neo4j import ( + "reflect" "testing" v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" ) // repoAnalysis is a minimal L1 analysis carrying only the repository layer: -// go.mod and go.sum artifacts, and two dependencies (one locked, one not). +// go.mod and go.sum artifacts, two dependencies (one locked, one not), and a +// nested tools/go.mod whose dependency its own tools/go.sum locks. func repoAnalysis() *v2.Analysis { const app = "can://frontend/frontend" goMod := app + "/artifact/go.mod" goSum := app + "/artifact/go.sum" + toolsMod := app + "/artifact/tools/go.mod" + toolsSum := app + "/artifact/tools/go.sum" return &v2.Analysis{ IdentityVersion: 2, SchemaVersion: v2.SchemaVersion, Language: v2.Language, MaxLevel: 1, Application: v2.Application{ IdentityVersion: 2, ID: app, Kind: "application", Artifacts: map[string]v2.Artifact{ - "go.mod": {ID: goMod, Kind: "artifact", Path: "go.mod", Format: "gomod", Roles: []string{"dependency-manifest"}}, - "go.sum": {ID: goSum, Kind: "artifact", Path: "go.sum", Format: "gosum", Roles: []string{"lockfile"}}, + "go.mod": {ID: goMod, Kind: "artifact", Path: "go.mod", Format: "gomod", Roles: []string{"dependency-manifest"}, + SizeBytes: 42, SHA256: "abc123", Source: "module frontend\n", Extraction: "full"}, + "go.sum": {ID: goSum, Kind: "artifact", Path: "go.sum", Format: "gosum", Roles: []string{"lockfile"}, Extraction: "none"}, + "tools/go.mod": {ID: toolsMod, Kind: "artifact", Path: "tools/go.mod", Format: "gomod", Extraction: "none"}, + "tools/go.sum": {ID: toolsSum, Kind: "artifact", Path: "tools/go.sum", Format: "gosum", Extraction: "none"}, }, Dependencies: []v2.Dependency{ {Name: "github.com/gorilla/mux", Ecosystem: "golang", Spec: "v1.8.0", Kind: "runtime", Direct: true, - LockedVersion: "v1.8.0", DeclaredIn: goMod, Prov: []string{"declared", "lockfile"}}, + LockedVersion: "v1.8.0", LockedIn: goSum, DeclaredIn: goMod, Prov: []string{"declared", "lockfile"}}, {Name: "golang.org/x/text", Ecosystem: "golang", Spec: "v0.14.0", Kind: "runtime", Direct: false, 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"}}, }, }, } @@ -51,31 +60,64 @@ func TestProject_RepositoryLayerRows(t *testing.T) { for _, e := range rows.Edges { edges[e.Type] = append(edges[e.Type], e) } - if len(edges[RelHasArtifact]) != 2 { - t.Errorf("HAS_ARTIFACT edges = %d, want 2 (go.mod, go.sum)", len(edges[RelHasArtifact])) + if len(edges[RelHasArtifact]) != 4 { + t.Errorf("HAS_ARTIFACT edges = %d, want 4", len(edges[RelHasArtifact])) } decl := edges[RelDeclaresDependency] - if len(decl) != 2 { - t.Fatalf("DECLARES_DEPENDENCY edges = %d, want 2", len(decl)) + if len(decl) != 3 { + t.Fatalf("DECLARES_DEPENDENCY edges = %d, want 3", len(decl)) } for _, e := range decl { - if e.From.Value != "can://frontend/frontend/artifact/go.mod" || e.To.Label != LabelPackage { - t.Errorf("DECLARES_DEPENDENCY wired %s -> %s:%s, want go.mod -> Package", e.From.Value, e.To.Label, e.To.Value) - } - if e.Key != "runtime" { - t.Errorf("DECLARES_DEPENDENCY _k = %q, want runtime", e.Key) + 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) } } + // #72: each LOCKS edge comes from the go.sum named by the dependency's + // locked_in, not from the root go.sum. Q2: the property is "version". + const base = "can://frontend/frontend/artifact/" + want := map[string]string{ + "pkg:golang/github.com/gorilla/mux": base + "go.sum", + "pkg:golang/golang.org/x/tools": base + "tools/go.sum", + } locks := edges[RelLocks] - if len(locks) != 1 { - t.Fatalf("LOCKS edges = %d, want 1 (only the locked dependency)", len(locks)) + if len(locks) != len(want) { + t.Fatalf("LOCKS edges = %d, want %d (one per locked dependency)", len(locks), len(want)) + } + for _, e := range locks { + if want[e.To.Value] != e.From.Value { + t.Errorf("LOCKS %s -> %s, want %s -> %s", e.From.Value, e.To.Value, want[e.To.Value], e.To.Value) + } + if _, old := e.Props["locked_version"]; old || e.Props["version"] == nil { + t.Errorf("LOCKS -> %s props = %v, want version and no locked_version", e.To.Value, e.Props) + } + } +} + +// TestProject_ArtifactProperties (#81): :Artifact carries the JSON artifact's +// facts, as the Python and TypeScript projectors do, plus kind (TypeScript). +// Empty values are left out. +func TestProject_ArtifactProperties(t *testing.T) { + nodes := map[string]NodeRow{} + for _, n := range Project(repoAnalysis()).Nodes { + nodes[n.Value] = n + } + goMod := nodes["can://frontend/frontend/artifact/go.mod"].Props + want := Props{ + "kind": "artifact", "path": "go.mod", "format": "gomod", "roles": []string{"dependency-manifest"}, + "size_bytes": int64(42), "sha256": "abc123", "source": "module frontend\n", "extraction": "full", } - if locks[0].From.Value != "can://frontend/frontend/artifact/go.sum" || - locks[0].To.Value != "pkg:golang/github.com/gorilla/mux" || - locks[0].Props["locked_version"] != "v1.8.0" { - t.Errorf("LOCKS = %+v, want go.sum -> mux with locked_version v1.8.0", locks[0]) + for k, v := range want { + if !reflect.DeepEqual(goMod[k], v) { + t.Errorf("go.mod %s = %#v, want %#v", k, goMod[k], v) + } + } + goSum := nodes["can://frontend/frontend/artifact/go.sum"].Props + for _, k := range []string{"source", "sha256"} { + if _, ok := goSum[k]; ok { + t.Errorf("go.sum has empty %s, want it left out", k) + } } } diff --git a/internal/neo4j/schema.go b/internal/neo4j/schema.go index 2ba98e8..86da832 100644 --- a/internal/neo4j/schema.go +++ b/internal/neo4j/schema.go @@ -232,7 +232,7 @@ var Nodes = []NodeSpec{ // :GoCanNode marker and falls under the prefix scope on wipe. { Label: LabelArtifact, MergeLabel: LabelArtifact, Key: "id", CanNode: true, - Props: []string{"path", "format"}, + Props: []string{"kind", "path", "format", "roles", "size_bytes", "sha256", "source", "extraction"}, }, // Neutral layer. Keyed by its pkg: purl (not a can:// id), so NO marker label // and outside prefix scoping — a sibling analyzer converges on the same node. @@ -269,7 +269,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: RelLocks, From: []string{LabelArtifact}, To: []string{LabelPackage}, Props: []string{"locked_version"}}, + {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}}, {Type: RelUnresolvedImport, From: []string{LabelApplication}, To: []string{LabelExternal}}, From d633744965347c450f78fffd6bf450eeb773ac87 Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Sun, 29 Nov 2026 17:13:46 -0500 Subject: [PATCH 3/4] fix(neo4j): reconcile shared artifacts on an eager push, never delete them wholesale (#70) The eager whole-app purge deleted every :GoCanNode under the app, and :Artifact carries :GoCanNode. :Artifact is shared with the Python and TypeScript analyzers, so an eager Go push deleted their artifact nodes too, with their edges (DECLARES_DEPENDENCY to pkg:pypi/..., config-key edges). The purge now skips :Artifact. An eager full push reconciles the app's artifacts before it upserts them, with the siblings' claim model (codeanalyzer-python PURGE_ARTIFACT_EDGES, RELEASE_VANISHED_ARTIFACTS): 1. delete the Go-owned edges on the app's artifacts: HAS_ARTIFACT from :GoApplication, incoming GO_ edges, and DECLARES_DEPENDENCY / LOCKS to pkg:golang/ packages. The push writes them again from this run; 2. for each artifact this run does not have, remove :GoCanNode and delete the node only when no analyzer still has a HAS_ARTIFACT edge to it. A lazy push and a -t push reconcile nothing (a lazy push never deletes), as in the sibling analyzers. Stale rows stay until the next --eager full push. The graph.cypher snapshot keeps its whole-app wipe, as Python's does. Tests: the query scope and the order (reconcile before the first artifact MERGE, only on eager full runs) on the fake DB; and three live tests (neo4j_it): an eager push removes a deleted file and a removed require, a lazy push keeps them, and a sibling's HAS_ARTIFACT and DECLARES_DEPENDENCY on a shared artifact survive an eager push. The last one fails on the old code. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 4 + docs/design/specs/v2-artifacts.md | 17 +++ internal/neo4j/artifact_integration_test.go | 150 ++++++++++++++++++++ internal/neo4j/artifact_reconcile_test.go | 103 ++++++++++++++ internal/neo4j/bolt.go | 68 ++++++++- 5 files changed, 340 insertions(+), 2 deletions(-) create mode 100644 internal/neo4j/artifact_integration_test.go create mode 100644 internal/neo4j/artifact_reconcile_test.go diff --git a/CLAUDE.md b/CLAUDE.md index cdc96a8..5f0cb27 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -238,6 +238,10 @@ shared neutral vocabulary verbatim; never rename a sibling's shared name). Spec: - Declare `:Artifact` / `:Package` / `:ConfigKey` and `HAS_ARTIFACT` / `DECLARES_DEPENDENCY` (`_k=kind`) / `LOCKS` / `DEFINES_CONFIG` **un-prefixed**, identical to the siblings, so a sibling analyzer over the same repo converges on the same node. + An `--eager` full Bolt push reconciles artifacts with the siblings' claim model (delete the + Go-owned edges, release vanished artifacts, delete a node only when no `HAS_ARTIFACT` is + left); the whole-app purge skips `:Artifact`; lazy and `-t` pushes reconcile nothing (#70) + [user, 2026-11-29]. `:Artifact` carries the JSON artifact's fields (`kind`, `path`, `format`, `roles`, `size_bytes`, `sha256`, `source`, `extraction`) and `LOCKS` carries `version`, as Python and TypeScript write them (#81, #72) [user, 2026-11-29]. diff --git a/docs/design/specs/v2-artifacts.md b/docs/design/specs/v2-artifacts.md index 4e89ffb..9cb4485 100644 --- a/docs/design/specs/v2-artifacts.md +++ b/docs/design/specs/v2-artifacts.md @@ -107,6 +107,23 @@ Each decision was made with the user, one question per decision, in the order be `version` (the sibling analyzers' name; it was `locked_version` before #72). - No `:ConfigKey` rows and no `DEFINES_CONFIG` rows in this change. +### Removing artifacts and dependencies that are gone (#70) [user, 2026-11-29] +- `:Artifact` is shared with the sibling analyzers. A Go push never deletes it wholesale: the + eager whole-app purge skips `:Artifact`. +- **Only an `--eager` full push reconciles** (Python and TypeScript parity). Before the artifact + rows are upserted, it: + 1. deletes the Go-owned edges on the app's artifacts (`/artifact/` prefix): + `HAS_ARTIFACT` from `:GoApplication`, incoming `GO_` edges, and `DECLARES_DEPENDENCY` / + `LOCKS` to `pkg:golang/` packages. The push then writes them again from this run; + 2. releases each artifact of the app that this run does not have: it removes `:GoCanNode`, + and deletes the node only when no analyzer still has a `HAS_ARTIFACT` edge to it. +- A lazy push and a `-t` push reconcile nothing: a lazy push never deletes. Stale artifact + and dependency rows stay until the next `--eager` full push. +- `:Package` nodes are never deleted (neutral, shared by every app that depends on them). +- The `graph.cypher` snapshot still wipes the app's artifacts with the rest of its + subgraph and rebuilds them, as Python's snapshot does. Another analyzer's edges into a + shared artifact are restored on that analyzer's next push. + ## Open items (flagged for review, not asked) These are defaults I chose while writing the spec. Confirm them during review: diff --git a/internal/neo4j/artifact_integration_test.go b/internal/neo4j/artifact_integration_test.go new file mode 100644 index 0000000..132b38f --- /dev/null +++ b/internal/neo4j/artifact_integration_test.go @@ -0,0 +1,150 @@ +//go:build neo4j_it + +package neo4j + +import ( + "context" + "testing" + + "github.com/neo4j/neo4j-go-driver/v5/neo4j" + + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// Live tests for the artifact reconcile (#70, Q4–Q6). Each builds a real +// analysis, gives it a repository layer, and pushes it with the streaming push. + +// withRepo returns a with the artifacts named by paths (go.mod and go.sum are +// always there) and the dependencies named by deps, each declared in go.mod +// and locked in go.sum. +func withRepo(t *testing.T, paths []string, deps []string) *v2.Analysis { + t.Helper() + a := buildMultipackageL2(t) + app := a.Application.ID + a.Application.Artifacts = map[string]v2.Artifact{} + for _, p := range append([]string{"go.mod", "go.sum"}, paths...) { + a.Application.Artifacts[p] = v2.Artifact{ID: app + "/artifact/" + p, Kind: "artifact", Path: p, Format: "text", Extraction: "none"} + } + a.Application.Dependencies = nil + for _, d := range deps { + a.Application.Dependencies = append(a.Application.Dependencies, v2.Dependency{ + Name: d, Ecosystem: "golang", Spec: "v1.0.0", Kind: "runtime", Direct: true, + LockedVersion: "v1.0.0", LockedIn: app + "/artifact/go.sum", DeclaredIn: app + "/artifact/go.mod", + Prov: []string{"declared", "lockfile"}, + }) + } + return a +} + +func pushIT(t *testing.T, ctx context.Context, a *v2.Analysis, cfg BoltConfig) { + t.Helper() + if _, _, err := PushBolt(ctx, treeSource(a), cfg); err != nil { + t.Fatalf("push: %v", err) + } +} + +func countIT(t *testing.T, ctx context.Context, cfg BoltConfig, q string, params map[string]any) int { + t.Helper() + drv, err := neo4j.NewDriverWithContext(cfg.URI, neo4j.BasicAuth(cfg.User, cfg.Password, "")) + if err != nil { + t.Fatalf("driver: %v", err) + } + defer drv.Close(ctx) + res, err := neo4j.ExecuteQuery(ctx, drv, q, params, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase(cfg.Database)) + if err != nil { + t.Fatalf("%s: %v", q, err) + } + return int(res.Records[0].Values[0].(int64)) +} + +// repoState counts what the reconcile changes: the config.yaml artifact, and +// the DECLARES_DEPENDENCY and LOCKS edges to golang.org/x/text. +func repoState(t *testing.T, ctx context.Context, cfg BoltConfig, app string) (config, declares, locks int) { + t.Helper() + p := map[string]any{"cfg": app + "/artifact/config.yaml", "pkg": v2.PackageID("golang", "golang.org/x/text")} + config = countIT(t, ctx, cfg, "MATCH (n:Artifact {id: $cfg}) RETURN count(n)", p) + declares = countIT(t, ctx, cfg, "MATCH (:Artifact)-[r:DECLARES_DEPENDENCY]->(:Package {id: $pkg}) RETURN count(r)", p) + locks = countIT(t, ctx, cfg, "MATCH (:Artifact)-[r:LOCKS]->(:Package {id: $pkg}) RETURN count(r)", p) + return +} + +// seed pushes the "before" state eagerly: config.yaml, and two dependencies. +func seed(t *testing.T, ctx context.Context, cfg BoltConfig) string { + t.Helper() + before := withRepo(t, []string{"config.yaml"}, []string{"github.com/gorilla/mux", "golang.org/x/text"}) + eager := cfg + eager.Eager, eager.FullRun = true, true + pushIT(t, ctx, before, eager) + app := before.Application.ID + if c, d, l := repoState(t, ctx, cfg, app); c != 1 || d != 1 || l != 1 { + t.Fatalf("seed: config %d, DECLARES_DEPENDENCY %d, LOCKS %d; want 1 each", c, d, l) + } + return app +} + +// after is the "after" state: config.yaml deleted, golang.org/x/text removed. +func after(t *testing.T) *v2.Analysis { + return withRepo(t, nil, []string{"github.com/gorilla/mux"}) +} + +func TestIntegration_EagerPushRemovesVanishedArtifacts(t *testing.T) { + ctx := context.Background() + cfg := itConfig(t) + app := seed(t, ctx, cfg) + + eager := cfg + eager.Eager, eager.FullRun = true, true + pushIT(t, ctx, after(t), eager) + if c, d, l := repoState(t, ctx, cfg, app); c != 0 || d != 0 || l != 0 { + t.Errorf("after an eager push: config %d, DECLARES_DEPENDENCY %d, LOCKS %d; want 0 each", c, d, l) + } + if n := countIT(t, ctx, cfg, "MATCH (:GoApplication {id: $app})-[:HAS_ARTIFACT]->(n:Artifact:GoCanNode) RETURN count(n)", + map[string]any{"app": app}); n != 2 { + t.Errorf("artifacts after an eager push = %d, want 2 (go.mod, go.sum)", n) + } +} + +func TestIntegration_LazyPushKeepsVanishedArtifacts(t *testing.T) { + ctx := context.Background() + cfg := itConfig(t) + app := seed(t, ctx, cfg) + + lazy := cfg + lazy.FullRun = true + pushIT(t, ctx, after(t), lazy) + if c, d, l := repoState(t, ctx, cfg, app); c != 1 || d != 1 || l != 1 { + t.Errorf("after a lazy push: config %d, DECLARES_DEPENDENCY %d, LOCKS %d; want 1 each (lazy never deletes)", c, d, l) + } +} + +// TestIntegration_EagerPushKeepsSharedArtifact (Q5): a sibling analyzer's claim +// on an artifact survives an eager Go push that no longer has the artifact, +// and so does its dependency edge on a kept artifact. +func TestIntegration_EagerPushKeepsSharedArtifact(t *testing.T) { + ctx := context.Background() + cfg := itConfig(t) + app := seed(t, ctx, cfg) + const py = "can://it-sibling/py" + p := map[string]any{"py": py, "cfg": app + "/artifact/config.yaml", "mod": app + "/artifact/go.mod"} + runIT(t, ctx, cfg, "MERGE (a:PyApplication {id: $py}) WITH a "+ + "MATCH (c:Artifact {id: $cfg}), (m:Artifact {id: $mod}) "+ + "MERGE (a)-[:HAS_ARTIFACT]->(c) "+ + "MERGE (m)-[:DECLARES_DEPENDENCY]->(:Package {id: 'pkg:pypi/requests'})", p) + t.Cleanup(func() { + runIT(t, ctx, cfg, "MATCH (n) WHERE n.id IN [$py, 'pkg:pypi/requests'] DETACH DELETE n", p) + }) + + eager := cfg + eager.Eager, eager.FullRun = true, true + pushIT(t, ctx, after(t), eager) + + if n := countIT(t, ctx, cfg, "MATCH (:PyApplication {id: $py})-[:HAS_ARTIFACT]->(c:Artifact {id: $cfg}) RETURN count(c)", p); n != 1 { + t.Errorf("the sibling's config.yaml artifact or its HAS_ARTIFACT is gone (count %d)", n) + } + if n := countIT(t, ctx, cfg, "MATCH (c:Artifact:GoCanNode {id: $cfg}) RETURN count(c)", p); n != 0 { + t.Errorf("config.yaml keeps the Go claim after Go no longer has it") + } + if n := countIT(t, ctx, cfg, "MATCH (:Artifact {id: $mod})-[r:DECLARES_DEPENDENCY]->(:Package {id: 'pkg:pypi/requests'}) RETURN count(r)", p); n != 1 { + t.Errorf("the sibling's DECLARES_DEPENDENCY on go.mod is gone") + } +} diff --git a/internal/neo4j/artifact_reconcile_test.go b/internal/neo4j/artifact_reconcile_test.go new file mode 100644 index 0000000..98fcb89 --- /dev/null +++ b/internal/neo4j/artifact_reconcile_test.go @@ -0,0 +1,103 @@ +package neo4j + +import ( + "context" + "slices" + "strings" + "testing" +) + +// The :Artifact node is shared with the sibling analyzers (#70, Q5). An eager +// full push must not delete it wholesale. It deletes only the Go-owned edges on +// the app's artifacts, then releases the artifacts this run no longer has: it +// removes the :GoCanNode claim and deletes the node only when no analyzer still +// has a HAS_ARTIFACT edge to it. A lazy push and a -t push reconcile nothing. + +func TestEagerPurge_SkipsArtifacts(t *testing.T) { + q, _ := eagerPurgeQuery("can://app/app") + if !strings.Contains(q, "NOT n:"+LabelArtifact) { + t.Errorf("eager purge deletes shared :Artifact nodes: %q", q) + } +} + +func TestReconcileQueries_AreScoped(t *testing.T) { + q, p := purgeArtifactEdgesQuery("can://app/app") + if p["pre"] != "can://app/app/artifact/" { + t.Errorf("purgeArtifactEdges prefix = %v, want the app's artifact prefix", p["pre"]) + } + for _, want := range []string{"t.id STARTS WITH $pre", "s:" + LabelApplication, "'pkg:golang/'", "IN TRANSACTIONS"} { + if !strings.Contains(q, want) { + t.Errorf("purgeArtifactEdges lacks %q: %q", want, q) + } + } + if strings.Contains(q, "DETACH DELETE") { + t.Errorf("purgeArtifactEdges deletes nodes: %q", q) + } + + rq, rp := releaseVanishedArtifactsQuery("can://app/app", []string{"can://app/app/artifact/go.mod"}) + assertScoped(t, "releaseVanishedArtifacts", strings.ReplaceAll(rq, "$pre", "$p"), map[string]any{"p": rp["pre"]}) + for _, want := range []string{"NOT n.id IN $keep", "REMOVE n:" + MarkerLabel, "NOT ()-[:" + RelHasArtifact + "]->(n)", "IN TRANSACTIONS"} { + if !strings.Contains(rq, want) { + t.Errorf("releaseVanishedArtifacts lacks %q: %q", want, rq) + } + } + if keep, _ := rp["keep"].([]string); !slices.Equal(keep, []string{"can://app/app/artifact/go.mod"}) { + t.Errorf("releaseVanishedArtifacts keep = %v", rp["keep"]) + } +} + +// TestBolt_ReconcileOnlyOnEagerFullRuns (Q4): the reconcile runs on an eager +// full push, before the first artifact MERGE, with every artifact id of the +// run as keep. A lazy push and an eager -t push run no reconcile statement. +func TestBolt_ReconcileOnlyOnEagerFullRuns(t *testing.T) { + a := repoAnalysis() + var arts []string + for _, art := range a.Application.Artifacts { + arts = append(arts, art.ID) + } + slices.Sort(arts) + + for _, tc := range []struct { + name string + cfg BoltConfig + reconcile bool + }{ + {"eager full", BoltConfig{Eager: true, FullRun: true}, true}, + {"lazy full", BoltConfig{FullRun: true}, false}, + {"eager -t", BoltConfig{Eager: true}, false}, + } { + t.Run(tc.name, func(t *testing.T) { + db := &fakeDB{} + if _, _, err := streamGraph(treeSource(a), newBoltWriter(context.Background(), db, a.Application.ID, tc.cfg)); err != nil { + t.Fatal(err) + } + edgesAt, releaseAt, firstArtifact := -1, -1, -1 + for i, st := range db.writes { + switch { + case strings.Contains(st.q, "DECLARES_DEPENDENCY|LOCKS"): + edgesAt = i + case strings.Contains(st.q, "REMOVE n:"+MarkerLabel): + releaseAt = i + keep, _ := st.params["keep"].([]string) + if got := slices.Sorted(slices.Values(keep)); !slices.Equal(got, arts) { + t.Errorf("keep = %v, want every artifact of the run %v", got, arts) + } + case firstArtifact < 0 && strings.Contains(st.q, "MERGE (n:"+LabelArtifact): + firstArtifact = i + } + } + if !tc.reconcile { + if edgesAt >= 0 || releaseAt >= 0 { + t.Errorf("reconcile ran (edges %d, release %d)", edgesAt, releaseAt) + } + return + } + if edgesAt < 0 || releaseAt < 0 || firstArtifact < 0 { + t.Fatalf("missing statement: edges %d, release %d, artifact MERGE %d", edgesAt, releaseAt, firstArtifact) + } + if !(edgesAt < releaseAt && releaseAt < firstArtifact) { + t.Errorf("order: edges %d, release %d, artifact MERGE %d; want edges < release < MERGE", edgesAt, releaseAt, firstArtifact) + } + }) + } +} diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index 0fd144e..24a047e 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -136,6 +136,10 @@ type boltWriter struct { level int // max_level of the begin row forced bool // forceFull || cfg.Eager: every module counts as changed scoped bool + // reconcile is set on an eager full push: shared then reconciles the + // artifacts under root (reconcileArtifacts). + reconcile bool + root string // 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 @@ -174,13 +178,20 @@ func (w *boltWriter) begin(app NodeRow) error { if err := w.eagerPurge(root); err != nil { return err } + w.root, w.reconcile = root, true } w.forced = forceFull || w.cfg.Eager return nil } -// shared upserts the module-less nodes (MERGE-only, every run). +// shared upserts the module-less nodes (MERGE-only, every run). On an eager +// full push it first reconciles the app's artifacts. func (w *boltWriter) shared(nodes []NodeRow) error { + if w.reconcile { + if err := w.reconcileArtifacts(nodes); err != nil { + return err + } + } if err := w.bufferNodes(nodes); err != nil { return err } @@ -427,11 +438,64 @@ func (w *boltWriter) purgeModule(moduleID string) error { // DB. Every destructive statement is scoped — never an unqualified DELETE. func eagerPurgeQuery(root string) (string, map[string]any) { // Batched to avoid exhausting the transaction memory limit on large apps. - return "MATCH (n:GoCanNode) WHERE n.id STARTS WITH $p OR n.id = $root " + + // :Artifact is shared with the sibling analyzers, so it is reconciled + // (reconcileArtifacts), never deleted wholesale here. + return "MATCH (n:GoCanNode) WHERE (n.id STARTS WITH $p OR n.id = $root) AND NOT n:" + LabelArtifact + " " + "CALL (n) { DETACH DELETE n } IN TRANSACTIONS OF 5000 ROWS", map[string]any{"p": descendantPrefix(root), "root": root} } +// artifactPrefix is the id prefix of an application's artifacts: +// /artifact/ (spec v2-artifacts). +func artifactPrefix(root string) string { + return descendantPrefix(root) + "artifact/" +} + +// purgeArtifactEdgesQuery deletes the Go-owned edges on the app's artifacts: +// HAS_ARTIFACT from :GoApplication, incoming GO_ edges, and DECLARES_DEPENDENCY +// and LOCKS to pkg:golang/ packages. The push then writes them again from this +// run. Edges that a sibling analyzer owns on the same artifact stay. It follows +// PURGE_ARTIFACT_EDGES in codeanalyzer-python. +func purgeArtifactEdgesQuery(root string) (string, map[string]any) { + return "MATCH (t:" + LabelArtifact + ") WHERE t.id STARTS WITH $pre " + + "CALL (t) { WITH [(t)<-[r]-(s) WHERE (type(r) = '" + RelHasArtifact + "' AND s:" + LabelApplication + ") " + + "OR type(r) STARTS WITH '" + RelPrefix + "' | r] " + + "+ [(t)-[d:" + RelDeclaresDependency + "|" + RelLocks + "]->(p:" + LabelPackage + ") WHERE p.id STARTS WITH 'pkg:golang/' | d] AS rs " + + "FOREACH (r IN rs | DELETE r) } IN TRANSACTIONS OF 1000 ROWS", + map[string]any{"pre": artifactPrefix(root)} +} + +// releaseVanishedArtifactsQuery releases the Go claim on the app's artifacts +// that this run does not have (keep is every artifact id of the run): it +// removes :GoCanNode, and deletes the node when no analyzer still has a +// HAS_ARTIFACT edge to it. The Go HAS_ARTIFACT edges are already gone +// (purgeArtifactEdgesQuery). It follows RELEASE_VANISHED_ARTIFACTS in +// codeanalyzer-python. +func releaseVanishedArtifactsQuery(root string, keep []string) (string, map[string]any) { + return "MATCH (n:" + LabelArtifact + ":GoCanNode) WHERE n.id STARTS WITH $pre AND NOT n.id IN $keep " + + "CALL (n) { REMOVE n:GoCanNode WITH n WHERE NOT ()-[:" + RelHasArtifact + "]->(n) DETACH DELETE n } " + + "IN TRANSACTIONS OF 1000 ROWS", + map[string]any{"pre": artifactPrefix(root), "keep": keep} +} + +// reconcileArtifacts runs on an eager full push, before the artifact rows are +// upserted (Q4: a lazy push never deletes). nodes are the shared rows of the +// run; their :Artifact ids are the ones to keep. +func (w *boltWriter) reconcileArtifacts(nodes []NodeRow) error { + keep := []string{} + for _, n := range nodes { + if n.Labels[0] == LabelArtifact { + keep = append(keep, n.Value) + } + } + q, p := purgeArtifactEdgesQuery(w.root) + if err := w.autoCommit(q, p); err != nil { + return err + } + q, p = releaseVanishedArtifactsQuery(w.root, keep) + return w.autoCommit(q, p) +} + func purgeModuleQuery(moduleID string) (string, map[string]any) { return "MATCH (n:GoCanNode) WHERE n.id = $m OR n.id STARTS WITH $p DETACH DELETE n", map[string]any{"m": moduleID, "p": descendantPrefix(moduleID)} From 59ed9a317d4749c1ae1289bd38c3c45236a5084d Mon Sep 17 00:00:00 2001 From: Rahul Krishna Date: Sun, 29 Nov 2026 17:38:56 -0500 Subject: [PATCH 4/4] feat(cli): capture artifact text by default; --no-artifact-text turns it off --artifact-text was off by default, so a Go push wrote :Artifact without source unless the user asked for it. Python and TypeScript capture the text by default and offer --no-artifact-text. The Go flags now do the same: --artifact-text is on by default (still accepted), and --no-artifact-text keeps the artifact inventory and drops the text. Cost: each text artifact is read a second time and its text is in the output. That is small for normal files; very large text files are #80. Also drops the issue and date tags this branch added to CLAUDE.md (review). Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 9 +++--- README.md | 3 +- cmd/codeanalyzer/main.go | 11 +++++-- cmd/codeanalyzer/main_test.go | 49 +++++++++++++++++++++++++++++++ docs/design/specs/v2-artifacts.md | 7 +++-- internal/options/options.go | 3 +- 6 files changed, 69 insertions(+), 13 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 5f0cb27..ae2663c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -168,8 +168,8 @@ Made with the user in the 2026-11-19 design loop, anchored on `codeanalyzer-pyth - **Scope:** all non-`.go` project files [user, 2026-11-19]. Binaries are metadata only (`source:""`) [user]. - **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:** only with `--artifact-text`, default off [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 (#72) [user, 2026-11-29]. +- **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]. - **Level:** L1, every level, not gated [user]. @@ -240,11 +240,10 @@ shared neutral vocabulary verbatim; never rename a sibling's shared name). Spec: to the siblings, so a sibling analyzer over the same repo converges on the same node. An `--eager` full Bolt push reconciles artifacts with the siblings' claim model (delete the Go-owned edges, release vanished artifacts, delete a node only when no `HAS_ARTIFACT` is - left); the whole-app purge skips `:Artifact`; lazy and `-t` pushes reconcile nothing (#70) - [user, 2026-11-29]. + left); the whole-app purge skips `:Artifact`; lazy and `-t` pushes reconcile nothing. `:Artifact` carries the JSON artifact's fields (`kind`, `path`, `format`, `roles`, `size_bytes`, `sha256`, `source`, `extraction`) and `LOCKS` carries `version`, as Python and - TypeScript write them (#81, #72) [user, 2026-11-29]. + TypeScript write them. The projector emits rows **only for facts the Go analyzer produces** (go.mod deps → `:Package` `pkg:golang/…`); absent facts emit **zero rows** (declared contract, empty projection). `GO_PROVIDES` / `GO_UNRESOLVED_IMPORT` stay `GO_`-prefixed (this analyzer's diff --git a/README.md b/README.md index f063d6d..cf09344 100644 --- a/README.md +++ b/README.md @@ -173,7 +173,7 @@ Flags: -f, --format string Output format: json|msgpack (default "json") --graph-field-depth int Field-path depth bound for L3 dataflow nodes (k limit; applies at -a 3 and -a 4) (default 3) -h, --help help for cango - --artifact-text Capture each text artifact's whole source in analysis.json (default: metadata only) + --artifact-text Capture each text artifact's whole source in the output (default true) -i, --input string Project root to analyze (required) -j, --jobs int Worker parallelism (default: CPU cores) --library-models string JSON file of library stand-in flows overriding the all-to-all default (-a 4 and --emit neo4j only) @@ -181,6 +181,7 @@ Flags: --neo4j-password string Neo4j password (env NEO4J_PASSWORD, default neo4j) --neo4j-uri string Live Bolt push target (env NEO4J_URI); omit to write graph.cypher --neo4j-user string Neo4j username (env NEO4J_USERNAME, default neo4j) + --no-artifact-text Keep the artifact inventory but drop the captured text -o, --output string Output directory for analysis.json (default: stdout) --skip-tests Skip *_test.go files (default true) --strict Fail non-zero on any L4 degradation (default: degrade and record it) diff --git a/cmd/codeanalyzer/main.go b/cmd/codeanalyzer/main.go index 6c2103c..480f391 100644 --- a/cmd/codeanalyzer/main.go +++ b/cmd/codeanalyzer/main.go @@ -47,6 +47,7 @@ func rootCmd() *cobra.Command { targetFiles []string skipTests bool artifactText bool + noArtText bool eager bool cacheDir string jobs int @@ -173,7 +174,7 @@ via CLDK(language="go").analysis(project_path=...).`, AnalyzerVersion: version, TargetFiles: targetFiles, SkipTests: skipTests, - ArtifactText: artifactText, + ArtifactText: artifactText && !noArtText, Eager: eager, CacheDir: cacheDir, Jobs: jobs, @@ -241,8 +242,12 @@ via CLDK(language="go").analysis(project_path=...).`, f.StringSliceVarP(&targetFiles, "target-files", "t", nil, "Restrict analysis to specific files (incremental mode)") f.BoolVar(&skipTests, "skip-tests", true, "Skip *_test.go files") - f.BoolVar(&artifactText, "artifact-text", false, - "Capture each text artifact's whole source in analysis.json (default: metadata only)") + // On by default, as in the Python and TypeScript analyzers; --no-artifact-text + // keeps the artifact inventory and drops the text. + f.BoolVar(&artifactText, "artifact-text", true, + "Capture each text artifact's whole source in the output") + f.BoolVar(&noArtText, "no-artifact-text", false, + "Keep the artifact inventory but drop the captured text") f.BoolVar(&eager, "eager", false, "Force clean rebuild (ignore cache)") f.StringVarP(&cacheDir, "cache-dir", "c", "", "Cache directory (default: ~/.cldk/go-cache)") f.IntVarP(&jobs, "jobs", "j", 0, "Worker parallelism (default: CPU cores)") diff --git a/cmd/codeanalyzer/main_test.go b/cmd/codeanalyzer/main_test.go index 966f28e..b2ec719 100644 --- a/cmd/codeanalyzer/main_test.go +++ b/cmd/codeanalyzer/main_test.go @@ -827,3 +827,52 @@ func TestNamespaceDefaultUsesNormalizedInput(t *testing.T) { t.Fatal(a.Application.ID) } } + +// ── --artifact-text ────────────────────────────────────────────────────────── + +// TestRootCmd_ArtifactTextOnByDefault: the text of a text artifact is captured +// by default and --no-artifact-text turns it off, as in the Python and +// TypeScript analyzers. --artifact-text is still accepted. +func TestRootCmd_ArtifactTextOnByDefault(t *testing.T) { + dir := t.TempDir() + for name, body := range map[string]string{ + "go.mod": "module example.com/at\n\ngo 1.25.0\n", + "main.go": "package main\n\nfunc main() {}\n", + "config.yaml": "port: 8080\n", + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + source := 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 { + Artifacts map[string]struct { + Source string `json:"source"` + } `json:"artifacts"` + } `json:"application"` + } + if err := json.Unmarshal([]byte(out), &doc); err != nil { + t.Fatal(err) + } + return doc.Application.Artifacts["config.yaml"].Source + } + for _, tc := range []struct { + flags []string + want string + }{ + {nil, "port: 8080\n"}, + {[]string{"--artifact-text"}, "port: 8080\n"}, + {[]string{"--no-artifact-text"}, ""}, + {[]string{"--artifact-text=false"}, ""}, + } { + if got := source(t, tc.flags...); got != tc.want { + t.Errorf("%v: config.yaml source = %q, want %q", tc.flags, got, tc.want) + } + } +} diff --git a/docs/design/specs/v2-artifacts.md b/docs/design/specs/v2-artifacts.md index 9cb4485..f75d01b 100644 --- a/docs/design/specs/v2-artifacts.md +++ b/docs/design/specs/v2-artifacts.md @@ -50,12 +50,13 @@ Each decision was made with the user, one question per decision, in the order be | `roles` | string[] | `dependency-manifest` for `go.mod`, `lockfile` for `go.sum`; others only when recognized | | `size_bytes` | int | always | | `sha256` | string | full file hash, always | - | `source` | string | whole file text **only** with `--artifact-text`; otherwise `""` | + | `source` | string | whole file text, unless `--no-artifact-text`; `""` for a binary file | | `extraction` | string | `none` \| `partial` \| `full`; `full` when `source` is set, else `none` | - **Binary files**: metadata only. `format:"binary"`, `size_bytes` and `sha256` set, `source:""` (user decision). -- **`--artifact-text`** (default **off**): when on, `source` carries the whole file text - (user decision). Off keeps default output to metadata. +- **`--artifact-text`** (default **on** [user, 2026-11-29]; it was off before): `source` + carries the whole file text. `--no-artifact-text` keeps the inventory and drops the text. + The flags and the default are the Python and TypeScript analyzers'. - **`config_keys`** is **deferred** (user decision): not emitted in this change. No `:ConfigKey` rows are written. diff --git a/internal/options/options.go b/internal/options/options.go index ebeb300..46e59f3 100644 --- a/internal/options/options.go +++ b/internal/options/options.go @@ -57,7 +57,8 @@ type AnalysisOptions struct { TargetFiles []string // SkipTests skips test files (files ending in _test.go). SkipTests bool - // ArtifactText captures each text artifact's whole source (--artifact-text). + // ArtifactText captures each text artifact's whole source. The CLI sets it by + // default; --no-artifact-text clears it. // Off by default: artifacts carry metadata only. ArtifactText bool // Eager forces a clean rebuild ignoring any cache.