Skip to content

About

Reads a Java/Spring Boot codebase into a deterministic knowledge graph (AST + complexity + Spring semantics) and renders idiomatic TypeScript/NestJS source.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Repository files navigation

Codeograph

Reads a Java/Spring Boot codebase and emits a deterministic knowledge graph — nodes, edges, complexity metrics, Spring-aware annotations — reproducible byte-for-byte across runs. (Not yet when the Java parser fails on a file — see Known gaps.)

Status: pre-1.0 — deterministic graph, LLM enrichment, eval framework, TypeScript/NestJS renderer, run manifest + structured logging, cost-safety floor + multi-provider LLM support. See ROADMAP.md for versions and what is planned, and docs/architecture.md for the full pipeline.

Point of view

A generation of tools already covers individual pieces of this space: deterministic graph analysis, architecture governance, security scanning, and same-language modernization. Codeograph builds on established patterns and positions itself honestly against that prior art as a narrow extension, not a reinvention or replacement.

Existing property-graph and analysis tools stop at understanding, and transpilers or modernization engines don't build on a shared architectural graph. Codeograph targets the seam between those families: it emits a deterministic, metrics-carrying knowledge graph for a Java/Spring codebase and then uses it to drive a pluggable cross-language renderer that generates NestJS source around a deterministic project scaffold.

Codeograph is built on the belief that codebases should be understood and structured deterministically, and that AI should sit on top of that as an augmentor — explaining, suggesting, and translating, but never quietly becoming the driver. Its stance is to see how far a deterministic knowledge graph can carry cross-stack work — understanding and rendering into new stacks — without handing control to AI.

Codeograph renders to TypeScript/NestJS today, with Go planned (see the Roadmap); it does not replace tools that already do governance, SAST, same-language refactoring, or transpilation well.

Requirements

  • Python ≥ 3.12
  • Java 17+ (for the bundled AST parser; regex fallback runs without it)
  • Maven 3.9+ (only when rebuilding the parser JAR)

Quick start

pip install -e ".[dev]"
codeograph run /path/to/java/project --out ./out

Output (always start from manifest.json):

File Description
out/manifest.json Entry point: run identity, schema_version: "2.0.0", SHA-256 of every artefact, llm_skipped flag
out/graph.json Deterministic AST graph — nodes, edges, complexity metrics
out/llm-annotations.json LLM per-node annotations, Pass 1 (full run only; absent on --ast-only, indicated by llm_skipped: true)
out/corpus-synthesis.json LLM corpus-level synthesis, Pass 2 (full run only; absent on --ast-only)
out/logs.jsonl Structured run log

Input can be a local directory path, a git URL, or a .zip archive.

Running tests

make test                     # Python unit tests
make lint                     # ruff
make typecheck                # mypy
make golden-update            # refresh Tier 1 / Tier 2 golden graphs

cd codeograph/parser/java
mvn test                      # Java parser tests (JavaParser-based)

Project layout

codeograph/                    Python package
  analyzer/                    CorpusAnalyzer — pipeline orchestrator
  cli/                         CLI entry point (run, eval, render, cache)
  config/                      pydantic-settings + YAML config source
  evals/                       eval framework — scorecards, checks, runner, report
  graph/                       GraphBuilder, GraphAssembler, GraphWriter + models
  input/                       corpus acquisition + source discovery
  llm/                         LLM provider, prompts, cache, middleware
  manifest/                    Manifest schema (2.0.0), IO, run_id, schema_cli
  parser/                      FileParserDispatcher, RegexFallback
    java/                      Maven module — builds parser.jar (JavaParser AST)
  passes/                      Pass 1 (annotator), Pass 2 (synthesizer)
  prompts/                     versioned prompt files (annotate_node, synthesize_corpus)
  renderers/                   pluggable renderer registry; typescript_nestjs/
  rendering/                   class selection + domain grouping (ADR-009)
  scripts/                     verify_gitleaks_pin + operational scripts
  telemetry/                   JSONL LLM telemetry emitter + aggregation
