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

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -80,9 +80,11 @@ packages/insights/ @codegraph/insights — the bottom-up EXPLANATION walk: uni
database) and its export, the `.insights.jsonl` side-car
(Specy domain vocabulary). Pure computation: source, model
calls and the database are injected.
packages/llm/ @codegraph/llm — LlmClient + OpenRouter (SDK) + Cloudflare
AI Gateway (REST) implementations + a deterministic fake.
The ONLY package that may import @openrouter/sdk.
packages/llm/ @codegraph/llm — LlmClient (the PORT) + its adapters: OpenRouter
(SDK), Cloudflare AI Gateway (REST), Claude Code headless
(subprocess: `claude -p`, found by discovery, no key) + a
deterministic fake. The Anthropic API (key) is a named empty
slot (PLAN §21.6). The ONLY package that may import @openrouter/sdk.
packages/cli/ @codegraph/cli — `codegraph` command.
packages/viz/ @codegraph/viz — Three.js code city: renders a laid-out
city.json artifact (its ONLY input; guard-enforced). The
Expand Down Expand Up @@ -246,9 +248,15 @@ node scripts/homebrew/render.mjs --version X.Y.Z --sums SHA256SUMS [--npm-sha256
./bin/codegraph explain model.jsonl --src DIR --dry-run # the walk plan, no call
./bin/codegraph explain model.jsonl --src DIR --estimate --price-in 0.10 --price-out 0.60 # tokens in/out + cost, no call
OPENROUTER_API_KEY=… ./bin/codegraph explain model.jsonl --src DIR [--max-calls N] [--yes]
# [--model SLUG] (default openai/gpt-5.6-luna) [--rollup-model SLUG] (types+modules; defaults to --model)
# [--model SLUG] (default per provider: openai/gpt-5.6-luna on openrouter/cloudflare, sonnet on claude-code)
# [--rollup-model SLUG] (types+modules; defaults to --model)
# prints the estimate on stderr and asks [y/N] first; --yes (required without a TTY) skips it
# or CLOUDFLARE_API_TOKEN=… CLOUDFLARE_ACCOUNT_ID=… [--provider cloudflare]
# or ./bin/codegraph explain model.jsonl --src DIR --provider claude-code [--claude-path FILE]
# the installed, logged-in Claude Code in headless mode (`claude -p`, one process per call, Sonnet, no key);
# the binary: --claude-path, else CLAUDE_CODE_PATH, else `claude` on PATH, else the known install locations.
# --provider auto (default) takes the one configured; with several: OpenRouter, Cloudflare, then Claude Code.
# --max-tokens does not apply to claude-code (noted, ignored); --concurrency N is N processes
# → model.insights.db (the working copy: one commit per finished unit) and its export
# model.insights.jsonl, both beside the model; re-runs redo only what changed
./bin/codegraph explain model.jsonl --export # the side-car from the store (after a killed run); no model read
Expand Down
212 changes: 208 additions & 4 deletions PLAN.md

Large diffs are not rendered by default.

15 changes: 11 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -288,6 +288,7 @@ codegraph replay --store gson.db --history gson-history.jsonl --serve
codegraph explain gson.jsonl --src ~/src/gson/gson/src/main/java --dry-run # the plan, no call
codegraph explain gson.jsonl --src ... --estimate --price-in 0.10 --price-out 0.60 # tokens and cost, no call
OPENROUTER_API_KEY=… codegraph explain gson.jsonl --src ... --max-calls 50 # shows the estimate, asks [y/N]
codegraph explain gson.jsonl --src ... --provider claude-code # the installed, logged-in Claude Code instead (Sonnet, no key)
codegraph explain gson.jsonl --src ... --model openai/gpt-5.6-luna --rollup-model anthropic/claude-sonnet-5 # pick the models
codegraph insights gson.jsonl # what was bought: records, concepts, what is owed, the spend
codegraph insights gson.jsonl --concept aggregate # the types the model read as aggregates
Expand All @@ -301,9 +302,14 @@ its export, `gson.insights.jsonl`; never into the model. `codegraph serve`
shows them on the selected type or module, marked as a model's inference.
Re-running redoes only the units whose inputs changed. On the reference
fixture a full run was 68 calls and about six cents. `--model` sets the model
for every unit (default `openai/gpt-5.6-luna`); `--rollup-model` overrides it
for types and modules only. Switching models re-explains the affected units. Cloudflare AI Gateway is
the other supported provider.
for every unit (default `openai/gpt-5.6-luna` on a key provider, `sonnet` on
Claude Code); `--rollup-model` overrides it for types and modules only.
Switching models re-explains the affected units. The calls go through one
port (`LlmClient`) and three adapters: OpenRouter (an API key), Cloudflare AI
Gateway (a token pair) and Claude Code headless (the `claude` CLI already
installed and logged in — found on `PATH` or named with `--claude-path`; no
key). `auto` prefers a key over the installed CLI; a direct Anthropic API
adapter is a named slot for later.

### Feed it to something else

Expand Down Expand Up @@ -367,7 +373,8 @@ Read these before you commit an afternoon.
repeatable, but the same package declared under several roots at once (main
and test sources, or one package split across modules) confuses noClasspath
resolution; pass such roots in separate runs.
- **`explain` costs money and needs a network.** It is the only command that
- **`explain` costs money and needs a network** (or an installed Claude Code,
which spends the subscription). It is the only command that
does. `--dry-run` and `--estimate` tell you what it would do first, a real
run asks for confirmation after showing the estimate (`--yes` in scripts),
and `--max-calls` caps it.
Expand Down
2 changes: 1 addition & 1 deletion WEBSITE.md
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,7 @@ Each page links to the tutorial or how-to that applies it.
| `time-as-structure.md` | Hotspots, ownership, co-change, hidden coupling and deadweight; why history is a dependency source cannot show; the replay design. | PLAN §11, Tornhill | write |
| `explaining-bottom-up.md` | Units, cycles as one unit, context packs, fingerprints, the side-car rule. | docs/insights.md | exists |
| `architecture.md` | The packages, the hard boundaries and why each exists. | CLAUDE.md, PLAN §1–2 | partial |
| `decisions.md` | The decision log. | PLAN §21 | exists |
| `decisions.md` | The decision log. | PLAN §23 | exists |
| `prior-art.md` | Moose/FamixNG, CodeCity, Structure101, Gource and Tornhill, Sourcetrail, jQAssistant, ArchUnit: what each does and where codegraph differs. | README credits | write |

### 4.5 Documentation debt found while writing (repository docs, not the site)
Expand Down
35 changes: 30 additions & 5 deletions docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,8 @@ codegraph domain-facts [model.jsonl] [--framework spring] [--out FILE]

codegraph explain [model.jsonl] [--src DIR] [--out FILE] [--dry-run]
[--estimate [--price-in USD --price-out USD]]
[--provider auto|openrouter|cloudflare]
[--provider auto|openrouter|cloudflare|claude-code]
[--claude-path FILE]
[--model SLUG] [--rollup-model SLUG] [--depth N]
[--max-calls N] [--max-tokens N] [--scope IDS]
[--concurrency N]
Expand Down Expand Up @@ -320,10 +321,34 @@ writes the side-car from the store and stops — after an interrupted run, or a
deleted file. Neither flag reads the model or needs a key.
Mutually dependent units (a cycle) are explained as one unit. Re-runs redo
only what changed (Merkle fingerprints over inputs, never over explanation
text). Needs `OPENROUTER_API_KEY`, or `CLOUDFLARE_API_TOKEN` +
`CLOUDFLARE_ACCOUNT_ID` [+ `CLOUDFLARE_AI_GATEWAY_ID`], unless `--dry-run` or
`--estimate`. `--model SLUG` overrides the model (default
`openai/gpt-5.6-luna`, `author/model` form on either provider) for every unit;
text). The model calls go through one of three adapters of one port
(`LlmClient`, in `@codegraph/llm`): `--provider openrouter` needs
`OPENROUTER_API_KEY`; `--provider cloudflare` (AI Gateway) needs
`CLOUDFLARE_API_TOKEN` + `CLOUDFLARE_ACCOUNT_ID` [+ `CLOUDFLARE_AI_GATEWAY_ID`];
`--provider claude-code` needs an installed and logged-in Claude Code and no
key — it runs the CLI in headless mode (`claude -p`), one process per call, so
`--concurrency N` is N processes and `--max-tokens` does not apply (the CLI has
no output cap; the flag is noted and ignored). The binary is `--claude-path
FILE` (which implies `claude-code` under `auto`, and is refused with a key
provider), else `CLAUDE_CODE_PATH`, else `claude` on `PATH`, else the known
install locations; naming one that does not exist is an error, never a
fall-through.
On Windows, an npm-global `claude.cmd` is found but cannot run (the adapter
spawns without a shell, and Node refuses `.cmd`/`.bat` there: `EINVAL`); use
the native installer's `claude.exe` (`%USERPROFILE%\.local\bin\claude.exe`),
with `--claude-path` if needed.
`auto` (the default) takes the one that is configured, and with several
OpenRouter, then Cloudflare, then Claude Code: a key is deliberate, an
installed CLI is ambient. `--dry-run` and `--estimate` need none of it. A
fourth adapter, the Anthropic API with an API key, is a named slot for later
(PLAN.md §21.6). `--model SLUG` overrides the model for every unit; it defaults
per provider: `openai/gpt-5.6-luna` (`author/model` form) on OpenRouter and
Cloudflare, `sonnet` on Claude Code — an alias the CLI resolves to the latest
Sonnet. The fingerprint carries the slug as requested (`sonnet`), each
record's `model` the id that served (`claude-sonnet-5-5`): a new Sonnet
behind the alias does not re-explain what was explained; a full id in
`--model` does. The trailer's cost on Claude Code is the CLI's
`total_cost_usd` at list price — a subscription is billed by its plan.
`--rollup-model SLUG` overrides it again for types and modules. The slug is
part of each record's fingerprint, so a new model re-explains what it covers.
A run that makes model calls first prints its token estimate on
Expand Down
87 changes: 70 additions & 17 deletions docs/insights.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,33 +21,82 @@ is why they live beside it.

