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
10 changes: 8 additions & 2 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,8 +168,8 @@ Made with the user in the 2026-11-19 design loop, anchored on `codeanalyzer-pyth
- **Scope:** all non-`.go` project files [user, 2026-11-19]. Binaries are metadata only (`source:""`) [user].
- **Artifact id:** `can://<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:** 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].
- **Source text:** `--artifact-text`, on by default; `--no-artifact-text` drops it (Python and TypeScript parity) [user]. `config_keys` deferred [user].
- **Dependencies:** every `go.mod` require; `direct=false` on `// indirect`; `kind:"runtime"`; `go.sum` supplies `locked_version` only, `go.sum`-only entries excluded [user]. `locked_in` names the `go.sum` artifact that locked it; the projector reads it, and `v2.PackageID` is the one package-id builder.
- **`provides_imports`:** longest-prefix match against `go.mod` module paths [user].
- **Level:** L1, every level, not gated [user].

Expand Down Expand Up @@ -238,6 +238,12 @@ shared neutral vocabulary verbatim; never rename a sibling's shared name). Spec:
- Declare `:Artifact` / `:Package` / `:ConfigKey` and `HAS_ARTIFACT` /
`DECLARES_DEPENDENCY` (`_k=kind`) / `LOCKS` / `DEFINES_CONFIG` **un-prefixed**, identical
to the siblings, so a sibling analyzer over the same repo converges on the same node.
An `--eager` full Bolt push reconciles artifacts with the siblings' claim model (delete the
Go-owned edges, release vanished artifacts, delete a node only when no `HAS_ARTIFACT` is
left); the whole-app purge skips `:Artifact`; lazy and `-t` pushes reconcile nothing.
`:Artifact` carries the JSON artifact's fields (`kind`, `path`, `format`, `roles`,
`size_bytes`, `sha256`, `source`, `extraction`) and `LOCKS` carries `version`, as Python and
TypeScript write them.
The projector emits rows **only for facts the Go analyzer produces** (go.mod deps →
`:Package` `pkg:golang/…`); absent facts emit **zero rows** (declared contract, empty
projection). `GO_PROVIDES` / `GO_UNRESOLVED_IMPORT` stay `GO_`-prefixed (this analyzer's
Expand Down
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -173,14 +173,15 @@ Flags:
-f, --format string Output format: json|msgpack (default "json")
--graph-field-depth int Field-path depth bound for L3 dataflow nodes (k limit; applies at -a 3 and -a 4) (default 3)
-h, --help help for cango
--artifact-text Capture each text artifact's whole source in analysis.json (default: metadata only)
--artifact-text Capture each text artifact's whole source in the output (default true)
-i, --input string Project root to analyze (required)
-j, --jobs int Worker parallelism (default: CPU cores)
--library-models string JSON file of library stand-in flows overriding the all-to-all default (-a 4 and --emit neo4j only)
--neo4j-database string Neo4j database (env NEO4J_DATABASE, optional)
--neo4j-password string Neo4j password (env NEO4J_PASSWORD, default neo4j)
--neo4j-uri string Live Bolt push target (env NEO4J_URI); omit to write graph.cypher
--neo4j-user string Neo4j username (env NEO4J_USERNAME, default neo4j)
--no-artifact-text Keep the artifact inventory but drop the captured text
-o, --output string Output directory for analysis.json (default: stdout)
--skip-tests Skip *_test.go files (default true)
--strict Fail non-zero on any L4 degradation (default: degrade and record it)
Expand Down
11 changes: 8 additions & 3 deletions cmd/codeanalyzer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,7 @@ func rootCmd() *cobra.Command {
targetFiles []string
skipTests bool
artifactText bool
noArtText bool
eager bool
cacheDir string
jobs int
Expand Down Expand Up @@ -173,7 +174,7 @@ via CLDK(language="go").analysis(project_path=...).`,
AnalyzerVersion: version,
TargetFiles: targetFiles,
SkipTests: skipTests,
ArtifactText: artifactText,
ArtifactText: artifactText && !noArtText,
Eager: eager,
CacheDir: cacheDir,
Jobs: jobs,
Expand Down Expand Up @@ -241,8 +242,12 @@ via CLDK(language="go").analysis(project_path=...).`,
f.StringSliceVarP(&targetFiles, "target-files", "t", nil,
"Restrict analysis to specific files (incremental mode)")
f.BoolVar(&skipTests, "skip-tests", true, "Skip *_test.go files")
f.BoolVar(&artifactText, "artifact-text", false,
"Capture each text artifact's whole source in analysis.json (default: metadata only)")
// On by default, as in the Python and TypeScript analyzers; --no-artifact-text
// keeps the artifact inventory and drops the text.
f.BoolVar(&artifactText, "artifact-text", true,
"Capture each text artifact's whole source in the output")
f.BoolVar(&noArtText, "no-artifact-text", false,
"Keep the artifact inventory but drop the captured text")
f.BoolVar(&eager, "eager", false, "Force clean rebuild (ignore cache)")
f.StringVarP(&cacheDir, "cache-dir", "c", "", "Cache directory (default: ~/.cldk/go-cache)")
f.IntVarP(&jobs, "jobs", "j", 0, "Worker parallelism (default: CPU cores)")
Expand Down
49 changes: 49 additions & 0 deletions cmd/codeanalyzer/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -827,3 +827,52 @@ func TestNamespaceDefaultUsesNormalizedInput(t *testing.T) {
t.Fatal(a.Application.ID)
}
}

// ── --artifact-text ──────────────────────────────────────────────────────────

// TestRootCmd_ArtifactTextOnByDefault: the text of a text artifact is captured
// by default and --no-artifact-text turns it off, as in the Python and
// TypeScript analyzers. --artifact-text is still accepted.
func TestRootCmd_ArtifactTextOnByDefault(t *testing.T) {
dir := t.TempDir()
for name, body := range map[string]string{
"go.mod": "module example.com/at\n\ngo 1.25.0\n",
"main.go": "package main\n\nfunc main() {}\n",
"config.yaml": "port: 8080\n",
} {
if err := os.WriteFile(filepath.Join(dir, name), []byte(body), 0o644); err != nil {
t.Fatal(err)
}
}
source := func(t *testing.T, flags ...string) string {
t.Helper()
out, _, err := runCmd(append([]string{"--input", dir, "--cache-dir", t.TempDir()}, flags...)...)
if err != nil {
t.Fatalf("%v: %v", flags, err)
}
var doc struct {
Application struct {
Artifacts map[string]struct {
Source string `json:"source"`
} `json:"artifacts"`
} `json:"application"`
}
if err := json.Unmarshal([]byte(out), &doc); err != nil {
t.Fatal(err)
}
return doc.Application.Artifacts["config.yaml"].Source
}
for _, tc := range []struct {
flags []string
want string
}{
{nil, "port: 8080\n"},
{[]string{"--artifact-text"}, "port: 8080\n"},
{[]string{"--no-artifact-text"}, ""},
{[]string{"--artifact-text=false"}, ""},
} {
if got := source(t, tc.flags...); got != tc.want {
t.Errorf("%v: config.yaml source = %q, want %q", tc.flags, got, tc.want)
}
}
}
37 changes: 30 additions & 7 deletions docs/design/specs/v2-artifacts.md
Original file line number Diff line number Diff line change
Expand Up @@ -50,12 +50,13 @@ Each decision was made with the user, one question per decision, in the order be
| `roles` | string[] | `dependency-manifest` for `go.mod`, `lockfile` for `go.sum`; others only when recognized |
| `size_bytes` | int | always |
| `sha256` | string | full file hash, always |
| `source` | string | whole file text **only** with `--artifact-text`; otherwise `""` |
| `source` | string | whole file text, unless `--no-artifact-text`; `""` for a binary file |
| `extraction` | string | `none` \| `partial` \| `full`; `full` when `source` is set, else `none` |
- **Binary files**: metadata only. `format:"binary"`, `size_bytes` and `sha256` set,
`source:""` (user decision).
- **`--artifact-text`** (default **off**): when on, `source` carries the whole file text
(user decision). Off keeps default output to metadata.
- **`--artifact-text`** (default **on** [user, 2026-11-29]; it was off before): `source`
carries the whole file text. `--no-artifact-text` keeps the inventory and drops the text.
The flags and the default are the Python and TypeScript analyzers'.
- **`config_keys`** is **deferred** (user decision): not emitted in this change. No
`:ConfigKey` rows are written.

Expand All @@ -79,6 +80,7 @@ Each decision was made with the user, one question per decision, in the order be
| `kind` | `"runtime"` for every entry (`go.mod` has no dev/optional split) |
| `direct` | `false` when the line carries `// indirect`, else `true` |
| `locked_version` | version pinned in `go.sum` for that module, when present |
| `locked_in` | the `go.sum` artifact id that gave `locked_version`, when present (#72) |
| `declared_in` | the `go.mod` artifact id |
| `provides_imports` | import paths in the project that resolve to this module (see below) |
| `prov` | `["declared"]`, plus `"lockfile"` when `go.sum` supplies `locked_version` |
Expand All @@ -94,14 +96,35 @@ Each decision was made with the user, one question per decision, in the order be
Not gated.

### Neo4j projection (the neutral layer, unchanged labels)
- `:Artifact {id, path, format}` (keyed by `id`, `CanNode=true`), under `HAS_ARTIFACT`
from `:GoApplication`.
- `:Package {id, ecosystem, name}` keyed by `id`.
- `:Artifact {id, kind, path, format, roles, size_bytes, sha256, source, extraction}` (keyed
by `id`, `CanNode=true`), under `HAS_ARTIFACT` from `:GoApplication`. These are the JSON
artifact's fields; empty values are left out. Python writes the same set, TypeScript the
same set plus `kind` (#81; the original `{id, path, format}` left the text and hash out).
- `:Package {id, ecosystem, name}` keyed by `id`. The id comes from `v2.PackageID`, the one
place a package id is built (#72).
- `DECLARES_DEPENDENCY` `(:Artifact)→(:Package)`, `_k = kind` (`runtime`), carrying `spec`,
`direct`, `prov` as properties.
- `LOCKS` `(:Artifact)→(:Package)` from `go.sum`, carrying `locked_version`.
- `LOCKS` `(:Artifact)→(:Package)` from the dependency's `locked_in` artifact, carrying
`version` (the sibling analyzers' name; it was `locked_version` before #72).
- No `:ConfigKey` rows and no `DEFINES_CONFIG` rows in this change.

### Removing artifacts and dependencies that are gone (#70) [user, 2026-11-29]
- `:Artifact` is shared with the sibling analyzers. A Go push never deletes it wholesale: the
eager whole-app purge skips `:Artifact`.
- **Only an `--eager` full push reconciles** (Python and TypeScript parity). Before the artifact
rows are upserted, it:
1. deletes the Go-owned edges on the app's artifacts (`<app>/artifact/` prefix):
`HAS_ARTIFACT` from `:GoApplication`, incoming `GO_` edges, and `DECLARES_DEPENDENCY` /
`LOCKS` to `pkg:golang/` packages. The push then writes them again from this run;
2. releases each artifact of the app that this run does not have: it removes `:GoCanNode`,
and deletes the node only when no analyzer still has a `HAS_ARTIFACT` edge to it.
- A lazy push and a `-t` push reconcile nothing: a lazy push never deletes. Stale artifact
and dependency rows stay until the next `--eager` full push.
- `:Package` nodes are never deleted (neutral, shared by every app that depends on them).
- The `graph.cypher` snapshot still wipes the app's artifacts with the rest of its
subgraph and rebuilds them, as Python's snapshot does. Another analyzer's edges into a
shared artifact are restored on that analyzer's next push.

## Open items (flagged for review, not asked)

These are defaults I chose while writing the spec. Confirm them during review:
Expand Down
150 changes: 150 additions & 0 deletions internal/neo4j/artifact_integration_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
//go:build neo4j_it

package neo4j

import (
"context"
"testing"

"github.com/neo4j/neo4j-go-driver/v5/neo4j"

v2 "github.com/codellm-devkit/codeanalyzer-go/internal/schema/v2"
)

// Live tests for the artifact reconcile (#70, Q4–Q6). Each builds a real
// analysis, gives it a repository layer, and pushes it with the streaming push.

// withRepo returns a with the artifacts named by paths (go.mod and go.sum are
// always there) and the dependencies named by deps, each declared in go.mod
// and locked in go.sum.
func withRepo(t *testing.T, paths []string, deps []string) *v2.Analysis {
t.Helper()
a := buildMultipackageL2(t)
app := a.Application.ID
a.Application.Artifacts = map[string]v2.Artifact{}
for _, p := range append([]string{"go.mod", "go.sum"}, paths...) {
a.Application.Artifacts[p] = v2.Artifact{ID: app + "/artifact/" + p, Kind: "artifact", Path: p, Format: "text", Extraction: "none"}
}
a.Application.Dependencies = nil
for _, d := range deps {
a.Application.Dependencies = append(a.Application.Dependencies, v2.Dependency{
Name: d, Ecosystem: "golang", Spec: "v1.0.0", Kind: "runtime", Direct: true,
LockedVersion: "v1.0.0", LockedIn: app + "/artifact/go.sum", DeclaredIn: app + "/artifact/go.mod",
Prov: []string{"declared", "lockfile"},
})
}
return a
}

func pushIT(t *testing.T, ctx context.Context, a *v2.Analysis, cfg BoltConfig) {
t.Helper()
if _, _, err := PushBolt(ctx, treeSource(a), cfg); err != nil {
t.Fatalf("push: %v", err)
}
}

func countIT(t *testing.T, ctx context.Context, cfg BoltConfig, q string, params map[string]any) int {
t.Helper()
drv, err := neo4j.NewDriverWithContext(cfg.URI, neo4j.BasicAuth(cfg.User, cfg.Password, ""))
if err != nil {
t.Fatalf("driver: %v", err)
}
defer drv.Close(ctx)
res, err := neo4j.ExecuteQuery(ctx, drv, q, params, neo4j.EagerResultTransformer, neo4j.ExecuteQueryWithDatabase(cfg.Database))
if err != nil {
t.Fatalf("%s: %v", q, err)
}
return int(res.Records[0].Values[0].(int64))
}

// repoState counts what the reconcile changes: the config.yaml artifact, and
// the DECLARES_DEPENDENCY and LOCKS edges to golang.org/x/text.
func repoState(t *testing.T, ctx context.Context, cfg BoltConfig, app string) (config, declares, locks int) {
t.Helper()
p := map[string]any{"cfg": app + "/artifact/config.yaml", "pkg": v2.PackageID("golang", "golang.org/x/text")}
config = countIT(t, ctx, cfg, "MATCH (n:Artifact {id: $cfg}) RETURN count(n)", p)
declares = countIT(t, ctx, cfg, "MATCH (:Artifact)-[r:DECLARES_DEPENDENCY]->(:Package {id: $pkg}) RETURN count(r)", p)
locks = countIT(t, ctx, cfg, "MATCH (:Artifact)-[r:LOCKS]->(:Package {id: $pkg}) RETURN count(r)", p)
return
}

// seed pushes the "before" state eagerly: config.yaml, and two dependencies.
func seed(t *testing.T, ctx context.Context, cfg BoltConfig) string {
t.Helper()
before := withRepo(t, []string{"config.yaml"}, []string{"github.com/gorilla/mux", "golang.org/x/text"})
eager := cfg
eager.Eager, eager.FullRun = true, true
pushIT(t, ctx, before, eager)
app := before.Application.ID
if c, d, l := repoState(t, ctx, cfg, app); c != 1 || d != 1 || l != 1 {
t.Fatalf("seed: config %d, DECLARES_DEPENDENCY %d, LOCKS %d; want 1 each", c, d, l)
}
return app
}

// after is the "after" state: config.yaml deleted, golang.org/x/text removed.
func after(t *testing.T) *v2.Analysis {
return withRepo(t, nil, []string{"github.com/gorilla/mux"})
}

func TestIntegration_EagerPushRemovesVanishedArtifacts(t *testing.T) {
ctx := context.Background()
cfg := itConfig(t)
app := seed(t, ctx, cfg)

eager := cfg
eager.Eager, eager.FullRun = true, true
pushIT(t, ctx, after(t), eager)
if c, d, l := repoState(t, ctx, cfg, app); c != 0 || d != 0 || l != 0 {
t.Errorf("after an eager push: config %d, DECLARES_DEPENDENCY %d, LOCKS %d; want 0 each", c, d, l)
}
if n := countIT(t, ctx, cfg, "MATCH (:GoApplication {id: $app})-[:HAS_ARTIFACT]->(n:Artifact:GoCanNode) RETURN count(n)",
map[string]any{"app": app}); n != 2 {
t.Errorf("artifacts after an eager push = %d, want 2 (go.mod, go.sum)", n)
}
}

func TestIntegration_LazyPushKeepsVanishedArtifacts(t *testing.T) {
ctx := context.Background()
cfg := itConfig(t)
app := seed(t, ctx, cfg)

lazy := cfg
lazy.FullRun = true
pushIT(t, ctx, after(t), lazy)
if c, d, l := repoState(t, ctx, cfg, app); c != 1 || d != 1 || l != 1 {
t.Errorf("after a lazy push: config %d, DECLARES_DEPENDENCY %d, LOCKS %d; want 1 each (lazy never deletes)", c, d, l)
}
}

// TestIntegration_EagerPushKeepsSharedArtifact (Q5): a sibling analyzer's claim
// on an artifact survives an eager Go push that no longer has the artifact,
// and so does its dependency edge on a kept artifact.
func TestIntegration_EagerPushKeepsSharedArtifact(t *testing.T) {
ctx := context.Background()
cfg := itConfig(t)
app := seed(t, ctx, cfg)
const py = "can://it-sibling/py"
p := map[string]any{"py": py, "cfg": app + "/artifact/config.yaml", "mod": app + "/artifact/go.mod"}
runIT(t, ctx, cfg, "MERGE (a:PyApplication {id: $py}) WITH a "+
"MATCH (c:Artifact {id: $cfg}), (m:Artifact {id: $mod}) "+
"MERGE (a)-[:HAS_ARTIFACT]->(c) "+
"MERGE (m)-[:DECLARES_DEPENDENCY]->(:Package {id: 'pkg:pypi/requests'})", p)
t.Cleanup(func() {
runIT(t, ctx, cfg, "MATCH (n) WHERE n.id IN [$py, 'pkg:pypi/requests'] DETACH DELETE n", p)
})

eager := cfg
eager.Eager, eager.FullRun = true, true
pushIT(t, ctx, after(t), eager)

if n := countIT(t, ctx, cfg, "MATCH (:PyApplication {id: $py})-[:HAS_ARTIFACT]->(c:Artifact {id: $cfg}) RETURN count(c)", p); n != 1 {
t.Errorf("the sibling's config.yaml artifact or its HAS_ARTIFACT is gone (count %d)", n)
}
if n := countIT(t, ctx, cfg, "MATCH (c:Artifact:GoCanNode {id: $cfg}) RETURN count(c)", p); n != 0 {
t.Errorf("config.yaml keeps the Go claim after Go no longer has it")
}
if n := countIT(t, ctx, cfg, "MATCH (:Artifact {id: $mod})-[r:DECLARES_DEPENDENCY]->(:Package {id: 'pkg:pypi/requests'}) RETURN count(r)", p); n != 1 {
t.Errorf("the sibling's DECLARES_DEPENDENCY on go.mod is gone")
}
}
Loading
Loading