Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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{<path>: 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://<app>/artifact/<path>`, app-scoped (Python parity) [user]. The Go projector's `:Artifact` flips to `CanNode=true`.
- **Package id:** version-less `pkg:golang/<module-path>` [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].
Expand Down
35 changes: 35 additions & 0 deletions cmd/codeanalyzer/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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")
}
}
27 changes: 21 additions & 6 deletions docs/design/specs/v2-artifacts.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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 |
| --- | --- | --- |
Expand Down Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions internal/core/analyzer.go
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
142 changes: 142 additions & 0 deletions internal/repository/discovery_rules_test.go
Original file line number Diff line number Diff line change
@@ -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")
}
}
Loading
Loading