diff --git a/CLAUDE.md b/CLAUDE.md index f4425d4..34f24ba 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -12,13 +12,43 @@ 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 - `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 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 + 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. + **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. + 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. +- **`start_line` / `end_line`** [user, 2026-11-21; spec `docs/design/specs/v2-span-lines.md`]: top-level keys next + 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). @@ -64,8 +94,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. @@ -129,6 +160,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/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-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. diff --git a/docs/design/specs/v2-artifacts.md b/docs/design/specs/v2-artifacts.md new file mode 100644 index 0000000..6d8ed76 --- /dev/null +++ b/docs/design/specs/v2-artifacts.md @@ -0,0 +1,155 @@ +# 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. + +## 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 + 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. diff --git a/docs/design/specs/v2-go-ids.md b/docs/design/specs/v2-go-ids.md new file mode 100644 index 0000000..b35ba2d --- /dev/null +++ b/docs/design/specs/v2-go-ids.md @@ -0,0 +1,158 @@ +# 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** (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 + 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. + +## 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. + +## 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. +- Any new node kind, edge kind, or field. +- Renaming the `signature` field (kept as-is). diff --git a/docs/design/specs/v2-span-lines.md b/docs/design/specs/v2-span-lines.md new file mode 100644 index 0000000..70edc4e --- /dev/null +++ b/docs/design/specs/v2-span-lines.md @@ -0,0 +1,40 @@ +# 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. + +## 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). +- Comments and variable declarations, which Python emits and v2 Go does not carry. diff --git a/go.mod b/go.mod index dcc5ee5..cfd3e2f 100644 --- a/go.mod +++ b/go.mod @@ -5,12 +5,12 @@ go 1.26.0 require ( github.com/neo4j/neo4j-go-driver/v5 v5.28.5 github.com/spf13/cobra v1.8.0 + golang.org/x/mod v0.42.0 golang.org/x/tools v0.52.0 ) require ( github.com/inconshreveable/mousetrap v1.1.0 // indirect github.com/spf13/pflag v1.0.5 // indirect - golang.org/x/mod v0.42.0 // indirect golang.org/x/sync v0.24.0 // indirect ) diff --git a/internal/core/analyzer.go b/internal/core/analyzer.go index a82ac2c..cef7c05 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" @@ -43,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. @@ -84,15 +89,37 @@ 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. 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.cacheRoot, + }) + 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/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/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) + } + } +} 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/core/external_collision_test.go b/internal/core/external_collision_test.go new file mode 100644 index 0000000..402f014 --- /dev/null +++ b/internal/core/external_collision_test.go @@ -0,0 +1,98 @@ +package core_test + +import ( + "encoding/json" + "os" + "path/filepath" + "testing" +) + +// Two library callees can share one @external id. Here, package example.com/dep +// has type Box with method Put, and its sub-package example.com/dep/Box has +// function Put. Both would be example.com/dep/Box/Put. Before the fix, one +// external_symbols entry overwrote the other, so the method's call edge resolved +// to the function's metadata. +// +// Practical shape (the dependency sits outside the project and is replaced in): +// +// dep/dep.go type Box struct{}; func (Box) Put(s string) string +// dep/Box/box.go package box; func Put(s string) string +// proj/main.go dep.Box{}.Put("a") ; box.Put("b") +func TestExternalIDs_TypeMethodAndFunctionKeepSeparateSymbols(t *testing.T) { + base := t.TempDir() + dep := filepath.Join(base, "dep") + proj := filepath.Join(base, "proj") + files := map[string]string{ + filepath.Join(dep, "go.mod"): "module example.com/dep\n\ngo 1.22\n", + filepath.Join(dep, "dep.go"): "package dep\n\ntype Box struct{}\n\nfunc (Box) Put(s string) string { return \"method:\" + s }\n", + filepath.Join(dep, "Box", "box.go"): "package box\n\nfunc Put(s string) string { return \"func:\" + s }\n", + filepath.Join(proj, "go.mod"): "module example.com/proj\n\ngo 1.22\n\nrequire example.com/dep v0.0.0\n\nreplace example.com/dep => " + dep + "\n", + filepath.Join(proj, "main.go"): "package main\n\nimport (\n\t\"fmt\"\n\n\t\"example.com/dep\"\n\tbox \"example.com/dep/Box\"\n)\n\n" + + "func main() {\n\tfmt.Println(dep.Box{}.Put(\"a\"), box.Put(\"b\"))\n}\n", + } + for path, content := range files { + if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil { + t.Fatal(err) + } + if err := os.WriteFile(path, []byte(content), 0o644); err != nil { + t.Fatal(err) + } + } + + var doc struct { + Application struct { + ExternalSymbols map[string]struct { + ID string `json:"id"` + Module string `json:"module"` + Signature string `json:"signature"` + } `json:"external_symbols"` + CallGraph []struct { + Src string `json:"src"` + Dst string `json:"dst"` + } `json:"call_graph"` + } `json:"application"` + } + if err := json.Unmarshal(emitCallGraphJSON(t, proj), &doc); err != nil { + t.Fatal(err) + } + + // Each callee needs its own symbol, with its own metadata. + var methodID, funcID string + for id, sym := range doc.Application.ExternalSymbols { + if sym.ID != id { + t.Errorf("symbol keyed %s carries id %s", id, sym.ID) + } + switch { + case sym.Signature == "Box.Put" && sym.Module == "example.com/dep": + methodID = id + case sym.Signature == "Put" && sym.Module == "example.com/dep/Box": + funcID = id + } + } + if methodID == "" { + t.Fatalf("no external symbol for method dep.Box.Put; have %+v", doc.Application.ExternalSymbols) + } + if funcID == "" { + t.Fatalf("no external symbol for function box.Put; have %+v", doc.Application.ExternalSymbols) + } + if methodID == funcID { + t.Fatalf("method and function share id %s", methodID) + } + + // The two calls from main must reach their own symbols. + var toMethod, toFunc bool + for _, e := range doc.Application.CallGraph { + if e.Dst == methodID { + toMethod = true + } + if e.Dst == funcID { + toFunc = true + } + } + if !toMethod { + t.Errorf("no call edge reaches the method symbol %s", methodID) + } + if !toFunc { + t.Errorf("no call edge reaches the function symbol %s", funcID) + } +} 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/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/core/span_lines_test.go b/internal/core/span_lines_test.go new file mode 100644 index 0000000..8d97983 --- /dev/null +++ b/internal/core/span_lines_test.go @@ -0,0 +1,110 @@ +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) + 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/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/bolt.go b/internal/neo4j/bolt.go index da5b001..3042f52 100644 --- a/internal/neo4j/bolt.go +++ b/internal/neo4j/bolt.go @@ -129,6 +129,22 @@ func (w *boltWriter) run() error { } } + // Purge every changed module before upserting any of them. A module's purge is + // 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] { + 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 +153,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 } @@ -326,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", @@ -338,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() @@ -347,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/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 78fde41..3cb6e93 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) } @@ -56,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, @@ -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) { @@ -95,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, ) @@ -117,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": lastSegment(t.ID), - "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, ) @@ -141,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, "") @@ -149,8 +195,23 @@ 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: owner} + p.b.Edge(RelDeclares, declaring, mRef, nil, "") + } } } @@ -170,7 +231,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, ) @@ -213,7 +275,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), }, @@ -388,6 +451,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/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..2ba98e8 100644 --- a/internal/neo4j/schema.go +++ b/internal/neo4j/schema.go @@ -190,26 +190,26 @@ 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, - 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,19 +220,22 @@ 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, 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/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/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/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..18a518f --- /dev/null +++ b/internal/repository/repository.go @@ -0,0 +1,379 @@ +// 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" + "errors" + "fmt" + "io" + "io/fs" + "os" + "path/filepath" + "sort" + "strings" + + "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. +// +// 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 := resolveDir(root) + if err != nil { + 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) + } + 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 { + 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)) { + 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 + } + info, err := d.Info() + if err != nil { + utils.Warn("repository: skipping %s: %v", rel, err) + return nil + } + art, err := readArtifact(p, info, rel, opts.CaptureText) + if err != nil { + // 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 + }) + if err != nil { + return nil, fmt.Errorf("artifact discovery: %w", err) + } + return out, nil +} + +// optionalDir resolves an optional directory setting; "" means unset. +func optionalDir(p string) (string, error) { + if p == "" { + 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 "", 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 + } +} + +// 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 + } + 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, s.binary()), + SizeBytes: s.size, + SHA256: hex.EncodeToString(s.sum()), + Extraction: "none", + } + switch rel { + case "go.mod": + art.Roles = []string{"dependency-manifest"} + case "go.sum": + art.Roles = []string{"lockfile"} + } + 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 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 base { + case "go.mod": + return "gomod" + 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" + } + 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. 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) + 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 { + 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") { + 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/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) + } + } + } +} 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) + } +} 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/ids.go b/internal/schema/v2/ids.go index e2e0788..fefc9f2 100644 --- a/internal/schema/v2/ids.go +++ b/internal/schema/v2/ids.go @@ -1,6 +1,8 @@ package v2 import ( + "crypto/sha256" + "encoding/hex" "fmt" "strings" "unicode" @@ -15,18 +17,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 +101,54 @@ 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) +} + +// DisambiguateExternalIDs gives every external callee a distinct id. plain maps a +// callee's full signature to its ExternalID. The dot-to-segment rule is not +// injective: a method Box.Put in package example.com/dep and a function Put in +// package example.com/dep/Box both give example.com/dep/Box/Put. A callee whose +// plain id is unique keeps it, so every id that was already emitted is unchanged. +// Callees that share a plain id each get ":" plus the first 16 hex digits of the +// SHA-256 of their own full signature. That suffix depends only on the callee, not +// on which other callees are present or in what order, so an id is stable while +// the collision lasts and no callee overwrites another. +func DisambiguateExternalIDs(plain map[string]string) map[string]string { + count := make(map[string]int, len(plain)) + for _, id := range plain { + count[id]++ + } + out := make(map[string]string, len(plain)) + for fullSig, id := range plain { + if count[id] > 1 { + sum := sha256.Sum256([]byte(fullSig)) + id += ":" + hex.EncodeToString(sum[:8]) + } + out[fullSig] = id + } + return out +} + +// 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 +161,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_external_test.go b/internal/schema/v2/ids_external_test.go new file mode 100644 index 0000000..10426e4 --- /dev/null +++ b/internal/schema/v2/ids_external_test.go @@ -0,0 +1,63 @@ +package v2 + +import "testing" + +const extApp = "can://ns/app" + +// Unique external ids are returned unchanged: every id already emitted stays valid. +func TestDisambiguateExternalIDs_UniqueIDsUnchanged(t *testing.T) { + plain := map[string]string{ + "fmt.Println": ExternalID(extApp, "fmt", "Println"), + "strings.Builder.WriteString": ExternalID(extApp, "strings", "Builder.WriteString"), + } + got := DisambiguateExternalIDs(plain) + for sig, id := range plain { + if got[sig] != id { + t.Errorf("%s: id changed from %s to %s", sig, id, got[sig]) + } + } +} + +// The motivating case: a method and a function that share a plain id both get +// distinct, suffixed ids, and neither keeps the plain one. +func TestDisambiguateExternalIDs_CollidingCalleesAreDistinct(t *testing.T) { + const method = "example.com/dep.Box.Put" + const function = "example.com/dep/Box.Put" + plainID := ExternalID(extApp, "example.com/dep/Box", "Put") // both map here + plain := map[string]string{ + method: ExternalID(extApp, "example.com/dep", "Box.Put"), + function: plainID, + } + if plain[method] != plain[function] { + t.Fatalf("fixture does not collide: %s vs %s", plain[method], plain[function]) + } + got := DisambiguateExternalIDs(plain) + if got[method] == got[function] { + t.Fatalf("colliding callees still share id %s", got[method]) + } + for sig := range plain { + if got[sig] == plainID { + t.Errorf("%s kept the plain id %s", sig, plainID) + } + } +} + +// The suffix depends only on the callee's own signature, so adding or removing an +// unrelated callee does not change an id, and the order of the set does not matter. +func TestDisambiguateExternalIDs_StableAcrossSets(t *testing.T) { + plainID := ExternalID(extApp, "example.com/dep/Box", "Put") + a := "example.com/dep.Box.Put" + b := "example.com/dep/Box.Put" + c := "example.com/other.Box.Put" + + pair := DisambiguateExternalIDs(map[string]string{a: plainID, b: plainID}) + triple := DisambiguateExternalIDs(map[string]string{ + a: plainID, b: plainID, c: ExternalID(extApp, "example.com/other", "Box.Put"), + }) + if pair[a] != triple[a] || pair[b] != triple[b] { + t.Errorf("an unrelated callee changed a colliding id: pair=%v triple=%v", pair, triple) + } + if triple[c] != ExternalID(extApp, "example.com/other", "Box.Put") { + t.Errorf("a unique callee was renamed: %s", triple[c]) + } +} 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 800c694..0f331e5 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). @@ -97,6 +100,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"` @@ -148,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 @@ -165,10 +177,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 ───────────────────────────────────────────────────────────────────── @@ -176,9 +190,14 @@ 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"` // BaseTypes are embedded type ids (struct/interface embedding — the explicit // spine). BaseTypes []string `json:"base_types,omitempty"` @@ -194,10 +213,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 ───────────────────────────────────────────────────────────────── @@ -205,10 +226,13 @@ 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"` - // Signature is the human-readable last path segment of ID (one signatureOf()). + 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"` // 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 @@ -248,6 +272,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"` } @@ -266,6 +292,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. @@ -341,3 +370,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/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/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 3f0279e..16dad46 100644 --- a/internal/syntactic_analysis/v2emit/emit.go +++ b/internal/syntactic_analysis/v2emit/emit.go @@ -248,12 +248,14 @@ 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), }, } - out.Application.ExternalSymbols = emitExternalSymbols(e.appID, app.Externals, e.sdg.standIns()) + out.Application.ExternalSymbols = emitExternalSymbols(app.Externals, e.idx.externals, e.sdg.standIns()) + out.Application.Artifacts, out.Application.Dependencies = emitRepository(e.appID, app.Repository) if e.flow.on { out.KLimit = kLimit } @@ -276,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), @@ -291,7 +296,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) @@ -303,29 +308,36 @@ 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) + tsp := lineSpan(li, t.StartLine, t.EndLine) out := v2.Type{ ID: typeID, Kind: typeKind(t), - Span: lineSpan(li, t.StartLine, t.EndLine), + Signature: t.Signature, + 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], } } } 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 } @@ -369,10 +381,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), @@ -416,10 +431,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, @@ -455,19 +473,23 @@ func calleeID(sig *string, idx sigIndex) *string { } // externalIDs maps each library callee's full signature to its @external id. +// +// The result is the single source of external ids: the call-edge index and +// external_symbols both read it, so an edge and its symbol always agree. Ids +// that collide are made distinct (v2.DisambiguateExternalIDs). func externalIDs(appID string, externals map[string]schema.GoExternalCallee) map[string]string { - ids := make(map[string]string, len(externals)) + plain := make(map[string]string, len(externals)) for fullSig, ext := range externals { - ids[fullSig] = v2.ExternalID(appID, ext.ImportPath, ext.Sig) + plain[fullSig] = v2.ExternalID(appID, ext.ImportPath, ext.Sig) } - return ids + return v2.DisambiguateExternalIDs(plain) } // emitExternalSymbols builds application.external_symbols, keyed by @external // id. Nil (omitted from JSON) when no library callee was recorded. At L4 // standIns (by full callee signature) gives each stand-in its body: its // formal vertices, id v2.GlobalOrdinal(external id, key). -func emitExternalSymbols(appID string, externals map[string]schema.GoExternalCallee, standIns map[string][]sdg.Vertex) map[string]v2.ExternalSymbol { +func emitExternalSymbols(externals map[string]schema.GoExternalCallee, ids map[string]string, standIns map[string][]sdg.Vertex) map[string]v2.ExternalSymbol { for _, sig := range slices.Sorted(maps.Keys(standIns)) { if _, ok := externals[sig]; !ok { warnf("L4 emit: stand-in %s is not an external symbol; its body is dropped", sig) @@ -478,7 +500,7 @@ func emitExternalSymbols(appID string, externals map[string]schema.GoExternalCal } out := make(map[string]v2.ExternalSymbol, len(externals)) for fullSig, ext := range externals { - id := v2.ExternalID(appID, ext.ImportPath, ext.Sig) + id := ids[fullSig] params := make([]v2.ExternalParameter, 0, len(ext.Params)) for _, p := range ext.Params { params = append(params, v2.ExternalParameter{Name: p.Name, Type: p.Type, IsVariadic: p.IsVariadic}) @@ -504,10 +526,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, }) } @@ -517,11 +542,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 } 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..3b98d89 100644 --- a/internal/syntactic_analysis/v2emit/gate_l3_test.go +++ b/internal/syntactic_analysis/v2emit/gate_l3_test.go @@ -502,13 +502,12 @@ 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 { 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 +530,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..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 @@ -599,7 +598,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) } 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 +} diff --git a/internal/syntactic_analysis/v2emit/sigindex.go b/internal/syntactic_analysis/v2emit/sigindex.go index 00ed238..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 @@ -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. @@ -80,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. diff --git a/scripts/eval_e2e.sh b/scripts/eval_e2e.sh new file mode 100755 index 0000000..34188ec --- /dev/null +++ b/scripts/eval_e2e.sh @@ -0,0 +1,187 @@ +#!/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 [--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). +# --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) +# 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 + +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 +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 + # 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 + +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; } + +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. +# 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=$? +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" +fi + +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 + +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 + 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 + +fi + +echo +if [ "$fail" -eq 0 ]; then + 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 +exit "$fail"