_generated/
  manifest.schema.json         committed JSON Schema (regenerated from Pydantic)
docs/
  architecture.md              current architecture snapshot
  adr/                         architecture decision records (ADR-001..035)
tests/
  fixtures/codeograph-corpus/  Tier 1 surgical fixture
  golden/codeograph-corpus/    stored golden graph (byte-equal regression)
  ...                          unit tests mirror codeograph/ layout

LLM Features

Codeograph includes an LLM enrichment pipeline (Passes 1 and 2) that adds semantic understanding alongside the deterministic AST graph, kept in files of its own:

  • Separate LLM Artefacts: Detailed per-node semantics (Pass 1) stored in llm-annotations.json; corpus-level synthesis (Pass 2) stored in corpus-synthesis.json.
  • Response Cache: A local SQLite cache (cache.db) stores responses. You can manage the cache using the codeograph cache CLI (e.g., codeograph cache stats or codeograph cache purge).
  • Telemetry: Every LLM call is recorded as a structured JSONL row in the telemetry/ output folder, carrying token usage, latency, and cache-hit details.

The graph tells Codeograph what is there — nodes, edges, framework semantics, and metrics from precise, reproducible deterministic analysis; LLM Pass 1 explains what it means at the per-node level. The LLM passes matter because they add the layer deterministic analysis cannot supply — per-node explanation, onboarding summaries, and role inference grounded in that verified structure, making the graph easier to read and more useful without changing what the system treats as truth. LLM Pass 2 reaches into riskier corpus-level synthesis, but all LLM output stays advisory in separate artefacts and is contained so the deterministic graph stays authoritative.

Cost-Safety Floor & Limits

To prevent accidental runaway API bills during large runs, Codeograph implements a pre-flight cost safety floor and middleware ceiling limits:

  • Pre-flight Cost Estimate: Before starting Pass 1, Codeograph parses the corpus (Pass 0), derives the expected call count (class_count + 1), queries a localized model pricing database (prices.toml), and prints an estimate of the total cost and calls. The figure is labelled as an estimate from a dated price table, not a quote — actual cost depends on the model, caching and the provider's current pricing.
  • TTY Confirmation Gate: If the estimated call count exceeds the default confirmation threshold (100 calls, configurable via --llm-call-confirm-threshold), the pipeline prompts the user on an interactive terminal (TTY) or auto-aborts in non-TTY environments (CI/pipelines). --yes / -y proceeds without a prompt; --non-interactive never prompts and aborts above the threshold unless --yes is also given.
  • Hard Ceilings: You can configure hard limits using --max-llm-calls N or --max-tokens-total M. A middleware wrapper checks both before each call and refuses a call that would pass either ceiling; the run then stops with exit status 1 and a message naming the ceiling and how many classes were annotated. No manifest is written for a stopped run.

Note

The estimate and the confirmation gate are permanent. The call and token ceilings remain until a ceiling in money is designed, which decides whether they stay. Planned additions: a dry run that estimates cost without making paid calls, a ceiling in money (--max-cost-usd), and a report of token use and cost at the end of each run and render. codeograph render shows no estimate and asks no confirmation yet — see Known gaps.

Rendering

codeograph render converts an existing run output into a TypeScript/NestJS project: each selected class is translated into full idiomatic NestJS source — method bodies included, not skeletons — via one LLM call, emitted alongside a deterministic Jinja2 project scaffold (package.json, tsconfig.json, bootstrap main.ts). Features the renderer cannot translate faithfully surface as reviewable TODO/stub placeholders or explicit refuse-to-render entries — never silent drops — under a configurable per-feature policy. Rendering is decoupled from LLM execution so you can tune rendering parameters (ORM mode, class budget, domain grouping) without re-running the expensive annotation passes.