@codegraph/insights pure: units, walk order, context packs, prompts,
fingerprints, plan, run, side-car format
@codegraph/llm the model clients: LlmClient + OpenRouter (SDK) +
Cloudflare AI Gateway (REST, plain fetch) + a fake
@codegraph/llm the port, LlmClient, and its adapters: OpenRouter
(SDK), Cloudflare AI Gateway (REST, plain fetch),
Claude Code headless (a subprocess) + a fake

`insights` depends on `core` and `analyzer` only and does no I/O: source text
arrives through an injected reader, the model call through an injected
`Completer`, finished records leave through a hook. `llm` is the **only
package allowed to import the provider SDK** — `packages/llm/test/boundary.test.ts`
scans the workspace for the import, and `eslint.config.js` restricts it. The
CLI wires the two: it owns the filesystem, the environment variable
(`OPENROUTER_API_KEY`) and the progress narration.
CLI wires the two: it owns the filesystem, the environment (the keys,
`CLAUDE_CODE_PATH`, `PATH`) and the progress narration.

The provider SDK is itself held behind a one-function `OpenRouterTransport`,
so every request/response/error path is driven by a fake transport in tests,
and an SDK change is repaired in one file.

**Two providers, one contract.** Both speak OpenAI's chat-completion shape,
parsed once in `chat.ts`. What differs: OpenRouter goes through its SDK
(camel-cased request and reply, its own API key per request); Cloudflare AI
Gateway goes through the AI REST API on `api.cloudflare.com` with plain
`fetch` (snake_case wire, one Cloudflare API token that both authenticates
and bills through Unified Billing or a stored provider key, an optional
`cf-aig-gateway-id`). Model names are the same `author/model` form on both,
so switching the route leaves every fingerprint — and every reusable record
— intact. `providers.ts` resolves `--provider auto|openrouter|cloudflare`
from the environment in one place: the single configured provider wins;
with both configured OpenRouter stays the default and the choice is printed.
The side-car header records the provider that served the run.
**One port, three adapters.** `LlmClient` (`client.ts`) is the port: one
structured completion in, parsed JSON out, one error type with `retryable`
decided once. Nothing above it — the run's `Completer`, the CLI's
`completerFor`, the store, the side-car — knows which adapter answered.
The two key adapters speak OpenAI's chat-completion shape, parsed once in
`chat.ts`: OpenRouter goes through its SDK (camel-cased request and reply,
its own API key per request); Cloudflare AI Gateway goes through the AI REST
API on `api.cloudflare.com` with plain `fetch` (snake_case wire, one
Cloudflare API token that both authenticates and bills through Unified
Billing or a stored provider key, an optional `cf-aig-gateway-id`). Model
names are the same `author/model` form on both, so switching the route
leaves every fingerprint — and every reusable record — intact.

