diff --git a/CLAUDE.md b/CLAUDE.md index ae2663c..4531c94 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -165,7 +165,7 @@ Reuses Group A ids/spans and the L3 vocabulary unchanged; every L4 fact is an ad ### 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]. +- **Scope:** all non-`.go` project files [user, 2026-11-19]. Binaries are metadata only (`source:""`) [user]. Discovery skips what the Go analysis skips (`utils.IsVendored`: `vendor`, `testdata`, `.git`, also a `.git` file), and the tool's own outputs (the `-o` and `-c` directories whole unless they hold the project; `graph.cypher` in the working directory for `--emit neo4j` without `-o`). A symlinked file is followed only to a file inside the project. - **Artifact id:** `can:///artifact/`, app-scoped (Python parity) [user]. The Go projector's `:Artifact` flips to `CanNode=true`. - **Package id:** version-less `pkg:golang/` [user]; version lives on the dependency edge. - **Source text:** `--artifact-text`, on by default; `--no-artifact-text` drops it (Python and TypeScript parity) [user]. `config_keys` deferred [user]. diff --git a/cmd/codeanalyzer/main_test.go b/cmd/codeanalyzer/main_test.go index b2ec719..b126669 100644 --- a/cmd/codeanalyzer/main_test.go +++ b/cmd/codeanalyzer/main_test.go @@ -876,3 +876,38 @@ func TestRootCmd_ArtifactTextOnByDefault(t *testing.T) { } } } + +// TestRootCmd_EmitNeo4jTwiceInProjectIsStable (#77): --emit neo4j with no -o +// writes graph.cypher to the current directory. Run from the project root, the +// second run must not capture the first run's graph.cypher as an artifact, so +// both runs write the same snapshot. +func TestRootCmd_EmitNeo4jTwiceInProjectIsStable(t *testing.T) { + dir := t.TempDir() + for name, body := range map[string]string{ + "go.mod": "module example.com/twice\n\ngo 1.25.0\n", + "main.go": "package main\n\nfunc main() {}\n", + "config.yaml": "port: 8080\n", + } { + if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil { + t.Fatal(err) + } + } + t.Chdir(dir) + var snapshots []string + for range 2 { + if _, _, err := runCmd("--input", ".", "--emit", "neo4j", "--cache-dir", t.TempDir()); err != nil { + t.Fatal(err) + } + data, err := os.ReadFile(filepath.Join(dir, "graph.cypher")) + if err != nil { + t.Fatal(err) + } + snapshots = append(snapshots, string(data)) + } + if strings.Contains(snapshots[1], "artifact/graph.cypher") { + t.Error("the second run captured the first run's graph.cypher as an artifact") + } + if snapshots[0] != snapshots[1] { + t.Error("two runs on an unchanged project wrote different snapshots") + } +} diff --git a/docs/design/specs/v2-artifacts.md b/docs/design/specs/v2-artifacts.md index f75d01b..d02787c 100644 --- a/docs/design/specs/v2-artifacts.md +++ b/docs/design/specs/v2-artifacts.md @@ -21,6 +21,10 @@ Anchor: `codeanalyzer-python` already emits this layer (`PyArtifact`, `PyDepende `codeanalyzer/schema/py_schema.py`), and `python-sdk/cldk/analysis/commons/artifacts.py` rebuilds it from Neo4j, with the neutral labels shared across analyzers. +In Go: `schema.GoArtifact` and `schema.GoDependency` (`internal/schema/schema.go`, the +analyzer model), emitted as `v2.Artifact` and `v2.Dependency` (`internal/schema/v2/schema.go`); +there is no config-key type, because `config_keys` is deferred. + ## Problem The v2 schema and projector declare the neutral repository-artifact layer, but the Go @@ -38,8 +42,8 @@ Each decision was made with the user, one question per decision, in the order be ### 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). + scope). `.go` files are modules, not artifacts. Discovery skips what the Go analysis skips + (`utils.IsVendored`: `vendor/`, `testdata/`, `.git`), see Resolution 2. - **Artifact fields** (Python `PyArtifact` parity): | field | type | notes | | --- | --- | --- | @@ -144,10 +148,21 @@ The open items were resolved with the defaults below. Two are deviations from th 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. +2. **Excluded paths** (revised 2026-11-29 [user], #73, #77, #78): + - Discovery uses the Go analysis's rule, `utils.IsVendored`: `vendor/`, `testdata/` and + `.git` are skipped at any depth. `.git` is skipped also when it is a file (a git worktree + or submodule), so its `gitdir:` host path never reaches the output. `testdata/` is skipped + because the Go toolchain ignores it; Python and TypeScript keep their test folders. + - The tool's own outputs, as in Python: the `-o` and `-c` directories are skipped whole when + they are inside the project. A directory that holds the project root (for example `-o .`) + is not skipped whole, because that would empty the inventory; only `analysis.json` and + `graph.cypher` in it are skipped. With `--emit neo4j` and no `-o`, the `graph.cypher` in + the current directory is skipped. Without this, a run that writes into the project would + capture the previous run's output. + - A symlinked file is followed when its target is a regular file inside the project and + not in a skipped path. It is recorded under the link's path, so a symlinked `go.mod` is + the artifact its dependencies name. A symlink to a directory, or to anything outside the + project, is skipped, so discovery never reads a file outside the project. 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 diff --git a/internal/core/analyzer.go b/internal/core/analyzer.go index cef7c05..1d90f0f 100644 --- a/internal/core/analyzer.go +++ b/internal/core/analyzer.go @@ -107,10 +107,16 @@ func (a *Analyzer) Analyze() (*schema.GoApplication, error) { } // The repository layer reads files outside the Go source, so it is computed // on every run, after the (possibly cached) application is ready. + // --emit neo4j with no -o writes graph.cypher to the current directory (#77). + var graphFile string + if a.opts.Emit == options.EmitNeo4j && a.opts.OutputDir == "" { + graphFile = "graph.cypher" // neo4j.GraphFileName + } facts, err := repository.Facts(a.opts.InputPath, app, repository.Options{ CaptureText: a.opts.ArtifactText, OutputDir: a.opts.OutputDir, CacheDir: a.cacheRoot, + GraphFile: graphFile, }) if err != nil { return nil, fmt.Errorf("repository layer: %w", err) diff --git a/internal/repository/discovery_rules_test.go b/internal/repository/discovery_rules_test.go new file mode 100644 index 0000000..64a6554 --- /dev/null +++ b/internal/repository/discovery_rules_test.go @@ -0,0 +1,142 @@ +package repository + +import ( + "os" + "path/filepath" + "testing" +) + +func symlink(t *testing.T, target, link string) { + t.Helper() + if err := os.Symlink(target, link); err != nil { + t.Skipf("symlinks not supported: %v", err) + } +} + +// TestFacts_SymlinkedGoModIsAnArtifact (#73): a go.mod that is a symlink to a +// file inside the project is an artifact under the link's path, so every +// dependency's declared_in names an artifact that exists. +func TestFacts_SymlinkedGoModIsAnArtifact(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{"build/go.mod.real": goMod, "main.go": "package main\n"}) + symlink(t, filepath.Join("build", "go.mod.real"), filepath.Join(root, "go.mod")) + + facts, err := Facts(root, appWithImports(), Options{}) + if err != nil { + t.Fatal(err) + } + art, ok := facts.Artifacts["go.mod"] + if !ok { + t.Fatalf("symlinked go.mod is not an artifact; have %v", facts.Artifacts) + } + if art.Format != "gomod" || art.Path != "go.mod" { + t.Errorf("go.mod artifact = %+v, want format gomod at path go.mod", art) + } + if len(facts.Dependencies) == 0 { + t.Fatal("no dependencies read from the symlinked go.mod") + } + for _, d := range facts.Dependencies { + if _, ok := facts.Artifacts[d.DeclaredIn]; !ok { + t.Errorf("dependency %s declared_in %q is not an artifact", d.Name, d.DeclaredIn) + } + } +} + +// TestDiscover_SymlinkOutsideProjectIsSkipped (#73): a symlink whose target is +// outside the project is not followed, so no file outside the project is read. +func TestDiscover_SymlinkOutsideProjectIsSkipped(t *testing.T) { + root, outside := t.TempDir(), t.TempDir() + writeTree(t, outside, map[string]string{"credentials": "secret\n"}) + writeTree(t, root, map[string]string{"README.md": "# app\n"}) + symlink(t, filepath.Join(outside, "credentials"), filepath.Join(root, "creds")) + symlink(t, outside, filepath.Join(root, "linked-dir")) + + got, err := Discover(root, Options{CaptureText: true}) + if err != nil { + t.Fatal(err) + } + for _, p := range []string{"creds", "linked-dir/credentials"} { + if _, ok := got[p]; ok { + t.Errorf("%s was captured: a symlink to outside the project", p) + } + } + if _, ok := got["README.md"]; !ok { + t.Error("README.md missing") + } +} + +// TestDiscover_SkipsTestdataAndGitFile (#78): discovery skips what the Go +// analysis skips (utils.IsVendored: vendor, testdata, .git), and an entry named +// .git also when it is a file (a git worktree or submodule). +func TestDiscover_SkipsTestdataAndGitFile(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{ + "README.md": "# app\n", + "testdata/golden.json": "{}", + "pkg/testdata/a.txtar": "-- a --\n", + "vendor/x/LICENSE": "MIT\n", + ".git": "gitdir: /Users/someone/src/app/.git/worktrees/wt\n", + "sub/.git": "gitdir: ../.git/modules/sub\n", + "sub/config.yaml": "a: 1\n", + "notes/testdata.md": "a file, not a testdata directory\n", + }) + got, err := Discover(root, Options{}) + if err != nil { + t.Fatal(err) + } + for _, p := range []string{"testdata/golden.json", "pkg/testdata/a.txtar", "vendor/x/LICENSE", ".git", "sub/.git"} { + if _, ok := got[p]; ok { + t.Errorf("%s was captured", p) + } + } + for _, p := range []string{"README.md", "sub/config.yaml", "notes/testdata.md"} { + if _, ok := got[p]; !ok { + t.Errorf("%s is missing", p) + } + } +} + +// TestDiscover_SkipsWholeOutputDirAndGraphFile (#77): the -o directory is +// skipped whole when it is inside the project (Python parity), and so is the +// graph.cypher that --emit neo4j writes without -o (GraphFile). +func TestDiscover_SkipsWholeOutputDirAndGraphFile(t *testing.T) { + root := t.TempDir() + writeTree(t, root, map[string]string{ + "README.md": "# app\n", + "out/analysis.json": "{}", + "out/other.txt": "written by someone else\n", + "graph.cypher": "CREATE;", + }) + opts := Options{OutputDir: filepath.Join(root, "out"), GraphFile: filepath.Join(root, "graph.cypher")} + got, err := Discover(root, opts) + if err != nil { + t.Fatal(err) + } + for _, p := range []string{"out/analysis.json", "out/other.txt", "graph.cypher"} { + if _, ok := got[p]; ok { + t.Errorf("%s was captured", p) + } + } + if _, ok := got["README.md"]; !ok { + t.Error("README.md missing") + } +} + +// TestDiscover_OutputDirHoldingTheProjectIsNotSkippedWhole (#77): an -o or +// cache directory at or above the project root would empty the inventory, so +// only the output files in it are skipped. +func TestDiscover_OutputDirHoldingTheProjectIsNotSkippedWhole(t *testing.T) { + parent := t.TempDir() + root := filepath.Join(parent, "app") + writeTree(t, root, map[string]string{"README.md": "# app\n", "analysis.json": "{}"}) + got, err := Discover(root, Options{OutputDir: root, CacheDir: parent}) + if err != nil { + t.Fatal(err) + } + if _, ok := got["README.md"]; !ok { + t.Errorf("inventory emptied by an -o / cache directory that holds the project: %v", got) + } + if _, ok := got["analysis.json"]; ok { + t.Error("own analysis.json was captured") + } +} diff --git a/internal/repository/repository.go b/internal/repository/repository.go index 8763858..12cfcb4 100644 --- a/internal/repository/repository.go +++ b/internal/repository/repository.go @@ -33,25 +33,32 @@ type Options struct { 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. + // into the project must not capture the previous run's output. Each is skipped + // whole, unless it holds the project root (that would empty the inventory); then + // only the output files in OutputDir are skipped. OutputDir string CacheDir string + // GraphFile is the graph.cypher that --emit neo4j writes when no OutputDir is + // set (in the current directory). It is skipped too. + GraphFile 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. // +// It skips what the Go analysis skips (utils.IsVendored: vendor, testdata and +// .git, also when .git is a file), and this tool's own outputs (Options). +// // 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. +// through one would otherwise yield no artifacts at all. A symlinked file inside +// the tree is followed when its target is a file inside the project, and is +// recorded under the link's path (a symlinked go.mod, #73). Any other symlink, +// including one to a directory, is skipped, so discovery never leaves the +// project root. func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { absRoot, err := resolveDir(root) if err != nil { @@ -65,6 +72,21 @@ func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { if err != nil { return nil, fmt.Errorf("resolving cache directory: %w", err) } + graphFile, err := optionalFile(opts.GraphFile) + if err != nil { + return nil, fmt.Errorf("resolving graph file: %w", err) + } + skipDirs := map[string]bool{} + for _, d := range []string{outDir, cacheDir} { + if d == "" { + continue + } + if utils.IsWithin(d, absRoot) { + utils.Warn("repository: not skipping %s: it holds the project; only this tool's output files in it are skipped", d) + continue + } + skipDirs[d] = true + } out := map[string]schema.GoArtifact{} err = filepath.WalkDir(absRoot, func(p string, d fs.DirEntry, werr error) error { rel, err := filepath.Rel(absRoot, p) @@ -82,19 +104,34 @@ func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { utils.Warn("repository: skipping %s: %v", rel, werr) return nil } + if p != absRoot && utils.IsVendored(rel) { + if d.IsDir() { + return filepath.SkipDir + } + return nil + } if d.IsDir() { - if p != absRoot && (skipDirNames[d.Name()] || (cacheDir != "" && p == cacheDir)) { + if skipDirs[p] { return filepath.SkipDir } return nil } - if !d.Type().IsRegular() || strings.HasSuffix(d.Name(), ".go") { + if strings.HasSuffix(d.Name(), ".go") || p == graphFile || + (outDir != "" && filepath.Dir(p) == outDir && outputFileNames[d.Name()]) { return nil } - if outDir != "" && filepath.Dir(p) == outDir && outputFileNames[d.Name()] { + var info fs.FileInfo + switch { + case d.Type().IsRegular(): + info, err = d.Info() + case d.Type()&fs.ModeSymlink != 0: + info, err = followSymlink(absRoot, p) + if info == nil && err == nil { + return nil + } + default: return nil } - info, err := d.Info() if err != nil { utils.Warn("repository: skipping %s: %v", rel, err) return nil @@ -115,6 +152,48 @@ func Discover(root string, opts Options) (map[string]schema.GoArtifact, error) { return out, nil } +// followSymlink returns the stat of the file a symlink at p points to, when +// that is a regular file inside root that discovery would not skip. Otherwise +// it returns nil: a link to a directory silently (directories are never +// followed), a link that leaves the project or ends in a skipped path with a +// warning, so no file outside the project, or under .git, is ever read. +func followSymlink(root, p string) (fs.FileInfo, error) { + target, err := filepath.EvalSymlinks(p) + if err != nil { + return nil, err + } + info, err := os.Stat(target) + if err != nil { + return nil, err + } + if info.IsDir() { + return nil, nil + } + if !info.Mode().IsRegular() { + return nil, fmt.Errorf("symlink to a non-regular file") + } + if !utils.IsWithin(root, target) { + return nil, fmt.Errorf("symlink to outside the project") + } + if utils.IsVendored(utils.RelativePath(root, target)) { + return nil, fmt.Errorf("symlink to a skipped path") + } + return info, nil +} + +// optionalFile resolves an optional file setting; "" means unset. The file need +// not exist yet. +func optionalFile(p string) (string, error) { + if p == "" { + return "", nil + } + dir, err := resolveDir(filepath.Dir(p)) + if err != nil { + return "", err + } + return filepath.Join(dir, filepath.Base(p)), nil +} + // optionalDir resolves an optional directory setting; "" means unset. func optionalDir(p string) (string, error) { if p == "" {