Two parts of this do not hold yet: a class refused by a feature policy is currently left out of the output without a placeholder, and the per-feature policies and domain grouping cannot yet be set — see Known gaps.

codeograph render --from ./out --out ./ts-out --target typescript

Key flags:

Flag Default Description
--from DIR required Output directory from a prior codeograph run
--out DIR required Destination for the rendered TypeScript project
--target typescript Renderer target (--list-targets prints registered targets)
--db-layer typeorm ORM mode. typeorm is the only value
--max-classes-per-domain N 3 Per-domain class cap (stratified sampling, ADR-009); 0 disables the cap and renders every class
--no-scaffold off Skip NestJS scaffold files (package.json, tsconfig, etc.)
--force off Overwrite --out if non-empty

Rendering calls the LLM once per selected class. The second run against the same corpus hits the response cache — no additional API cost.

Evaluation

codeograph eval runs scorecard checks against an existing run output. Scorecards are JSON sidecar files written to <out>/evals/.

# Single-corpus scorecard
codeograph eval run ./out

# Cross-corpus comparison across multiple runs
codeograph eval report ./run1 ./run2 ./run3

eval run options:

Flag Description
--scorecard graph|ts Restrict to specific scorecards (default: all)
--check <id> Run only the named check IDs
--skip-check <id> Skip named check IDs

The graph scorecard runs 6 deterministic checks (structural_completeness, relationship_correctness, internal_consistency, schema_validity, reproducibility, golden_graph_agreement); some of them measure less than their names say — see Known gaps. The code-quality scorecard runs 3 checks (compilation, feature coverage, llm_judge — the latter two are skip: llm_judge pending ADR-020 calibration, feature coverage for the reason under Known gaps; compilation does not run yet either, see Known gaps).

You can also run eval automatically as part of codeograph run using --eval:

codeograph run /path/to/project --out ./out --eval

Logging

Codeograph emits logs via two channels simultaneously:

  • Console (stderr): Human-readable plaintext, default level INFO. Format: <UTC timestamp> <LEVEL> [area] message.
  • File (<out>/logs.jsonl): Structured JSONL at DEBUG level, always written during a run. Fields: run_id, logger, context, level, ts, msg.

Log level is controlled via global flags (before the subcommand):

codeograph -v run ...        # DEBUG console output
codeograph -q run ...        # WARNING only
codeograph -qq run ...       # ERROR only
codeograph --log-level DEBUG run ...   # explicit level (wins over -v/-q)

The run manifest (manifest.json) is written once at the terminal checkpoint, after all passes complete. It records the run_id, artefact SHA-256s, schema version (2.0.0), and optional pointers to scorecards and compile-checks. The committed JSON Schema at _generated/manifest.schema.json is the external validator contract; a CI gate keeps it in sync with the Pydantic source.