The third adapter, **Claude Code headless** (`claude-code.ts`, PLAN.md §21),
is a subprocess: one `claude -p --output-format json` process per call, so
`--concurrency N` is N processes. It runs with `--safe-mode`, not `--bare`:
`--bare` restricts authentication to an API key and drops the subscription
login this adapter exists for, while `--safe-mode` keeps the login and
disables every customization (CLAUDE.md, hooks, plugins, MCP servers, output
styles); the default persona is replaced by `--system-prompt` and tools are
off (`--tools ""`), so the model can only answer. The user prompt goes
through stdin — a context pack with source can exceed Linux's 128 KB
per-argument limit — while the system prompt and the `--json-schema` ride as
arguments. The result JSON is read into the port's response:
`structured_output` is the parsed answer (fenced text through the shared
`extractJson` when a version lacks it), `usage` gives the tokens (input,
cache creation and cache read summed as what was sent), `total_cost_usd`
the cost (list price; a subscription is billed by its plan). The fingerprint
carries the slug as requested (`sonnet`), the record's `model` the id that
served (`modelUsage`'s key, `claude-sonnet-5-5`): a new Sonnet behind the
alias does not re-explain what was explained, a full id in `--model` does.
`--max-tokens` has no counterpart on the CLI and is noted, then
ignored. Like the SDK behind `OpenRouterTransport`, the process is held
behind a one-function seam (`ClaudeCodeProcess.run`): every test drives the
adapter with recorded stdout, stderr and exit codes, and nothing is spawned.

**Discovery and precedence.** `claude-code-discovery.ts` finds the binary as
a pure function of the flag, the environment and an `exists` probe — never a
process, so `--dry-run` resolves a provider without spawning — in this
order: `--claude-path`, `CLAUDE_CODE_PATH`, `claude` in each directory of
`PATH`, then the install locations the docs name (`~/.local/bin/claude`,
`~/.claude/local/claude`, Homebrew's, and on Windows
`%USERPROFILE%\.local\bin\claude.exe` and `%APPDATA%\npm\claude.cmd`). An
explicit path that does not exist is an answer naming it, never a
fall-through to another binary. One Windows limit: a found `claude.cmd`
cannot be run — the adapter spawns without a shell, and Node refuses
`.cmd`/`.bat` there (`EINVAL`, the CVE-2024-27980 mitigation) — so the run
fails with `claude-code: cannot run …\claude.cmd: EINVAL`; the native
installer's `claude.exe` works, and `--claude-path` can point at it.
`providers.ts` resolves `--provider
auto|openrouter|cloudflare|claude-code` in one place: a key provider is
configured when its variables are set, Claude Code when discovery found a
binary; `auto` takes the single configured one, and with several a fixed
precedence — OpenRouter, then Cloudflare, then Claude Code — because an
exported key is a deliberate act while an installed CLI is ambient, so the
CLI never overrides a key (the reason line names the flag for each
alternative). The side-car header records the provider that served the run.
The fourth adapter — the Anthropic API with `ANTHROPIC_API_KEY`,
`--provider anthropic` — is a named, empty slot (PLAN.md §21.6): one more
entry in `providers.ts`, nothing above the port.

## IN-2 · Units and the walk order

Expand Down Expand Up @@ -355,7 +404,11 @@ once the callee exists.
calls it will make, the estimated prompt tokens per level — and makes no call;
it needs no key. `--estimate` prints only the volume: calls, input and output
tokens per level, and a cost when `--price-in`/`--price-out` (USD per million
tokens) are given. Input is the rendered prompts at four characters per token;
tokens) are given. Input is the rendered prompts at four characters per token,
plus what the transport adds to every prompt — nothing on the key providers;
on Claude Code its scaffolding (1 850 tokens a call) and the response schema,
which it sends as prompt (fitted on the Java fixture, where operations then
land within 1 % of what was billed);
output is a measured figure per block asked for (operation 470, type 530,
module 530 tokens), plus 120 per word and 125 per glossary entry asked to
define — fitted on a live prompt-2 run of gpt-5.6-luna over Spring PetClinic,
Expand Down
2 changes: 1 addition & 1 deletion docs/model-metamodel.md
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ decides how order manifests physically.
makes v1's rendered-id uniqueness a *consequence* of it.
- [x] Property suite: natural-key uniqueness, injectivity, and canonical order
as a total order, generatively (`packages/core/test/properties.test.ts`).
- [x] PLAN.md §9.1/§21/§22 (milestones/decisions): decisions recorded.
- [x] PLAN.md §9.1/§22/§23 (milestones/decisions): decisions recorded.

Done in M6 (PLAN.md §9.2), as planned: the `children` key is gone from `Entity`,
the `TRAITS` table and the wire — the trait declaration stays — and closure,
Expand Down
Loading
Loading