From 75e0411ac60a36bee310bfd43514601680016ad1 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Thu, 19 Nov 2026 21:35:55 -0500 Subject: [PATCH 01/21] docs(design): repository-artifact and dependency datamodel for schema v2 Spec and CLAUDE.md schema decisions from the design loop: application.artifacts (all non-.go files, metadata-first, --artifact-text opt-in), can:///artifact ids, version-less pkg:golang package ids, go.mod requires as dependencies with go.sum locks, L1 at every level. Config keys deferred. Co-Authored-By: Claude Haiku 5.5 --- CLAUDE.md | 11 +++ docs/design/specs/v2-artifacts.md | 131 ++++++++++++++++++++++++++++++ 2 files changed, 142 insertions(+) create mode 100644 docs/design/specs/v2-artifacts.md diff --git a/CLAUDE.md b/CLAUDE.md index f4425d4..9091930 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -129,6 +129,17 @@ Reuses Group A ids/spans and the L3 vocabulary unchanged; every L4 fact is an ad - A Go-specific `select` cfg kind was not added (`select` is a `switch` with `switch_case` edges). +### Repository-artifact decisions (spec `docs/design/specs/v2-artifacts.md`, branch `feat/artifacts`) +Made with the user in the 2026-11-19 design loop, anchored on `codeanalyzer-python`'s `PyArtifact` / `PyDependency`. +- **Placement:** `application.artifacts{: artifact}` (map); `application.dependencies[]` (list). +- **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]. +- **`provides_imports`:** longest-prefix match against `go.mod` module paths [user]. +- **Level:** L1, every level, not gated [user]. + ## Neo4j-projection decisions The graph projection (`--emit neo4j`) is a **second projection of the same v2 envelope**, diff --git a/docs/design/specs/v2-artifacts.md b/docs/design/specs/v2-artifacts.md new file mode 100644 index 0000000..b06bfe8 --- /dev/null +++ b/docs/design/specs/v2-artifacts.md @@ -0,0 +1,131 @@ +# Spec: repository artifacts and dependencies (codeanalyzer-go) + +> **Cross-repo spec.** Canonical home is `codellm-devkit/.github → docs/design/specs/`, +> beside the coordinating parent issue. Staged locally on `feat/artifacts` until that repo +> is available (same precedent as `v2-l1-emission.md`). This is the design transcript of the +> datamodel loop, linked from the tracking record, not pasted into it. + +## Contract-Impact Triage + +**Does this change schema v2 output?** Yes. It adds two application-scoped fields +(`artifacts`, `dependencies`), new id shapes for artifact and package nodes, one new CLI flag +(`--artifact-text`), and populates the already-declared Neo4j neutral layer (`:Artifact`, +`:Package`, `HAS_ARTIFACT`, `DECLARES_DEPENDENCY`, `LOCKS`). + +| Change type | Analyzers | SDKs | Docs | +| --- | --- | --- | --- | +| Schema v2 evolution (additive) | **codeanalyzer-go** (emit + projector); codeanalyzer-python: none (parity adopted, no id change) | **python-sdk** (Go backend reconstruction of `:Artifact` / `:Package`) | `CLAUDE.md` § Schema decisions, this spec | + +Anchor: `codeanalyzer-python` already emits this layer (`PyArtifact`, `PyDependency`, +`PyConfigKey`, `application.artifacts`, `application.dependencies`, +`codeanalyzer/schema/py_schema.py`), and `python-sdk/cldk/analysis/commons/artifacts.py` +rebuilds it from Neo4j, with the neutral labels shared across analyzers. + +## Problem + +The v2 schema and projector declare the neutral repository-artifact layer, but the Go +analyzer never populates it. `go.mod` is read only for `go mod download`. Against the Go +analysis of `microservices-demo/src/frontend`, `MATCH (n:Artifact)` returns 0 rows. + +## Design-loop decisions (the transcript) + +Each decision was made with the user, one question per decision, in the order below. + +### Application placement +- **`application.artifacts`** is a **map keyed by repo-relative path**, as Python does. Stays + reachable from `application` by containment (keystone rule). +- **`application.dependencies`** is a **list** (Python parity). + +### Artifact scope and fields +- **Scope: all non-`.go` project files** (user decision, broader than the recommended manifests-only + scope). `.go` files are modules, not artifacts. Directories `.git/` and `vendor/` are excluded + (implementation default, see Open items). +- **Artifact fields** (Python `PyArtifact` parity): + | field | type | notes | + | --- | --- | --- | + | `id` | string | `can:///artifact/` | + | `kind` | string | `"artifact"` | + | `path` | string | repo-relative POSIX path (also the map key) | + | `format` | string | `toml\|yaml\|json\|ini\|properties\|requirements\|dockerfile\|text\|binary`, plus Go's `gomod` / `gosum` (Open items) | + | `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 `""` | + | `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. +- **`config_keys`** is **deferred** (user decision): not emitted in this change. No + `:ConfigKey` rows are written. + +### Artifact id +- **`can:///artifact/`** (Python parity, user decision). App-scoped, so the + projector's `can:////` prefix scoping covers artifact nodes. This changes the + Go projector's `:Artifact` flag to `CanNode=true`; the current Go schema comment ("neutral, + not a can:// id") is superseded. + +### Package and dependencies +- **Package id: version-less `pkg:golang/`** (user decision), for example + `pkg:golang/github.com/gorilla/mux`. Mirrors Python's `pkg:pypi/`. The version lives + on the edge and the record, so every dependent app converges on one `:Package`. +- **Dependency records come from every `go.mod` `require`** (user decision). Direct and + indirect entries alike. + | field | source | + | --- | --- | + | `name` | module path | + | `ecosystem` | `"golang"` | + | `spec` | version in `go.mod` (for example `v1.8.0`) | + | `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 | + | `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` | +- **`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). + +### Analysis level +- **L1, every level** (user decision). Parse-only facts, identical at `-a 1` through `-a 4`. + 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`. +- `DECLARES_DEPENDENCY` `(:Artifact)→(:Package)`, `_k = kind` (`runtime`), carrying `spec`, + `direct`, `prov` as properties. +- `LOCKS` `(:Artifact)→(:Package)` from `go.sum`, carrying `locked_version`. +- No `:ConfigKey` rows and no `DEFINES_CONFIG` rows in this change. + +## Open items (flagged for review, not asked) + +These are defaults I chose while writing the spec. Confirm them during review: + +1. **`format` values for go.mod and go.sum.** I used `gomod` and `gosum`, because the Python + enum has no Go case. The alternative is `text`. +2. **Excluded directories.** `.git/` and `vendor/` are skipped. `vendor/` is third-party + source, not project configuration. +3. **Imports with no matching requirement.** Not recorded. They are `unresolved_imports` in + Python. That field is deferred with the repository-provenance field. +4. **`locked_version` when `go.sum` has several lines for one module** (the `h1:` and + `/go.mod` hashes). Take the version common to both lines; error if they disagree. + +## Consumers + +- **codeanalyzer-go**: emits the fields; the projector writes the rows above. Tests: a fixture + with `go.mod` and `go.sum`, a projector test for the new rows, and a `--artifact-text` + on/off test. +- **python-sdk**: the Go backend reads `:Artifact` / `:Package` through the shared + `cldk/analysis/commons/artifacts.py` reconstructors. The Go backend needs its artifact getters + added. Scope of that rung is decided at decomposition. + +## Out of scope (deferred) + +- Config keys and `DEFINES_CONFIG` (user decision). +- `unresolved_imports`, repository provenance (`repository`), `config_uses`. +- Codeanalyzer-python: no change. From cf2cab1ab626901c59070d0c5421f78f50c86d6c Mon Sep 17 00:00:00 2001 From: lambertpw Date: Thu, 19 Nov 2026 22:08:12 -0500 Subject: [PATCH 02/21] feat(artifacts): emit repository artifacts and go.mod dependencies at L1 Adds application.artifacts (every non-.go project file: format, roles, size, sha256; source only with --artifact-text) and application.dependencies (go.mod requires with direct, locked_version from go.sum, provides_imports by longest prefix). The Neo4j projector writes :Artifact (app-scoped), :Package (pkg:golang/), HAS_ARTIFACT, DECLARES_DEPENDENCY and LOCKS. Config keys are deferred. Refs codellm-devkit/codeanalyzer-go#45 Co-Authored-By: Claude Haiku 5.5 --- README.md | 1 + cmd/codeanalyzer/main.go | 4 + docs/design/specs/v2-artifacts.md | 24 ++ internal/core/analyzer.go | 20 ++ internal/core/repository_test.go | 109 +++++++ internal/neo4j/project.go | 44 +++ internal/neo4j/repository_test.go | 97 ++++++ internal/neo4j/schema.go | 13 +- internal/options/options.go | 3 + internal/repository/repository.go | 279 ++++++++++++++++++ internal/repository/repository_test.go | 235 +++++++++++++++ internal/schema/schema.go | 38 +++ internal/schema/v2/schema.go | 34 +++ internal/syntactic_analysis/v2emit/emit.go | 1 + .../syntactic_analysis/v2emit/repository.go | 57 ++++ 15 files changed, 954 insertions(+), 5 deletions(-) create mode 100644 internal/core/repository_test.go create mode 100644 internal/neo4j/repository_test.go create mode 100644 internal/repository/repository.go create mode 100644 internal/repository/repository_test.go create mode 100644 internal/syntactic_analysis/v2emit/repository.go diff --git a/README.md b/README.md index 0d61c82..f063d6d 100644 --- a/README.md +++ b/README.md @@ -173,6 +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) -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) diff --git a/cmd/codeanalyzer/main.go b/cmd/codeanalyzer/main.go index d2b5379..3cceee3 100644 --- a/cmd/codeanalyzer/main.go +++ b/cmd/codeanalyzer/main.go @@ -46,6 +46,7 @@ func rootCmd() *cobra.Command { libraryModels string targetFiles []string skipTests bool + artifactText bool eager bool cacheDir string jobs int @@ -172,6 +173,7 @@ via CLDK(language="go").analysis(project_path=...).`, AnalyzerVersion: version, TargetFiles: targetFiles, SkipTests: skipTests, + ArtifactText: artifactText, Eager: eager, CacheDir: cacheDir, Jobs: jobs, @@ -238,6 +240,8 @@ 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)") 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/docs/design/specs/v2-artifacts.md b/docs/design/specs/v2-artifacts.md index b06bfe8..6d8ed76 100644 --- a/docs/design/specs/v2-artifacts.md +++ b/docs/design/specs/v2-artifacts.md @@ -115,6 +115,30 @@ These are defaults I chose while writing the spec. Confirm them during review: 4. **`locked_version` when `go.sum` has several lines for one module** (the `h1:` and `/go.mod` hashes). Take the version common to both lines; error if they disagree. +## Resolution (implementation, branch `feat/artifacts`) + +The open items were resolved with the defaults below. Two are deviations from the wording +above, marked **(deviation)**: + +1. **`format`**: `gomod` for `go.mod`, `gosum` for `go.sum`, adopted. +2. **Excluded directories**: `.git/` and `vendor/` are skipped at any depth. The tool's own + outputs are also skipped when they sit in the project: `analysis.json` and `graph.cypher` + in the `-o` directory, and the `-c` cache subtree. Without this, a run that writes into the + project would capture the previous run's output. +3. **Unrecorded imports**: an import matching no `go.mod` requirement is not recorded. +4. **Locked version (deviation)**: a requirement is locked only when go.sum has **both** the + `h1:` and the `/go.mod` line for the exact required version. A version with only one line + is left unlocked (`locked_version` absent, `prov` without `lockfile`), with no error. A + disagreement cannot arise, since the lookup is keyed by the required version. +5. **Artifact id root (deviation)**: the code's grammar is `can:////…`, the + same root every other node uses, so an artifact id is + `can:////artifact/`. The `can:///artifact/` form in the + decisions above is shorthand for that root. + +Also decided at implementation: `source` is omitted from JSON when empty (`omitempty`), not +written as `""`; only the root `go.mod` contributes dependencies (nested modules are artifacts +only); `dependencies` is absent when there is no root `go.mod`. + ## Consumers - **codeanalyzer-go**: emits the fields; the projector writes the rows above. Tests: a fixture diff --git a/internal/core/analyzer.go b/internal/core/analyzer.go index a82ac2c..b9dbf34 100644 --- a/internal/core/analyzer.go +++ b/internal/core/analyzer.go @@ -32,6 +32,7 @@ import ( "github.com/codellm-devkit/codeanalyzer-go/internal/analysis" "github.com/codellm-devkit/codeanalyzer-go/internal/dataflow" "github.com/codellm-devkit/codeanalyzer-go/internal/options" + "github.com/codellm-devkit/codeanalyzer-go/internal/repository" "github.com/codellm-devkit/codeanalyzer-go/internal/schema" "github.com/codellm-devkit/codeanalyzer-go/internal/sdg" "github.com/codellm-devkit/codeanalyzer-go/internal/semantic_analysis" @@ -93,6 +94,25 @@ func New(opts options.AnalysisOptions) *Analyzer { // Analyze runs the full analysis pipeline and returns a GoApplication. func (a *Analyzer) Analyze() (*schema.GoApplication, error) { + app, err := a.analyze() + if err != nil { + return nil, err + } + // The repository layer reads files outside the Go source, so it is computed + // on every run, after the (possibly cached) application is ready. + facts, err := repository.Facts(a.opts.InputPath, app, repository.Options{ + CaptureText: a.opts.ArtifactText, + OutputDir: a.opts.OutputDir, + CacheDir: a.opts.CacheDir, + }) + if err != nil { + return nil, fmt.Errorf("repository layer: %w", err) + } + app.Repository = facts + return app, nil +} + +func (a *Analyzer) analyze() (*schema.GoApplication, error) { if _, err := resolveIdentity(a.opts); err != nil { return nil, err } diff --git a/internal/core/repository_test.go b/internal/core/repository_test.go new file mode 100644 index 0000000..1f72580 --- /dev/null +++ b/internal/core/repository_test.go @@ -0,0 +1,109 @@ +package core_test + +import ( + "encoding/json" + "os" + "path/filepath" + "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" +) + +// repoProject is a Go module with no requires (so no network materialization), +// one .go file, and two non-.go files. +func repoProject(t *testing.T) string { + t.Helper() + dir := t.TempDir() + files := map[string]string{ + "go.mod": "module example.com/repoapp\n\ngo 1.25.0\n", + "go.sum": "", + "main.go": "package main\n\nfunc main() {}\n", + "README.md": "# repo app\n", + } + for rel, content := range files { + if err := os.WriteFile(filepath.Join(dir, rel), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + return dir +} + +// emitJSON runs Analyze at level 1 and returns the v2 analysis.json bytes. +func emitJSON(t *testing.T, dir string, artifactText bool) []byte { + t.Helper() + opts := options.AnalysisOptions{ + InputPath: dir, AppName: "repoapp", Level: options.LevelSymbolTable, + SkipTests: true, CacheDir: t.TempDir(), OutputDir: t.TempDir(), ArtifactText: artifactText, + } + app, err := core.New(opts).Analyze() + if err != nil { + t.Fatal(err) + } + identity, err := v2.ResolveIdentity("repoapp", nil) + if err != nil { + t.Fatal(err) + } + payload := v2emit.Emit(app, identity, dir, int(opts.Level), "test", 0, nil, nil) + out, err := json.Marshal(payload) + if err != nil { + t.Fatal(err) + } + return out +} + +func TestAnalyze_ArtifactsDefaultMetadataOnly(t *testing.T) { + dir := repoProject(t) + var doc struct { + Application struct { + Artifacts map[string]v2.Artifact `json:"artifacts"` + } `json:"application"` + } + if err := json.Unmarshal(emitJSON(t, dir, false), &doc); err != nil { + t.Fatal(err) + } + art, ok := doc.Application.Artifacts["README.md"] + if !ok { + t.Fatalf("README.md missing from artifacts: %v", doc.Application.Artifacts) + } + if art.ID != "can://repoapp/repoapp/artifact/README.md" { + t.Errorf("artifact id = %q", art.ID) + } + if art.Format != "text" || art.Extraction != "none" || art.Source != "" { + t.Errorf("default artifact should be metadata only: %+v", art) + } + if _, ok := doc.Application.Artifacts["main.go"]; ok { + t.Errorf("a .go file became an artifact") + } +} + +func TestAnalyze_ArtifactTextCapturesSource(t *testing.T) { + dir := repoProject(t) + var doc struct { + Application struct { + Artifacts map[string]v2.Artifact `json:"artifacts"` + } `json:"application"` + } + if err := json.Unmarshal(emitJSON(t, dir, true), &doc); err != nil { + t.Fatal(err) + } + art := doc.Application.Artifacts["README.md"] + if art.Source != "# repo app\n" || art.Extraction != "full" { + t.Errorf("--artifact-text: source/extraction = %q/%q", art.Source, art.Extraction) + } + mod := doc.Application.Artifacts["go.mod"] + if mod.Format != "gomod" || len(mod.Roles) != 1 || mod.Roles[0] != "dependency-manifest" { + t.Errorf("go.mod artifact = %+v", mod) + } +} + +func TestAnalyze_ArtifactsReproducibleAcrossRuns(t *testing.T) { + dir := repoProject(t) + a := emitJSON(t, dir, false) + b := emitJSON(t, dir, false) + if string(a) != string(b) { + t.Errorf("two runs over the same project differ") + } +} diff --git a/internal/neo4j/project.go b/internal/neo4j/project.go index 78fde41..04111d1 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -2,6 +2,7 @@ package neo4j import ( "encoding/json" + "sort" "strings" v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" @@ -33,6 +34,7 @@ func Project(a *v2.Analysis) GraphRows { declared: collectDeclaredIDs(a), } p.projectApplication() + p.projectRepository() for _, mod := range a.Application.SymbolTable { p.projectModule(mod) } @@ -84,6 +86,48 @@ func (p *projector) appRef() NodeRef { return NodeRef{Label: LabelApplication, KeyProp: "id", Value: p.analysis.Application.ID} } +// ─── repository layer (spec v2-artifacts) ──────────────────────────────────── + +// projectRepository writes the artifact and dependency rows. An artifact is an +// app-scoped node (its id is a can:// id) hung off the application; a dependency +// is a neutral :Package keyed by its version-less purl, declared by the go.mod +// artifact and, when go.sum locks it, locked by the go.sum artifact. +func (p *projector) projectRepository() { + arts := p.analysis.Application.Artifacts + paths := make([]string, 0, len(arts)) + for path := range arts { + paths = append(paths, path) + } + sort.Strings(paths) + for _, path := range paths { + art := arts[path] + ref := p.b.Node( + []string{LabelArtifact, MarkerLabel}, + "id", art.ID, + Props{"path": art.Path, "format": art.Format}, + "", // 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, + 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}, "") + } + } +} + // ─── module ────────────────────────────────────────────────────────────────── func (p *projector) projectModule(m v2.Module) { diff --git a/internal/neo4j/repository_test.go b/internal/neo4j/repository_test.go new file mode 100644 index 0000000..b2554f6 --- /dev/null +++ b/internal/neo4j/repository_test.go @@ -0,0 +1,97 @@ +package neo4j + +import ( + "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). +func repoAnalysis() *v2.Analysis { + const app = "can://frontend/frontend" + goMod := app + "/artifact/go.mod" + goSum := app + "/artifact/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"}}, + }, + 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"}}, + {Name: "golang.org/x/text", Ecosystem: "golang", Spec: "v0.14.0", Kind: "runtime", Direct: false, + DeclaredIn: goMod, Prov: []string{"declared"}}, + }, + }, + } +} + +func TestProject_RepositoryLayerRows(t *testing.T) { + rows := Project(repoAnalysis()) + + nodes := map[string]NodeRow{} + for _, n := range rows.Nodes { + nodes[n.Value] = n + } + + goMod := nodes["can://frontend/frontend/artifact/go.mod"] + if !hasLabel(goMod, LabelArtifact) || !hasLabel(goMod, MarkerLabel) { + t.Errorf("artifact node labels = %v, want Artifact + %s (app-scoped)", goMod.Labels, MarkerLabel) + } + mux := nodes["pkg:golang/github.com/gorilla/mux"] + if !hasLabel(mux, LabelPackage) || hasLabel(mux, MarkerLabel) { + t.Errorf("package node labels = %v, want Package only (neutral, no marker)", mux.Labels) + } + + edges := map[string][]EdgeRow{} + 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])) + } + + decl := edges[RelDeclaresDependency] + if len(decl) != 2 { + t.Fatalf("DECLARES_DEPENDENCY edges = %d, want 2", 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) + } + } + + locks := edges[RelLocks] + if len(locks) != 1 { + t.Fatalf("LOCKS edges = %d, want 1 (only the locked dependency)", len(locks)) + } + 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]) + } +} + +func TestProject_NoRepositoryLayerEmitsNoRows(t *testing.T) { + a := repoAnalysis() + a.Application.Artifacts, a.Application.Dependencies = nil, nil + rows := Project(a) + for _, n := range rows.Nodes { + if hasLabel(n, LabelArtifact) || hasLabel(n, LabelPackage) { + t.Errorf("repository node %v emitted without facts", n.Labels) + } + } + for _, e := range rows.Edges { + switch e.Type { + case RelHasArtifact, RelDeclaresDependency, RelLocks: + t.Errorf("repository edge %s emitted without facts", e.Type) + } + } +} diff --git a/internal/neo4j/schema.go b/internal/neo4j/schema.go index 18853b4..274d39d 100644 --- a/internal/neo4j/schema.go +++ b/internal/neo4j/schema.go @@ -227,12 +227,15 @@ var Nodes = []NodeSpec{ Props: []string{"name", "path", "signature", "module"}, }, - // Neutral layer. Keyed by own id (not a can:// id), so NO marker label and - // outside prefix scoping — a sibling analyzer converges on the same node. + // Repository layer. An artifact id is can:////artifact/ + // (spec v2-artifacts, Python parity), so it is app-scoped: it carries the + // :GoCanNode marker and falls under the prefix scope on wipe. { - Label: LabelArtifact, MergeLabel: LabelArtifact, Key: "id", CanNode: false, + Label: LabelArtifact, MergeLabel: LabelArtifact, Key: "id", CanNode: true, Props: []string{"path", "format"}, }, + // 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. { Label: LabelPackage, MergeLabel: LabelPackage, Key: "id", CanNode: false, Props: []string{"ecosystem", "name"}, @@ -265,8 +268,8 @@ var Rels = []RelSpec{ // Repository layer. {Type: RelHasArtifact, From: []string{LabelApplication}, To: []string{LabelArtifact}}, - {Type: RelDeclaresDependency, From: []string{LabelArtifact}, To: []string{LabelPackage}, Discriminant: "kind"}, - {Type: RelLocks, From: []string{LabelArtifact}, To: []string{LabelPackage}}, + {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: RelDefinesConfig, From: []string{LabelArtifact}, To: []string{LabelConfigKey}}, {Type: RelProvides, From: []string{LabelPackage}, To: []string{LabelExternal}}, {Type: RelUnresolvedImport, From: []string{LabelApplication}, To: []string{LabelExternal}}, diff --git a/internal/options/options.go b/internal/options/options.go index 13f0af9..ebeb300 100644 --- a/internal/options/options.go +++ b/internal/options/options.go @@ -57,6 +57,9 @@ 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). + // Off by default: artifacts carry metadata only. + ArtifactText bool // Eager forces a clean rebuild ignoring any cache. Eager bool // CacheDir is where per-file caches and intermediate data are stored. diff --git a/internal/repository/repository.go b/internal/repository/repository.go new file mode 100644 index 0000000..45906d1 --- /dev/null +++ b/internal/repository/repository.go @@ -0,0 +1,279 @@ +// Package repository collects the repository-artifact layer (spec +// docs/design/specs/v2-artifacts.md): every non-.go project file as an artifact, +// and the go.mod requires as dependencies, with go.sum supplying locked versions. +// +// It reads files outside the Go source the symbol table sees, so it runs on every +// analysis (never from the cache) and is independent of the analysis level. +package repository + +import ( + "bytes" + "crypto/sha256" + "encoding/hex" + "fmt" + "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" + "golang.org/x/mod/modfile" +) + +// Ecosystem is the purl type used for Go modules (pkg:golang/). +const Ecosystem = "golang" + +// Options controls discovery. +type Options struct { + // CaptureText puts each text artifact's whole source into Source (--artifact-text). + CaptureText bool + // OutputDir and CacheDir are the tool's own output locations. When either lies + // inside the project, its files are not artifacts: a run that writes analysis.json + // into the project must not capture the previous run's output. + OutputDir string + CacheDir string +} + +// skipDirNames are directories never walked: VCS metadata and vendored third-party code. +var skipDirNames = map[string]bool{".git": true, "vendor": true} + +// outputFileNames are the files this tool writes into OutputDir. +var outputFileNames = map[string]bool{"analysis.json": true, "graph.cypher": true} + +// 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. +func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { + absRoot, err := filepath.Abs(root) + if err != nil { + return nil, 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 { + return werr + } + if d.IsDir() { + if p != absRoot && (skipDirNames[d.Name()] || (cacheDir != "" && p == cacheDir)) { + return filepath.SkipDir + } + return nil + } + if !d.Type().IsRegular() || strings.HasSuffix(d.Name(), ".go") { + return nil + } + if outDir != "" && filepath.Dir(p) == outDir && outputFileNames[d.Name()] { + return nil + } + rel, err := filepath.Rel(absRoot, p) + if err != nil { + return err + } + art, err := readArtifact(p, filepath.ToSlash(rel), opts.CaptureText) + if err != nil { + return err + } + out[art.Path] = art + return nil + }) + if err != nil { + return nil, fmt.Errorf("artifact discovery: %w", err) + } + return out, nil +} + +func absOrEmpty(p string) string { + if p == "" { + return "" + } + abs, err := filepath.Abs(p) + if err != nil { + return "" + } + return abs +} + +// 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) + if err != nil { + return schema.GoArtifact{}, err + } + sum := sha256.Sum256(data) + art := schema.GoArtifact{ + Path: rel, + Format: formatOf(rel, data), + SizeBytes: int64(len(data)), + SHA256: hex.EncodeToString(sum[:]), + Extraction: "none", + } + switch rel { + case "go.mod": + art.Roles = []string{"dependency-manifest"} + case "go.sum": + art.Roles = []string{"lockfile"} + } + if captureText && art.Format != "binary" { + art.Source = string(data) + 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 { + base := filepath.Base(rel) + switch { + case base == "go.mod": + return "gomod" + case base == "go.sum": + return "gosum" + 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" + case ".yaml", ".yml": + return "yaml" + case ".json": + return "json" + case ".ini", ".cfg": + return "ini" + case ".properties": + return "properties" + } + return "text" +} + +// Facts builds the repository layer for a project: its artifacts, and the +// dependencies declared by the root go.mod. imports are the project's import +// paths (from the symbol table), used to fill provides_imports. +func Facts(root string, app *schema.GoApplication, opts Options) (*schema.RepositoryFacts, error) { + artifacts, err := Discover(root, opts) + if err != nil { + return nil, err + } + facts := &schema.RepositoryFacts{Artifacts: artifacts} + modPath := filepath.Join(root, "go.mod") + modData, err := os.ReadFile(modPath) + if err != nil { + // No root go.mod: artifacts only, no dependencies. + return facts, nil + } + f, err := modfile.Parse("go.mod", modData, nil) + if err != nil { + utils.Warn("repository: go.mod does not parse, dependencies skipped: %v", err) + return facts, nil + } + locked := parseGoSum(filepath.Join(root, "go.sum")) + imports := projectImports(app) + + deps := make([]schema.GoDependency, 0, len(f.Require)) + for _, r := range f.Require { + dep := schema.GoDependency{ + Name: r.Mod.Path, + Ecosystem: Ecosystem, + Spec: r.Mod.Version, + Kind: "runtime", + Direct: !r.Indirect, + DeclaredIn: "go.mod", + Prov: []string{"declared"}, + } + if locked[r.Mod.Path][r.Mod.Version] { + dep.LockedVersion = r.Mod.Version + dep.Prov = append(dep.Prov, "lockfile") + } + deps = append(deps, dep) + } + sort.Slice(deps, func(i, j int) bool { return deps[i].Name < deps[j].Name }) + assignImports(deps, imports) + facts.Dependencies = deps + return facts, nil +} + +// 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. +func parseGoSum(path string) map[string]map[string]bool { + type seen struct{ h1, gomod bool } + entries := map[string]map[string]*seen{} + data, err := os.ReadFile(path) + if err != nil { + return map[string]map[string]bool{} + } + for _, line := range strings.Split(string(data), "\n") { + fields := strings.Fields(line) + if len(fields) != 3 { + continue + } + mod, ver := fields[0], fields[1] + gomod := strings.HasSuffix(ver, "/go.mod") + ver = strings.TrimSuffix(ver, "/go.mod") + if entries[mod] == nil { + entries[mod] = map[string]*seen{} + } + if entries[mod][ver] == nil { + entries[mod][ver] = &seen{} + } + if gomod { + entries[mod][ver].gomod = true + } else { + entries[mod][ver].h1 = true + } + } + out := map[string]map[string]bool{} + for mod, vers := range entries { + out[mod] = map[string]bool{} + for ver, s := range vers { + out[mod][ver] = s.h1 && s.gomod + } + } + return out +} + +// 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. +func projectImports(app *schema.GoApplication) []string { + seen := map[string]bool{} + for _, f := range app.SymbolTable { + for _, imp := range f.Imports { + seen[imp.Module] = true + } + } + out := make([]string, 0, len(seen)) + for p := range seen { + out = append(out, p) + } + sort.Strings(out) + return out +} + +// assignImports gives each import to the dependency whose module path is its +// longest prefix (the path itself, or a path under it followed by "/"). An +// import matching no requirement is not recorded. +func assignImports(deps []schema.GoDependency, imports []string) { + for _, imp := range imports { + best := -1 + bestLen := -1 + for i, d := range deps { + if (imp == d.Name || strings.HasPrefix(imp, d.Name+"/")) && len(d.Name) > bestLen { + best, bestLen = i, len(d.Name) + } + } + if best >= 0 { + deps[best].ProvidesImports = append(deps[best].ProvidesImports, imp) + } + } +} diff --git a/internal/repository/repository_test.go b/internal/repository/repository_test.go new file mode 100644 index 0000000..0c048ef --- /dev/null +++ b/internal/repository/repository_test.go @@ -0,0 +1,235 @@ +package repository + +import ( + "os" + "path/filepath" + "reflect" + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" +) + +// writeTree creates the files under root (path → content). A NUL in content +// makes a file binary. +func writeTree(t *testing.T, root string, files map[string]string) { + t.Helper() + for rel, content := range files { + p := filepath.Join(root, filepath.FromSlash(rel)) + if err := os.MkdirAll(filepath.Dir(p), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(p, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } +} + +// appWithImports is a symbol-table stub carrying the given import paths in one file. +func appWithImports(paths ...string) *schema.GoApplication { + imps := make([]schema.GoImport, 0, len(paths)) + for _, p := range paths { + imps = append(imps, schema.GoImport{Module: p}) + } + return &schema.GoApplication{SymbolTable: map[string]schema.GoFile{"main.go": {Imports: imps}}} +} + +const goMod = `module example.com/app + +go 1.25.0 + +require ( + cloud.google.com/go v0.1.0 + cloud.google.com/go/auth v0.2.0 + github.com/gorilla/mux v1.8.0 + golang.org/x/text v0.14.0 // indirect +) +` + +// go.sum: mux has both lines for its version (locked); auth too; cloud.google.com/go +// has only its h1 line (not locked); x/text has only its /go.mod line (not locked). +const goSum = `cloud.google.com/go v0.1.0 h1:AAA= +cloud.google.com/go/auth v0.2.0 h1:BBB= +cloud.google.com/go/auth v0.2.0/go.mod h1:CCC= +github.com/gorilla/mux v1.8.0 h1:DDD= +github.com/gorilla/mux v1.8.0/go.mod h1:EEE= +golang.org/x/text v0.14.0/go.mod h1:FFF= +` + +func TestFacts_DependenciesLocksAndImports(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{"go.mod": goMod, "go.sum": goSum, "main.go": "package main\n"}) + + facts, err := Facts(root, appWithImports( + "github.com/gorilla/mux", + "cloud.google.com/go/auth/credentials", // longest prefix: cloud.google.com/go/auth + "cloud.google.com/go/storage", // only cloud.google.com/go matches + "fmt", // stdlib: no requirement + ), Options{}) + if err != nil { + t.Fatal(err) + } + + want := []schema.GoDependency{ + {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"}, + 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"}, + 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"}}, + } + if !reflect.DeepEqual(facts.Dependencies, want) { + t.Errorf("dependencies:\n got %+v\n want %+v", facts.Dependencies, want) + } +} + +func TestFacts_ArtifactsClassifiedAndSkipped(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{ + "go.mod": goMod, + "go.sum": goSum, + "main.go": "package main\n", + "main_test.go": "package main\n", + "Dockerfile": "FROM scratch\n", + "config/app.yaml": "a: 1\n", + "config/settings.env": "KEY=value\n", + "blob.dat": "ab\x00cd", + ".git/HEAD": "ref: refs/heads/main\n", + "vendor/x/y.txt": "vendored\n", + }) + + facts, err := Facts(root, appWithImports(), Options{}) + if err != nil { + t.Fatal(err) + } + got := map[string]schema.GoArtifact{} + for p, a := range facts.Artifacts { + got[p] = a + } + wantFormats := map[string]string{ + "go.mod": "gomod", + "go.sum": "gosum", + "Dockerfile": "dockerfile", + "config/app.yaml": "yaml", + "config/settings.env": "text", + "blob.dat": "binary", + } + if len(got) != len(wantFormats) { + t.Errorf("artifacts = %v, want exactly %v", keys(got), keys(wantFormats)) + } + for p, f := range wantFormats { + a, ok := got[p] + if !ok { + t.Errorf("missing artifact %s", p) + continue + } + if a.Format != f { + t.Errorf("%s format = %q, want %q", p, a.Format, f) + } + if a.Extraction != "none" || a.Source != "" { + t.Errorf("%s captured source without --artifact-text: %+v", p, a) + } + if len(a.SHA256) != 64 { + t.Errorf("%s sha256 = %q, want 64 hex chars", p, a.SHA256) + } + } + if r := got["go.mod"].Roles; !reflect.DeepEqual(r, []string{"dependency-manifest"}) { + t.Errorf("go.mod roles = %v", r) + } + if r := got["go.sum"].Roles; !reflect.DeepEqual(r, []string{"lockfile"}) { + t.Errorf("go.sum roles = %v", r) + } +} + +func TestDiscover_CaptureTextOnlyForText(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{"go.mod": goMod, "blob.dat": "ab\x00cd"}) + + on, err := Discover(root, Options{CaptureText: true}) + if err != nil { + t.Fatal(err) + } + if on["go.mod"].Source != goMod || on["go.mod"].Extraction != "full" { + t.Errorf("go.mod with --artifact-text: source/extraction = %q/%q", on["go.mod"].Source, on["go.mod"].Extraction) + } + if on["blob.dat"].Source != "" || on["blob.dat"].Extraction != "none" { + t.Errorf("binary captured source: %+v", on["blob.dat"]) + } +} + +func TestDiscover_ExcludesOwnOutputsAndCache(t *testing.T) { + root := t.TempDir() + cache := filepath.Join(root, "cache") + writeTree(t, root, map[string]string{ + "README.md": "# app\n", + "analysis.json": "{}", + "graph.cypher": "CREATE;", + "cache/entry.bin": "x\x00", + "notes/analysis.json": "{}", // not the output dir: kept + }) + + got, err := Discover(root, Options{OutputDir: root, CacheDir: cache}) + if err != nil { + t.Fatal(err) + } + if _, ok := got["analysis.json"]; ok { + t.Errorf("own output analysis.json was captured") + } + if _, ok := got["graph.cypher"]; ok { + t.Errorf("own output graph.cypher was captured") + } + if _, ok := got["cache/entry.bin"]; ok { + t.Errorf("cache subtree was captured") + } + if _, ok := got["notes/analysis.json"]; !ok { + t.Errorf("unrelated notes/analysis.json was wrongly excluded") + } + if _, ok := got["README.md"]; !ok { + t.Errorf("README.md missing") + } +} + +func TestFacts_NoGoModMeansArtifactsOnly(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{"Dockerfile": "FROM scratch\n"}) + + facts, err := Facts(root, appWithImports("fmt"), Options{}) + if err != nil { + t.Fatal(err) + } + if len(facts.Dependencies) != 0 { + t.Errorf("dependencies without go.mod: %+v", facts.Dependencies) + } + if _, ok := facts.Artifacts["Dockerfile"]; !ok { + t.Errorf("Dockerfile artifact missing") + } +} + +func TestParseGoSum_OnlyFullPairsLock(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{"go.sum": goSum}) + got := parseGoSum(filepath.Join(root, "go.sum")) + if !got["github.com/gorilla/mux"]["v1.8.0"] { + t.Errorf("mux v1.8.0 has both lines; want locked") + } + if got["cloud.google.com/go"]["v0.1.0"] { + t.Errorf("cloud.google.com/go has only h1; want not locked") + } + if got["golang.org/x/text"]["v0.14.0"] { + t.Errorf("golang.org/x/text has only /go.mod; want not locked") + } + if n := len(parseGoSum(filepath.Join(root, "absent"))); n != 0 { + t.Errorf("missing go.sum locked %d modules", n) + } +} + +func keys[V any](m map[string]V) []string { + out := make([]string, 0, len(m)) + for k := range m { + out = append(out, k) + } + return out +} diff --git a/internal/schema/schema.go b/internal/schema/schema.go index 84335d5..99bf2c2 100644 --- a/internal/schema/schema.go +++ b/internal/schema/schema.go @@ -214,6 +214,44 @@ type GoApplication struct { // Externals holds the library (out-of-project) functions the resolver saw // called, keyed by the full callee signature (".[Type.]Name"). Externals map[string]GoExternalCallee `json:"externals,omitempty"` + // Repository holds the repository-artifact facts (non-.go project files and + // go.mod/go.sum dependencies), set by the analyzer after symbol-table + // construction. Never cached or serialized in the v1 model: it is recomputed + // on every run, since it reads files outside the analyzed Go source. + Repository *RepositoryFacts `json:"-"` +} + +// RepositoryFacts is the repository-artifact layer (spec v2-artifacts): every +// non-.go project file as an artifact, and the go.mod requires as dependencies. +type RepositoryFacts struct { + // Artifacts is keyed by repo-relative POSIX path. + Artifacts map[string]GoArtifact + // Dependencies is sorted by module path. + Dependencies []GoDependency +} + +// GoArtifact is one non-.go project file. +type GoArtifact struct { + Path string + Format string + Roles []string + SizeBytes int64 + SHA256 string + Source string // whole file text, only when --artifact-text is on + Extraction string // none | full +} + +// GoDependency is one go.mod require, evidence-tagged by go.sum. +type GoDependency struct { + Name string + Ecosystem string + Spec string + Kind string + Direct bool + LockedVersion string // go.sum version of Spec, when both its h1 and /go.mod lines exist + DeclaredIn string // path of the go.mod artifact + ProvidesImports []string // project import paths that resolve to this module + Prov []string // declared | lockfile } // GoExternalCallee describes a library function or method called from the diff --git a/internal/schema/v2/schema.go b/internal/schema/v2/schema.go index 800c694..ce3eefa 100644 --- a/internal/schema/v2/schema.go +++ b/internal/schema/v2/schema.go @@ -97,6 +97,12 @@ type Application struct { // reaches, keyed by their `can:////@external//` id. // Absent when the analysis saw no library call. ExternalSymbols map[string]ExternalSymbol `json:"external_symbols,omitempty"` + // Artifacts holds every non-.go project file, keyed by its repo-relative path + // (spec v2-artifacts). Level-independent; absent when the project has no files. + Artifacts map[string]Artifact `json:"artifacts,omitempty"` + // Dependencies holds the go.mod requires, sorted by module path. Absent when + // the project has no root go.mod. + Dependencies []Dependency `json:"dependencies,omitempty"` // ParamIn and ParamOut are the L4 interprocedural parameter edges between // global body-node ids. Absent below -a 4. ParamIn []ParamEdge `json:"param_in,omitempty"` @@ -341,3 +347,31 @@ type Edge struct { // Weight accumulates when merging edges from multiple backends. Weight int `json:"weight,omitempty"` } + +// Artifact is one non-.go project file. Its id is can:////artifact/. +// Source is the whole file text only under --artifact-text; otherwise absent. +type Artifact struct { + ID string `json:"id"` + Kind string `json:"kind"` // always "artifact" + Path string `json:"path"` + Format string `json:"format"` + Roles []string `json:"roles,omitempty"` + SizeBytes int64 `json:"size_bytes"` + SHA256 string `json:"sha256"` + Source string `json:"source,omitempty"` + Extraction string `json:"extraction"` // none | full +} + +// Dependency is one declared module requirement from go.mod. Its package is +// pkg:/, version-less; the version lives on the record. +type Dependency struct { + Name string `json:"name"` + Ecosystem string `json:"ecosystem"` // always "golang" + Spec string `json:"spec"` // version required by go.mod + 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 + ProvidesImports []string `json:"provides_imports,omitempty"` + Prov []string `json:"prov"` // declared | lockfile +} diff --git a/internal/syntactic_analysis/v2emit/emit.go b/internal/syntactic_analysis/v2emit/emit.go index 3f0279e..1371aa4 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/v2emit/emit.go @@ -254,6 +254,7 @@ func (e *emitter) envelope(app *schema.GoApplication, maxLevel int, analyzerVers }, } out.Application.ExternalSymbols = emitExternalSymbols(e.appID, app.Externals, e.sdg.standIns()) + out.Application.Artifacts, out.Application.Dependencies = emitRepository(e.appID, app.Repository) if e.flow.on { out.KLimit = kLimit } diff --git a/internal/syntactic_analysis/v2emit/repository.go b/internal/syntactic_analysis/v2emit/repository.go new file mode 100644 index 0000000..b68924f --- /dev/null +++ b/internal/syntactic_analysis/v2emit/repository.go @@ -0,0 +1,57 @@ +package v2emit + +import ( + "github.com/codellm-devkit/codeanalyzer-go/internal/schema" + v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2" +) + +// artifactID is an artifact's durable id: the application root, then the +// artifact segment and the repo-relative path (spec v2-artifacts). +func artifactID(appID, relPath string) string { + return appID + "/artifact/" + relPath +} + +// 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. +func emitRepository(appID string, facts *schema.RepositoryFacts) (map[string]v2.Artifact, []v2.Dependency) { + if facts == nil { + return nil, nil + } + var arts map[string]v2.Artifact + if len(facts.Artifacts) > 0 { + arts = make(map[string]v2.Artifact, len(facts.Artifacts)) + for path, a := range facts.Artifacts { + arts[path] = v2.Artifact{ + ID: artifactID(appID, path), + Kind: "artifact", + Path: a.Path, + Format: a.Format, + Roles: a.Roles, + SizeBytes: a.SizeBytes, + SHA256: a.SHA256, + Source: a.Source, + Extraction: a.Extraction, + } + } + } + var deps []v2.Dependency + for _, d := range facts.Dependencies { + declared := "" + if d.DeclaredIn != "" { + declared = artifactID(appID, d.DeclaredIn) + } + deps = append(deps, v2.Dependency{ + Name: d.Name, + Ecosystem: d.Ecosystem, + Spec: d.Spec, + Kind: d.Kind, + Direct: d.Direct, + LockedVersion: d.LockedVersion, + DeclaredIn: declared, + ProvidesImports: d.ProvidesImports, + Prov: d.Prov, + }) + } + return arts, deps +} From 144cbcb656c4d5b9ff3c78f59f4199ee84fbefdc Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 07:17:32 -0500 Subject: [PATCH 03/21] 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 0f68195b53eee9ffd80952d01df3e78bd5270ecb Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 07:28:50 -0500 Subject: [PATCH 04/21] 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 04111d1..782ee2b 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -162,7 +162,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 7ed66ce9b6ea211238752158e445d3d59b402820 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 07:56:57 -0500 Subject: [PATCH 05/21] 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 210a5111e461a27e0636c3ca0f6063ef183af07a Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 07:59:07 -0500 Subject: [PATCH 06/21] 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 e605867a40b50277aeddc750762c20cf89db71d4 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 08:39:11 -0500 Subject: [PATCH 07/21] 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 85e2ed141acfc1b0e626957b470436d44204a68b Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 09:18:38 -0500 Subject: [PATCH 08/21] 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 000ebad234620a6d8485f7acc2572df0ad00ffef Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 10:47:17 -0500 Subject: [PATCH 09/21] 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 dd9349bf92ab166fba734a330a8f090f06d99aeb Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 10:50:51 -0500 Subject: [PATCH 10/21] 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 782ee2b..8790153 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -195,6 +195,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 19c862a6517a82d2667528fc565917ecaa441768 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 10:53:17 -0500 Subject: [PATCH 11/21] fix(neo4j): purge every changed module before upserting any An eager push purged and upserted module by module. A node is owned by one module but can carry another module's id prefix (a method declared in rpc.go, owned by main.go), so purging rpc.go after main.go had upserted it deleted the method. All purges now run before any upsert. Refs codellm-devkit/codeanalyzer-go#46 --- internal/neo4j/bolt.go | 19 ++++++++++++++----- 1 file changed, 14 insertions(+), 5 deletions(-) diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index da5b001..8a96fa4 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -129,6 +129,20 @@ func (w *boltWriter) run() error { } } + // Purge every changed module before upserting any of them. A module's purge is + // by id prefix, and a node a module OWNS may carry another module's prefix (a + // method declared in rpc.go but owned by main.go's receiver). Purging rpc.go + // after main.go had upserted that method would delete it, so all purges run first. + if w.cfg.Eager && scoped { + for _, m := range sortedModuleKeys(byModule) { + if !changed[m] { + continue + } + if err := w.purgeModule(m); err != nil { + return err + } + } + } // Upsert shared nodes (MERGE-only, every run) then changed-module nodes. if err := w.upsertNodes(shared); err != nil { return err @@ -137,11 +151,6 @@ func (w *boltWriter) run() error { if !changed[m] { continue } - if w.cfg.Eager && scoped { - if err := w.purgeModule(m); err != nil { - return err - } - } if err := w.upsertNodes(byModule[m]); err != nil { return err } From 7acabb670e650b99f25fcd710ac762358b68f39d Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 14:50:52 -0500 Subject: [PATCH 12/21] 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 60ce063f6b2f49a3d1a8f1158a0720c8db302821 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Fri, 20 Nov 2026 14:53:36 -0500 Subject: [PATCH 13/21] 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 8790153..d8e4327 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -58,7 +58,7 @@ func (p *projector) projectApplication() { []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 6290919133847ffad9d14e8b9aad4db545d625b6 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sat, 21 Nov 2026 08:29:54 -0500 Subject: [PATCH 14/21] 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 eb276e124bb50e5b79422dc0658e5d879ed5a268 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sat, 21 Nov 2026 08:34:33 -0500 Subject: [PATCH 15/21] 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 d8e4327..63f7ca5 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -139,6 +139,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, ) @@ -161,9 +162,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, ) @@ -185,7 +187,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, "") @@ -220,7 +222,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, ) @@ -263,7 +266,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), }, @@ -438,6 +442,18 @@ func collectDeclaredIDs(a *v2.Analysis) 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 4f95fed6b9800e6a9ed453048bf2019d9780f6b1 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sat, 21 Nov 2026 08:43:25 -0500 Subject: [PATCH 16/21] 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 205b7cd5fa21fd7cdec14ef326e80a16e3f729c7 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sun, 22 Nov 2026 15:28:23 -0500 Subject: [PATCH 17/21] 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 5edcfe94cc6e48f80d5335feae200551002ffb7f Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sun, 22 Nov 2026 15:33:15 -0500 Subject: [PATCH 18/21] 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 355b56732c9f741ec4dcc97ec0ed277dbda10b60 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sun, 22 Nov 2026 15:56:23 -0500 Subject: [PATCH 19/21] 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 | 38 +++-- internal/neo4j/crossfile_lazy_push_test.go | 172 +++++++++++++++++++++ internal/neo4j/project.go | 13 +- 3 files changed, 209 insertions(+), 14 deletions(-) create mode 100644 internal/neo4j/crossfile_lazy_push_test.go diff --git a/internal/neo4j/bolt.go b/internal/neo4j/bolt.go index 8a96fa4..3042f52 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -130,9 +130,11 @@ func (w *boltWriter) run() error { } // Purge every changed module before upserting any of them. A module's purge is - // by id prefix, and a node a module OWNS may carry another module's prefix (a - // method declared in rpc.go but owned by main.go's receiver). Purging rpc.go - // after main.go had upserted that method would delete it, so all purges run first. + // by id prefix, and it deletes rows that another module upserted if the two + // differ. A module owns exactly the nodes whose id carries its prefix (a + // cross-file method is owned by its declaring file), so the purge and the + // upsert agree. Purging all changed modules first still keeps any ordering + // dependence out of the eager path. if w.cfg.Eager && scoped { for _, m := range sortedModuleKeys(byModule) { if !changed[m] { @@ -335,10 +337,9 @@ func (w *boltWriter) pruneVanishedModules(byModule map[string][]NodeRow) error { // changedModules compares each module's content_hash in rows against the DB. func (w *boltWriter) changedModules(byModule map[string][]NodeRow) (map[string]bool, error) { - changed := map[string]bool{} + dbHash := map[string]string{} for _, m := range sortedModuleKeys(byModule) { - localHash := moduleHash(byModule[m]) - var dbHash string + var h string err := w.read(func(tx neo4j.ManagedTransaction) error { res, err := tx.Run(w.ctx, "MATCH (m:GoModule {id: $id}) RETURN m.content_hash AS h", @@ -347,8 +348,8 @@ func (w *boltWriter) changedModules(byModule map[string][]NodeRow) (map[string]b return err } if res.Next(w.ctx) { - if h, ok := res.Record().Get("h"); ok && h != nil { - dbHash, _ = h.(string) + if v, ok := res.Record().Get("h"); ok && v != nil { + h, _ = v.(string) } } return res.Err() @@ -356,13 +357,26 @@ func (w *boltWriter) changedModules(byModule map[string][]NodeRow) (map[string]b if err != nil { return nil, err } - // Changed when the hash differs or the module is new, or when either side - // has no hash (can't prove unchanged → upsert). - if localHash == "" || dbHash == "" || localHash != dbHash { + dbHash[m] = h + } + return changedAgainst(byModule, func(m string) string { return dbHash[m] }), nil +} + +// changedAgainst reports the modules whose rows must be upserted: a module +// changed when its content_hash differs from the database's, when it is new, or +// when either side has no hash (we cannot prove it unchanged). dbHash is the +// stored hash of a module, "" when the module is absent. The comparison 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 { + local := moduleHash(nodes) + db := dbHash(m) + if local == "" || db == "" || local != db { changed[m] = true } } - return changed, nil + 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 63f7ca5..3cb6e93 100644 --- a/internal/neo4j/project.go +++ b/internal/neo4j/project.go @@ -195,12 +195,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 d2ae0e44c954b63e8dd21e777b497fe646f9d773 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sun, 22 Nov 2026 16:09:28 -0500 Subject: [PATCH 20/21] 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 265eb02a1733453b425514b747b8959df85f8a46 Mon Sep 17 00:00:00 2001 From: lambertpw Date: Sun, 22 Nov 2026 16:24:30 -0500 Subject: [PATCH 21/21] fix(core): exclude the whole cache root from artifact discovery, not one app's subdirectory With the cache inside the project (-c ./cache), each application writes its analysis_cache.json beneath identity-v2-/. New() replaced the cache directory with that per-application subdirectory, and the repository layer was given only the subdirectory. So each run excluded its own cache and nothing else: run B recorded run A's identity-v2-/analysis_cache.json as a project artifact. With --artifact-text its full source, another application's analysis, was written into B's analysis.json. The Analyzer now keeps the cache root as the user gave it, and the repository layer excludes all of it. Every application's subdirectory is covered, including ones written by applications not yet analyzed. The cache root is the tool's own location, so nothing under it is project source. A root equal to the project directory is still not excluded (the walk never skips its own root). Test: TestAnalyze_CacheRootInsideProjectIsNotAnArtifact runs two applications against one in-project cache and fails on the old code (appB records cache/identity-v2-/analysis_cache.json as an artifact). Co-Authored-By: Claude Haiku 5.5 --- internal/core/analyzer.go | 11 ++++-- internal/core/cache_leak_test.go | 58 ++++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+), 2 deletions(-) create mode 100644 internal/core/cache_leak_test.go diff --git a/internal/core/analyzer.go b/internal/core/analyzer.go index b9dbf34..cef7c05 100644 --- a/internal/core/analyzer.go +++ b/internal/core/analyzer.go @@ -44,6 +44,10 @@ import ( // Analyzer is the top-level analysis driver. Construct with New() and call Analyze(). type Analyzer struct { opts options.AnalysisOptions + // cacheRoot is the cache directory as the user gave it, before the + // per-application identity-v2- suffix. The repository layer excludes all + // of it, so no application's cache is recorded as a project artifact. + cacheRoot string // l3 is the Phase 5 side table (nil below L3). It stays off // schema.GoApplication: schema must not depend on dataflow, and the // cached v1 model has no L3 facts. @@ -85,11 +89,14 @@ func resolveIdentity(opts options.AnalysisOptions) (v2.Identity, error) { // New creates an Analyzer with a cache isolated by canonical application identity. func New(opts options.AnalysisOptions) *Analyzer { + // The root is kept before the per-application suffix: it is the tool's own cache + // location, and every application's subdirectory lives beneath it. + cacheRoot := opts.CacheDir if identity, err := resolveIdentity(opts); err == nil && opts.CacheDir != "" { key := sha256.Sum256([]byte(identity.ApplicationID)) opts.CacheDir = filepath.Join(opts.CacheDir, fmt.Sprintf("identity-v2-%x", key)) } - return &Analyzer{opts: opts} + return &Analyzer{opts: opts, cacheRoot: cacheRoot} } // Analyze runs the full analysis pipeline and returns a GoApplication. @@ -103,7 +110,7 @@ func (a *Analyzer) Analyze() (*schema.GoApplication, error) { facts, err := repository.Facts(a.opts.InputPath, app, repository.Options{ CaptureText: a.opts.ArtifactText, OutputDir: a.opts.OutputDir, - CacheDir: a.opts.CacheDir, + CacheDir: a.cacheRoot, }) if err != nil { return nil, fmt.Errorf("repository layer: %w", err) diff --git a/internal/core/cache_leak_test.go b/internal/core/cache_leak_test.go new file mode 100644 index 0000000..548f388 --- /dev/null +++ b/internal/core/cache_leak_test.go @@ -0,0 +1,58 @@ +package core_test + +import ( + "os" + "path/filepath" + "strings" + "testing" + + "github.com/codellm-devkit/codeanalyzer-go/internal/core" + "github.com/codellm-devkit/codeanalyzer-go/internal/options" +) + +// The cache directory lives inside the project (-c ./cache). Each application +// writes its own identity-v2-/analysis_cache.json beneath it. Before the +// fix, the repository layer excluded only the current application's subdirectory, +// so run B recorded run A's cache as an artifact, with its full source under +// --artifact-text. Those bytes are another application's analysis. +// +// Practical shape of the project: +// +// project/ +// go.mod main.go +// cache/ +// identity-v2-/analysis_cache.json <- written by run A +// identity-v2-/analysis_cache.json <- written by run B +func TestAnalyze_CacheRootInsideProjectIsNotAnArtifact(t *testing.T) { + dir := t.TempDir() + files := map[string]string{ + "go.mod": "module example.com/cl\n\ngo 1.22\n", + "main.go": "package main\n\nfunc main() {}\n", + } + for rel, content := range files { + if err := os.WriteFile(filepath.Join(dir, rel), []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + cache := filepath.Join(dir, "cache") + + // Run A, then run B: B is the run whose output must not carry A's cache. + for _, app := range []string{"appA", "appB"} { + opts := options.AnalysisOptions{ + InputPath: dir, AppName: app, Level: options.LevelSymbolTable, + SkipTests: true, CacheDir: cache, OutputDir: t.TempDir(), ArtifactText: true, + } + got, err := core.New(opts).Analyze() + if err != nil { + t.Fatalf("%s: %v", app, err) + } + for path := range got.Repository.Artifacts { + if strings.HasPrefix(path, "cache/") || strings.Contains(path, "analysis_cache.json") { + t.Errorf("%s recorded cache file %q as a project artifact", app, path) + } + } + if _, ok := got.Repository.Artifacts["go.mod"]; !ok { + t.Errorf("%s: go.mod missing from artifacts; the project itself must still be discovered", app) + } + } +}