Limitations

  • TypeScript/NestJS renderer only. The Go renderer (ADR-011) is planned — scope SC-009 in the Roadmap.
  • Providers: Anthropic, OpenRouter, and any OpenAI-compatible endpoint; Ollama and Bedrock not scheduled. All run through a LangChain-based provider abstraction (AnthropicProvider, OpenRouterProvider, OpenAICompatibleProvider with a configurable base_url). Ollama and Bedrock are wired in the resolver but raise NotImplementedError. A single model (default claude-sonnet-4-6) serves all stages by default; per-stage model overrides (llm_model_fast / deep / render, used by Pass 1 / Pass 2 / rendering) are configurable, but there is no curated differential per-stage mapping, and none is scheduled.
  • Sync LLM calls; no Batch API. All LLM calls are synchronous. The Anthropic Batch API (50% discount) is not scheduled.
  • CI runs on Linux only. Local tests pass on Windows/macOS; the automated CI infrastructure runs on ubuntu-latest. Multi-OS CI is not scheduled; it would be added on contributor demand.
  • No live-LLM tests. The test suite uses a deterministic MockLlmProvider. No tests make live API calls; the 80% line coverage gate applies to codeograph/.
  • Eval covers two committed corpora. spring-rest-sample and spring-blog-api are the baseline corpora; codeograph eval report provides cross-corpus comparison. Additional corpora can be added to examples/ per CONTRIBUTING.md.
  • semantic_accuracy and llm_judge checks are skipped. The graph and code-quality scorecards reserve these slots; calibration data and the LLM-judge harness are planned — scope SC-010 in the Roadmap (ADR-020).
  • Coverage check means feature coverage, not test coverage. The code-quality scorecard coverage check measures which Spring annotation categories from the ADR-010 audit were translated into TypeScript — not pytest line coverage.
  • Per-run output is <out> itself. There is no --runs-dir flag. Each codeograph run invocation owns its --out directory. To keep multiple run histories, use distinct --out paths (e.g. --out ./runs/$(date -u +%Y-%m-%dT%H-%M-%SZ)/).
  • Manifest schema is strict-additive within 2.x. Field removal, rename, type-change, or required/optional flips require a 3.0.0 major bump and a superseding ADR. New fields land as minor bumps. External consumers can pin a 2.x validator and rely on forward compatibility.
  • No log rotation or color output. logs.jsonl grows unboundedly per run; no log-level env-var override. None of these is scheduled.
  • Gitleaks secret scanning is enforced in CI; merges are blocked on detection; no admin bypass. The pre-commit hook is opt-in (pre-commit install after setup); CI is the mandatory gate. The gitleaks version is exact-pinned in both secrets-scan.yml and .pre-commit-config.yaml with a CI parity check, and a scheduled full-history scan runs nightly (non-blocking). See CONTRIBUTING.md for the finding-response runbook.
  • Output stability tracks schema_version, not the application version. The app version (codeograph --version, currently 0.5.0) and the artefact schema_version are independent version lines. Consumers scripting against graph.json / manifest.json should pin or check schema_version; the app version is not a format-stability guarantee. The tool ships in 0.x — 1.0.0 is published only at the stability gate (ADR-026).

Known gaps

The limitations above are deliberate scope. These are different: places where the code does not yet do what this README, the requirements, or an accepted ADR says it does. Each is tracked for a fix.

  • A parser failure can change the graph. When the Java parser times out on a file (30 s), crashes, or cannot start because Java is not available, that file is extracted by the regex fallback, with no retry. The same source can therefore produce a different graph on a slow or misconfigured machine. Each fallback is logged as a warning.
  • No classpath resolution yet, for Maven or Gradle. Method calls are resolved by a source-only heuristic (self-calls, and calls on a class, field or parameter whose type is a project class — imported, in the caller's own package, or through a wildcard import); a call through a local variable, and every call after the first in a chain, stays unresolved and is emitted as calls_unresolved, never dropped. Symbol-solver resolution against the local Maven repository (ADR-003) is not yet implemented.
  • Some graph-scorecard checks measure less than their names say. structural_completeness reports the share of declarations extracted by the full parser rather than comparing the graph against the source; relationship_correctness checks only that resolved calls point at nodes that exist; internal_consistency runs four rules: the check that every annotation names a class in the graph (next entry) is not among them, and its unresolved-call rule checks only that an origin and a target are present; reproducibility re-runs extraction without enrichment and compares those runs with each other, not with the scored graph, and it skips for git and archive sources when evaluated after the run with eval run. The rationale text in the committed example scorecards overstates the first three.
  • The annotations are not checked against the graph. Every entry in llm-annotations.json should belong to a class in the graph, checked by the internal-consistency evaluation (ADR-006). No check reads the annotations yet, so an annotation for a class that is not in the graph goes unnoticed.
  • Refused classes leave no placeholder. A class refused by a feature policy, or whose render call fails, is left out of the rendered output; a refusal is logged at debug level only.
  • Render policies and domain grouping cannot yet be set. codeograph render reads only its command-line flags; the [render.typescript] configuration section is not read yet, so the defaults always apply — security and WebFlux classes refused, other unsupported features rendered as stub + TODO, package-prefix domain grouping. WebFlux classes are detected from the LLM's annotations rather than from the graph, so a class whose annotation is missing, or does not list its reactive return types, is rendered instead of refused.
  • The feature-coverage check does not run yet. The code-quality scorecard's coverage check needs a record of which features rendering translated, and rendering does not yet write one, so the check is always reported as skipped.
  • Rendered code is not compile-checked yet. The code-quality scorecard's compilation check looks for its compile record where the manifest no longer keeps it, and beside the run rather than the rendered project, so it is always reported as skipped; the CI evaluation does not run the TypeScript toolchain either.
  • Telemetry records no per-call cost. Each call's cost estimate is written as 0.0, so the cost lines in codeograph cache report always read ~$0.00. The pre-flight estimate shown before a run is computed separately and is unaffected.
  • codeograph render runs without the cost estimate and confirmation gate. It shows no estimate, asks no confirmation and takes no ceiling flags. A call or token ceiling set by environment variable or config file does apply to it; without one, its LLM calls are bounded only by the per-domain class cap, and not at all when the cap is disabled with 0.
  • Cloning a git URL that needs credentials can wait for input. git clone runs with prompting enabled, so for a private repository without stored credentials git may ask for a username and wait — in CI, a hang — instead of failing with an error that names the cause.
  • --non-interactive does not abort at the confirmation gate. Despite the description above, --non-interactive on its own lets a run above the call threshold go ahead without confirmation. In CI, pass --max-llm-calls to bound the spend; do not rely on --non-interactive to stop it.
  • Prompt caching is not requested yet. The cache marker that marks the shared prompt for the provider's reduced rate is not sent to Anthropic or, through OpenRouter, to an upstream that needs it, so only a provider that caches an identical prefix on its own gives the lower rate. The tool's own response cache is unaffected.
  • The response cache does not tell OpenAI-compatible endpoints apart. Two endpoints serving the same model id share cached responses, so a run against one can be answered from the other's. Use a separate CODEOGRAPH_CACHE_DIR per endpoint, or purge the cache when you switch.
  • An empty or unrecognised project is not reported as a failure. A directory with no Java file, or with Java files but no pom.xml or build.gradle, finishes with exit status 0, an empty graph and a manifest. Check the "Discovered … module(s) … Java file(s)" line after a run on a path you have not used before.
  • The graph has no module nodes. Modules are found and each class is linked to its module by a contains edge, but no node is written for the module itself, so a module's name and build system are not in graph.json and the edge's source is not among the nodes.
  • Some dependency edges still miss references the file does not import by name. depends_on edges follow a class in the file's own package and a project class reached through a wildcard import. JPA relation edges still need an explicit import, an autowires edge carries the field's type as written (OrderRepository, not its full name), and a library type gets no edge and no unresolved marker.
  • A superclass or interface from outside the project can stay unqualified. Project classes resolve to their full names, whether the file imports them, shares their package or imports their package with *. A JDK or library type the file does not import by name — extends Exception, or a type reached through import org.example.*; — keeps the name as written (Exception, not java.lang.Exception), though the graph schema describes these fields as fully qualified.
  • A nested .gitignore is not read, and other-language source is skipped silently. Only the project root's and each module root's ignore file applies, so a file ignored by one deeper in the tree is still analysed. A src/main/kotlin root is dropped without a log line or a record.
  • Configuration files are read from the current working directory. .env and config.yaml are looked up where the command runs, so running codeograph run . from inside the analysed project reads that project's own files. Run from a neutral directory, or pass settings through environment variables.

Documentation

About

Reads a Java/Spring Boot codebase into a deterministic knowledge graph (AST + complexity + Spring semantics) and renders idiomatic TypeScript/NestJS source.

Topics

Resources

Contributing

Stars

0 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages