From 9524a9018f59eda51ae2baa292a109c2cf67e85e Mon Sep 17 00:00:00 2001 From: Jeremie Grodziski Date: Mon, 23 Nov 2026 10:16:20 +0000 Subject: [PATCH 01/16] feat(analyzer): add helper views and store query The node and dep views had three copies in the docs and none in the code. They get one definition (store/helper-views.ts), created as TEMP views in the connection that asks for them. store/query.ts runs ONE read-only statement over a store: the handle is read-only, and the text must be a single statement that begins with a keyword that reads, because a read-only handle still executes VACUUM INTO. Parameters are bound by name and checked both ways before the statement runs: SQLite binds NULL to a parameter nobody gave, which returns no row and reads as "there are none". Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01PKCVh2essA8PpHntfjvJtH --- packages/analyzer/src/index.ts | 2 + packages/analyzer/src/store/helper-views.ts | 71 +++++ packages/analyzer/src/store/query.ts | 272 ++++++++++++++++ packages/analyzer/src/store/sqlite.ts | 10 + packages/analyzer/test/public-api.test.ts | 7 + .../analyzer/test/store-helper-views.test.ts | 191 ++++++++++++ packages/analyzer/test/store-query.test.ts | 295 ++++++++++++++++++ 7 files changed, 848 insertions(+) create mode 100644 packages/analyzer/src/store/helper-views.ts create mode 100644 packages/analyzer/src/store/query.ts create mode 100644 packages/analyzer/test/store-helper-views.test.ts create mode 100644 packages/analyzer/test/store-query.test.ts diff --git a/packages/analyzer/src/index.ts b/packages/analyzer/src/index.ts index 8ef5f812..882acb2c 100644 --- a/packages/analyzer/src/index.ts +++ b/packages/analyzer/src/index.ts @@ -91,6 +91,8 @@ export * from "./store/schema.js"; export * from "./store/import.js"; export * from "./store/fold-sql.js"; export * from "./store/ids.js"; +export * from "./store/helper-views.js"; +export * from "./store/query.js"; export * from "./store/diagnose.js"; export * from "./store/cache.js"; export * from "./store/temporal.js"; diff --git a/packages/analyzer/src/store/helper-views.ts b/packages/analyzer/src/store/helper-views.ts new file mode 100644 index 00000000..dfc8837c --- /dev/null +++ b/packages/analyzer/src/store/helper-views.ts @@ -0,0 +1,71 @@ +/** + * THE TWO HELPER VIEWS, DEFINED ONCE (PLAN.md §24.4). + * + * The store keeps natural keys and surrogates (MM-1); a person writing SQL + * wants the rendered id every report prints and an edge with its names + * resolved. `node` and `dep` give both. They are TEMP views: they live in the + * connection that creates them and never in the store, so a read-only handle + * holds them and the cache's bytes do not change. + * + * This text is what `codegraph query` creates, what `codegraph query --views` + * prints for another SQLite client, and what the documentation shows — the + * CLI's `helper-views-docs.test.ts` holds the copies in `docs/` and `website/` + * equal to it. Change a view here, and those pages in the same commit. + * + * `node.id` restates `renderId` in SQL, with the one hazard `ids.ts` names: + * "is this entity its own module?" is `e.id = e.module_id`, never a comparison + * of symbols. `store-helper-views.test.ts` checks it against the analyzer's + * own ids on every language's fixture and on a namesake corpus. + * + * Named `helper-views`, not `views`: `src/views.ts` is the pipeline's + * predicate views (`internalOnly`, `declaredOnly`), a different thing. + */ + +import type { SqliteDatabase } from "./sqlite.js"; + +/** One row per entity: the surrogate, the rendered id, the kind and name, and where it sits. */ +export const NODE_VIEW_SQL = `CREATE TEMP VIEW node AS +SELECT e.id AS ref, + (SELECT value FROM meta WHERE key = 'lang') || ':' || m.symbol + -- no '/' for a module (it names itself) nor for an empty symbol (an anonymous function) + || CASE WHEN e.id = e.module_id OR e.symbol = '' THEN '' ELSE '/' || e.symbol END + || CASE WHEN e.disambiguator IS NULL THEN '' ELSE '#' || e.disambiguator END + AS id, + k.name AS kind, + e.name AS name, + -- \`IS 1\`, not \`= 1\`: a non-stubbable entity has NULL here, and \`= 1\` + -- would make every comparison NULL and quietly drop every method. + e.is_stub IS 1 AS is_stub, + e.module_id AS module_ref, + e.parent_id AS parent_ref, + e.trait_set_id AS trait_set_id + FROM entity e + JOIN entity m ON m.id = e.module_id + JOIN kind k ON k.id = e.kind_id;`; + +/** One row per edge: its two ends by surrogate, its kind and provenance by name, its anchor. */ +export const DEP_VIEW_SQL = `CREATE TEMP VIEW dep AS +SELECT x.id AS ref, + x.from_id AS from_ref, + x.to_id AS to_ref, + ek.name AS kind, + p.name AS provenance, + f.path AS file, + x.anchor_start AS line + FROM edge x + JOIN edge_kind ek ON ek.id = x.kind_id + JOIN provenance p ON p.id = x.provenance_id + JOIN file f ON f.id = x.anchor_file_id;`; + +/** Both statements, in the order to run them — the text `codegraph query --views` prints. */ +export const HELPER_VIEWS_SQL = `${NODE_VIEW_SQL}\n\n${DEP_VIEW_SQL}\n`; + +/** + * Create `node` and `dep` in this connection's temp schema. + * + * Once per connection: a second call throws SQLite's own "view node already + * exists", which is a caller's bug and not a state to paper over. + */ +export function createHelperViews(db: SqliteDatabase): void { + db.exec(HELPER_VIEWS_SQL); +} diff --git a/packages/analyzer/src/store/query.ts b/packages/analyzer/src/store/query.ts new file mode 100644 index 00000000..08ec40a1 --- /dev/null +++ b/packages/analyzer/src/store/query.ts @@ -0,0 +1,272 @@ +/** + * ONE READ-ONLY STATEMENT OVER A STORE (PLAN.md §24.4). + * + * This is the engine of `codegraph query`: SQL somebody wrote — a person, or + * an agent following the discovery walk — run against `model.db`. + * + * READ-ONLY IS HELD TWICE, because once is not enough. A handle opened + * `readOnly` refuses every write to the store, and still executes + * `VACUUM INTO 'file'`, which writes a full copy of the database wherever the + * text says (measured: 221 184 bytes from the Java fixture). The handle + * protects the store, not the disk. So the TEXT is checked as well: + * + * - it is ONE statement. SQLite's `prepare` compiles the first statement and + * silently ignores whatever follows the `;` — so `SELECT 1; DELETE …` would + * not delete, and would not say it had not. A tail is refused, not dropped; + * - it begins with a keyword that reads (`QUERY_STATEMENT_KEYWORDS`). A + * `WITH` can still introduce a write; that one the handle refuses. + * + * PARAMETERS ARE BOUND, NEVER SPLICED. An entity id holds parentheses and + * commas, and in Ruby quotes. And they are checked by name before the + * statement runs, in both directions: SQLite binds NULL to a parameter nobody + * gave, which returns zero rows and reads as "there are none". + * + * Nothing here opens a file or creates a view: the caller hands an open + * database, with `createHelperViews` applied if the statement wants them. + */ + +import type { SqliteDatabase, SqliteNamedParameters, SqliteValue } from "./sqlite.js"; + +/** A statement must begin with one of these. Everything else is refused before SQLite sees it. */ +export const QUERY_STATEMENT_KEYWORDS = ["SELECT", "WITH", "VALUES", "EXPLAIN"] as const; + +/** What a statement's TEXT says about itself, found by scanning it — nothing is run. */ +export interface StatementShape { + /** + * The first token, upper-cased when it is a word: `SELECT`, `VACUUM`. A + * first token that is not a word is given as written (`(`). Empty when the + * text holds no statement at all. + */ + readonly keyword: string; + /** The `:name` parameters, without the colon, once each, in order of first use. */ + readonly params: readonly string[]; + /** Parameters in a spelling that is not bound here (`?`, `?2`, `@name`, `$name`), as written. */ + readonly foreignParams: readonly string[]; + /** True when something other than space and comments follows the first statement's `;`. */ + readonly hasTail: boolean; +} + +const isWordStart = (char: string): boolean => /[A-Za-z_]/.test(char); +const isWordPart = (char: string): boolean => /[A-Za-z0-9_$]/.test(char); +const isSpace = (char: string): boolean => /\s/.test(char); + +/** + * Scan a statement's text the way SQLite's tokenizer delimits it: string + * literals, the three quoted-identifier forms and both comment forms are + * skipped whole, so a `;`, a `:name` or a keyword inside one is not seen. + * + * Not a parser, and it does not need to be one: it answers three questions + * (first keyword, parameters, is there a second statement) that depend only + * on where the tokens are. + */ +export function statementShape(sql: string): StatementShape { + let keyword = ""; + let hasTail = false; + let ended = false; + const params: string[] = []; + const foreignParams: string[] = []; + + /** Any real token: the first one names the statement, one after the `;` is a tail. */ + const token = (text: string, word: boolean): void => { + if (ended) hasTail = true; + else if (keyword === "") keyword = word ? text.toUpperCase() : text; + }; + + /** Skip a quoted run closed by `close`, where a doubled `close` is an escape. */ + const quoted = (from: number, close: string): number => { + let at = from + 1; + while (at < sql.length) { + if (sql[at] === close) { + if (sql[at + 1] === close && close !== "]") at += 2; + else return at + 1; + } else { + at += 1; + } + } + return at; // unterminated: SQLite will say so; nothing after it is a token + }; + + const wordFrom = (from: number): number => { + let at = from; + while (at < sql.length && isWordPart(sql[at]!)) at += 1; + return at; + }; + + let at = 0; + while (at < sql.length) { + const char = sql[at]!; + const next = sql[at + 1]; + + if (isSpace(char)) { + at += 1; + } else if (char === "-" && next === "-") { + const eol = sql.indexOf("\n", at); + at = eol === -1 ? sql.length : eol + 1; + } else if (char === "/" && next === "*") { + const close = sql.indexOf("*/", at + 2); + at = close === -1 ? sql.length : close + 2; + } else if (char === "'" || char === '"' || char === "`") { + token(char, false); + at = quoted(at, char); + } else if (char === "[") { + token(char, false); + at = quoted(at, "]"); + } else if (char === ";") { + // The first `;` ends the statement; a later one is an empty statement. + if (keyword !== "") ended = true; + at += 1; + } else if (char === ":" && next !== undefined && isWordStart(next)) { + const end = wordFrom(at + 1); + const name = sql.slice(at + 1, end); + token(`:${name}`, false); + if (!params.includes(name)) params.push(name); + at = end; + } else if ((char === "@" || char === "$") && next !== undefined && isWordStart(next)) { + const end = wordFrom(at + 1); + token(sql.slice(at, end), false); + foreignParams.push(sql.slice(at, end)); + at = end; + } else if (char === "?") { + let end = at + 1; + while (end < sql.length && /[0-9]/.test(sql[end]!)) end += 1; + token(sql.slice(at, end), false); + foreignParams.push(sql.slice(at, end)); + at = end; + } else if (isWordStart(char)) { + const end = wordFrom(at); + token(sql.slice(at, end), true); + at = end; + } else { + token(char, false); + at += 1; + } + } + + return { keyword, params, foreignParams, hasTail }; +} + +/** Why a statement was not run. `sqlite` is SQLite's own refusal, in its own words. */ +export type QueryRefusal = + | "empty" + | "not-read-only" + | "several-statements" + | "foreign-parameter" + | "missing-parameter" + | "unknown-parameter" + | "sqlite"; + +/** + * A statement that was not run. Always the caller's text at fault, never the + * store: a command maps it to a usage error, with `message` as the sentence. + */ +export class QueryRefused extends Error { + readonly reason: QueryRefusal; + + constructor(reason: QueryRefusal, message: string, options?: { cause?: unknown }) { + super(message, options); + this.name = "QueryRefused"; + this.reason = reason; + } +} + +export interface QueryOptions { + /** Values for the statement's `:name` parameters, keyed without the colon. */ + readonly params?: Readonly> | undefined; + /** Keep at most this many rows; every row is still counted. Absent keeps them all. */ + readonly limit?: number | undefined; +} + +export interface QueryResult { + /** Column names as the statement gives them — two may be equal, which is why rows are arrays. */ + readonly columns: readonly string[]; + /** The rows kept, each in column order. */ + readonly rows: readonly (readonly SqliteValue[])[]; + /** How many rows the statement returned, kept or not. */ + readonly total: number; + /** True when `rows` is fewer than `total`. */ + readonly truncated: boolean; +} + +const list = (names: readonly string[]): string => names.map((name) => `:${name}`).join(", "); + +/** The checks that need no database: what the text is, and whether the parameters match it. */ +function checkStatement(sql: string, given: readonly string[]): void { + const shape = statementShape(sql); + if (shape.keyword === "") { + throw new QueryRefused("empty", "the statement is empty"); + } + if (!(QUERY_STATEMENT_KEYWORDS as readonly string[]).includes(shape.keyword)) { + throw new QueryRefused( + "not-read-only", + `a query is one statement that reads, beginning with ${QUERY_STATEMENT_KEYWORDS.join(", ")}; this one begins with ${shape.keyword}`, + ); + } + if (shape.hasTail) { + throw new QueryRefused( + "several-statements", + "a query is ONE statement; this text holds another after the ';' (SQLite would have ignored it without a word)", + ); + } + if (shape.foreignParams.length > 0) { + const first = shape.foreignParams[0]!; + const named = /^[@$]/.test(first) ? `:${first.slice(1)}` : ":name"; + throw new QueryRefused( + "foreign-parameter", + `parameter ${first} is not bound here: write it ${named} and give its value by name`, + ); + } + const missing = shape.params.filter((name) => !given.includes(name)); + if (missing.length > 0) { + throw new QueryRefused( + "missing-parameter", + `the statement names ${list(missing)} and no value was given — SQLite would bind NULL and return nothing`, + ); + } + const unknown = given.filter((name) => !shape.params.includes(name)); + if (unknown.length > 0) { + throw new QueryRefused( + "unknown-parameter", + shape.params.length === 0 + ? `a value was given for ${list(unknown)}, and the statement names no parameter` + : `a value was given for ${list(unknown)}, and the statement names only ${list(shape.params)}`, + ); + } +} + +/** + * Run one read-only statement and return its rows. + * + * @throws QueryRefused when the text is not one reading statement, when its + * parameters and the values given do not match, or when SQLite refuses it + * (unknown column, syntax, a write behind a `WITH`) — with SQLite's message. + */ +export function queryStore(db: SqliteDatabase, sql: string, options: QueryOptions = {}): QueryResult { + const params = options.params ?? {}; + checkStatement(sql, Object.keys(params)); + + const bound: SqliteNamedParameters = {}; + for (const [name, value] of Object.entries(params)) { + // The binding stores a JS number as REAL, so `typeof(:n)` would say `real` + // for 41. A whole number is bound as the INTEGER it is. + bound[`:${name}`] = typeof value === "number" && Number.isSafeInteger(value) ? BigInt(value) : value; + } + + try { + const statement = db.prepare(sql); + statement.setReturnArrays(true); + const columns = statement.columns().map((column) => column.name); + + const limit = options.limit ?? Number.POSITIVE_INFINITY; + const rows: SqliteValue[][] = []; + let total = 0; + for (const row of statement.iterate(bound) as unknown as Iterable) { + if (total < limit) rows.push(row); + total += 1; + } + return { columns, rows, total, truncated: rows.length < total }; + } catch (error) { + if (error instanceof QueryRefused) throw error; + const message = error instanceof Error ? error.message : String(error); + throw new QueryRefused("sqlite", message, { cause: error }); + } +} diff --git a/packages/analyzer/src/store/sqlite.ts b/packages/analyzer/src/store/sqlite.ts index 1aa55f89..bb18b34c 100644 --- a/packages/analyzer/src/store/sqlite.ts +++ b/packages/analyzer/src/store/sqlite.ts @@ -53,6 +53,9 @@ export type SqliteValue = null | number | bigint | string | Uint8Array; /** A result row. NOTE: `node:sqlite` returns these with a NULL prototype. */ export type SqliteRow = Record; +/** Values for a statement's named parameters, keyed as the statement spells them (`:id`). */ +export type SqliteNamedParameters = Record; + /** * A prepared statement, described by what the store needs rather than by what * `node:sqlite` happens to offer — see `SqliteApi`. @@ -63,6 +66,13 @@ export interface SqliteStatement { all(...params: SqliteValue[]): SqliteRow[]; /** Row-at-a-time. The import and hydrate paths use this, never `all()`. */ iterate(...params: SqliteValue[]): IterableIterator; + /** The same, with the statement's NAMED parameters bound from an object (`{ ":id": … }`). */ + iterate(named: SqliteNamedParameters): IterableIterator; + /** + * The result's columns, in order — known before a row is read, so an answer + * with no row still has a header. `store/query.ts` is the one reader. + */ + columns(): readonly { readonly name: string }[]; /** * Return each row as a positional array instead of an object. Measured on * fineract's 1 023 147 entity and edge rows: **3.83s as objects, 1.46s as diff --git a/packages/analyzer/test/public-api.test.ts b/packages/analyzer/test/public-api.test.ts index b2e037f0..883d0c97 100644 --- a/packages/analyzer/test/public-api.test.ts +++ b/packages/analyzer/test/public-api.test.ts @@ -78,6 +78,9 @@ const PUBLIC_API = { "diagnoseStore", "renderStoreIds", "storeLang", + "createHelperViews", + "statementShape", + "queryStore", ], } as const; @@ -98,6 +101,10 @@ const PUBLIC_VALUES = [ "META_KEYS", "ENTITY_KEY_STORAGE", "EDGE_KEY_STORAGE", + "NODE_VIEW_SQL", + "DEP_VIEW_SQL", + "HELPER_VIEWS_SQL", + "QUERY_STATEMENT_KEYWORDS", ] as const; const SRC = fileURLToPath(new URL("../src", import.meta.url)); diff --git a/packages/analyzer/test/store-helper-views.test.ts b/packages/analyzer/test/store-helper-views.test.ts new file mode 100644 index 00000000..f38ee20e --- /dev/null +++ b/packages/analyzer/test/store-helper-views.test.ts @@ -0,0 +1,191 @@ +import { createHash } from "node:crypto"; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterAll, describe, expect, it } from "vitest"; +import { + DEP_VIEW_SQL, + HELPER_VIEWS_SQL, + NODE_VIEW_SQL, + STORE_OPEN_OPTIONS, + createHelperViews, + hydrateModel, + importModel, + loadSqlite, + openStore, + type SqliteDatabase, +} from "../src/index.js"; + +/** + * THE TWO HELPER VIEWS HAVE ONE DEFINITION (PLAN.md §24.4). + * + * `node` and `dep` are what every hand-written query over the store starts + * from: `node.id` is the rendered id every report prints, `dep` is an edge with + * its names resolved. They were three pasted copies in the documentation; they + * are now this module's constants, which `codegraph query` creates and the + * documentation is pinned to (the CLI's `helper-views-docs.test.ts`). + * + * What is held here is what a reader of ANY language's store relies on: + * + * - `node.id` is `renderId`, entity for entity — five extractors, five + * disambiguator conventions, one expression; + * - `dep` loses no edge and invents none; + * - creating them writes nothing: they live in the connection's temp schema. + */ + +const LANGUAGES = ["java", "csharp", "typescript", "elixir", "ruby"] as const; + +function fixture(lang: string): string { + return fileURLToPath(new URL(`../../../fixtures/${lang}/expected/model.jsonl`, import.meta.url)); +} + +const scratch = mkdtempSync(join(tmpdir(), "codegraph-helper-views-")); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +function storeOf(lang: string): string { + const path = join(scratch, `${lang}.db`); + importModel(fixture(lang), path); + return path; +} + +function readOnly(path: string): SqliteDatabase { + return loadSqlite().open(path, { ...STORE_OPEN_OPTIONS, readOnly: true }); +} + +const sha = (path: string): string => createHash("sha256").update(readFileSync(path)).digest("hex"); + +describe("the helper views: one definition", () => { + it("is the two statements, node then dep, and nothing else", () => { + expect(NODE_VIEW_SQL.startsWith("CREATE TEMP VIEW node AS")).toBe(true); + expect(DEP_VIEW_SQL.startsWith("CREATE TEMP VIEW dep AS")).toBe(true); + expect(NODE_VIEW_SQL.trimEnd().endsWith(";")).toBe(true); + expect(DEP_VIEW_SQL.trimEnd().endsWith(";")).toBe(true); + expect(HELPER_VIEWS_SQL).toBe(`${NODE_VIEW_SQL}\n\n${DEP_VIEW_SQL}\n`); + }); + + it.each(LANGUAGES)("%s: node.id is renderId, entity for entity, in surrogate order", (lang) => { + const path = storeOf(lang); + const store = openStore(path); + const expected = hydrateModel(store).entities.map((entity) => entity.id); + store.close(); + expect(expected.length, "a fixture with no entity proves nothing").toBeGreaterThan(50); + + const db = readOnly(path); + try { + createHelperViews(db); + const rendered = db.prepare("SELECT id FROM node ORDER BY ref").all().map((row) => row.id); + expect(rendered).toEqual(expected); + } finally { + db.close(); + } + }); + + it.each(LANGUAGES)("%s: dep is the model's edges — none lost, none invented", (lang) => { + const path = storeOf(lang); + const store = openStore(path); + const model = hydrateModel(store); + store.close(); + const expected = model.edges + .map((edge) => [edge.from, edge.to, edge.edge, edge.provenance].join(" | ")) + .sort(); + expect(expected.length).toBeGreaterThan(50); + + const db = readOnly(path); + try { + createHelperViews(db); + const rows = db + .prepare( + `SELECT f.id AS from_id, t.id AS to_id, d.kind, d.provenance + FROM dep d JOIN node f ON f.ref = d.from_ref JOIN node t ON t.ref = d.to_ref`, + ) + .all() + .map((row) => [row.from_id, row.to_id, row.kind, row.provenance].join(" | ")) + .sort(); + expect(rows).toEqual(expected); + } finally { + db.close(); + } + }); + + it("dep carries the anchor the navigator opens: a file and a line", () => { + const db = readOnly(storeOf("java")); + try { + createHelperViews(db); + const row = db + .prepare("SELECT file, line FROM dep WHERE kind = 'inheritance' ORDER BY ref LIMIT 1") + .get(); + expect(row?.file).toMatch(/\.java$/); + expect(row?.line).toBeGreaterThan(0); + } finally { + db.close(); + } + }); + + /** + * A type whose symbol equals its module's path. Comparing SYMBOLS to decide + * "is this entity its own module?" renders the class as its own package — + * two entities, one id. No fixture has a namesake, so one is built here. + */ + it("keeps a type distinct from a module of the same name", () => { + const model = join(scratch, "namesake.jsonl"); + const lines = [ + { + t: "header", + schemaVersion: "1.0.0", + lang: "x", + extractor: { name: "helper-views", version: "0.0.0" }, + root: "/corpus", + dict: { + kinds: ["package", "class"], + traits: ["TNamed", "TModule", "TType", "TChildOf"], + edges: ["reference"], + provenance: ["declared"], + }, + }, + { t: "f", i: 0, path: "A.java" }, + { t: "e", i: 0, k: 0, tr: [0, 1], m: 0, s: "A", name: "A", definedIn: [0], isStub: false }, + { t: "e", i: 1, k: 1, tr: [0, 2, 3], m: 0, s: "A", name: "A", isStub: false, parent: 0 }, + { t: "x", k: 0, f: 1, o: 0, p: 0, anchor: [0, 1, 1] }, + { t: "eof", counts: { files: 1, entities: 2, edges: 1 } }, + ]; + writeFileSync(model, `${lines.map((line) => JSON.stringify(line)).join("\n")}\n`, "utf8"); + const path = join(scratch, "namesake.db"); + importModel(model, path); + + const db = readOnly(path); + try { + createHelperViews(db); + const ids = db.prepare("SELECT id FROM node ORDER BY ref").all().map((row) => row.id); + expect(ids).toEqual(["x:A", "x:A/A"]); + } finally { + db.close(); + } + }); +}); + +describe("the helper views: created in the connection, never in the store", () => { + it("leaves the store's bytes untouched on a read-only handle", () => { + const path = storeOf("java"); + const before = sha(path); + const db = readOnly(path); + createHelperViews(db); + expect(db.prepare("SELECT count(*) AS n FROM node").get()?.n).toBeGreaterThan(0); + db.close(); + expect(sha(path)).toBe(before); + }); + + it("is gone with the connection: the next one does not see them", () => { + const path = storeOf("java"); + const first = readOnly(path); + createHelperViews(first); + first.close(); + + const second = readOnly(path); + try { + expect(() => second.prepare("SELECT count(*) FROM node")).toThrow(/no such table: node/); + } finally { + second.close(); + } + }); +}); diff --git a/packages/analyzer/test/store-query.test.ts b/packages/analyzer/test/store-query.test.ts new file mode 100644 index 00000000..93db5dd6 --- /dev/null +++ b/packages/analyzer/test/store-query.test.ts @@ -0,0 +1,295 @@ +import { createHash } from "node:crypto"; +import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { + QUERY_STATEMENT_KEYWORDS, + QueryRefused, + STORE_OPEN_OPTIONS, + createHelperViews, + importModel, + loadSqlite, + queryStore, + statementShape, + type QueryRefusal, + type SqliteDatabase, +} from "../src/index.js"; + +/** + * ONE READ-ONLY STATEMENT (PLAN.md §24.4, §24.9). + * + * `queryStore` is what `codegraph query` runs: text a person or an agent + * wrote, over a store. Two things make that safe to hand to an agent, and a + * read-only handle is only one of them — measured before this was written, a + * handle opened `readOnly` still lets `VACUUM INTO 'file'` write a copy of the + * database anywhere on disk. So the text is checked too: ONE statement, and it + * begins with a keyword that reads. + * + * The second half of this file is the other thing a caller is trusting: that + * a parameter is BOUND (an id holds parentheses, commas and, in Ruby, quotes), + * that a parameter nobody gave is an error rather than a silent NULL — which + * would print zero rows and read as "there are none" — and that the answer + * says how many rows there were when it shows only some. + */ + +const FIXTURE = fileURLToPath(new URL("../../../fixtures/java/expected/model.jsonl", import.meta.url)); + +const scratch = mkdtempSync(join(tmpdir(), "codegraph-store-query-")); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +const STORE = join(scratch, "model.db"); +let db: SqliteDatabase; + +beforeAll(() => { + importModel(FIXTURE, STORE); + db = loadSqlite().open(STORE, { ...STORE_OPEN_OPTIONS, readOnly: true }); + createHelperViews(db); +}); +afterAll(() => db.close()); + +const sha = (path: string): string => createHash("sha256").update(readFileSync(path)).digest("hex"); + +function refusal(sql: string, params?: Record): QueryRefusal | "accepted" { + try { + queryStore(db, sql, params === undefined ? {} : { params }); + return "accepted"; + } catch (error) { + if (error instanceof QueryRefused) return error.reason; + throw error; + } +} + +describe("statementShape: what the text is, without running it", () => { + it("names the first keyword, whatever precedes it", () => { + expect(statementShape("select 1").keyword).toBe("SELECT"); + expect(statementShape(" \n\t WITH a AS (SELECT 1) SELECT * FROM a").keyword).toBe("WITH"); + expect(statementShape("-- a header\n-- two lines\nVALUES (1)").keyword).toBe("VALUES"); + expect(statementShape("/* block\n comment */ explain query plan select 1").keyword).toBe("EXPLAIN"); + }); + + it("is not fooled by a comment that hides the real verb", () => { + expect(statementShape("/* SELECT */ DELETE FROM entity").keyword).toBe("DELETE"); + expect(statementShape("-- SELECT 1\nVACUUM INTO 'x'").keyword).toBe("VACUUM"); + }); + + it("reports an empty text as having no keyword", () => { + expect(statementShape("").keyword).toBe(""); + expect(statementShape(" -- only a comment\n").keyword).toBe(""); + expect(statementShape(";").keyword).toBe(""); + }); + + it("names a first token that is not a word", () => { + expect(statementShape("(SELECT 1)").keyword).toBe("("); + }); + + it("sees a second statement, and only a real one", () => { + expect(statementShape("SELECT 1").hasTail).toBe(false); + expect(statementShape("SELECT 1;").hasTail).toBe(false); + expect(statementShape("SELECT 1;\n -- done\n").hasTail).toBe(false); + expect(statementShape("SELECT 1; /* nothing */ ;").hasTail).toBe(false); + expect(statementShape("SELECT 1; DELETE FROM entity").hasTail).toBe(true); + expect(statementShape("SELECT 1;SELECT 2").hasTail).toBe(true); + }); + + it("does not split on a semicolon inside a literal, an identifier or a comment", () => { + expect(statementShape("SELECT 'a; DELETE FROM entity'").hasTail).toBe(false); + expect(statementShape("SELECT 'it''s; here' AS x").hasTail).toBe(false); + expect(statementShape('SELECT 1 AS "a;b"').hasTail).toBe(false); + expect(statementShape("SELECT 1 AS `a;b`").hasTail).toBe(false); + expect(statementShape("SELECT 1 AS [a;b]").hasTail).toBe(false); + expect(statementShape("SELECT 1 -- ; DELETE FROM entity").hasTail).toBe(false); + expect(statementShape("SELECT 1 /* ; DELETE */").hasTail).toBe(false); + }); + + it("lists the named parameters once each, in order of first use", () => { + const shape = statementShape("SELECT :a, :b_2, :a FROM node WHERE id = :id"); + expect(shape.params).toEqual(["a", "b_2", "id"]); + expect(shape.foreignParams).toEqual([]); + }); + + it("finds no parameter inside a literal, an identifier or a comment", () => { + expect(statementShape("SELECT ':x', \":y\", [:z] -- :w\n /* :v */").params).toEqual([]); + }); + + it("names the parameter spellings it will not bind", () => { + expect(statementShape("SELECT ?, ?2, @name, $other").foreignParams).toEqual(["?", "?2", "@name", "$other"]); + }); +}); + +describe("queryStore: what it refuses", () => { + it("accepts exactly the four keywords that read", () => { + expect([...QUERY_STATEMENT_KEYWORDS]).toEqual(["SELECT", "WITH", "VALUES", "EXPLAIN"]); + expect(refusal("SELECT 1")).toBe("accepted"); + expect(refusal("WITH a(x) AS (VALUES (1)) SELECT x FROM a")).toBe("accepted"); + expect(refusal("VALUES (1), (2)")).toBe("accepted"); + expect(refusal("EXPLAIN QUERY PLAN SELECT * FROM node")).toBe("accepted"); + }); + + it("refuses an empty text", () => { + expect(refusal("")).toBe("empty"); + expect(refusal("-- nothing here")).toBe("empty"); + }); + + // PLAN.md §24.9, first row. Each of these gets through a read-only handle or + // would mislead if it silently did nothing. + it.each([ + ["VACUUM INTO, which a read-only handle allows", `VACUUM INTO '${join(scratch, "copy.db")}'`], + ["ATTACH", `ATTACH DATABASE '${join(scratch, "attached.db")}' AS other`], + ["PRAGMA writable_schema", "PRAGMA writable_schema = ON"], + ["CREATE TEMP TABLE", "CREATE TEMP TABLE t AS SELECT 1 AS a"], + ["DELETE", "DELETE FROM entity"], + ["DROP VIEW", "DROP VIEW node"], + ["a comment hiding a DELETE", "/* SELECT */ DELETE FROM entity"], + ["a line comment hiding a VACUUM", `-- SELECT 1\nVACUUM INTO '${join(scratch, "copy2.db")}'`], + ])("refuses %s as not read-only", (_label, sql) => { + expect(refusal(sql)).toBe("not-read-only"); + }); + + it("refuses two statements rather than running the first and dropping the second", () => { + expect(refusal("SELECT 1; SELECT 2")).toBe("several-statements"); + expect(refusal(`SELECT 1; VACUUM INTO '${join(scratch, "copy3.db")}'`)).toBe("several-statements"); + }); + + it("lets SQLite refuse a write that a WITH introduces", () => { + expect(refusal("WITH a AS (SELECT 1) DELETE FROM entity")).toBe("sqlite"); + expect(refusal("WITH a AS (SELECT 1) INSERT INTO node(ref) SELECT 1")).toBe("sqlite"); + }); + + it("refuses a mistyped verb before SQLite sees it, naming the verbs that read", () => { + try { + queryStore(db, "SELEC 1"); + expect.unreachable("a mistyped verb must be refused"); + } catch (error) { + expect(error).toBeInstanceOf(QueryRefused); + expect((error as QueryRefused).reason).toBe("not-read-only"); + expect((error as QueryRefused).message).toContain("SELECT, WITH, VALUES, EXPLAIN"); + expect((error as QueryRefused).message).toContain("SELEC"); + } + }); + + it("says SQLite's own words for a statement SQLite cannot compile", () => { + try { + queryStore(db, "SELECT nope FROM node"); + expect.unreachable("an unknown column must be refused"); + } catch (error) { + expect((error as QueryRefused).reason).toBe("sqlite"); + expect((error as QueryRefused).message).toContain("no such column: nope"); + } + }); + + it("wrote nothing: no file appeared and the store is byte for byte what it was", () => { + const before = sha(STORE); + for (const sql of [ + `VACUUM INTO '${join(scratch, "v.db")}'`, + `ATTACH DATABASE '${join(scratch, "a.db")}' AS other`, + "PRAGMA writable_schema = ON", + "CREATE TEMP TABLE t AS SELECT 1 AS a", + `SELECT 1; VACUUM INTO '${join(scratch, "v2.db")}'`, + "/* SELECT */ DELETE FROM entity", + "WITH a AS (SELECT 1) DELETE FROM entity", + `EXPLAIN VACUUM INTO '${join(scratch, "v3.db")}'`, + ]) { + refusal(sql); + } + expect(readdirSync(scratch).sort()).toEqual(["model.db"]); + expect(existsSync(join(scratch, "v.db"))).toBe(false); + expect(sha(STORE)).toBe(before); + // ...and the views this connection holds are still there. + expect(queryStore(db, "SELECT count(*) AS n FROM node").rows[0]?.[0]).toBeGreaterThan(0); + }); +}); + +describe("queryStore: parameters are bound, never spliced", () => { + it("binds an id that holds parentheses and a comma", () => { + const id = "java:com.acme.order/Order.discount(int)"; + const result = queryStore(db, "SELECT id, kind FROM node WHERE id = :id", { params: { id } }); + expect(result.rows).toEqual([[id, "method"]]); + }); + + it("binds a value that would end the statement if it were pasted in", () => { + const hostile = "x'; DELETE FROM entity; --"; + const result = queryStore(db, "SELECT :v AS v", { params: { v: hostile } }); + expect(result.rows).toEqual([[hostile]]); + }); + + it("binds a number as a number", () => { + const result = queryStore(db, "SELECT typeof(:n) AS t, :n + 1 AS next", { params: { n: 41 } }); + expect(result.rows).toEqual([["integer", 42]]); + }); + + it("refuses a parameter the statement names and nobody gave", () => { + expect(refusal("SELECT id FROM node WHERE id = :id")).toBe("missing-parameter"); + try { + queryStore(db, "SELECT :a, :b", { params: { a: 1 } }); + expect.unreachable(); + } catch (error) { + expect((error as QueryRefused).message).toContain(":b"); + expect((error as QueryRefused).message).not.toContain(":a,"); + } + }); + + it("refuses a parameter given that the statement does not name", () => { + expect(refusal("SELECT 1", { extra: "x" })).toBe("unknown-parameter"); + }); + + it("refuses the spellings it does not bind, naming the one it does", () => { + expect(refusal("SELECT ?")).toBe("foreign-parameter"); + try { + queryStore(db, "SELECT @id"); + expect.unreachable(); + } catch (error) { + expect((error as QueryRefused).message).toContain("@id"); + expect((error as QueryRefused).message).toContain(":id"); + } + }); +}); + +describe("queryStore: the answer", () => { + it("gives the columns as written, in order, and the rows as arrays", () => { + const result = queryStore( + db, + "SELECT kind, count(*) AS n FROM node WHERE is_stub = 0 GROUP BY kind ORDER BY n DESC, kind", + ); + expect(result.columns).toEqual(["kind", "n"]); + expect(result.rows[0]).toEqual(["method", 43]); + expect(result.total).toBe(result.rows.length); + expect(result.truncated).toBe(false); + }); + + it("keeps two columns of the same name apart", () => { + const result = queryStore(db, "SELECT 1 AS a, 2 AS a"); + expect(result.columns).toEqual(["a", "a"]); + expect(result.rows).toEqual([[1, 2]]); + }); + + it("names the columns of an answer with no row", () => { + const result = queryStore(db, "SELECT id, kind FROM node WHERE 0"); + expect(result.columns).toEqual(["id", "kind"]); + expect(result).toMatchObject({ rows: [], total: 0, truncated: false }); + }); + + it("cuts at the limit and still counts every row", () => { + const all = queryStore(db, "SELECT id FROM node ORDER BY ref"); + const cut = queryStore(db, "SELECT id FROM node ORDER BY ref", { limit: 5 }); + expect(all.total).toBeGreaterThan(100); + expect(cut.rows).toEqual(all.rows.slice(0, 5)); + expect(cut.total).toBe(all.total); + expect(cut.truncated).toBe(true); + }); + + it("is not truncated when the limit is exactly the row count", () => { + const all = queryStore(db, "SELECT id FROM node"); + const exact = queryStore(db, "SELECT id FROM node", { limit: all.total }); + expect(exact.truncated).toBe(false); + expect(exact.rows.length).toBe(all.total); + }); + + it("reads the schema with statements that are themselves SELECTs", () => { + const tables = queryStore(db, "SELECT name FROM sqlite_schema WHERE type = 'table' ORDER BY name"); + expect(tables.rows.map((row) => row[0])).toContain("entity"); + const columns = queryStore(db, "SELECT name FROM pragma_table_info('entity')"); + expect(columns.rows.map((row) => row[0])).toContain("module_id"); + }); +}); From f3129e94872f6d0572614a8150147437de9faa11 Mon Sep 17 00:00:00 2001 From: Jeremie Grodziski Date: Mon, 23 Nov 2026 10:16:20 +0000 Subject: [PATCH 02/16] feat(cli): add codegraph query SQL over a model's store with the SQLite already in the binary, so an ad-hoc question needs no sqlite3 on the machine: codegraph query app.jsonl "SELECT kind, count(*) FROM node GROUP BY 1" codegraph query app.jsonl --file reach.sql --param id=... --json codegraph query --views Rows on stdout as a table, --json (codegraph.queryResult/1) or --csv, cut at --limit (50) with the total on stderr. Every refusal is a usage error (exit 2), SQLite's included; a file that is not a model is exit 3. --param-file NAME=FILE binds a file's whole text, as text: one statement reads the rows another saved with --json (json_each(:NAME, '$.rows')), so a list of ids is never retyped on a command line. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01PKCVh2essA8PpHntfjvJtH --- packages/cli/scripts/sea-smoke.mjs | 17 +- packages/cli/src/args.ts | 231 ++++++++- packages/cli/src/commands/query.ts | 354 ++++++++++++++ packages/cli/src/main.ts | 3 + packages/cli/test/dispatch.test.ts | 1 + packages/cli/test/e2e-exit-codes.test.ts | 15 + packages/cli/test/e2e-help.test.ts | 2 +- packages/cli/test/e2e-stream-purity.test.ts | 42 ++ packages/cli/test/query.test.ts | 493 ++++++++++++++++++++ 9 files changed, 1153 insertions(+), 5 deletions(-) create mode 100644 packages/cli/src/commands/query.ts create mode 100644 packages/cli/test/query.test.ts diff --git a/packages/cli/scripts/sea-smoke.mjs b/packages/cli/scripts/sea-smoke.mjs index b29616b4..15b516c6 100644 --- a/packages/cli/scripts/sea-smoke.mjs +++ b/packages/cli/scripts/sea-smoke.mjs @@ -4,7 +4,8 @@ // 1. `codegraph --version` prints packages/cli/package.json's version — the // asset path of version.ts, not the fallback; // 2. `codegraph analyze` on the Java fixture is byte-identical to what the -// ESM build prints — one CLI, two builds; +// ESM build prints — one CLI, two builds; so is `codegraph query`, which +// runs on the SQLite inside the image, and it still refuses a write; // 3. `codegraph serve --app` under the fake extractor answers the page from // the image's assets (index.html and the script it references), opens // fixtures/java/src, and hands out //navigator.json and city.json; @@ -54,6 +55,20 @@ for (const report of ["deps", "cycles", "coupling"]) { ); } +// 2b. query: the SQLite inside the image answers, byte-identical to the ESM build +{ + const args = ["query", fixture, "SELECT kind, count(*) AS n FROM node WHERE is_stub = 0 GROUP BY kind ORDER BY n DESC, kind", "--json"]; + const fromImage = spawnSync(image, args, { encoding: "utf8", cwd: ROOT }); + const fromEsm = spawnSync(process.execPath, [join(CLI_DIR, "dist", "index.js"), ...args], { encoding: "utf8", cwd: ROOT }); + check( + fromImage.status === 0 && fromImage.stdout === fromEsm.stdout && fromImage.stdout.includes("codegraph.queryResult/1"), + `query --json is byte-identical to the ESM build (${fromImage.stdout.length} bytes)`, + `image exit ${fromImage.status}: ${fromImage.stderr.slice(0, 300)}`, + ); + const refused = spawnSync(image, ["query", fixture, "VACUUM INTO 'sea-smoke-must-not-exist.db'"], { encoding: "utf8", cwd: ROOT }); + check(refused.status === 2 && refused.stdout === "", "query refuses a statement that writes (exit 2)", `exit ${refused.status}: ${refused.stderr.slice(0, 200)}`); +} + // 3. serve --app from the image's own assets const dataDir = mkdtempSync(join(tmpdir(), "codegraph-sea-smoke-")); const registry = join(dataDir, "registry.json"); diff --git a/packages/cli/src/args.ts b/packages/cli/src/args.ts index d6c6fefe..47f599be 100644 --- a/packages/cli/src/args.ts +++ b/packages/cli/src/args.ts @@ -25,6 +25,7 @@ export const COMMAND_NAMES = [ "validate", "analyze", "import", + "query", "export", "city", "navigator", @@ -113,6 +114,11 @@ export interface PositionalSpec { readonly defaultPath?: (() => string) | undefined; /** How to produce the default when it is missing — each artifact has its own maker. */ readonly missingHint?: string | undefined; + /** + * ONE more positional after the first, always optional (`query [sql]`). + * Never with `variadic`: a second argument must mean one thing. + */ + readonly second?: { readonly name: string; readonly describe: string } | undefined; } export interface CommandSpec { @@ -1079,6 +1085,95 @@ export const IMPORT_SPEC: CommandSpec = { ], }; +/** `query` prints this many rows unless told otherwise: a result is read, not scrolled. */ +export const DEFAULT_QUERY_LIMIT = 50; + +/** The three ways `query` writes its rows. */ +export const QUERY_FORMATS = ["table", "json", "csv"] as const; +export type QueryFormat = (typeof QUERY_FORMATS)[number]; + +/** + * `codegraph query`: one read-only SQL statement over a model's store (PLAN.md + * §24.4). It exists so that no step of the discovery walk needs `sqlite3` on + * the machine: the SQLite that builds the store is already in this binary. + * + * The model is REQUIRED and comes first, unlike the commands that default it: + * with an optional statement after it, a lone argument could be either, and a + * command that guesses which is a command that runs the wrong thing. + */ +export const QUERY_SPEC: CommandSpec = { + name: "query", + summary: "Run one read-only SQL statement over a model's store, with the node and dep views.", + positional: { + name: "model.jsonl", + describe: + "The model to query, through its store (model.db, built beside it when missing or stale) — or a model.db itself.", + variadic: false, + required: true, + second: { + name: "sql", + describe: + "The statement, quoted: ONE statement beginning with SELECT, WITH, VALUES or EXPLAIN. " + + "The views node (one row per entity, with its rendered id) and dep (one row per edge, names resolved) are there.", + }, + }, + options: [ + { + name: "file", + type: "string", + describe: "Read the statement from this file instead of the command line.", + placeholder: "FILE", + }, + { + name: "param", + type: "string", + describe: + "Bind :NAME in the statement to VALUE — bound, never pasted into the text, so an id needs no escaping. " + + "Repeat it per parameter. A whole or decimal number is bound as a number, anything else as text.", + placeholder: "NAME=VALUE", + multiple: true, + }, + { + name: "param-file", + type: "string", + describe: + "Bind :NAME to the whole text of FILE, as text: a result saved with --json, a list. " + + "json_each(:NAME, '$.rows') then reads the saved rows, so one statement builds on another's file.", + placeholder: "NAME=FILE", + multiple: true, + }, + { + name: "limit", + type: "string", + describe: "Print at most N rows; how many there were is said on stderr.", + placeholder: "N", + integer: true, + defaultValue: String(DEFAULT_QUERY_LIMIT), + }, + { + name: "all", + type: "boolean", + describe: "Print every row.", + }, + { + name: "csv", + type: "boolean", + describe: "Print the rows as CSV: a header line, then one line per row.", + }, + { + name: "json", + type: "boolean", + describe: "Print a codegraph.queryResult/1 document: columns, rows (one array per row), total, truncated.", + }, + { + name: "views", + type: "boolean", + describe: + "Print the SQL that creates node and dep, for another SQLite client, and exit. Takes no model and no other option.", + }, + ], +}; + /** * `codegraph timeline` reads the TEMPORAL store: an entity's life across the * revisions `import --at` accumulated. Lifespans are derived by the query, @@ -1362,6 +1457,7 @@ export const COMMAND_SPECS: readonly CommandSpec[] = [ VALIDATE_SPEC, ANALYZE_SPEC, IMPORT_SPEC, + QUERY_SPEC, EXPORT_SPEC, CITY_SPEC, NAVIGATOR_SPEC, @@ -1606,6 +1702,24 @@ export interface ImportOptions extends ModelInputOptions { readonly json: boolean; } +export interface QueryOptions { + /** `--views`: print the helper views' SQL; nothing is read. */ + readonly views: boolean; + /** The model.jsonl, or a model.db; undefined only with `--views`. */ + readonly model: string | undefined; + /** The statement as typed; undefined when `--file` gives it. */ + readonly sql: string | undefined; + /** `--file FILE`: where the statement is; undefined when it was typed. */ + readonly file: string | undefined; + /** `--param NAME=VALUE`, by name without the colon; the values as typed. */ + readonly params: Readonly>; + /** `--param-file NAME=FILE`, by name without the colon; the paths as typed. Never a name `params` has. */ + readonly paramFiles: Readonly>; + /** Rows to print; undefined is every row (`--all`). */ + readonly limit: number | undefined; + readonly format: QueryFormat; +} + export interface TimelineOptions { /** The rendered entity id to look up. */ readonly id: string; @@ -1690,6 +1804,7 @@ export type Invocation = | { readonly kind: "run"; readonly command: "validate"; readonly options: ValidateOptions } | { readonly kind: "run"; readonly command: "analyze"; readonly options: AnalyzeOptions } | { readonly kind: "run"; readonly command: "import"; readonly options: ImportOptions } + | { readonly kind: "run"; readonly command: "query"; readonly options: QueryOptions } | { readonly kind: "run"; readonly command: "export"; readonly options: ExportOptions } | { readonly kind: "run"; readonly command: "city"; readonly options: CityOptions } | { readonly kind: "run"; readonly command: "navigator"; readonly options: NavigatorOptions } @@ -1727,6 +1842,7 @@ export function usageLine(spec: CommandSpec): string { if (spec.positional !== undefined) { const name = spec.positional.variadic ? `${spec.positional.name}...` : spec.positional.name; parts.push(spec.positional.required ? `<${name}>` : `[${name}]`); + if (spec.positional.second !== undefined) parts.push(`[${spec.positional.second.name}]`); } for (const option of spec.options) { parts.push(option.required === true ? flagSyntax(option) : `[${flagSyntax(option)}]`); @@ -1794,6 +1910,8 @@ export function renderHelp(spec: CommandSpec | undefined): string { ? `${spec.positional.describe} (default: ${fallback()}, what the extractor writes here)` : `${spec.positional.describe} (default: ${fallback()})`; lines.push(` ${name} ${describe}`); + const second = spec.positional.second; + if (second !== undefined) lines.push(` [${second.name}] ${second.describe}`); } lines.push(""); lines.push("options:"); @@ -2044,7 +2162,15 @@ function positionalsOf(spec: CommandSpec, positionals: readonly string[]): reado ); } } - if (!spec.positional.variadic && positionals.length > 1) { + const second = spec.positional.second; + if (second !== undefined && positionals.length > 2) { + // Almost always a statement the shell split into words. + throw new UsageError( + `${spec.name} takes a ${spec.positional.name} and one ${second.name}, but ${positionals.length} arguments were given`, + `Quote the ${second.name} so the shell passes it as one argument.\n${usageLine(spec)}`, + ); + } + if (!spec.positional.variadic && second === undefined && positionals.length > 1) { throw new UsageError( `${spec.name} takes a single ${spec.positional.name}`, usageLine(spec), @@ -2113,9 +2239,10 @@ export function parseInvocation(argv: readonly string[]): Invocation { // `serve --app` opens folders through its routes, so no model is defaulted // from the working directory — the one command whose positional is optional. const isApp = spec.name === "serve" && flagOf(values, "app"); - // `walk --print-definition [explain]` reads no model either: its positional, if any, names a built-in. + // `walk --print-definition [explain]` and `query --views` read no model: a positional, if any, is not one. const printing = spec.name === "walk" && flagOf(values, "print-definition"); - const models = isApp || printing ? parsed.positionals : positionalsOf(spec, parsed.positionals); + const isViews = spec.name === "query" && flagOf(values, "views"); + const models = isApp || printing || isViews ? parsed.positionals : positionalsOf(spec, parsed.positionals); switch (spec.name) { case "validate": @@ -2379,6 +2506,8 @@ export function parseInvocation(argv: readonly string[]): Invocation { json: flagOf(values, "json"), }, }; + case "query": + return { kind: "run", command: "query", options: queryOf(values, spec, models) }; case "timeline": return { kind: "run", @@ -2572,6 +2701,102 @@ function printDefinitionOf(values: ParsedValues, positionals: readonly string[]) return { ...walkOptionsOf({}, []), printDefinition: which === "explain" ? "explain" : "default" }; } +/** A parameter's name as SQLite reads it after the colon. */ +const PARAM_NAME = /^[A-Za-z_][A-Za-z0-9_$]*$/; + +/** + * `--param NAME=VALUE` and `--param-file NAME=FILE`, each split at the FIRST + * `=`: a value, like a path, may hold others. A value may be empty; a file may + * not. One name is bound once, whichever of the two flags gives it. + */ +function paramsOf(values: ParsedValues): { params: Readonly>; paramFiles: Readonly> } { + const params: Record = {}; + const paramFiles: Record = {}; + const read = (option: "param" | "param-file", into: Record): void => { + const shape = option === "param" ? "NAME=VALUE" : "NAME=FILE"; + for (const raw of stringsOf(values, option)) { + const cut = raw.indexOf("="); + const name = (cut === -1 ? raw : raw.slice(0, cut)).replace(/^:/, ""); + const value = raw.slice(cut + 1); + if (cut === -1 || !PARAM_NAME.test(name) || (option === "param-file" && value === "")) { + throw new UsageError( + `--${option} needs ${shape}, got '${raw}'`, + option === "param" + ? "NAME is the parameter as the statement writes it after the colon: --param id='java:com.acme/Order' binds :id." + : "NAME is the parameter as the statement writes it after the colon: --param-file rows=saved.json binds :rows to that file's text.", + ); + } + if (Object.hasOwn(params, name) || Object.hasOwn(paramFiles, name)) { + throw new UsageError(`parameter ${name} is given twice`, "One value per parameter: --param or --param-file, once."); + } + into[name] = value; + } + }; + read("param", params); + read("param-file", paramFiles); + return { params, paramFiles }; +} + +/** + * `query`'s shapes: `--views` alone, or a model with ONE source for the + * statement. Each contradiction is refused by name rather than resolved by a + * precedence nobody would guess. + */ +function queryOf(values: ParsedValues, spec: CommandSpec, positionals: readonly string[]): QueryOptions { + const file = stringOf(values, "file"); + const { params, paramFiles } = paramsOf(values); + const json = flagOf(values, "json"); + const csv = flagOf(values, "csv"); + const all = flagOf(values, "all"); + const limit = integerOf(values, "limit"); + + if (flagOf(values, "views")) { + const stray = + positionals[0] ?? + (file !== undefined ? "--file" : undefined) ?? + (Object.keys(params).length > 0 ? "--param" : undefined) ?? + (Object.keys(paramFiles).length > 0 ? "--param-file" : undefined) ?? + (json ? "--json" : csv ? "--csv" : all ? "--all" : limit !== undefined ? "--limit" : undefined); + if (stray !== undefined) { + throw new UsageError( + `--views prints the two views and reads nothing: it takes no model and no other option (got '${stray}')`, + "Run 'codegraph query --views' alone; the views are already there in every 'codegraph query …'.", + ); + } + return { views: true, model: undefined, sql: undefined, file: undefined, params: {}, paramFiles: {}, limit: undefined, format: "table" }; + } + + const [model, sql] = positionals; + if (sql === undefined && file === undefined) { + throw new UsageError( + "query needs a statement", + `Quote it after the model, or pass --file FILE.\n${usageLine(spec)}`, + ); + } + if (sql !== undefined && file !== undefined) { + throw new UsageError( + "query takes ONE statement: the one on the command line, or the one in --file", + "Drop one of the two.", + ); + } + if (json && csv) { + throw new UsageError("--json and --csv are two forms of the same rows", "Pass one of them, or neither for the table."); + } + if (all && limit !== undefined) { + throw new UsageError("--all and --limit contradict each other", "--all prints every row; --limit N prints at most N."); + } + return { + views: false, + model, + sql, + file, + params, + paramFiles, + limit: all ? undefined : (limit ?? DEFAULT_QUERY_LIMIT), + format: json ? "json" : csv ? "csv" : "table", + }; +} + function vocabularyOf(values: ParsedValues): Omit { const scope = stringOf(values, "scope"); const drift = stringOf(values, "drift"); diff --git a/packages/cli/src/commands/query.ts b/packages/cli/src/commands/query.ts new file mode 100644 index 00000000..7d6dfc60 --- /dev/null +++ b/packages/cli/src/commands/query.ts @@ -0,0 +1,354 @@ +import { accessSync, closeSync, constants, mkdtempSync, openSync, readFileSync, readSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { + DB_VERSION, + HELPER_VIEWS_SQL, + QueryRefused, + createHelperViews, + importModel, + openCache, + openStore, + queryStore, + type QueryRefusal, + type QueryResult, + type SqliteDatabase, + type SqliteValue, +} from "@codegraph/analyzer"; +import type { QueryOptions } from "../args.js"; +import { EXIT, UsageError, type ExitCode } from "../exit.js"; +import { errLine, type IoSink } from "../io.js"; + +/** + * `codegraph query [sql] [--file FILE] [--param NAME=VALUE]… [--param-file NAME=FILE]…`. + * + * SQL over a model's store, with the SQLite that is already in this binary — + * so an ad-hoc question needs no `sqlite3` on the machine, and an agent + * following the discovery walk has one way to ask it (PLAN.md §24.4). + * + * The engine is the analyzer's (`queryStore`): ONE statement, beginning with a + * keyword that reads, its parameters bound by name. This command resolves the + * flags, finds the store, and moves bytes (decision 7). + * + * STREAM PURITY (decision 3): stdout carries the rows, in the form asked for, + * and nothing else. Which store answered and how many rows there were — said + * every time, because "0 rows" is an answer — are stderr. + * + * EVERY REFUSAL IS A USAGE ERROR (exit 2), SQLite's included: a statement that + * does not compile is a mistake in what was typed, never a bug in codegraph + * (exit 1) and never a finding about the model (exit 3). The one exit 3 is a + * file that is not a model at all, as everywhere else. + */ +export function queryCommand(options: QueryOptions, io: IoSink): ExitCode { + if (options.views) { + io.out(HELPER_VIEWS_SQL); + return EXIT.OK; + } + + // The parser guarantees a model outside --views; the type cannot say so. + const path = options.model as string; + const sql = options.sql ?? readStatement(options.file as string); + + const source = openQueryable(path, io); + if (source === undefined) return EXIT.FINDINGS; + + try { + createHelperViews(source.db); + const result = run(source.db, sql, options); + io.out(FORMATTERS[options.format](result)); + errLine(io, countLine(result)); + return EXIT.OK; + } finally { + source.close(); + } +} + +function readStatement(file: string): string { + try { + return readFileSync(file, "utf8"); + } catch (error) { + throw new UsageError( + `cannot read ${file}: ${error instanceof Error ? error.message : String(error)}`, + "Check the path exists and is a readable file, or type the statement after the model.", + { cause: error }, + ); + } +} + +/** `--param` values arrive as text. One that reads as a number is bound as that number. */ +function paramValue(text: string): SqliteValue { + if (/^-?\d+$/.test(text)) { + const whole = Number(text); + return Number.isSafeInteger(whole) ? whole : BigInt(text); + } + return /^-?\d+\.\d+$/.test(text) ? Number(text) : text; +} + +/** + * `--param-file NAME=FILE`: the file's whole text, bound as TEXT whatever it + * reads as. It is how one statement builds on another's saved rows — + * `json_each(:NAME, '$.rows')` over a `--json` result — without anybody + * retyping a list of ids on a command line. + */ +function paramFileText(name: string, file: string): string { + try { + return readFileSync(file, "utf8"); + } catch (error) { + throw new UsageError( + `cannot read ${file}, given as --param-file ${name}: ${error instanceof Error ? error.message : String(error)}`, + "Check the path exists and is a readable file: its whole text is what :" + name + " is bound to.", + { cause: error }, + ); + } +} + +function run(db: SqliteDatabase, sql: string, options: QueryOptions): QueryResult { + const params: Record = {}; + for (const [name, text] of Object.entries(options.params)) params[name] = paramValue(text); + for (const [name, file] of Object.entries(options.paramFiles)) params[name] = paramFileText(name, file); + try { + return queryStore(db, sql, { params, limit: options.limit }); + } catch (error) { + if (error instanceof QueryRefused) throw new UsageError(...refusalText(error), { cause: error }); + throw error; + } +} + +const SCHEMA_HINT = + "List what there is: codegraph query \"SELECT type, name FROM sqlite_schema ORDER BY name\". " + + "The views node and dep are always there; 'codegraph query --views' prints them."; + +const HINTS: Readonly> = { + empty: "Quote one statement after the model, or pass --file FILE.", + "not-read-only": "query never writes: not to the store, not to another file.", + "several-statements": "Run them one at a time.", + "foreign-parameter": "Then: --param NAME=VALUE, once per parameter.", + "missing-parameter": "Give each one: --param NAME=VALUE, or --param-file NAME=FILE for a file's text.", + "unknown-parameter": "Drop it, or name it in the statement as :NAME.", + sqlite: SCHEMA_HINT, +}; + +function refusalText(error: QueryRefused): [message: string, hint: string] { + const message = error.reason === "sqlite" ? `SQLite refused the statement: ${error.message}` : error.message; + return [message, HINTS[error.reason]]; +} + +interface Queryable { + readonly db: SqliteDatabase; + close(): void; +} + +const SQLITE_MAGIC = "SQLite format 3\u0000"; + +/** A store is told from a model by its first bytes, never by its file name. */ +function isSqliteFile(path: string): boolean { + const fd = openSync(path, "r"); + try { + const head = Buffer.alloc(SQLITE_MAGIC.length); + const read = readSync(fd, head, 0, head.length, 0); + return read === head.length && head.toString("latin1") === SQLITE_MAGIC; + } finally { + closeSync(fd); + } +} + +/** + * The store to query: the file itself when it is one, else the model's cache, + * built or reused exactly as `analyze` does — and, when no cache can be had + * beside the model, a temporary store that is deleted on the way out. + * + * Returns undefined, having said why, when the file is not a model: that is a + * finding about the file (exit 3), which `validate` details. + */ +function openQueryable(path: string, io: IoSink): Queryable | undefined { + try { + accessSync(path, constants.R_OK); + } catch (error) { + throw new UsageError( + `cannot read ${path}: ${error instanceof Error ? error.message : String(error)}`, + "Check the path exists and is a readable file.", + { cause: error }, + ); + } + + if (isSqliteFile(path)) return openGivenStore(path); + + const attempt = openCache(path); + if (attempt.store !== undefined) { + const db = attempt.store.db; + errLine(io, `cache: ${attempt.store.path}`); + return { db, close: () => db.close() }; + } + if (attempt.reason === "the model could not be read") return notAModel(path, io); + + // FAILING TO CACHE IS NOT FAILING (store/cache.ts): a read-only directory or + // a store kept for its revisions still deserves an answer. + const directory = mkdtempSync(join(tmpdir(), "codegraph-query-")); + const discard = (): void => rmSync(directory, { recursive: true, force: true }); + try { + const store = join(directory, "model.db"); + importModel(path, store); + const db = openStore(store); + errLine(io, `cache: not used — ${attempt.reason}. Querying a temporary store.`); + return { + db, + close: () => { + db.close(); + discard(); + }, + }; + } catch (error) { + discard(); + if (error instanceof Error && error.name === "JsonlError") return notAModel(path, io); + throw error; + } +} + +function notAModel(path: string, io: IoSink): undefined { + errLine(io, `codegraph: cannot query ${path}: it is not a model.jsonl the reader accepts`); + errLine(io, `Run 'codegraph validate ${path}' for the detail.`); + return undefined; +} + +/** A `.db` handed over directly: it must be a store, and of the version this build reads. */ +function openGivenStore(path: string): Queryable { + const foreign = (cause: unknown): UsageError => + new UsageError( + `${path} is a SQLite file, but not a codegraph store`, + "Pass a model.jsonl, or the model.db that 'codegraph import' wrote beside one.", + { cause }, + ); + + let db: SqliteDatabase; + try { + db = openStore(path); + } catch (error) { + throw foreign(error); + } + + let version: number; + try { + const row = db.prepare("SELECT value FROM meta WHERE key = 'dbVersion'").get(); + version = Number(row?.value ?? Number.NaN); + } catch (error) { + db.close(); + throw foreign(error); + } + if (version !== DB_VERSION) { + db.close(); + throw new UsageError( + `${path} is a store of version ${Number.isNaN(version) ? "unknown" : version}; this build reads ${DB_VERSION}`, + "Pass the model.jsonl it was built from: its store is rebuilt when it has to be.", + ); + } + return { db, close: () => db.close() }; +} + +function countLine(result: QueryResult): string { + if (result.truncated) { + return `${result.rows.length} of ${result.total} rows shown — --all prints every row, --limit N another count.`; + } + return `${result.total} ${result.total === 1 ? "row" : "rows"}.`; +} + +// ---------------------------------------------------------------- the three forms + +/** A cell as text. A blob (codegraph writes none) is shown the way SQL writes one. */ +function cellText(value: SqliteValue): string { + if (value === null) return "NULL"; + if (value instanceof Uint8Array) return `x'${Buffer.from(value).toString("hex")}'`; + return String(value); +} + +const ESCAPES: Readonly> = { "\n": "\\n", "\r": "\\r", "\t": "\\t" }; + +/** One row, one line: a line break inside a cell is written as the two characters `\n`. */ +function tableCell(value: SqliteValue): string { + return cellText(value).replace(/[\n\r\t]/g, (char) => ESCAPES[char] ?? char); +} + +/** + * An aligned table: the column names as the statement gives them, a rule, the + * rows. A column whose every value is a number is right-aligned, so magnitudes + * line up; NULL is written NULL so it cannot be read as an empty string. + */ +export function formatTable(result: QueryResult): string { + const numeric = result.columns.map((_name, column) => { + const values = result.rows.map((row) => row[column]).filter((value) => value !== null); + return values.length > 0 && values.every((value) => typeof value === "number" || typeof value === "bigint"); + }); + // One number of decimals per column: `round(x, 1)` gives 6 for 6.0, and a + // column reading 90.9, 6, 3.3 hides that all three are shares to one place. + const decimals = result.columns.map((_name, column) => { + if (numeric[column] !== true) return 0; + const texts = result.rows.map((row) => row[column]).filter((value) => value !== null).map(String); + if (texts.some((text) => /e/i.test(text))) return 0; // exponent form: leave as written + return Math.max(0, ...texts.map((text) => (text.split(".")[1] ?? "").length)); + }); + const cells = result.rows.map((row) => + row.map((value, column) => { + const places = decimals[column] ?? 0; + return places > 0 && typeof value === "number" ? value.toFixed(places) : tableCell(value); + }), + ); + const widths = result.columns.map((name, column) => + Math.max(name.length, ...cells.map((row) => row[column]?.length ?? 0)), + ); + const line = (row: readonly string[]): string => + row + .map((text, column) => { + const width = widths[column] ?? 0; + return numeric[column] === true ? text.padStart(width) : text.padEnd(width); + }) + .join(" ") + .trimEnd(); + + const lines = [line(result.columns), widths.map((width) => "-".repeat(width)).join(" "), ...cells.map(line)]; + return `${lines.join("\n")}\n`; +} + +/** What JSON has for a cell: null, a number, a string. */ +function jsonCell(value: SqliteValue): null | number | string { + if (value === null || typeof value === "number" || typeof value === "string") return value; + if (typeof value === "bigint") return Number.isSafeInteger(Number(value)) ? Number(value) : value.toString(); + return cellText(value); +} + +/** + * `codegraph.queryResult/1`, laid out by hand: ONE ROW PER LINE. A generic + * pretty-printer puts every cell on its own line, which turns fifty rows of + * four columns into two hundred lines that diff badly and read worse. + */ +export function formatJson(result: QueryResult): string { + const array = (values: readonly unknown[]): string => `[${values.map((value) => JSON.stringify(value)).join(", ")}]`; + const rows = result.rows.map((row) => ` ${array(row.map(jsonCell))}`); + return [ + "{", + ' "kind": "codegraph.queryResult/1",', + ` "columns": ${array(result.columns)},`, + rows.length === 0 ? ' "rows": [],' : ` "rows": [\n${rows.join(",\n")}\n ],`, + ` "total": ${result.total},`, + ` "truncated": ${result.truncated}`, + "}", + "", + ].join("\n"); +} + +/** RFC 4180, LF-terminated as the other CSV exports are; NULL is an empty field. */ +function csvField(value: SqliteValue | string): string { + if (value === null) return ""; + const text = typeof value === "string" ? value : cellText(value); + const quote = /[",\n\r]/.test(text) || text !== text.trim(); + return quote ? `"${text.replaceAll('"', '""')}"` : text; +} + +export function formatCsv(result: QueryResult): string { + const lines = [result.columns.map(csvField).join(","), ...result.rows.map((row) => row.map(csvField).join(","))]; + return `${lines.join("\n")}\n`; +} + +const FORMATTERS: Readonly string>> = { + table: formatTable, + json: formatJson, + csv: formatCsv, +}; diff --git a/packages/cli/src/main.ts b/packages/cli/src/main.ts index dae4a86c..b226a729 100644 --- a/packages/cli/src/main.ts +++ b/packages/cli/src/main.ts @@ -13,6 +13,7 @@ import { snapshotsCommand } from "./commands/snapshots.js"; import { timelineCommand } from "./commands/timeline.js"; import { replayCommand } from "./commands/replay.js"; import { profilesCommand } from "./commands/profiles.js"; +import { queryCommand } from "./commands/query.js"; import { validateCommand } from "./commands/validate.js"; import { vocabularyCommand } from "./commands/vocabulary.js"; import { EXIT, isUsageError, type ExitCode } from "./exit.js"; @@ -97,6 +98,8 @@ function dispatch(invocation: Invocation, io: IoSink): ExitCode | Promise { ["analyze", ["analyze", FIXTURE, "--report", "deps"]], ["export", ["export", FIXTURE, "--format", "dot"]], ["profiles", ["profiles"]], + ["query", ["query", FIXTURE, "SELECT count(*) AS n FROM node"]], ]; it.each(commands)("%s is wired and runs", (_name, argv) => { diff --git a/packages/cli/test/e2e-exit-codes.test.ts b/packages/cli/test/e2e-exit-codes.test.ts index 6ba54f24..49bd9233 100644 --- a/packages/cli/test/e2e-exit-codes.test.ts +++ b/packages/cli/test/e2e-exit-codes.test.ts @@ -72,6 +72,11 @@ const SUCCESS_CASES: readonly Case[] = [ argv: ["export", FIXTURE, "--format", "csv", "--level", "type", "--declared-only"], expected: EXIT.OK, }, + { why: "a query over the store", argv: ["query", FIXTURE, "SELECT kind, count(*) AS n FROM node GROUP BY kind"], expected: EXIT.OK }, + { why: "a query with a bound parameter, as json", argv: ["query", FIXTURE, "SELECT id FROM node WHERE kind = :kind", "--param", "kind=package", "--json"], expected: EXIT.OK }, + // No row is an answer, not a failure: the header and "0 rows." on stderr. + { why: "a query that finds nothing", argv: ["query", FIXTURE, "SELECT id FROM node WHERE 0", "--csv"], expected: EXIT.OK }, + { why: "the helper views' SQL", argv: ["query", "--views"], expected: EXIT.OK }, { why: "the corpus's words", argv: ["vocabulary", FIXTURE], expected: EXIT.OK }, { why: "the words per type, as json", @@ -132,6 +137,15 @@ const USAGE_CASES: readonly Case[] = [ expected: EXIT.USAGE, }, { why: "a positional profiles does not take", argv: ["profiles", FIXTURE], expected: EXIT.USAGE }, + // A statement SQLite or the read-only rule refuses is a mistake in what was + // typed: never a bug in codegraph (1), never a finding about the model (3). + { why: "a query with no statement", argv: ["query", FIXTURE], expected: EXIT.USAGE }, + { why: "a query that writes", argv: ["query", FIXTURE, "DELETE FROM entity"], expected: EXIT.USAGE }, + { why: "a query that copies the store to a file", argv: ["query", FIXTURE, "VACUUM INTO '/tmp/codegraph-must-not-exist.db'"], expected: EXIT.USAGE }, + { why: "two statements in one query", argv: ["query", FIXTURE, "SELECT 1; SELECT 2"], expected: EXIT.USAGE }, + { why: "a query SQLite cannot compile", argv: ["query", FIXTURE, "SELECT nope FROM node"], expected: EXIT.USAGE }, + { why: "a query parameter nobody gave", argv: ["query", FIXTURE, "SELECT id FROM node WHERE id = :id"], expected: EXIT.USAGE }, + { why: "a query on a model that is not there", argv: ["query", "/no/such/directory/model.jsonl", "SELECT 1"], expected: EXIT.USAGE }, { why: "an unknown language", argv: ["profiles", "--lang", "klingon"], expected: EXIT.USAGE }, { why: "an unknown word class", argv: ["vocabulary", FIXTURE, "--class", "nouns"], expected: EXIT.USAGE }, { why: "an unknown role to weigh", argv: ["vocabulary", FIXTURE, "--weights", "class=8"], expected: EXIT.USAGE }, @@ -184,6 +198,7 @@ const FINDING_CASES: readonly Case[] = [ expected: EXIT.FINDINGS, }, { why: "the words of a model with a self edge", argv: ["vocabulary", models.selfEdge], expected: EXIT.FINDINGS }, + { why: "a query on a file that is not a model", argv: ["query", models.malformedJson, "SELECT 1"], expected: EXIT.FINDINGS }, ]; /** diff --git a/packages/cli/test/e2e-help.test.ts b/packages/cli/test/e2e-help.test.ts index 1c3ecf91..e971fb8e 100644 --- a/packages/cli/test/e2e-help.test.ts +++ b/packages/cli/test/e2e-help.test.ts @@ -21,7 +21,7 @@ import { */ const FIXTURE = javaFixture(); -const COMMANDS = ["validate", "analyze", "export", "profiles", "walk"] as const; +const COMMANDS = ["validate", "analyze", "export", "profiles", "walk", "query"] as const; beforeAll(ensureCliBinary, 120_000); diff --git a/packages/cli/test/e2e-stream-purity.test.ts b/packages/cli/test/e2e-stream-purity.test.ts index 7442e982..5a5edbfa 100644 --- a/packages/cli/test/e2e-stream-purity.test.ts +++ b/packages/cli/test/e2e-stream-purity.test.ts @@ -75,6 +75,48 @@ describe("export puts ONLY the artifact on stdout", () => { }); }); +describe("query puts ONLY the rows on stdout", () => { + const SQL = "SELECT id, kind FROM node WHERE kind = 'package' AND is_stub = 0 ORDER BY id"; + + it("--json yields one codegraph.queryResult/1 document and nothing else", () => { + const result = runCli(["query", FIXTURE, SQL, "--json"]); + expect(result.code, describeResult(result)).toBe(EXIT.OK); + const json = parseJsonArtifact(result.stdout, "query --json stdout"); + expect(json["kind"]).toBe("codegraph.queryResult/1"); + expect(json["columns"]).toEqual(["id", "kind"]); + expect((json["rows"] as unknown[]).length).toBe(3); + expect(json["total"]).toBe(3); + }); + + it("--csv yields a rectangular table and nothing else", () => { + const result = runCli(["query", FIXTURE, SQL, "--csv"]); + expect(result.code, describeResult(result)).toBe(EXIT.OK); + const table = parseCsv(result.stdout); + expect(table.header).toEqual(["id", "kind"]); + expect(table.rows.map((row) => table.column(row, "id"))).toEqual([ + "java:com.acme.order", + "java:com.acme.order.adapter", + "java:com.acme.order.legacy", + ]); + }); + + it("says which store answered and how many rows on stderr, never on stdout", () => { + const result = runCli(["query", FIXTURE, SQL]); + expect(result.code, describeResult(result)).toBe(EXIT.OK); + expect(result.stdout.split("\n").filter((line) => line !== "").length).toBe(2 + 3); + expect(result.stdout).not.toMatch(/cache|rows\./); + expect(result.stderr).toMatch(/^cache: .*model\.db$/m); + expect(result.stderr).toContain("3 rows."); + }); + + it("a refused statement leaves stdout empty", () => { + const result = runCli(["query", FIXTURE, "DROP TABLE entity"]); + expect(result.code, describeResult(result)).toBe(EXIT.USAGE); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain("SELECT, WITH, VALUES, EXPLAIN"); + }); +}); + describe("the human stream carries the warnings, and stdout stays an artifact", () => { /** * Folding the java fixture to module level drops 5 base edges as unplaceable diff --git a/packages/cli/test/query.test.ts b/packages/cli/test/query.test.ts new file mode 100644 index 00000000..98e3d462 --- /dev/null +++ b/packages/cli/test/query.test.ts @@ -0,0 +1,493 @@ +import { createHash } from "node:crypto"; +import { + chmodSync, + copyFileSync, + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; +import { HELPER_VIEWS_SQL, importModel } from "@codegraph/analyzer"; +import { DEFAULT_QUERY_LIMIT, parseInvocation, UsageError, type QueryOptions } from "../src/args.js"; +import { EXIT } from "../src/exit.js"; +import { captureIo, type CapturedIo } from "../src/io.js"; +import { runSync } from "../src/main.js"; +import { parseCsv } from "./artifact-grammar.js"; + +/** + * `codegraph query`: SQL over a model's store, with no `sqlite3` on the + * machine (PLAN.md §24.4). + * + * The engine — one statement, a keyword that reads, bound parameters — is the + * analyzer's and is tested there (`store-query.test.ts`). What is checked here + * is the COMMAND: what it accepts on a command line, where each byte goes + * (rows on stdout, everything else on stderr), the three output forms saying + * the same thing, the exit code of every refusal, and that a run leaves the + * disk as it found it apart from the cache every reading command writes. + */ + +const FIXTURE = fileURLToPath(new URL("../../../fixtures/java/expected/model.jsonl", import.meta.url)); + +const scratch = mkdtempSync(join(tmpdir(), "codegraph-query-")); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +/** A private copy of the fixture: the command writes the cache beside its model. */ +const MODEL = join(scratch, "app.jsonl"); +const STORE = join(scratch, "app.db"); +beforeAll(() => { + copyFileSync(FIXTURE, MODEL); + importModel(MODEL, STORE); +}); + +const sha = (path: string): string => createHash("sha256").update(readFileSync(path)).digest("hex"); + +function query(...argv: string[]): { io: CapturedIo; code: number } { + const io = captureIo(); + const code = runSync(["query", ...argv], io); + return { io, code }; +} + +function parsed(...argv: string[]): QueryOptions { + const invocation = parseInvocation(["query", ...argv]); + if (invocation.kind !== "run" || invocation.command !== "query") throw new Error("not a query invocation"); + return invocation.options; +} + +function usageError(...argv: string[]): UsageError { + try { + parseInvocation(["query", ...argv]); + } catch (error) { + if (error instanceof UsageError) return error; + throw error; + } + throw new Error(`expected a usage error for: query ${argv.join(" ")}`); +} + +const KINDS = "SELECT kind, count(*) AS n FROM node WHERE is_stub = 0 GROUP BY kind ORDER BY n DESC, kind"; + +describe("query: the command line", () => { + it("takes the model, then the statement", () => { + expect(parsed("app.jsonl", "SELECT 1")).toEqual({ + views: false, + model: "app.jsonl", + sql: "SELECT 1", + file: undefined, + params: {}, + paramFiles: {}, + limit: DEFAULT_QUERY_LIMIT, + format: "table", + }); + }); + + it("reads the statement from --file, with parameters by name", () => { + expect( + parsed("app.jsonl", "--file", "reach.sql", "--param", "id=java:a/B.c(int)", "--param", "n=3", "--json"), + ).toEqual({ + views: false, + model: "app.jsonl", + sql: undefined, + file: "reach.sql", + params: { id: "java:a/B.c(int)", n: "3" }, + paramFiles: {}, + limit: DEFAULT_QUERY_LIMIT, + format: "json", + }); + }); + + it("splits a parameter at its FIRST '=', and accepts the colon", () => { + expect(parsed("m", "SELECT :a, :b", "--param", "a=x=y", "--param", ":b=").params).toEqual({ a: "x=y", b: "" }); + }); + + it("--param-file names a file whose whole text is the value", () => { + const options = parsed("m", "SELECT :rows, :id", "--param-file", "rows=queries/10-saved.json", "--param", "id=x"); + expect(options.paramFiles).toEqual({ rows: "queries/10-saved.json" }); + expect(options.params).toEqual({ id: "x" }); + // A path may hold an '=': the name ends at the first one. + expect(parsed("m", "SELECT :a", "--param-file", ":a=dir=1/f.json").paramFiles).toEqual({ a: "dir=1/f.json" }); + }); + + it("--limit N keeps N rows; --all keeps every one", () => { + expect(parsed("m", "SELECT 1", "--limit", "5").limit).toBe(5); + expect(parsed("m", "SELECT 1", "--all").limit).toBeUndefined(); + expect(parsed("m", "SELECT 1", "--csv").format).toBe("csv"); + }); + + it("--views stands alone and reads no model", () => { + expect(parsed("--views")).toMatchObject({ views: true, model: undefined, sql: undefined }); + expect(usageError("--views", "app.jsonl").message).toContain("--views"); + expect(usageError("--views", "--json").message).toContain("--views"); + expect(usageError("--views", "--param-file", "a=f").message).toContain("--param-file"); + }); + + it.each([ + ["no model", [], "model.jsonl"], + ["no statement", ["app.jsonl"], "--file"], + ["a statement twice", ["app.jsonl", "SELECT 1", "--file", "q.sql"], "--file"], + ["two output forms", ["app.jsonl", "SELECT 1", "--json", "--csv"], "--csv"], + ["--all with --limit", ["app.jsonl", "SELECT 1", "--all", "--limit", "3"], "--all"], + ["a limit of zero", ["app.jsonl", "SELECT 1", "--limit", "0"], "--limit"], + ["a parameter with no '='", ["app.jsonl", "SELECT :a", "--param", "a"], "NAME=VALUE"], + ["a parameter with no name", ["app.jsonl", "SELECT :a", "--param", "=x"], "NAME=VALUE"], + ["a parameter name that is not a word", ["app.jsonl", "SELECT 1", "--param", "a b=x"], "NAME=VALUE"], + ["one parameter twice", ["app.jsonl", "SELECT :a", "--param", "a=1", "--param", "a=2"], "twice"], + ["a parameter file with no '='", ["app.jsonl", "SELECT :a", "--param-file", "a"], "NAME=FILE"], + ["a parameter file with no file", ["app.jsonl", "SELECT :a", "--param-file", "a="], "NAME=FILE"], + ["one parameter file twice", ["app.jsonl", "SELECT :a", "--param-file", "a=f", "--param-file", "a=g"], "twice"], + ["one parameter as a value and as a file", ["app.jsonl", "SELECT :a", "--param", "a=1", "--param-file", "a=f"], "twice"], + ])("refuses %s", (_label, argv, names) => { + const error = usageError(...argv); + expect(`${error.message}\n${error.hint ?? ""}`).toContain(names); + }); + + it("says to quote a statement the shell split into words", () => { + const error = usageError("app.jsonl", "SELECT", "1"); + expect(error.message).toContain("3"); + expect(error.hint ?? "").toMatch(/quote/i); + }); + + it("documents both arguments in its usage line", () => { + const { io, code } = query("--help"); + expect(code).toBe(EXIT.OK); + expect(io.stdout()).toContain("usage: codegraph query [sql]"); + expect(io.stdout()).toContain("--param NAME=VALUE"); + expect(io.stdout()).toContain("--param-file NAME=FILE"); + expect(io.stdout()).toContain(`default: ${DEFAULT_QUERY_LIMIT}`); + }); +}); + +describe("query: the table", () => { + it("prints an aligned table on stdout, and nothing else there", () => { + const { io, code } = query(MODEL, KINDS); + expect(code).toBe(EXIT.OK); + expect(io.stdoutLines()).toEqual([ + "kind n", + "------------- --", + "method 43", + "parameter 35", + "attribute 21", + "constructor 19", + "class 14", + "lambda 6", + "localVariable 6", + "package 3", + "interface 2", + "annotation 1", + "enum 1", + "record 1", + ]); + }); + + it("says which store answered and how many rows, on stderr", () => { + const { io } = query(MODEL, KINDS); + expect(io.stderrLines()).toEqual([`cache: ${STORE}`, "12 rows."]); + }); + + it("is byte-identical across two runs, stderr included", () => { + const first = query(MODEL, KINDS).io; + const second = query(MODEL, KINDS).io; + expect(second.stdout()).toBe(first.stdout()); + expect(second.stderr()).toBe(first.stderr()); + }); + + it("prints the header and the count when there is no row", () => { + const { io, code } = query(MODEL, "SELECT id, kind FROM node WHERE 0"); + expect(code).toBe(EXIT.OK); + expect(io.stdoutLines()).toEqual(["id kind", "-- ----"]); + expect(io.stderr()).toContain("0 rows."); + }); + + it("writes NULL as NULL, and keeps a cell on its line", () => { + const { io } = query(MODEL, "SELECT NULL AS a, 'two\nlines' AS b, 1.5 AS c"); + expect(io.stdoutLines()).toEqual(["a b c", "---- ---------- ---", "NULL two\\nlines 1.5"]); + }); + + it("gives every number of a column the same decimals, so a share of 6.0 does not read as 6", () => { + const { io } = query(MODEL, "VALUES (90.9, 1), (6.0, 20), (3.25, 300)"); + expect(io.stdoutLines()).toEqual(["column1 column2", "------- -------", " 90.90 1", " 6.00 20", " 3.25 300"]); + }); + + it(`cuts at ${DEFAULT_QUERY_LIMIT} rows and says how many there were`, () => { + const { io, code } = query(MODEL, "SELECT id FROM node ORDER BY ref"); + expect(code).toBe(EXIT.OK); + expect(io.stdoutLines().length).toBe(2 + DEFAULT_QUERY_LIMIT); + expect(io.stderr()).toContain(`${DEFAULT_QUERY_LIMIT} of 179 rows shown`); + expect(io.stderr()).toContain("--all"); + }); + + it("--limit and --all move the cut", () => { + expect(query(MODEL, "SELECT id FROM node", "--limit", "3").io.stdoutLines().length).toBe(2 + 3); + const all = query(MODEL, "SELECT id FROM node", "--all").io; + expect(all.stdoutLines().length).toBe(2 + 179); + expect(all.stderr()).toContain("179 rows."); + }); +}); + +describe("query: --json and --csv say what the table says", () => { + it("--json is one codegraph.queryResult/1 document, a row per line", () => { + const { io, code } = query(MODEL, KINDS, "--json", "--limit", "2"); + expect(code).toBe(EXIT.OK); + expect(io.stdout()).toBe( + [ + "{", + ' "kind": "codegraph.queryResult/1",', + ' "columns": ["kind", "n"],', + ' "rows": [', + ' ["method", 43],', + ' ["parameter", 35]', + " ],", + ' "total": 12,', + ' "truncated": true', + "}", + "", + ].join("\n"), + ); + }); + + it("--json with no row is still a document with its columns", () => { + const { io } = query(MODEL, "SELECT id FROM node WHERE 0", "--json"); + expect(JSON.parse(io.stdout())).toEqual({ + kind: "codegraph.queryResult/1", + columns: ["id"], + rows: [], + total: 0, + truncated: false, + }); + }); + + it("--json carries NULL, numbers and text as JSON has them", () => { + const { io } = query(MODEL, "SELECT NULL AS a, 2 AS b, 1.5 AS c, 'x\"y' AS d", "--json"); + expect((JSON.parse(io.stdout()) as { rows: unknown[][] }).rows).toEqual([[null, 2, 1.5, 'x"y']]); + }); + + it("--csv is a header and one line per row, quoted where it must be", () => { + const { io, code } = query(MODEL, "SELECT id, name, NULL AS missing FROM node WHERE kind = 'method' ORDER BY id", "--csv", "--all"); + expect(code).toBe(EXIT.OK); + const table = parseCsv(io.stdout()); + expect(table.header).toEqual(["id", "name", "missing"]); + expect(table.rows.length).toBe(43); + // An id with a comma in it — two parameters — survives as ONE field. + const withComma = table.rows.find((row) => table.column(row, "id").includes(",")); + expect(withComma, "the fixture has a method of two parameters").toBeDefined(); + for (const row of table.rows) expect(table.column(row, "missing")).toBe(""); + }); + + it("the three forms hold the same rows", () => { + const sql = "SELECT id, kind FROM node WHERE kind IN ('class', 'interface') AND is_stub = 0 ORDER BY id"; + const json = JSON.parse(query(MODEL, sql, "--json", "--all").io.stdout()) as { rows: string[][] }; + const csv = parseCsv(query(MODEL, sql, "--csv", "--all").io.stdout()); + const table = query(MODEL, sql, "--all").io.stdoutLines().slice(2); + expect(json.rows.length).toBe(16); + expect(csv.rows).toEqual(json.rows); + expect(table.map((line) => line.split(/\s{2,}/))).toEqual(json.rows); + }); +}); + +describe("query: where the statement and the store come from", () => { + it("--views prints the two helper views and reads nothing", () => { + const { io, code } = query("--views"); + expect(code).toBe(EXIT.OK); + expect(io.stdout()).toBe(HELPER_VIEWS_SQL); + expect(io.stderr()).toBe(""); + }); + + it("reads the statement from a file, comments and all", () => { + const file = join(scratch, "kinds.sql"); + writeFileSync(file, `-- kinds, stubs excluded\n${KINDS};\n`, "utf8"); + const fromFile = query(MODEL, "--file", file).io; + expect(fromFile.stdout()).toBe(query(MODEL, KINDS).io.stdout()); + }); + + it("binds --param by name: an id with parentheses needs no escaping", () => { + const { io, code } = query(MODEL, "SELECT kind FROM node WHERE id = :id", "--param", "id=java:com.acme.order/Order.discount(int)", "--json"); + expect(code).toBe(EXIT.OK); + expect((JSON.parse(io.stdout()) as { rows: unknown[][] }).rows).toEqual([["method"]]); + }); + + it("binds a parameter that reads as a number as a number, and anything else as text", () => { + const { io } = query( + MODEL, + "SELECT typeof(:i), typeof(:r), typeof(:t), typeof(:e)", + "--param", "i=-12", "--param", "r=0.5", "--param", "t=12a", "--param", "e=", + "--json", + ); + expect((JSON.parse(io.stdout()) as { rows: unknown[][] }).rows).toEqual([["integer", "real", "text", "text"]]); + }); + + /** + * What `--param-file` is for: one saved result feeds the next statement. The + * rows a `--json` run wrote are read back with `json_each`, so a walk can + * build on a file a person can open instead of on a list retyped by hand. + */ + it("binds --param-file to the whole text of the file: a saved result is read back row for row", () => { + const saved = join(scratch, "10-kinds.json"); + const first = query(MODEL, KINDS, "--all", "--json").io.stdout(); + writeFileSync(saved, first, "utf8"); + + const { io, code } = query( + MODEL, + "SELECT json_extract(j.value, '$[0]') AS kind, json_extract(j.value, '$[1]') AS n FROM json_each(:saved, '$.rows') j ORDER BY j.key", + "--param-file", `saved=${saved}`, + "--all", "--json", + ); + expect(code).toBe(EXIT.OK); + const rows = (text: string): unknown[][] => (JSON.parse(text) as { rows: unknown[][] }).rows; + expect(rows(io.stdout())).toEqual(rows(first)); + expect(rows(first).length).toBe(12); + }); + + it("binds a file's text as text, whatever it reads as, and joins it with the model", () => { + const number = join(scratch, "n.txt"); + writeFileSync(number, "42", "utf8"); + const typed = query(MODEL, "SELECT typeof(:n), :n", "--param-file", `n=${number}`, "--json").io.stdout(); + expect((JSON.parse(typed) as { rows: unknown[][] }).rows).toEqual([["text", "42"]]); + + const ids = join(scratch, "ids.json"); + writeFileSync(ids, JSON.stringify(["java:com.acme.order/Order.discount(int)", "java:nowhere/Nothing"]), "utf8"); + const joined = query( + MODEL, + "SELECT j.value AS id, n.kind FROM json_each(:ids) j LEFT JOIN node n ON n.id = j.value ORDER BY j.key", + "--param-file", `ids=${ids}`, + "--json", + ).io.stdout(); + expect((JSON.parse(joined) as { rows: unknown[][] }).rows).toEqual([ + ["java:com.acme.order/Order.discount(int)", "method"], + ["java:nowhere/Nothing", null], + ]); + }); + + it("accepts a model.db itself, and then names no cache", () => { + const { io, code } = query(STORE, KINDS); + expect(code).toBe(EXIT.OK); + expect(io.stdoutLines()[2]).toBe("method 43"); + expect(io.stderrLines()).toEqual(["12 rows."]); + }); + + it("builds the store beside a model that has none", () => { + const dir = mkdtempSync(join(scratch, "fresh-")); + const model = join(dir, "m.jsonl"); + copyFileSync(FIXTURE, model); + const { io, code } = query(model, "SELECT count(*) AS n FROM node"); + expect(code).toBe(EXIT.OK); + expect(io.stdoutLines()).toEqual([" n", "---", "179"]); + expect(existsSync(join(dir, "m.db"))).toBe(true); + }); + + it.runIf(process.getuid?.() !== 0)("answers from a temporary store when none can be written beside the model", () => { + const dir = mkdtempSync(join(scratch, "readonly-")); + const model = join(dir, "m.jsonl"); + copyFileSync(FIXTURE, model); + chmodSync(dir, 0o555); + try { + const { io, code } = query(model, "SELECT count(*) AS n FROM node"); + expect(code).toBe(EXIT.OK); + expect(io.stdoutLines()[2]).toBe("179"); + expect(io.stderr()).toContain("cache: not used"); + expect(readdirSync(dir)).toEqual(["m.jsonl"]); + } finally { + chmodSync(dir, 0o755); + } + }); +}); + +describe("query: every refusal is a usage error, and says what to type", () => { + it.each([ + ["a statement that does not read", "DELETE FROM entity", "SELECT, WITH, VALUES, EXPLAIN"], + ["VACUUM INTO", `VACUUM INTO '${join(scratch, "copy.db")}'`, "VACUUM"], + ["two statements", "SELECT 1; SELECT 2", "ONE statement"], + ["an unknown column", "SELECT nope FROM node", "no such column: nope"], + ["an unknown table", "SELECT * FROM nodes", "no such table: nodes"], + ["a parameter nobody gave", "SELECT id FROM node WHERE id = :id", "--param"], + ["a positional parameter", "SELECT ?", ":name"], + ])("%s exits 2 with nothing on stdout", (_label, sql, names) => { + const { io, code } = query(MODEL, sql); + expect(code).toBe(EXIT.USAGE); + expect(io.stdout()).toBe(""); + expect(io.stderr()).toContain(names); + expect(io.stderr()).not.toContain("bug in codegraph"); + expect(io.stderr()).not.toMatch(/\n\s+at /); + }); + + it("a parameter the statement does not name exits 2", () => { + const { io, code } = query(MODEL, "SELECT 1", "--param", "id=x"); + expect(code).toBe(EXIT.USAGE); + expect(io.stderr()).toContain(":id"); + }); + + it("a parameter file that cannot be read, or that the statement does not name, exits 2", () => { + const absent = join(scratch, "absent.json"); + const unread = query(MODEL, "SELECT :rows", "--param-file", `rows=${absent}`); + expect(unread.code).toBe(EXIT.USAGE); + expect(unread.io.stdout()).toBe(""); + expect(unread.io.stderr()).toContain(absent); + expect(unread.io.stderr()).toContain("--param-file rows"); + + const present = join(scratch, "present.json"); + writeFileSync(present, "[]", "utf8"); + const unnamed = query(MODEL, "SELECT 1", "--param-file", `rows=${present}`); + expect(unnamed.code).toBe(EXIT.USAGE); + expect(unnamed.io.stderr()).toContain(":rows"); + }); + + it("an unreadable model, statement file or foreign database exits 2", () => { + expect(query(join(scratch, "absent.jsonl"), "SELECT 1").code).toBe(EXIT.USAGE); + expect(query(MODEL, "--file", join(scratch, "absent.sql")).code).toBe(EXIT.USAGE); + + const foreign = join(scratch, "foreign.db"); + importModel(MODEL, foreign); + // A real SQLite file that is not a store: the header page of one, alone. + writeFileSync(foreign, readFileSync(foreign).subarray(0, 16)); + const { io, code } = query(foreign, "SELECT 1"); + expect(code).toBe(EXIT.USAGE); + expect(io.stderr()).toContain("not a codegraph store"); + }); + + it("a file that is not a model is a FINDING about the file (exit 3), with the command that says why", () => { + const dir = mkdtempSync(join(scratch, "broken-")); + const broken = join(dir, "broken.jsonl"); + writeFileSync(broken, '{"t":"header"}\nnot json\n', "utf8"); + const { io, code } = query(broken, "SELECT 1"); + expect(code).toBe(EXIT.FINDINGS); + expect(io.stdout()).toBe(""); + expect(io.stderr()).toContain(`codegraph validate ${broken}`); + }); +}); + +describe("query writes nothing (PLAN.md §24.9)", () => { + it("no refused statement leaves a file, and the store is byte for byte what it was", () => { + const dir = mkdtempSync(join(scratch, "sealed-")); + mkdirSync(join(dir, "out")); + const model = join(dir, "m.jsonl"); + copyFileSync(FIXTURE, model); + expect(query(model, "SELECT 1").code).toBe(EXIT.OK); // builds the cache, once + const store = join(dir, "m.db"); + const before = sha(store); + + const target = (name: string): string => join(dir, "out", name); + const attempts = [ + `VACUUM INTO '${target("vacuum.db")}'`, + `ATTACH DATABASE '${target("attached.db")}' AS other`, + "PRAGMA writable_schema = ON", + "CREATE TEMP TABLE t AS SELECT 1 AS a", + `SELECT 1; VACUUM INTO '${target("tail.db")}'`, + "/* SELECT */ DELETE FROM entity", + `-- SELECT 1\nVACUUM INTO '${target("hidden.db")}'`, + "WITH a AS (SELECT 1) DELETE FROM entity", + ]; + for (const sql of attempts) { + const { io, code } = query(model, sql); + expect(code, sql).toBe(EXIT.USAGE); + expect(io.stdout(), sql).toBe(""); + } + + expect(readdirSync(join(dir, "out"))).toEqual([]); + expect(readdirSync(dir).sort()).toEqual(["m.db", "m.jsonl", "out"]); + expect(sha(store)).toBe(before); + }); +}); From b54a27e4353c67fbe60a2018061b42f15136f06e Mon Sep 17 00:00:00 2001 From: Jeremie Grodziski Date: Mon, 23 Nov 2026 10:16:20 +0000 Subject: [PATCH 03/16] feat(analyzer,cli): join hotspots with a model history --report hotspots --model FILE gives each changed file its lines, its cyclomatic complexity, the size of its dependency cycle and its rank in four families: classic (revisions x lines), branchy (x cyclomatic, the default order), tangled (in a cycle), fragile (x fix density). --rank chooses the order. A score of 0 is not ranked: no measured operation is "not measured", never "simple". Each row says who holds the file without a name: the main author's share, that author's row in --report authors, the day last seen. history --report summary --model FILE adds the share of commits that cross a top-level directory of the model. A --model with an invalid line loaded as an empty model, and hidden then answered "none" with exit 0. It is now exit 3 for every report that reads a model. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01PKCVh2essA8PpHntfjvJtH --- packages/analyzer/src/evolution.ts | 256 +++++++++++- .../analyzer/test/evolution-hotspots.test.ts | 327 +++++++++++++++ packages/analyzer/test/public-api.test.ts | 13 + packages/cli/src/args.ts | 52 ++- packages/cli/src/commands/history.ts | 210 +++++++++- packages/cli/test/history-joined.test.ts | 380 ++++++++++++++++++ packages/cli/test/scm.test.ts | 1 + 7 files changed, 1226 insertions(+), 13 deletions(-) create mode 100644 packages/analyzer/test/evolution-hotspots.test.ts create mode 100644 packages/cli/test/history-joined.test.ts diff --git a/packages/analyzer/src/evolution.ts b/packages/analyzer/src/evolution.ts index c6161c2f..99d18ed5 100644 --- a/packages/analyzer/src/evolution.ts +++ b/packages/analyzer/src/evolution.ts @@ -1,5 +1,7 @@ -import type { Edge, SourceAnchor } from "@codegraph/core"; +import type { Edge, Entity, SourceAnchor } from "@codegraph/core"; import type { CodeGraph } from "./graph.js"; +import { sortIds } from "./order.js"; +import { stronglyConnectedComponents } from "./scc.js"; /** * THE CROSS-GRAPH QUERIES (M9b, PLAN §11.2) — the ones only a tool holding @@ -254,3 +256,255 @@ export function deadWeight( ); return { rows, outsideHistory }; } + +/** + * What the model measures in ONE FILE — the complexity side of a hotspot + * (M23b, PLAN §24.5). `undefined` is "nothing in this file carries the key", + * never zero: a file of constants has no cyclomatic complexity to report, and + * a ranking must not read that as "simple". + */ +export interface FileMeasure { + /** Source lines: the outermost measured entities written in the file. */ + readonly sloc: number | undefined; + /** `cyclomatic` summed over every entity written in the file. */ + readonly cyclomatic: number | undefined; + /** Files in this file's dependency cycle, itself included; 0 when it is in none. */ + readonly cycle: number; +} + +function measured(entity: Entity, key: string): number | undefined { + const value = (entity as { metrics?: Record }).metrics?.[key]; + return typeof value === "number" && Number.isFinite(value) ? value : undefined; +} + +/** + * One measure per file of `deps.files`. + * + * LINES ARE COUNTED ONCE. A class's `sloc` already holds its methods' and its + * nested classes'; a TypeScript module's holds everything in the file. So a + * file's lines are those of the entities with NO measured ancestor in the same + * file — the same-file clause is for a type written across several files, + * whose members elsewhere have no outer entity where they stand. + * + * CYCLOMATIC IS SUMMED, because each operation carries its own branches and a + * lambda's are charged to the lambda: the sum the city draws as a height. + * + * THE CYCLE is a strongly connected component of the FILE graph `deps` holds: + * declared facts by default, so "this file is in a cycle" is one too. + */ +export function fileMeasures(graph: CodeGraph, deps: FileDependencies): ReadonlyMap { + const sloc = new Map(); + const cyclomatic = new Map(); + + const anchorFile = (entity: Entity | undefined): string | undefined => + (entity as { anchor?: SourceAnchor } | undefined)?.anchor?.file; + const insideMeasured = (id: string, file: string): boolean => { + const seen = new Set(); + for (let at = graph.parentOf(id); at !== undefined && !seen.has(at); at = graph.parentOf(at)) { + seen.add(at); + const above = graph.entity(at); + if (above !== undefined && anchorFile(above) === file && measured(above, "sloc") !== undefined) return true; + } + return false; + }; + + for (const entity of graph.entities.values()) { + const file = anchorFile(entity); + if (file === undefined) continue; + const branches = measured(entity, "cyclomatic"); + if (branches !== undefined) cyclomatic.set(file, (cyclomatic.get(file) ?? 0) + branches); + const lines = measured(entity, "sloc"); + if (lines !== undefined && !insideMeasured(entity.id, file)) sloc.set(file, (sloc.get(file) ?? 0) + lines); + } + + const files = sortIds(deps.files); + const cycle = new Map(); + for (const component of stronglyConnectedComponents(files, (file) => [...(deps.out.get(file) ?? [])])) { + if (component.length < 2) continue; + for (const file of component) cycle.set(file, component.length); + } + + return new Map( + files.map((file) => [file, { sloc: sloc.get(file), cyclomatic: cyclomatic.get(file), cycle: cycle.get(file) ?? 0 }] as const), + ); +} + +/** + * The four ways the discovery walk ranks a hotspot (docs: discover/activity): + * effort times one kind of trouble each. + * + * classic revisions x source lines + * branchy revisions x cyclomatic complexity + * tangled revisions, for a file locked in a dependency cycle + * fragile revisions x fix density — which is the number of fixes + */ +export const HOTSPOT_FAMILIES = ["classic", "branchy", "tangled", "fragile"] as const; +export type HotspotFamily = (typeof HOTSPOT_FAMILIES)[number]; +export const DEFAULT_HOTSPOT_FAMILY: HotspotFamily = "branchy"; + +/** One file's activity, as `@codegraph/scm`'s `hotspots` reports it. */ +export interface FileActivity { + readonly path: string; + readonly revisions: number; + readonly churn: number; + readonly fixes: number; + readonly bugDensity: number; + readonly authors: number; +} + +/** The model's side of a joined row, added to whatever the history side carried. */ +export interface JoinedHotspotMeasures { + /** The model file the history path joined to. */ + readonly model: string; + /** `null`, not 0, when the model measured nothing of that kind in the file. */ + readonly sloc: number | null; + readonly cyclomatic: number | null; + readonly cycle: number; + readonly scores: Readonly>; + /** 1-based position in each family; `null` where the score is 0. */ + readonly ranks: Readonly>; +} + +/** The history's row, whole — a caller's extra fields ride along — plus the model's side. */ +export type JoinedHotspotRow = A & JoinedHotspotMeasures; + +export interface JoinedHotspotReport { + /** The family `rows` is ordered by. */ + readonly rank: HotspotFamily; + /** Ranked rows first, then the unranked ones by revisions; ties by path. */ + readonly rows: readonly JoinedHotspotRow[]; + /** History files with no counterpart in the model (docs, build files, deleted files). */ + readonly outsideModel: number; + /** Model files no mined commit touched. */ + readonly outsideHistory: number; +} + +/** + * THE JOINED HOTSPOT REPORT: each file the history and the model both know, + * with its effort, its complexity, and its place in the four families. + * + * A score of 0 is NOT RANKED. It means "no effort" or "nothing measured", and + * a file with thirty revisions and no measured operation must not be shown as + * the simplest of the busy ones. + */ +export function joinedHotspots( + activity: readonly A[], + measures: ReadonlyMap, + join: FileJoin, + options: { readonly rank?: HotspotFamily | undefined } = {}, +): JoinedHotspotReport { + const rank = options.rank ?? DEFAULT_HOTSPOT_FAMILY; + type Draft = A & Omit & { ranks: Record }; + const drafts: Draft[] = []; + let outsideModel = 0; + + for (const row of activity) { + const model = join.modelOf.get(row.path); + const measure = model === undefined ? undefined : measures.get(model); + if (model === undefined || measure === undefined) { + outsideModel += 1; + continue; + } + drafts.push({ + ...row, + model, + sloc: measure.sloc ?? null, + cyclomatic: measure.cyclomatic ?? null, + cycle: measure.cycle, + scores: { + classic: row.revisions * (measure.sloc ?? 0), + branchy: row.revisions * (measure.cyclomatic ?? 0), + tangled: measure.cycle > 0 ? row.revisions : 0, + // revisions x (fixes / revisions): stated as the integer it is. + fragile: row.fixes, + }, + ranks: { classic: null, branchy: null, tangled: null, fragile: null }, + }); + } + + const by = (family: HotspotFamily) => (a: Draft, b: Draft): number => + b.scores[family] - a.scores[family] || + b.revisions - a.revisions || + (a.path < b.path ? -1 : a.path > b.path ? 1 : 0); + for (const family of HOTSPOT_FAMILIES) { + [...drafts].sort(by(family)).forEach((row, position) => { + if (row.scores[family] > 0) row.ranks[family] = position + 1; + }); + } + drafts.sort(by(rank)); + + let outsideHistory = 0; + for (const file of measures.keys()) if (!join.historyOf.has(file)) outsideHistory += 1; + + return { rank, rows: drafts, outsideModel, outsideHistory }; +} + +export interface CrossModuleShare { + /** The directory every joined model file lives under; "" when they share none. */ + readonly root: string; + /** The top-level directories below `root`, sorted; "." is `root` itself. */ + readonly modules: readonly string[]; + /** Commits that touch at least one file of the model. */ + readonly commits: number; + /** Of those, the ones that touch two top-level directories or more. */ + readonly crossing: number; + /** crossing / commits; 0 — not NaN — when no commit touches the model. */ + readonly share: number; + /** Commits over `maxChangesetSize` files, left out of both counts. */ + readonly skipped: number; +} + +/** + * HOW OFTEN A COMMIT CROSSES A MODULE — the number that says whether the + * folders are boundaries (docs: discover/boundaries, check 3). A "module" here + * is a TOP-LEVEL DIRECTORY of the model: the first path segment below the + * directory all its files share. Paths, not ids — a path is the one thing the + * history and the model both carry, and an id is never parsed (invariant 7). + * In Java that segment is the first package below the common root. + * + * A changeset is the list of history paths one commit touched. + */ +export function crossModuleShare( + changesets: Iterable, + join: FileJoin, + options: { readonly maxChangesetSize?: number | undefined } = {}, +): CrossModuleShare { + const directories = [...join.historyOf.keys()].map((file) => file.split("/").slice(0, -1)); + let shared = directories[0] ?? []; + for (const directory of directories) { + let length = 0; + while (length < shared.length && length < directory.length && shared[length] === directory[length]) length += 1; + shared = shared.slice(0, length); + } + const moduleOf = (modelFile: string): string => modelFile.split("/").slice(0, -1)[shared.length] ?? "."; + + const modules = new Set(); + for (const file of join.historyOf.keys()) modules.add(moduleOf(file)); + + let commits = 0; + let crossing = 0; + let skipped = 0; + for (const changeset of changesets) { + if (options.maxChangesetSize !== undefined && changeset.length > options.maxChangesetSize) { + skipped += 1; + continue; + } + const touched = new Set(); + for (const path of changeset) { + const model = join.modelOf.get(path); + if (model !== undefined) touched.add(moduleOf(model)); + } + if (touched.size === 0) continue; + commits += 1; + if (touched.size > 1) crossing += 1; + } + + return { + root: shared.join("/"), + modules: sortIds(modules), + commits, + crossing, + share: commits === 0 ? 0 : crossing / commits, + skipped, + }; +} diff --git a/packages/analyzer/test/evolution-hotspots.test.ts b/packages/analyzer/test/evolution-hotspots.test.ts new file mode 100644 index 00000000..3252d54a --- /dev/null +++ b/packages/analyzer/test/evolution-hotspots.test.ts @@ -0,0 +1,327 @@ +import { describe, expect, it } from "vitest"; +import type { Edge, Entity } from "@codegraph/core"; +import { buildGraph } from "../src/graph.js"; +import { loadModels } from "../src/load.js"; +import { + HOTSPOT_FAMILIES, + crossModuleShare, + fileDependencies, + fileMeasures, + joinOnPaths, + joinedHotspots, + type FileActivity, +} from "../src/evolution.js"; +import { pkg, toyModel } from "./fixture.js"; + +/** + * THE JOINED HOTSPOT REPORT (M23b, PLAN §24.5), hand-counted. + * + * The model, extracted from `src/`: + * + * com/x/order/Order.java Order 40 lines · place() cc 6 · a lambda in it cc 2 + * · nested Order.Line 8 lines · Line.total() cc 1 + * com/x/order/Pricing.java Pricing 20 lines · price() cc 9 + * com/x/stock/Stock.java Stock 30 lines · reserve() cc 4 + * com/x/stock/Bin.java Bin 10 lines · no operation, so no cyclomatic + * com/x/App.java App 5 lines · main() cc 1 + * gen/Dto.java Dto, measured by nothing, touched by no commit + * + * declared: Order <-> Pricing (a cycle of two files) Order -> Stock -> Bin + * App -> Order + * derived: Bin -> Stock (would close a second cycle; an inference does not) + * + * The history, mined from the repository root: + * + * src/com/x/order/Order.java 10 revisions, 2 fixes + * src/com/x/order/Pricing.java 4 revisions, 3 fixes + * src/com/x/stock/Stock.java 12 revisions, 0 fixes + * src/com/x/stock/Bin.java 30 revisions, 1 fix + * src/com/x/App.java 1 revision, 0 fixes + * README.md 50 revisions — no counterpart in the model + */ + +const FILE = { + order: "com/x/order/Order.java", + pricing: "com/x/order/Pricing.java", + stock: "com/x/stock/Stock.java", + bin: "com/x/stock/Bin.java", + app: "com/x/App.java", + dto: "gen/Dto.java", +} as const; +const HIST = Object.fromEntries(Object.entries(FILE).map(([key, path]) => [key, `src/${path}`])) as Record; + +function entity( + id: string, + kind: string, + traits: readonly string[], + parent: string, + file: string, + metrics?: Readonly>, +): Entity { + return { + id, + kind, + traits: ["TNamed", "TChildOf", "TSourceAnchor", ...traits], + name: id, + isStub: false, + parent, + anchor: { file, span: [1, 10] }, + ...(metrics === undefined ? {} : { metrics }), + } as unknown as Entity; +} + +const type = (id: string, parent: string, file: string, sloc?: number): Entity => + entity(id, "class", ["TType", "TWithChildren"], parent, file, sloc === undefined ? undefined : { sloc }); +const operation = (id: string, parent: string, file: string, cyclomatic: number, kind = "method"): Entity => + ({ ...entity(id, kind, ["TInvocable"], parent, file, { cyclomatic, sloc: 3 }), signature: "()" }) as Entity; + +function edge(from: string, to: string, file: string, provenance = "declared"): Edge { + return { edge: "reference", from, to, provenance, anchor: { file, span: [1, 1] } } as unknown as Edge; +} + +const graph = buildGraph( + loadModels( + toyModel( + [ + pkg("com.x"), + pkg("com.x.order"), + pkg("com.x.stock"), + pkg("gen"), + type("Order", "com.x.order", FILE.order, 40), + operation("Order.place", "Order", FILE.order, 6), + operation("Order.place.lambda", "Order.place", FILE.order, 2, "lambda"), + type("Order.Line", "Order", FILE.order, 8), + operation("Order.Line.total", "Order.Line", FILE.order, 1), + type("Pricing", "com.x.order", FILE.pricing, 20), + operation("Pricing.price", "Pricing", FILE.pricing, 9), + type("Stock", "com.x.stock", FILE.stock, 30), + operation("Stock.reserve", "Stock", FILE.stock, 4), + type("Bin", "com.x.stock", FILE.bin, 10), + type("App", "com.x", FILE.app, 5), + operation("App.main", "App", FILE.app, 1), + type("Dto", "gen", FILE.dto), + ], + [ + edge("Order.place", "Pricing", FILE.order), + edge("Pricing.price", "Order", FILE.pricing), + edge("Order", "Stock", FILE.order), + edge("Stock", "Bin", FILE.stock), + edge("App.main", "Order", FILE.app), + edge("Bin", "Stock", FILE.bin, "derived"), + ], + ), + { sources: ["test"] }, + ).union, +); + +const deps = fileDependencies(graph); +const measures = fileMeasures(graph, deps); + +const activity = (path: string, revisions: number, fixes: number): FileActivity => ({ + path, + revisions, + churn: revisions * 10, + fixes, + bugDensity: fixes / revisions, + authors: 1, +}); +const ACTIVITY: readonly FileActivity[] = [ + activity("README.md", 50, 0), + activity(HIST.bin, 30, 1), + activity(HIST.stock, 12, 0), + activity(HIST.order, 10, 2), + activity(HIST.pricing, 4, 3), + activity(HIST.app, 1, 0), +]; +const join = joinOnPaths(deps.files, ACTIVITY.map((row) => row.path)); + +describe("fileMeasures: what the model measures in one file", () => { + it("counts a file's lines once: the outermost measured entity, not what is nested in it", () => { + // Order (40) holds Order.Line (8) and the operations' own lines: 40, not 40 + 8 + 3 + 3 + 3. + expect(measures.get(FILE.order)?.sloc).toBe(40); + expect(measures.get(FILE.pricing)?.sloc).toBe(20); + }); + + it("sums cyclomatic over every operation written in the file, a lambda apart from its method", () => { + expect(measures.get(FILE.order)?.cyclomatic).toBe(6 + 2 + 1); + expect(measures.get(FILE.stock)?.cyclomatic).toBe(4); + }); + + it("says unmeasured, not zero, where nothing carries the key", () => { + expect(measures.get(FILE.bin)).toEqual({ sloc: 10, cyclomatic: undefined, cycle: 0 }); + expect(measures.get(FILE.dto)).toEqual({ sloc: undefined, cyclomatic: undefined, cycle: 0 }); + }); + + it("gives each file the size of its dependency cycle, on declared facts", () => { + expect(measures.get(FILE.order)?.cycle).toBe(2); + expect(measures.get(FILE.pricing)?.cycle).toBe(2); + // Stock -> Bin is declared, Bin -> Stock only derived: no cycle is stated. + expect(measures.get(FILE.stock)?.cycle).toBe(0); + expect(measures.get(FILE.bin)?.cycle).toBe(0); + }); + + it("counts an inferred cycle when asked to fold inferences too", () => { + const loose = fileDependencies(graph, { declaredOnly: false }); + expect(fileMeasures(graph, loose).get(FILE.bin)?.cycle).toBe(2); + }); + + it("measures every file of the model, and only those", () => { + expect([...measures.keys()].sort()).toEqual(Object.values(FILE).sort()); + }); +}); + +describe("joinedHotspots: effort times complexity, four ways", () => { + const report = joinedHotspots(ACTIVITY, measures, join); + const row = (path: string) => report.rows.find((one) => one.path === path)!; + + it("names the four families, in the page's order", () => { + expect(HOTSPOT_FAMILIES).toEqual(["classic", "branchy", "tangled", "fragile"]); + }); + + it("keeps the files that joined, and counts the two kinds that did not", () => { + expect(report.rows.map((one) => one.path).sort()).toEqual([HIST.app, HIST.bin, HIST.order, HIST.pricing, HIST.stock].sort()); + expect(report.outsideModel).toBe(1); // README.md + expect(report.outsideHistory).toBe(1); // gen/Dto.java + }); + + it("carries both sides on each row", () => { + expect(row(HIST.order)).toMatchObject({ + path: HIST.order, + model: FILE.order, + revisions: 10, + churn: 100, + fixes: 2, + bugDensity: 0.2, + authors: 1, + sloc: 40, + cyclomatic: 9, + cycle: 2, + }); + }); + + it("scores classic = revisions x lines", () => { + expect(Object.fromEntries(report.rows.map((one) => [one.model, one.scores.classic]))).toEqual({ + [FILE.order]: 400, + [FILE.stock]: 360, + [FILE.bin]: 300, + [FILE.pricing]: 80, + [FILE.app]: 5, + }); + expect([HIST.order, HIST.stock, HIST.bin, HIST.pricing, HIST.app].map((path) => row(path).ranks.classic)).toEqual([1, 2, 3, 4, 5]); + }); + + it("scores branchy = revisions x cyclomatic, and ranks no file it could not measure", () => { + expect([HIST.order, HIST.stock, HIST.pricing, HIST.app].map((path) => row(path).scores.branchy)).toEqual([90, 48, 36, 1]); + expect([HIST.order, HIST.stock, HIST.pricing, HIST.app].map((path) => row(path).ranks.branchy)).toEqual([1, 2, 3, 4]); + // Bin has 30 revisions and no measured operation: unmeasured is written null, never 0. + expect(row(HIST.bin)).toMatchObject({ cyclomatic: null, scores: { branchy: 0 }, ranks: { branchy: null } }); + }); + + it("scores tangled = revisions for a file in a cycle, nothing for the others", () => { + expect(row(HIST.order)).toMatchObject({ scores: { tangled: 10 }, ranks: { tangled: 1 } }); + expect(row(HIST.pricing)).toMatchObject({ scores: { tangled: 4 }, ranks: { tangled: 2 } }); + expect(row(HIST.bin)).toMatchObject({ scores: { tangled: 0 }, ranks: { tangled: null } }); + }); + + it("scores fragile = revisions x fix density, which is the fixes", () => { + expect([HIST.pricing, HIST.order, HIST.bin].map((path) => row(path).scores.fragile)).toEqual([3, 2, 1]); + expect([HIST.pricing, HIST.order, HIST.bin].map((path) => row(path).ranks.fragile)).toEqual([1, 2, 3]); + expect(row(HIST.stock).ranks.fragile).toBeNull(); + }); + + it("orders the rows by the family asked for, the unranked last by revisions", () => { + expect(report.rank).toBe("branchy"); + expect(report.rows.map((one) => one.path)).toEqual([HIST.order, HIST.stock, HIST.pricing, HIST.app, HIST.bin]); + expect(joinedHotspots(ACTIVITY, measures, join, { rank: "classic" }).rows.map((one) => one.path)).toEqual([ + HIST.order, + HIST.stock, + HIST.bin, + HIST.pricing, + HIST.app, + ]); + expect(joinedHotspots(ACTIVITY, measures, join, { rank: "fragile" }).rows.map((one) => one.path)).toEqual([ + HIST.pricing, + HIST.order, + HIST.bin, + HIST.stock, + HIST.app, + ]); + expect(joinedHotspots(ACTIVITY, measures, join, { rank: "tangled" }).rows.map((one) => one.path)).toEqual([ + HIST.order, + HIST.pricing, + HIST.bin, + HIST.stock, + HIST.app, + ]); + }); + + it("breaks a tie on the score by revisions, then by path: the same bytes on every run", () => { + const tied = [activity("src/com/x/order/Pricing.java", 10, 0), activity("src/com/x/order/Order.java", 10, 0)]; + const flat = new Map([ + [FILE.order, { sloc: 7, cyclomatic: 3, cycle: 0 }], + [FILE.pricing, { sloc: 7, cyclomatic: 3, cycle: 0 }], + ]); + const tiedJoin = joinOnPaths(flat.keys(), tied.map((one) => one.path)); + const rows = joinedHotspots(tied, flat, tiedJoin).rows; + expect(rows.map((one) => one.model)).toEqual([FILE.order, FILE.pricing]); + expect(rows.map((one) => one.ranks.branchy)).toEqual([1, 2]); + }); + + it("is serializable as it stands: no undefined, no Set", () => { + const text = JSON.stringify(report); + expect(JSON.parse(text)).toEqual(report); + }); +}); + +describe("crossModuleShare: how often a commit crosses a top-level directory of the model", () => { + /** + * The model's files share `com/x`; below it: `order`, `stock`, and App.java + * in the directory itself. Six commits: + * + * Order + Pricing one directory + * Order + Stock CROSSES + * README touches no file of the model: not counted + * App + Bin + README CROSSES (the root directory counts as one) + * Stock one directory + * Order + Pricing + Stock + Bin sweeping at a limit of 3: skipped + */ + const changesets = [ + [HIST.order, HIST.pricing], + [HIST.order, HIST.stock], + ["README.md"], + [HIST.app, HIST.bin, "README.md"], + [HIST.stock], + [HIST.order, HIST.pricing, HIST.stock, HIST.bin], + ]; + + it("counts by hand: 2 of 4", () => { + expect(crossModuleShare(changesets, join, { maxChangesetSize: 3 })).toEqual({ + root: "com/x", + modules: [".", "order", "stock"], + commits: 4, + crossing: 2, + share: 0.5, + skipped: 1, + }); + }); + + it("counts the sweeping commit when the limit lets it through", () => { + expect(crossModuleShare(changesets, join)).toMatchObject({ commits: 5, crossing: 3, skipped: 0 }); + }); + + it("answers 0, not NaN, when no commit touches the model", () => { + expect(crossModuleShare([["README.md"]], join)).toMatchObject({ commits: 0, crossing: 0, share: 0 }); + }); + + it("has one module and nothing to cross when the model is one directory", () => { + const flat = joinOnPaths(["a/A.java", "a/B.java"], ["src/a/A.java", "src/a/B.java"]); + expect(crossModuleShare([["src/a/A.java", "src/a/B.java"]], flat)).toEqual({ + root: "a", + modules: ["."], + commits: 1, + crossing: 0, + share: 0, + skipped: 0, + }); + }); +}); diff --git a/packages/analyzer/test/public-api.test.ts b/packages/analyzer/test/public-api.test.ts index 883d0c97..6bf394cc 100644 --- a/packages/analyzer/test/public-api.test.ts +++ b/packages/analyzer/test/public-api.test.ts @@ -82,6 +82,17 @@ const PUBLIC_API = { "statementShape", "queryStore", ], + // The cross-graph queries: the declared graph joined with mined history, on + // paths. The CLI's `history` reports call each of them. + evolution: [ + "joinOnPaths", + "fileDependencies", + "hiddenCoupling", + "deadWeight", + "fileMeasures", + "joinedHotspots", + "crossModuleShare", + ], } as const; /** Non-function exports that are part of the contract too. */ @@ -105,6 +116,8 @@ const PUBLIC_VALUES = [ "DEP_VIEW_SQL", "HELPER_VIEWS_SQL", "QUERY_STATEMENT_KEYWORDS", + "HOTSPOT_FAMILIES", + "DEFAULT_HOTSPOT_FAMILY", ] as const; const SRC = fileURLToPath(new URL("../src", import.meta.url)); diff --git a/packages/cli/src/args.ts b/packages/cli/src/args.ts index 47f599be..f62a8bf2 100644 --- a/packages/cli/src/args.ts +++ b/packages/cli/src/args.ts @@ -1,7 +1,16 @@ import { accessSync, constants } from "node:fs"; import { basename, resolve } from "node:path"; import { parseArgs } from "node:util"; -import { FOLD_LEVELS, FRAMEWORK_PROFILES, SelectorError, parseTerm, type FoldLevel, type Selector } from "@codegraph/analyzer"; +import { + FOLD_LEVELS, + FRAMEWORK_PROFILES, + HOTSPOT_FAMILIES, + SelectorError, + parseTerm, + type FoldLevel, + type HotspotFamily, + type Selector, +} from "@codegraph/analyzer"; import { CLOSURES, EXPLAIN_WALK_NAME, WALK_NAME_PATTERN, type Closure } from "@codegraph/insights"; import { METRIC_PREFIXES, SCALES, metricNames } from "@codegraph/city"; import { SCOPE_LEVELS, TERM_CLASSES, WEIGHT_KEYS, type ScopeLevel, type TermClass, type WeightKey } from "@codegraph/vocabulary"; @@ -54,7 +63,9 @@ export type FormatName = (typeof FORMATS)[number]; /** * `history --report` values. The last two are the CROSS-GRAPH reports (M9b): - * they join the mined history with a model, so they read `--model` too. + * they join the mined history with a model, so they read `--model` too. Since + * M23b `hotspots` and `summary` join one WHEN `--model` is given, and are the + * history's own reports when it is not. */ export const HISTORY_REPORTS = [ "summary", @@ -1325,10 +1336,21 @@ export const HISTORY_SPEC: CommandSpec = { name: "model", type: "string", describe: - "Model for the cross-graph reports (hidden, deadweight); " + - "defaults to this directory's default model.", + "A model to join on file paths. hidden and deadweight need one (default: this " + + "directory's default model). Given to hotspots, each file gains its lines, its " + + "cyclomatic complexity, its dependency cycle and its rank in four families; given " + + "to summary, the share of commits that cross a top-level directory of the model.", placeholder: "FILE", }, + { + name: "rank", + type: "string", + describe: + "hotspots with --model: the family the rows are ordered by — classic (revisions x " + + "lines), branchy (revisions x cyclomatic; the default), tangled (revisions of a file " + + "in a dependency cycle), fragile (revisions x fix density).", + choices: HOTSPOT_FAMILIES, + }, { name: "min-support", type: "string", @@ -1762,6 +1784,8 @@ export interface HistoryOptions { readonly top: number | undefined; /** `--model FILE` for the cross-graph reports; undefined means the default model. */ readonly model: string | undefined; + /** `--rank FAMILY`: the order of the joined hotspot report; undefined is its default. */ + readonly rank: HotspotFamily | undefined; /** Coupling thresholds; the specs' defaults unless overridden. */ readonly minSupport: number; readonly minConfidence: number; @@ -2488,15 +2512,30 @@ export function parseInvocation(argv: readonly string[]): Invocation { }, }; } - case "history": + case "history": { + const report = (stringOf(values, "report") ?? DEFAULT_HISTORY_REPORT) as HistoryReportName; + const rank = stringOf(values, "rank") as HotspotFamily | undefined; + if (rank !== undefined && report !== "hotspots") { + throw new UsageError( + `--rank orders the joined hotspot report, not ${report}`, + "Use it with --report hotspots --model FILE.", + ); + } + if (rank !== undefined && stringOf(values, "model") === undefined) { + throw new UsageError( + "--rank needs a model to rank by", + "Name it: --report hotspots --model FILE --rank " + rank, + ); + } return { kind: "run", command: "history", options: { history: models[0] as string, - report: (stringOf(values, "report") ?? DEFAULT_HISTORY_REPORT) as HistoryReportName, + report, top: integerOf(values, "top"), model: stringOf(values, "model"), + rank, minSupport: integerOf(values, "min-support") ?? 3, minConfidence: (integerOf(values, "min-confidence") ?? 50) / 100, serve: flagOf(values, "serve"), @@ -2506,6 +2545,7 @@ export function parseInvocation(argv: readonly string[]): Invocation { json: flagOf(values, "json"), }, }; + } case "query": return { kind: "run", command: "query", options: queryOf(values, spec, models) }; case "timeline": diff --git a/packages/cli/src/commands/history.ts b/packages/cli/src/commands/history.ts index e24a1d65..dcf0678e 100644 --- a/packages/cli/src/commands/history.ts +++ b/packages/cli/src/commands/history.ts @@ -1,17 +1,25 @@ import { readFileSync } from "node:fs"; import { Buffer } from "node:buffer"; import { + HOTSPOT_FAMILIES, buildGraph, + crossModuleShare, deadWeight, fileDependencies, + fileMeasures, hiddenCoupling, joinOnPaths, + joinedHotspots, + type CodeGraph, + type CrossModuleShare, type DeadWeightReport, type FileJoin, type HiddenCouplingReport, + type JoinedHotspotReport, } from "@codegraph/analyzer"; import { buildFileCity, cityToJsonString, layoutFileCity } from "@codegraph/city"; import { + COUPLING_DEFAULTS, HistoryError, authorStats, decodeHistoryText, @@ -39,6 +47,12 @@ import { startCityServer, vizAssets, type CityServerOptions } from "../serve.js" * exercised. The join itself lives in the analyzer; this command only feeds * both sides in. * + * `hotspots` and `summary` join a model ONLY WHEN `--model` NAMES ONE (M23b): + * they are the history's own reports otherwise, and a `model.jsonl` that + * happens to sit in the directory must not change what they print. Joined, + * `hotspots` is effort times complexity in four families, and `summary` gains + * the share of commits that cross a top-level directory of the model. + * * `--serve` hosts the FILE-LEVEL REPLAY: the history becomes a laid-out city * artifact (buildings = file lineages, districts = directories) with a * `replay` block — commits as ticks, heights as keyframe series — and the @@ -110,13 +124,49 @@ export function historyCommand( return EXIT.OK; } + try { + return printReport(history, options, io); + } catch (error) { + if (error instanceof NotAModel) return EXIT.FINDINGS; + throw error; + } +} + +function printReport(history: History, options: HistoryOptions, io: IoSink): ExitCode { switch (options.report) { - case "summary": - outLines(io, options.json ? [jsonOf("summary", summarize(history))] : summaryText(history)); + case "summary": { + const crossing = options.model === undefined ? undefined : crossModule(history, options, io); + outLines( + io, + options.json + ? [jsonOf("summary", { ...summarize(history), ...(crossing === undefined ? {} : { crossModule: crossing }) })] + : [...summaryText(history), ...(crossing === undefined ? [] : [crossModuleLine(crossing)])], + ); return EXIT.OK; + } case "hotspots": { const top = options.top ?? 20; const rows = hotspots(history); + if (options.model !== undefined) { + const { graph, deps, join } = crossGraph(history, options, io); + const report = joinedHotspots(withOwners(history, rows), fileMeasures(graph, deps), join, { rank: options.rank }); + reportUnjoined(report, rows.length, io); + outLines( + io, + options.json + ? [ + jsonOf("hotspots", { + rank: report.rank, + total: report.rows.length, + outsideModel: report.outsideModel, + outsideHistory: report.outsideHistory, + rows: report.rows.slice(0, top), + }), + ] + : joinedHotspotsText(history, report, top), + ); + return EXIT.OK; + } outLines( io, options.json @@ -192,12 +242,19 @@ export function historyCommand( } } -/** Load the model side and join it, once, for either cross-graph report. */ +/** + * The `--model` was readable and is not a model. Thrown, not returned, so no + * report can be computed over the empty union such a file loads as: "none — + * every co-changed pair is explained" would then be said of nothing at all. + */ +class NotAModel extends Error {} + +/** Load the model side and join it, once, for any report that reads both graphs. */ function crossGraph( history: History, options: HistoryOptions, io: IoSink, -): { deps: ReturnType; join: FileJoin } { +): { graph: CodeGraph; deps: ReturnType; join: FileJoin } { const modelPath = options.model ?? defaultModelPath(); let loaded: ReturnType; try { @@ -209,10 +266,17 @@ function crossGraph( { cause: error }, ); } + const unreadable = loaded.diagnostics.schemaErrors[0]; + if (unreadable !== undefined) { + errLine(io, `${modelPath} is not a model: ${unreadable.message}`); + errLine(io, `Run 'codegraph validate ${modelPath}' for every finding.`); + throw new NotAModel(modelPath); + } if (!loaded.clean) { errLine(io, `warning: ${modelPath} has findings; the join was computed anyway.`); } - const deps = fileDependencies(buildGraph(loaded.union)); + const graph = buildGraph(loaded.union); + const deps = fileDependencies(graph); const join = joinOnPaths(deps.files, history.paths); if (join.ambiguous.length > 0) { errLine( @@ -220,7 +284,94 @@ function crossGraph( `note: ${join.ambiguous.length} paths joined ambiguously and were left out of the join.`, ); } - return { deps, join }; + return { graph, deps, join }; +} + +/** + * The share of commits crossing a top-level directory of the model. Sweeping + * commits are left out by the limit `coupling` uses, and for its reason: a + * reformat touches every directory and says nothing about the cut. + */ +function crossModule(history: History, options: HistoryOptions, io: IoSink): CrossModuleShare { + const { join } = crossGraph(history, options, io); + const changesets: string[][] = history.commits.map(() => []); + for (const change of history.changes) { + const path = history.paths[change.path]; + if (path !== undefined) changesets[change.commit]?.push(path); + } + const share = crossModuleShare(changesets, join, { maxChangesetSize: COUPLING_DEFAULTS.maxChangesetSize }); + if (share.skipped > 0) { + errLine( + io, + `note: ${share.skipped} sweeping commits left out of the cross-module share ` + + `(changesets over ${COUPLING_DEFAULTS.maxChangesetSize} files cross everything).`, + ); + } + return share; +} + +function crossModuleLine(share: CrossModuleShare): string { + const where = `${share.modules.length} ${share.root === "" ? "at its root" : `under ${share.root}`}`; + return ( + ` cross-module: ${share.crossing} of ${share.commits} commits touching the model ` + + `cross its top-level directories (${percent(share.share)}; ${where})` + ); +} + +type OwnedHotspot = ReturnType[number] & { + /** The owner's share of the lines added to the file; `null` when nobody added any. */ + readonly ownerShare: number | null; + /** The day of that owner's last commit ANYWHERE in the history. */ + readonly ownerLastSeen: string | null; + /** That owner's row in `--report authors`, from 1: two files with one rank have one owner. */ + readonly ownerRank: number | null; +}; + +/** + * Ownership WITHOUT A NAME. The walk asks "is whoever wrote most of this still + * around?" and "do the hotspots have one owner?", and its report may be handed + * to someone else: a share, a date and a ROW NUMBER answer both without + * putting a person in it. The row is the owner's in `--report authors`, which + * is where the name is. Same owner rule as that report and the bus factor. + */ +function withOwners(history: History, rows: ReturnType): OwnedHotspot[] { + const owners = fileOwners(history); + const lastSeen = new Map(); + for (const commit of history.commits) { + const author = history.authors[commit.author]; + if (author !== undefined) lastSeen.set(author, Math.max(lastSeen.get(author) ?? 0, commit.time)); + } + const rank = new Map(authorStats(history).rows.map((author, index) => [author.author, index + 1])); + return rows.map((row) => { + const owner = owners.get(row.path); + const seen = owner === undefined ? undefined : lastSeen.get(owner.name); + return { + ...row, + ownerShare: owner?.share ?? null, + ownerLastSeen: seen === undefined ? null : day(seen), + ownerRank: owner === undefined ? null : (rank.get(owner.name) ?? null), + }; + }); +} + +/** What the join left out, on stderr: a low joined count means the model came from elsewhere. */ +function reportUnjoined(report: JoinedHotspotReport, historyFiles: number, io: IoSink): void { + const plural = (count: number, one: string, many: string): string => (count === 1 ? one : many); + if (report.outsideModel > 0) { + errLine( + io, + `note: ${report.outsideModel} of ${historyFiles} history files ` + + `${plural(report.outsideModel, "has", "have")} no counterpart in the model ` + + `(docs, build files, deleted files, anything outside the extracted root).`, + ); + } + if (report.outsideHistory > 0) { + errLine( + io, + `note: ${report.outsideHistory} model ${plural(report.outsideHistory, "file was", "files were")} ` + + `touched by no mined commit.`, + ); + } } function reportSkipped(report: CoChangeReport, io: IoSink): void { @@ -305,6 +456,53 @@ function hotspotsText( return lines; } +/** `-` for what was not measured or not ranked: absent is not zero. */ +const cell = (value: number | null): string => (value === null ? "-" : String(value)); + +function joinedHotspotsText( + history: History, + report: JoinedHotspotReport, + top: number, +): readonly string[] { + const shown = report.rows.slice(0, top); + const lines = [ + `hotspots of ${history.repo}, joined with the model ` + + `(top ${shown.length} of ${report.rows.length} files, by ${report.rank} rank):`, + ]; + if (report.rows.length === 0) { + lines.push(" none — no history file matches a file of the model. Was it extracted inside this clone?"); + return lines; + } + lines.push( + ...table( + [ + "REVISIONS", "SLOC", "CYCLOMATIC", "CYCLE", "FIXES", "DENSITY", "AUTHORS", "OWNER", + ...HOTSPOT_FAMILIES.map((family) => family.toUpperCase()), + "PATH", + ], + shown.map((row) => [ + String(row.revisions), + cell(row.sloc), + cell(row.cyclomatic), + String(row.cycle), + String(row.fixes), + row.bugDensity.toFixed(2), + String(row.authors), + row.ownerShare === null ? "-" : `${Math.round(row.ownerShare * 100)}% #${row.ownerRank ?? "?"}`, + ...HOTSPOT_FAMILIES.map((family) => cell(row.ranks[family])), + row.path, + ]), + ), + ); + lines.push( + "ranks: classic = revisions x sloc, branchy = revisions x cyclomatic, " + + "tangled = revisions of a file in a dependency cycle (CYCLE = its files), " + + "fragile = revisions x density = fixes; - = not ranked. " + + "OWNER = the share of the file's added lines its main author wrote, and that author's row in --report authors.", + ); + return lines; +} + function authorsText( history: History, rows: ReturnType["rows"], diff --git a/packages/cli/test/history-joined.test.ts b/packages/cli/test/history-joined.test.ts new file mode 100644 index 00000000..92858f68 --- /dev/null +++ b/packages/cli/test/history-joined.test.ts @@ -0,0 +1,380 @@ +import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterAll, describe, expect, it } from "vitest"; +import { encodeModelToString, renderId, type Edge, type Entity, type Model } from "@codegraph/core"; +import { HOTSPOT_FAMILIES } from "@codegraph/analyzer"; +import { HISTORY_SCHEMA_VERSION, encodeHistoryToString, type History } from "@codegraph/scm"; + +import { HISTORY_SPEC } from "../src/args.js"; +import { EXIT } from "../src/exit.js"; +import { captureIo, type CapturedIo } from "../src/io.js"; +import { runSync } from "../src/main.js"; + +/** + * `history --report hotspots --model FILE` and `history --report summary + * --model FILE` (M23b, PLAN §24.5): the join the discovery walk's third step + * asked a spreadsheet for. End to end, on one hand-counted story. + * + * The model, extracted from `src/`: + * + * com/x/order/Order.java 40 lines · cyclomatic 6 + 2 (a lambda) + 1 = 9 + * com/x/order/Pricing.java 20 lines · cyclomatic 9 + * com/x/stock/Stock.java 30 lines · cyclomatic 4 + * com/x/App.java 5 lines · cyclomatic 1 + * gen/Dto.java measured by nothing, touched by no commit + * declared: Order <-> Pricing (a cycle) Order -> Stock App -> Order + * + * The history, eight commits: + * + * c0 FIX Order Pricing c4 Stock App + * c1 Order Stock c5 README + * c2 FIX Order c6 Stock + * c3 FIX Pricing c7 Order Pricing + * + * revisions fixes classic branchy tangled fragile + * Order 4 2 160 #1 36 #1 4 #1 2 #1 + * Pricing 3 2 60 #3 27 #2 3 #2 2 #2 + * Stock 3 0 90 #2 12 #3 - - + * App 1 0 5 #4 1 #4 - - + * + * Seven commits touch the model; c1 (order + stock) and c4 (stock + the root) + * cross a top-level directory: 2 of 7. + * + * Every change adds 2 lines. Alice makes c0..c6, one a day from 1970-01-01; + * Bob makes c7. So Alice wrote 6 of Order's 8 added lines (75%) and 4 of + * Pricing's 6 (67%), all of Stock's and App's, and was last seen on 01-07. + */ + +const scratch = mkdtempSync(join(tmpdir(), "codegraph-cli-joined-")); +afterAll(() => rmSync(scratch, { recursive: true, force: true })); + +const MODEL_FILE = { + order: "com/x/order/Order.java", + pricing: "com/x/order/Pricing.java", + stock: "com/x/stock/Stock.java", + app: "com/x/App.java", + dto: "gen/Dto.java", +} as const; +const HIST = { + order: `src/${MODEL_FILE.order}`, + pricing: `src/${MODEL_FILE.pricing}`, + stock: `src/${MODEL_FILE.stock}`, + app: `src/${MODEL_FILE.app}`, + readme: "README.md", +} as const; + +function historyFile(): string { + const paths: string[] = Object.values(HIST).slice().sort(); + const commits: { files: string[]; fix: boolean }[] = [ + { files: [HIST.order, HIST.pricing], fix: true }, + { files: [HIST.order, HIST.stock], fix: false }, + { files: [HIST.order], fix: true }, + { files: [HIST.pricing], fix: true }, + { files: [HIST.stock, HIST.app], fix: false }, + { files: [HIST.readme], fix: false }, + { files: [HIST.stock], fix: false }, + { files: [HIST.order, HIST.pricing], fix: false }, + ]; + const history: History = { + schemaVersion: HISTORY_SCHEMA_VERSION, + scm: "git", + miner: "codegraph-scm@test", + repo: "demo", + authors: ["Alice ", "Bob "], + paths, + commits: commits.map((commit, index) => ({ + hash: index.toString(16).padStart(40, "0"), + // Bob makes the last commit; Alice's last one is c6, on the seventh day. + author: index === 7 ? 1 : 0, + time: index * 86_400, + isFix: commit.fix, + isRevert: false, + })), + changes: commits.flatMap((commit, index) => + commit.files + .map((file) => paths.indexOf(file)) + .sort((x, y) => x - y) + .map((path) => ({ commit: index, path, added: 2, deleted: 1 })), + ), + }; + const path = join(scratch, "demo-history.jsonl"); + writeFileSync(path, encodeHistoryToString(history), "utf8"); + return path; +} + +const id = (module: string, symbol: string): string => renderId({ lang: "java", module, symbol }); + +function modelFile(): string { + const pkg = (module: string): Entity => + ({ id: id(module, ""), kind: "package", traits: ["TNamed", "TModule", "TWithChildren"], name: module, definedIn: [], isStub: false }) as unknown as Entity; + const type = (module: string, name: string, file: string, sloc?: number): Entity => + ({ + id: id(module, name), + kind: "class", + traits: [ + "TNamed", "TType", "TWithInheritances", "TWithImplements", "TWithChildren", "TChildOf", "TSourceAnchor", + ...(sloc === undefined ? [] : ["TMetrics"]), + ], + name, + isStub: false, + parent: id(module, ""), + anchor: { file, span: [1, 40] }, + ...(sloc === undefined ? {} : { metrics: { sloc } }), + }) as unknown as Entity; + const method = (module: string, symbol: string, parent: string, file: string, cyclomatic: number, kind = "method"): Entity => + ({ + id: id(module, symbol), + kind, + traits: ["TNamed", "TInvocable", "TChildOf", "TSourceAnchor", "TMetrics"], + name: symbol, + signature: "()", + isStub: false, + parent: id(module, parent), + anchor: { file, span: [2, 4] }, + metrics: { cyclomatic, sloc: 3 }, + }) as unknown as Entity; + const edge = (from: string, to: string, file: string): Edge => + ({ edge: "reference", from, to, provenance: "declared", anchor: { file, span: [3, 3] } }) as unknown as Edge; + + const model = { + schemaVersion: "1.0.0", + lang: "java", + extractor: { name: "test", version: "0" }, + root: "demo/src", + entities: [ + pkg("com.x"), + pkg("com.x.order"), + pkg("com.x.stock"), + pkg("gen"), + type("com.x.order", "Order", MODEL_FILE.order, 40), + method("com.x.order", "Order.place()", "Order", MODEL_FILE.order, 6), + method("com.x.order", "Order.place().lambda", "Order.place()", MODEL_FILE.order, 2, "lambda"), + method("com.x.order", "Order.total()", "Order", MODEL_FILE.order, 1), + type("com.x.order", "Pricing", MODEL_FILE.pricing, 20), + method("com.x.order", "Pricing.price()", "Pricing", MODEL_FILE.pricing, 9), + type("com.x.stock", "Stock", MODEL_FILE.stock, 30), + method("com.x.stock", "Stock.reserve()", "Stock", MODEL_FILE.stock, 4), + type("com.x", "App", MODEL_FILE.app, 5), + method("com.x", "App.main()", "App", MODEL_FILE.app, 1), + type("gen", "Dto", MODEL_FILE.dto), + ], + edges: [ + edge(id("com.x.order", "Order.place()"), id("com.x.order", "Pricing"), MODEL_FILE.order), + edge(id("com.x.order", "Pricing.price()"), id("com.x.order", "Order"), MODEL_FILE.pricing), + edge(id("com.x.order", "Order"), id("com.x.stock", "Stock"), MODEL_FILE.order), + edge(id("com.x", "App.main()"), id("com.x.order", "Order"), MODEL_FILE.app), + ], + } as unknown as Model; + const path = join(scratch, "demo-model.jsonl"); + writeFileSync(path, encodeModelToString(model), "utf8"); + return path; +} + +const HISTORY_PATH = historyFile(); +const MODEL_PATH = modelFile(); + +function invoke(argv: readonly string[]): { io: CapturedIo; code: number } { + const io = captureIo(); + const code = runSync(argv, io); + return { io, code }; +} + +interface JoinedRow { + path: string; + model: string; + revisions: number; + fixes: number; + bugDensity: number; + sloc: number | null; + cyclomatic: number | null; + cycle: number; + scores: Record; + ranks: Record; +} +interface JoinedJson { + report: string; + rank: string; + total: number; + outsideModel: number; + outsideHistory: number; + rows: JoinedRow[]; +} + +describe("history --report hotspots --model: the joined report", () => { + const joined = (extra: readonly string[] = []): { io: CapturedIo; code: number; json: JoinedJson } => { + const result = invoke(["history", HISTORY_PATH, "--report", "hotspots", "--model", MODEL_PATH, "--json", ...extra]); + return { ...result, json: JSON.parse(result.io.stdout()) as JoinedJson }; + }; + + it("ranks the four joined files, branchy first, and says what did not join", () => { + const { code, json, io } = joined(); + expect(code).toBe(EXIT.OK); + expect(json).toMatchObject({ report: "hotspots", rank: "branchy", total: 4, outsideModel: 1, outsideHistory: 1 }); + expect(json.rows.map((row) => row.path)).toEqual([HIST.order, HIST.pricing, HIST.stock, HIST.app]); + expect(io.stderr()).toContain("1 of 5 history files has no counterpart in the model"); + expect(io.stderr()).toContain("1 model file was touched by no mined commit"); + }); + + it("counts Order by hand: both sides, the four scores, the four ranks", () => { + expect(joined().json.rows[0]).toEqual({ + path: HIST.order, + model: MODEL_FILE.order, + revisions: 4, + added: 8, + deleted: 4, + churn: 12, + fixes: 2, + bugDensity: 0.5, + authors: 2, + ownerShare: 0.75, + ownerLastSeen: "1970-01-07", + ownerRank: 1, + sloc: 40, + cyclomatic: 9, + cycle: 2, + scores: { classic: 160, branchy: 36, tangled: 4, fragile: 2 }, + ranks: { classic: 1, branchy: 1, tangled: 1, fragile: 1 }, + }); + }); + + it("ranks each family on its own: Stock is second by size, third by branching, absent from the last two", () => { + const stock = joined().json.rows.find((row) => row.path === HIST.stock)!; + expect(stock.scores).toEqual({ classic: 90, branchy: 12, tangled: 0, fragile: 0 }); + expect(stock.ranks).toEqual({ classic: 2, branchy: 3, tangled: null, fragile: null }); + }); + + it.each([ + ["classic", [HIST.order, HIST.stock, HIST.pricing, HIST.app]], + ["branchy", [HIST.order, HIST.pricing, HIST.stock, HIST.app]], + ["tangled", [HIST.order, HIST.pricing, HIST.stock, HIST.app]], + ["fragile", [HIST.order, HIST.pricing, HIST.stock, HIST.app]], + ] as const)("--rank %s orders the rows by that family", (rank, order) => { + const { json } = joined(["--rank", rank]); + expect(json.rank).toBe(rank); + expect(json.rows.map((row) => row.path)).toEqual(order); + }); + + it("says who holds each file as a share and a date, never as a name", () => { + const { io, json } = joined(); + expect(json.rows.map((row) => [(row as unknown as { ownerShare: number }).ownerShare, (row as unknown as { ownerLastSeen: string }).ownerLastSeen])).toEqual([ + [0.75, "1970-01-07"], + [4 / 6, "1970-01-07"], + [1, "1970-01-07"], + [1, "1970-01-07"], + ]); + // Alice has 7 commits, Bob 1: she is row 1 of `--report authors`, and every file here is hers. + expect(json.rows.map((row) => (row as unknown as { ownerRank: number }).ownerRank)).toEqual([1, 1, 1, 1]); + const authors = JSON.parse(invoke(["history", HISTORY_PATH, "--report", "authors", "--json"]).io.stdout()) as { rows: { author: string }[] }; + expect(authors.rows[0]!.author).toBe("Alice "); + const text = invoke(["history", HISTORY_PATH, "--report", "hotspots", "--model", MODEL_PATH]).io; + for (const out of [io.stdout(), io.stderr(), text.stdout(), text.stderr()]) { + expect(out).not.toContain("Alice"); + expect(out).not.toContain("Bob"); + } + }); + + it("--top cuts the rows and keeps the total and every rank", () => { + const { json } = joined(["--rank", "classic", "--top", "2"]); + expect(json.total).toBe(4); + expect(json.rows.map((row) => [row.path, row.ranks["classic"]])).toEqual([ + [HIST.order, 1], + [HIST.stock, 2], + ]); + }); + + it("prints a table a person can read, the ranks as columns and a legend under it", () => { + const { io, code } = invoke(["history", HISTORY_PATH, "--report", "hotspots", "--model", MODEL_PATH]); + expect(code).toBe(EXIT.OK); + expect(io.stdout().split("\n").filter((line) => line !== "")).toEqual([ + "hotspots of demo, joined with the model (top 4 of 4 files, by branchy rank):", + " REVISIONS SLOC CYCLOMATIC CYCLE FIXES DENSITY AUTHORS OWNER CLASSIC BRANCHY TANGLED FRAGILE PATH", + " 4 40 9 2 2 0.50 2 75% #1 1 1 1 1 src/com/x/order/Order.java", + " 3 20 9 2 2 0.67 2 67% #1 3 2 2 2 src/com/x/order/Pricing.java", + " 3 30 4 0 0 0.00 1 100% #1 2 3 - - src/com/x/stock/Stock.java", + " 1 5 1 0 0 0.00 1 100% #1 4 4 - - src/com/x/App.java", + "ranks: classic = revisions x sloc, branchy = revisions x cyclomatic, tangled = revisions of a file in a dependency cycle (CYCLE = its files), fragile = revisions x density = fixes; - = not ranked. OWNER = the share of the file's added lines its main author wrote, and that author's row in --report authors.", + ]); + }); + + it("without --model it is the history's own report, unchanged", () => { + const { io, code } = invoke(["history", HISTORY_PATH, "--report", "hotspots", "--json"]); + expect(code).toBe(EXIT.OK); + const parsed = JSON.parse(io.stdout()) as { total: number; rank?: string; rows: Record[] }; + expect(parsed.total).toBe(5); + expect(parsed.rank).toBeUndefined(); + expect(parsed.rows[0]).toEqual({ path: HIST.order, revisions: 4, added: 8, deleted: 4, churn: 12, fixes: 2, bugDensity: 0.5, authors: 2 }); + }); + + it("refuses --rank where there is nothing to rank by", () => { + const noModel = invoke(["history", HISTORY_PATH, "--report", "hotspots", "--rank", "classic"]); + expect(noModel.code).toBe(EXIT.USAGE); + expect(noModel.io.stderr()).toContain("--model"); + const otherReport = invoke(["history", HISTORY_PATH, "--report", "authors", "--model", MODEL_PATH, "--rank", "classic"]); + expect(otherReport.code).toBe(EXIT.USAGE); + expect(otherReport.io.stderr()).toContain("--report hotspots"); + const unknown = invoke(["history", HISTORY_PATH, "--report", "hotspots", "--model", MODEL_PATH, "--rank", "biggest"]); + expect(unknown.code).toBe(EXIT.USAGE); + }); + + it("a model that cannot be read is a usage error naming --model", () => { + const { io, code } = invoke(["history", HISTORY_PATH, "--report", "hotspots", "--model", join(scratch, "nowhere.jsonl")]); + expect(code).toBe(EXIT.USAGE); + expect(io.stderr()).toContain("--model"); + expect(io.stdout()).toBe(""); + }); + + it("offers the analyzer's four families, and no other, as --rank", () => { + const rank = HISTORY_SPEC.options.find((option) => option.name === "rank"); + expect(rank?.choices).toEqual(HOTSPOT_FAMILIES); + }); +}); + +describe("a --model that is not a model", () => { + /** + * Found while writing this file: a model with one invalid line loaded as an + * EMPTY union, the join matched nothing, and `hidden` printed "none — every + * co-changed pair is explained by a declared dependency path". A report over + * nothing is not a report: the file is the finding, as for every model command. + */ + const broken = join(scratch, "broken-model.jsonl"); + writeFileSync(broken, '{"t":"header","schemaVersion":"1.0.0"}\n', "utf8"); + + it.each(["hotspots", "summary", "hidden", "deadweight"])("%s: exit 3, the reason on stderr, nothing on stdout", (report) => { + const { io, code } = invoke(["history", HISTORY_PATH, "--report", report, "--model", broken]); + expect(code).toBe(EXIT.FINDINGS); + expect(io.stdout()).toBe(""); + expect(io.stderr()).toContain("is not a model"); + expect(io.stderr()).toContain("codegraph validate"); + }); +}); + +describe("history --report summary --model: how often a commit crosses a module", () => { + it("counts by hand: 2 of the 7 commits that touch the model", () => { + const { io, code } = invoke(["history", HISTORY_PATH, "--report", "summary", "--model", MODEL_PATH, "--json"]); + expect(code).toBe(EXIT.OK); + const parsed = JSON.parse(io.stdout()) as { commits: number; crossModule: Record }; + expect(parsed.commits).toBe(8); + expect(parsed.crossModule).toEqual({ + root: "com/x", + modules: [".", "order", "stock"], + commits: 7, + crossing: 2, + share: 2 / 7, + skipped: 0, + }); + }); + + it("adds one line to the text, after the history's own", () => { + const { io } = invoke(["history", HISTORY_PATH, "--report", "summary", "--model", MODEL_PATH]); + const lines = io.stdout().split("\n").filter((line) => line !== ""); + expect(lines[0]).toBe("history of demo: 8 commits by 2 authors over 5 files"); + expect(lines.at(-1)).toBe(" cross-module: 2 of 7 commits touching the model cross its top-level directories (28.6%; 3 under com/x)"); + }); + + it("says nothing of modules without a model", () => { + const { io } = invoke(["history", HISTORY_PATH, "--report", "summary", "--json"]); + expect(JSON.parse(io.stdout())).not.toHaveProperty("crossModule"); + expect(invoke(["history", HISTORY_PATH, "--report", "summary"]).io.stdout()).not.toContain("cross-module"); + }); +}); diff --git a/packages/cli/test/scm.test.ts b/packages/cli/test/scm.test.ts index dbd15553..da614ff0 100644 --- a/packages/cli/test/scm.test.ts +++ b/packages/cli/test/scm.test.ts @@ -269,6 +269,7 @@ describe("codegraph history reports hand-counted numbers", () => { report: "summary", top: undefined, model: undefined, + rank: undefined, minSupport: 3, minConfidence: 0.5, serve: true, From 3e8ca29d223c7c31d6341c38941bffda37da1bc3 Mon Sep 17 00:00:00 2001 From: Jeremie Grodziski Date: Mon, 23 Nov 2026 10:16:20 +0000 Subject: [PATCH 04/16] docs: document query and the discovery steps docs/cli.md and the website's CLI reference gain query and the joined history reports. The discovery pages run their SQL as written, which they did not: a view rendered a wrong id for an anonymous TypeScript function, three queries named Java's kinds and found nothing elsewhere, a sum counted a nested type twice, and printed tables were not their query's rows. Step 3 loses its sqlite3-to-spreadsheet recipe for two commands. Step 4 is rewritten around an inventory of entry points from a table of names, the chain behind each on facts and with candidates, and what nothing reaches. A test holds the three docs copies of the helper views equal to the analyzer's definition. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01PKCVh2essA8PpHntfjvJtH --- docs/cli.md | 80 ++ docs/sql-cookbook.md | 3 +- packages/cli/test/helper-views-docs.test.ts | 86 ++ website/content/docs/discover/_index.md | 9 +- website/content/docs/discover/activity.md | 122 ++- website/content/docs/discover/boundaries.md | 109 ++- website/content/docs/discover/stimuli.md | 860 +++++++++++++++--- website/content/docs/discover/structure.md | 179 ++-- website/content/docs/how-to/history-joins.md | 28 +- website/content/docs/how-to/query-model-db.md | 3 +- website/content/docs/reference/cli/_index.md | 1 + website/content/docs/reference/cli/history.md | 35 +- website/content/docs/reference/cli/query.md | 109 +++ website/content/docs/tutorials/sql.md | 2 +- 14 files changed, 1370 insertions(+), 256 deletions(-) create mode 100644 packages/cli/test/helper-views-docs.test.ts create mode 100644 website/content/docs/reference/cli/query.md diff --git a/docs/cli.md b/docs/cli.md index 615bd820..1b612382 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -46,6 +46,12 @@ codegraph import model.jsonl [--out FILE] [--at SHA [--time T]] [--json] # build the SQLite analysis store (model.db) beside a model; # --at appends the model as a snapshot of the TEMPORAL store +codegraph query model.jsonl ["SELECT …"] [--file FILE] [--param NAME=VALUE]… [--param-file NAME=FILE]… + [--limit N | --all] [--json | --csv] + # ONE read-only SQL statement over the store, with the node + # and dep views; no sqlite3 needed +codegraph query --views # the SQL of the two views, for another client + codegraph serve [model.jsonl] [--port N] [--host ADDR] [--name STR] [--height METRIC] [--height-scale linear|sqrt|log] [--footprint METRIC] [--footprint-scale linear|sqrt|log] @@ -112,6 +118,7 @@ codegraph snapshots [repo] --jar FILE (--every N | --tags) codegraph history [history.jsonl] [--top N] [--json] [--report summary|hotspots|authors|coupling|hidden|deadweight] [--min-support N] [--min-confidence PCT] [--model FILE] + [--rank classic|branchy|tangled|fragile] [--serve [--port N] [--host ADDR]] [--city FILE] codegraph timeline java:com.acme/Basket [--store FILE] [--json] @@ -157,6 +164,51 @@ skip parsing and lets you query the graph yourself snapshot: revisions accumulate in one store, keyed by the natural key across time, and `timeline` and `replay` read them. +### `query` +Runs one SQL statement over a model's store and prints its rows — the SQLite +that builds the store is in the binary, so no `sqlite3` is needed +([SQL cookbook](sql-cookbook.md) for the schema and the recipes). The model +comes first and is required; the statement follows it, quoted, or comes from +`--file`. A `model.db` is accepted in place of the model. The two helper +views, `node` (one row per entity, with the rendered id every report prints) +and `dep` (one row per edge, its names resolved), are created for every run; +`query --views` prints their SQL for another client. + +```bash +codegraph query app.jsonl "SELECT kind, count(*) AS n FROM node GROUP BY kind ORDER BY n DESC" +codegraph query app.jsonl --file reach.sql --param id='java:com.acme.order/Order.discount(int)' --json +``` + +**It never writes**, and that is held twice: the store is opened read-only, +and the text must be ONE statement beginning with `SELECT`, `WITH`, `VALUES` +or `EXPLAIN`. The second rule is not redundant — a read-only SQLite handle +still executes `VACUUM INTO 'file'`, which writes a copy of the database +anywhere on disk — and a second statement after a `;` is refused rather than +silently ignored, which is what SQLite itself would do with it. + +**Parameters are bound, never pasted into the text:** `--param NAME=VALUE` +binds `:NAME`, so an id with parentheses, commas or quotes needs no escaping. +A value that is a whole or decimal number is bound as a number, anything else +as text. A parameter the statement names and nobody gave is an error, not a +NULL: SQLite would bind NULL, return no row, and that would read as "there +are none". + +**One statement builds on another's saved rows:** `--param-file NAME=FILE` +binds `:NAME` to the whole text of a file, always as text. With a result saved +by `--json`, `json_each(:NAME, '$.rows')` gives one row per saved row, each an +array: `json_extract(r.value, '$[0]')` is its first column. So a list of ids +is never retyped on a command line, and what a result was computed from is a +file that can be opened. One name is bound once: by `--param` or by +`--param-file`. + +The rows go to stdout as an aligned table, as CSV (`--csv`) or as a +`codegraph.queryResult/1` document (`--json`: `columns`, `rows` as arrays, +`total`, `truncated`). At most 50 are printed unless `--limit N` or `--all` +says otherwise; which store answered and how many rows there were — "0 rows." +included — go to stderr. Every refusal, SQLite's own included, is a usage +error (exit 2) carrying SQLite's message; a file that is not a model is a +finding (exit 3), as everywhere. + ### `serve` Opens the model browser on port 4177 (every interface unless `--host` narrows it): ONE page over the model, built from one graph under one view. Its tabs: @@ -564,6 +616,34 @@ co-change the declared graph cannot explain — and `deadweight` — declared dependencies history never exercised. `--serve` opens the file-level city replay, a Gource-style timeline over the commits. +`hotspots` and `summary` join a model too, but only when `--model` names one; +without it they are the history's own reports, whatever sits in the directory. + +- `--report hotspots --model FILE` is effort times complexity. Each file the + history and the model both know gains its source lines (`SLOC`, counted + once: a nested type is inside the type around it), its cyclomatic complexity + summed over its operations, the size of its dependency cycle (`CYCLE`, on + declared dependencies folded to files; 0 when it is in none) and its rank in + four families: `classic` (revisions × lines), `branchy` (revisions × + cyclomatic), `tangled` (revisions, for a file in a cycle), `fragile` + (revisions × fix density, which is the fixes). `--rank` chooses the order + (default `branchy`). A score of 0 is not ranked: `-` in the table, `null` + in the JSON, as is a measure nothing in the file carries. Each row also + says who holds the file WITHOUT A NAME: `ownerShare` (the main author's + share of the lines added), `ownerRank` (that author's row in `--report + authors`, from 1 — two files with one rank have one owner; the table prints + both as `75% #2`) and, in the JSON, `ownerLastSeen`, the day that author + last committed anywhere in the history. The names are `--report authors`' + to give. stderr says how many + history files found no counterpart in the model. +- `--report summary --model FILE` adds `cross-module`: of the commits that + touch the model, the share that touch two or more of its top-level + directories (the first path segment below the directory all its files + share). Commits over 30 files are left out and counted on stderr. + +A `--model` that is readable and is not a model is a finding, exit `3`, for +every report that reads one: no report is printed over an empty join. + ### `timeline` One entity's life across a temporal store: when it appeared, when it was last seen, its LOC series per revision (derived at query time, never stored). diff --git a/docs/sql-cookbook.md b/docs/sql-cookbook.md index 19c39f53..e3377391 100644 --- a/docs/sql-cookbook.md +++ b/docs/sql-cookbook.md @@ -65,7 +65,8 @@ assumes them. CREATE TEMP VIEW node AS SELECT e.id AS ref, (SELECT value FROM meta WHERE key = 'lang') || ':' || m.symbol - || CASE WHEN e.id = e.module_id THEN '' ELSE '/' || e.symbol END + -- no '/' for a module (it names itself) nor for an empty symbol (an anonymous function) + || CASE WHEN e.id = e.module_id OR e.symbol = '' THEN '' ELSE '/' || e.symbol END || CASE WHEN e.disambiguator IS NULL THEN '' ELSE '#' || e.disambiguator END AS id, k.name AS kind, diff --git a/packages/cli/test/helper-views-docs.test.ts b/packages/cli/test/helper-views-docs.test.ts new file mode 100644 index 00000000..4f883aec --- /dev/null +++ b/packages/cli/test/helper-views-docs.test.ts @@ -0,0 +1,86 @@ +import { readFileSync, readdirSync, statSync } from "node:fs"; +import { fileURLToPath } from "node:url"; +import { describe, expect, it } from "vitest"; +import { DEP_VIEW_SQL, NODE_VIEW_SQL } from "@codegraph/analyzer"; + +/** + * THE DOCUMENTATION SHOWS THE VIEWS THE BINARY CREATES (PLAN.md §24.4). + * + * `node` and `dep` have one definition, in `@codegraph/analyzer` + * (`store/helper-views.ts`): `codegraph query` creates them from it and + * `codegraph query --views` prints it. Three pages show the same SQL for a + * reader who pastes it into `sqlite3`, DuckDB or Datasette. Before this test + * they were three hand-kept copies, and one line of them was wrong for every + * reader at once (an anonymous TypeScript function rendered `ts:m/#23:2` + * where every report prints `ts:m#23:2`). + * + * Two pages show the views as the code writes them, comment for comment; the + * tutorial shows a compact form in one block. Both are held: the first two + * byte for byte, the third up to comments and spacing. + */ + +const page = (path: string): string => + readFileSync(fileURLToPath(new URL(`../../../${path}`, import.meta.url)), "utf8"); + +/** Every fenced ```sql block of a markdown page, in order. */ +function sqlBlocks(markdown: string): string[] { + const blocks: string[] = []; + const fence = /```sql\n([\s\S]*?)```/g; + for (let match = fence.exec(markdown); match !== null; match = fence.exec(markdown)) { + blocks.push(match[1]!.trim()); + } + return blocks; +} + +/** A statement with its comments dropped and its spacing collapsed. */ +const normalized = (sql: string): string => + sql + .replace(/--.*$/gm, "") + .replace(/\s+/g, " ") + .trim(); + +const VERBATIM = ["website/content/docs/how-to/query-model-db.md", "docs/sql-cookbook.md"] as const; +const COMPACT = "website/content/docs/tutorials/sql.md"; + +describe("the helper views in the documentation are the ones in the binary", () => { + it.each(VERBATIM)("%s shows node, then dep, exactly as the code has them", (path) => { + const blocks = sqlBlocks(page(path)); + const node = blocks.find((block) => block.startsWith("CREATE TEMP VIEW node")); + const dep = blocks.find((block) => block.startsWith("CREATE TEMP VIEW dep")); + expect(node, `${path} no longer shows the node view`).toBe(NODE_VIEW_SQL); + expect(dep, `${path} no longer shows the dep view`).toBe(DEP_VIEW_SQL); + }); + + it(`${COMPACT} shows both in one block, the same statements up to comments and spacing`, () => { + const block = sqlBlocks(page(COMPACT)).find((candidate) => candidate.startsWith("CREATE TEMP VIEW node")); + expect(block, `${COMPACT} no longer shows the views`).toBeDefined(); + expect(normalized(block ?? "")).toBe(`${normalized(NODE_VIEW_SQL)} ${normalized(DEP_VIEW_SQL)}`); + }); + + it("no other page defines them: a fourth copy would be the one nobody pins", () => { + // Every page that creates a view named node or dep must be listed above. + const known = new Set([...VERBATIM, COMPACT]); + const defining = listMarkdown().filter((path) => /CREATE\s+(TEMP\s+)?VIEW\s+(node|dep)\b/i.test(page(path))); + expect(defining.filter((path) => !known.has(path))).toEqual([]); + expect(defining.length).toBe(known.size); + }); +}); + +/** Every markdown file under docs/, website/content/ and plugin/, repository-relative. */ +function listMarkdown(): string[] { + const root = fileURLToPath(new URL("../../../", import.meta.url)); + const walk = (relative: string): string[] => { + let names: string[]; + try { + names = readdirSync(`${root}${relative}`); + } catch { + return []; // a directory this checkout does not have + } + return names.flatMap((name) => { + const child = `${relative}/${name}`; + if (statSync(`${root}${child}`).isDirectory()) return walk(child); + return name.endsWith(".md") ? [child] : []; + }); + }; + return ["docs", "website/content", "plugin"].flatMap(walk); +} diff --git a/website/content/docs/discover/_index.md b/website/content/docs/discover/_index.md index 96d201c6..558ccb5f 100644 --- a/website/content/docs/discover/_index.md +++ b/website/content/docs/discover/_index.md @@ -24,7 +24,7 @@ stops and where you, or a language model, take over. | 1 | [**Structure and elements**](/docs/discover/structure/) — what is here, how big, how branchy, how tangled? | counts, sizes, complexity, cycles, a city | extract, `analyze`, SQL, `serve` | ready | | 2 | [**Boundaries and style**](/docs/discover/boundaries/) — how is it cut, in which style, and do the cuts hold? | the module map, the stack, the framework roles | `export`, SQL, `--framework spring` | ready, with ad-hoc queries | | 3 | [**Activity**](/docs/discover/activity/) — where does the effort go, who spends it, what changes together? | hotspots, owners, hidden coupling, dead weight | `scm`, `history` | ready | -| 4 | [**Stimuli and flows**](/docs/discover/stimuli/) — what reacts to the outside world or to time, and what does each reaction reach? | an entry-point inventory and the chain each one runs | SQL, the navigator | partly: Spring only, chains by query | +| 4 | [**Stimuli and flows**](/docs/discover/stimuli/) — what reacts to the outside world or to time, and what does each reaction reach? | an entry-point inventory by kind, the chain each one runs, the use cases, what nothing reaches | nine query files, the navigator | ready from a table of names: five frameworks checked, any other yours to list | | 5 | [**Meaning**](/docs/discover/meaning/) — what does each unit do, in domain words? | one explanation per method, type and module | `explain` | ready, costs money | | 6 | [**Domain**](/docs/discover/domain/) — which part is the business, and what is its model? | a `.domain` model and a refactoring report | `domain-facts` + the Specy skill | ready, not yet fed by step 5 | @@ -73,8 +73,11 @@ first hours of reading. ## Words used in this section - **Module.** The unit of code organisation the language has: a Java package, - a C# namespace. Codegraph folds dependencies up to it. -- **Type.** A class, interface, enum, record or annotation. + a C# namespace, a file in TypeScript, Elixir and Ruby. Codegraph folds + dependencies up to it. +- **Type.** A class, interface, enum, record or annotation; also a C# struct, + a TypeScript type alias, an Elixir module or protocol, a Ruby class or + module. Whatever its kind is called, it carries the trait `TType`. - **SLOC.** Source lines of code, blank lines and comments excluded. Every extractor measures it per type and per method. - **Cyclomatic complexity.** The number of independent paths through a diff --git a/website/content/docs/discover/activity.md b/website/content/docs/discover/activity.md index 28b982a8..0806abad 100644 --- a/website/content/docs/discover/activity.md +++ b/website/content/docs/discover/activity.md @@ -90,48 +90,58 @@ ten is a test that is hard to keep green. ## Join effort with complexity A hotspot is complexity **times** effort, and the two tables come from two -sources: the history is per file, the model is per type and method. Join them -on the file path. First, complexity per file from the model: - -```sql -.mode csv -.headers on -.output app-complexity.csv -SELECT f.path AS file, - sum(CASE WHEN em.key = 'sloc' - AND k.name IN ('class', 'interface', 'enum', 'record', 'annotation') - THEN em.value END) AS sloc, - sum(CASE WHEN em.key = 'cyclomatic' THEN em.value END) AS cyclomatic - FROM entity e - JOIN file f ON f.id = e.anchor_file_id - JOIN kind k ON k.id = e.kind_id - LEFT JOIN entity_metric em ON em.entity_id = e.id - WHERE e.is_stub IS NOT 1 - GROUP BY f.path ORDER BY cyclomatic DESC; -.output stdout -``` - -Then the hotspots as data: +sources: the history is per file, the model is per type and method. Give the +model to the same report and it joins them on the file path: ```bash -codegraph history app-history.jsonl --report hotspots --top 500 --json > app-hotspots.json -``` - -Join the two on the path in a spreadsheet, a notebook or ten lines of any -language, and sort by `revisions × cyclomatic`. Two things to know about the -join: the model's paths are relative to the source root you extracted, the -history's to the repository root, so match on the **suffix**; and a file in -the history with no counterpart in the model (docs, build files, anything -outside the extracted root) is expected, not an error. - -{{< callout type="info" >}} -A single `hotspots` report that ranks files by revisions × complexity from a -model given with `--model` is planned. Until it lands, the join above is two -files and a spreadsheet, and the rank family it should produce is worth -knowing anyway: **classic** (revisions × lines), **branchy** (revisions × -cyclomatic), **tangled** (revisions × membership in a cycle from step 1) and -**fragile** (revisions × fix density). Each finds a different kind of trouble. -{{< /callout >}} +codegraph history app-history.jsonl --report hotspots --model app.jsonl --top 20 +``` + +```text +note: 654 of 1082 history files have no counterpart in the model (docs, build files, deleted files, anything outside the extracted root). +hotspots of codegraph, joined with the model (top 5 of 428 files, by branchy rank): + REVISIONS SLOC CYCLOMATIC CYCLE FIXES DENSITY AUTHORS OWNER CLASSIC BRANCHY TANGLED FRAGILE PATH + 45 2158 276 0 1 0.02 2 91% #1 1 1 - 20 packages/cli/src/args.ts + 15 919 241 0 3 0.20 2 89% #1 2 2 - 3 packages/cli/test/explain.test.ts + 13 750 244 0 2 0.15 2 98% #1 3 3 - 8 packages/cli/src/commands/explain.ts + 13 609 208 0 3 0.23 2 84% #1 4 4 - 4 packages/insights/test/run.test.ts + 15 482 122 0 2 0.13 1 100% #1 5 5 - 7 packages/viz/src/three/cityScene.ts +ranks: classic = revisions x sloc, branchy = revisions x cyclomatic, tangled = revisions of a file in a dependency cycle (CYCLE = its files), fragile = revisions x density = fixes; - = not ranked. OWNER = the share of the file's added lines its main author wrote, and that author's row in --report authors. +``` + +**How to read it.** `SLOC` is the file's source lines and `CYCLOMATIC` the sum +over its operations, both from step 1's model. `CYCLE` is the number of files +locked in a dependency cycle with this one, itself included; 0 when it is in +none. `AUTHORS` is how many people touched the file. `OWNER` is the share of +its added lines that its main author wrote, then that author's row in the +`authors` report below: two files with the same `#` have the same owner. With +`--json` each row also has `ownerLastSeen`, the day that author last committed +anywhere in the history. None of this names anyone. The four right-hand columns are the file's **rank** in +four families, and each family finds a different kind of trouble: + +- **classic**: revisions × lines. Large code that is worked on. +- **branchy**: revisions × cyclomatic. Complicated code that is worked on. It + is the order of the table; `--rank classic`, `tangled` or `fragile` chooses + another. +- **tangled**: revisions, among the files that are in a dependency cycle. A + change there pulls the other files of the cycle with it. +- **fragile**: revisions × fix density, which is the number of fix commits. + Where bugs are repaired again and again. + +A `-` is "not ranked": no effort, or nothing measured in that family. A file of +constants has no cyclomatic complexity, and that is not the same as being +simple. A file near the top of two or three families belongs on the shortlist; +a file that tops only one tells you which kind of trouble it is. The test file +in second place above is the triage rule at work: a test that is hard to keep +green. + +Two things to know about the join. The model's paths are relative to the +source root you extracted, the history's to the repository root, so they are +matched on the path **suffix**: the model must come from a directory inside +the mined clone. And the first line counts the history files that found no +counterpart: docs, build files, files deleted since, anything outside the +extracted root. That is expected; a count close to the total means the model +was extracted from somewhere else. ## See who works where @@ -151,8 +161,9 @@ authors of gson (202): Two readings matter for discovery: **knowledge concentration** (one author owns most of the hotspots: a truck-factor risk, and the person to interview first) and **knowledge loss** (the owner of a hotspot no longer works on the -project: the code nobody can explain). The bot on the third line is why you -filter before you count. +project: the code nobody can explain). The joined table above already says +both per hotspot, as `OWNER` and `ownerLastSeen`; this report is where the +names are, and `#3` there is its third row. The bot on the third line is why you filter before you count. {{< callout type="warning" >}} Authorship data describes how a team works. It is never a measure of a @@ -205,11 +216,28 @@ the model was extracted from somewhere other than inside the mined clone. thresholds and the join. Finally, the number step 2 was waiting for: **how often does a commit cross a -top-level module?** Fold the coupling pairs to their first path segment and -count the pairs whose segments differ. Roughly a third of commits crossing -modules is what a stable layered application shows; two thirds is a codebase -growing feature by feature through every layer at once. That share is what -decides whether the folders are boundaries or filing. +top-level module?** The summary answers when it is given the model: + +```bash +codegraph history app-history.jsonl --report summary --model app.jsonl +``` + +```text +history of codegraph: 378 commits by 5 authors over 1082 files + span: 2026-08-18 .. 2026-11-18 (92 days) + churn: +826970 / -214341 (1041311 lines) + firefighting: 50 fixes (13.2% of commits), 0 reverts + momentum: 0.85x (last 90 days vs lifetime rate) + cross-module: 54 of 206 commits touching the model cross its top-level directories (26.2%; 11 at its root) +``` + +A top-level module is here a top-level **directory** of the model: the first +path segment below the directory all its files share. In Java that is the +first package below the common root. Only commits that touch the model are +counted, and those over 30 files are left out, as for coupling. Roughly a +third of commits crossing modules is what a stable layered application shows; +two thirds is a codebase growing feature by feature through every layer at +once. That share is what decides whether the folders are boundaries or filing. ## See it move diff --git a/website/content/docs/discover/boundaries.md b/website/content/docs/discover/boundaries.md index 1ddd0c08..08785d43 100644 --- a/website/content/docs/discover/boundaries.md +++ b/website/content/docs/discover/boundaries.md @@ -86,21 +86,26 @@ frameworks, the libraries, the I/O. Rank them by how often the corpus references them: ```sql -SELECT m.symbol AS external_module, count(*) AS refs +SELECT m.symbol AS external_module, + m.is_stub IS NOT 1 AS own, + count(*) AS refs FROM dep d JOIN node n ON n.ref = d.to_ref JOIN entity m ON m.id = n.module_ref WHERE n.is_stub = 1 - GROUP BY m.symbol ORDER BY refs DESC + GROUP BY m.id ORDER BY refs DESC, external_module LIMIT 40; ``` -| external_module | refs | -|---|---| -| `java.lang` | 39 | -| `java.util` | 15 | -| `com.megacorp.ledger` | 10 | -| `java.time` | 3 | +| external_module | own | refs | +|---|---|---| +| `java.lang` | 0 | 39 | +| `java.util` | 0 | 15 | +| `com.megacorp.ledger` | 0 | 10 | +| `java.lang.annotation` | 0 | 4 | +| `java.util.function` | 0 | 4 | +| `com.acme.order` | 1 | 3 | +| `java.time` | 0 | 3 | **How to read it.** Skip the standard library and read the rest as a bill of materials. `org.springframework.web` is Spring MVC; `jakarta.persistence` is @@ -110,21 +115,44 @@ a vendor package like `com.megacorp.ledger` above is an **external system the corpus depends on** and belongs in the outbound list at the end of this page. Copy the table into your notebook; it is the stack. +A row with `own` = 1 is not the outside world: the module is one of yours, and +what is counted is the names in it that no extracted file declares. That is +code generated at build time, a type that lives in another source root, or a +name the extractor could not resolve and placed in the package it was written +in. A handful is normal; many means a source root is missing from the model. + +How fine the table is depends on the language. Java and C# give one row per +package or namespace. TypeScript gives one per npm package, with `` for +the language's own library. Elixir and Ruby give a few roots (`` and +``, `` and ``): there the bill of materials is the build +file, `mix.exs` or the `Gemfile`, and this table only says how much the code +leans on each side. + Which of your modules reach which external ones is the next question, and it is the one that tests a hexagonal cut: ```sql SELECT src.symbol AS module, ext.symbol AS reaches, count(*) AS refs FROM dep d - JOIN node f ON f.ref = d.from_ref + JOIN node f ON f.ref = d.from_ref JOIN entity src ON src.id = f.module_ref - JOIN node t ON t.ref = d.to_ref + JOIN node t ON t.ref = d.to_ref JOIN entity ext ON ext.id = t.module_ref - WHERE t.is_stub = 1 AND f.is_stub IS NOT 1 - GROUP BY src.symbol, ext.symbol - ORDER BY src.symbol, refs DESC; + WHERE t.is_stub = 1 AND f.is_stub IS NOT 1 AND ext.is_stub = 1 + GROUP BY src.id, ext.id + ORDER BY module, refs DESC, reaches; ``` +| module | reaches | refs | +|---|---|---| +| `com.acme.order` | `java.lang` | 34 | +| `com.acme.order` | `java.util` | 15 | +| `com.acme.order` | `com.megacorp.ledger` | 8 | +| `com.acme.order` | `java.lang.annotation` | 4 | + +Only external modules are on the right-hand side; the `own` rows of the table +above are left out. + A module called `domain` that reaches `jakarta.persistence` or `org.springframework.web` is a violation the code admits to. Write each one down with its count; small counts are one annotation that leaked, large ones @@ -132,10 +160,12 @@ are a layer that never existed. ## Find the patterns from the annotations -Frameworks write their roles into the code as annotations (Java) or -attributes (C#), and codegraph keeps every use as an `annotationUse` edge with -its written arguments. A census of annotation names is the fastest honest -fingerprint of the style: +Frameworks write their roles into the code as annotations (Java), attributes +(C#) or decorators (TypeScript), and codegraph keeps every use as an +`annotationUse` edge with its written arguments. A census of annotation names +is the fastest honest fingerprint of the style. Elixir and Ruby have no such +construct, and the census is empty there: their frameworks speak through +`use`, mixins and naming, which the module map and the stub table show. ```sql SELECT a.name AS annotation, am.symbol AS declared_in, count(*) AS uses @@ -144,7 +174,7 @@ SELECT a.name AS annotation, am.symbol AS declared_in, count(*) AS uses JOIN entity a ON a.id = x.to_id JOIN entity am ON am.id = a.module_id WHERE ek.name = 'annotationUse' - GROUP BY a.name, am.symbol ORDER BY uses DESC, a.name; + GROUP BY a.id ORDER BY uses DESC, annotation, declared_in; ``` | annotation | declared_in | uses | @@ -158,28 +188,47 @@ On a Spring codebase the same query returns `RestController`, `Service`, counts per module are the architecture fingerprint: a module that is 80% controllers is the presentation layer whatever its name. -From there, one targeted query per pattern. The **REST controllers and their -routes**, arguments included, on a Spring codebase: +From there, one targeted query per pattern: everything that carries one of a +list of annotations, with the arguments as written. The list is a parameter, +`:names`, a JSON array: ```sql -SELECT n.id AS annotated, a.name AS annotation, x.arguments +SELECT a.name AS annotation, x.arguments, n.id AS annotated FROM edge x JOIN edge_kind ek ON ek.id = x.kind_id JOIN entity a ON a.id = x.to_id JOIN node n ON n.ref = x.from_id WHERE ek.name = 'annotationUse' - AND a.name IN ('RestController', 'Controller', 'RequestMapping', - 'GetMapping', 'PostMapping', 'PutMapping', - 'DeleteMapping', 'PatchMapping') - ORDER BY n.id; + AND a.name IN (SELECT value FROM json_each(:names)) + ORDER BY annotated, annotation; ``` +| annotation | arguments | annotated | +|---|---|---| +| `Retention` | `[{"name":"value","value":{"k":"enum","type":169,"name":"RUNTIME"}}]` | `java:com.acme.order/Audited` | +| `Audited` | `[{"name":"value","value":{"k":"unevaluated","source":"LedgerClient.AUDIT_TAG"}}]` | `java:com.acme.order/Order.discount(int)` | +| `Audited` | `[{"name":"value","value":{"k":"string","v":"monthly"}}]` | `java:com.acme.order/Reporting.max(java.util.List)` | + +That is the reference fixture, asked for `["Audited","Retention"]`. The **REST +controllers and their routes** of a Spring codebase are the same statement +with another list: + +```bash +codegraph query app.jsonl --file annotated-with.sql \ + --param names='["RestController","Controller","RequestMapping","GetMapping","PostMapping","PutMapping","DeleteMapping","PatchMapping"]' +``` + +[`codegraph query`](/docs/reference/cli/query/) binds the list with `--param`; +in the `sqlite3` shell it is `.parameter set :names '[…]'`. + `arguments` is a JSON array of the written values, so the path of a -`@GetMapping("/owners/{id}")` is in there as a string literal. Swap the name -list for `Entity`/`Table`/`Id` and you have the persistence model; -for `KafkaListener`/`JmsListener`/`RabbitListener` the message consumers; -for `Scheduled` the timers; for `[ApiController]`/`[HttpGet]` the ASP.NET -Core equivalents. +`@GetMapping("/owners/{id}")` is in there as a string literal: +`[{"name":"value","value":{"k":"string","v":"/owners/{id}"}}]`. Swap the list +for `["Entity","Table","Id"]` and you have the persistence model; for +`["KafkaListener","JmsListener","RabbitListener"]` the message consumers; for +`["Scheduled"]` the timers. In C# the model names the attribute's class, so +the ASP.NET Core equivalents are `["ApiControllerAttribute","HttpGetAttribute"]`, +suffix included. {{< callout type="info" >}} These queries are three tables and a name list. If SQL is not your language, diff --git a/website/content/docs/discover/stimuli.md b/website/content/docs/discover/stimuli.md index 8635ca43..87a42173 100644 --- a/website/content/docs/discover/stimuli.md +++ b/website/content/docs/discover/stimuli.md @@ -16,23 +16,30 @@ gives you the **slice** that runs when it fires: a use case, read from the code. The two together are the best map a newcomer can have, because they start from the outside, which is how the business sees the system. -**Before you start:** `app.db` with the helper views from step 1, and the -annotation census from step 2. +**Before you start:** the model from step 1, and the annotation census from +step 2. Every block below is a query file run with +[`codegraph query`](/docs/reference/cli/query/); the statements are at +[the end of this page](#the-statements) and in +[`plugin/queries/`](https://github.com/defsquare/codegraph/tree/main/plugin/queries) +of the repository. `--param-file` hands one query the saved result of another. {{< callout type="warning" >}} -This is the least finished step. What exists today: a Spring entry-point -reading, a generic query for methods nothing in the corpus calls, and a -recursive query that walks a call chain. What does not exist yet: a -framework-aware inventory that classifies every stimulus by kind, and a -one-command forward slice per entry point. The page gives you the pieces -and says which part you assemble by hand. +What exists today: an inventory of entry points from a table of names you +give, the chain behind each of them, on facts and with candidates, and what +no chain touches. What does not exist yet: a command that does it in one +step, and a way to find a handler that is *passed* to the framework instead +of being marked for it (an Express route, an ASP.NET minimal API, a Phoenix +route). The page says where that bites. {{< /callout >}} ## Inventory the entry points -Three detection layers, strongest first. Use all three and merge. +Three detection layers, strongest first. One query runs all three and says +which one found each row. -**1. Framework annotations.** For Spring, codegraph already recognises them: +**1. Framework annotations.** An annotation on a method is written in the +source: `@GetMapping`, `[HttpPost]`, `@Cron()`. For Spring, codegraph already +recognises a list of them: ```bash codegraph analyze app.jsonl --report wiring @@ -48,96 +55,170 @@ entry points: 7 (called from outside the corpus) … ``` -The entry points are the web mappings, the event listeners, the scheduled -methods and the beans the container calls. For any framework, Spring -included, the annotation query from step 2 does the same with a name list -you choose. A starting list, by the kind of stimulus: +For any framework, Spring included, the inventory below does the same with a +list of names you choose. The annotation census of step 2 shows which names +the code uses. -| Stimulus | What it is, in domain words | Annotations and interfaces to look for | +**2. Supertypes the framework calls.** A class implementing `Runnable`, `Job` +or `CommandLineRunner`, a controller extending `ActionController::Base`, is +called with no annotation on it. The census of the external types the code +extends, implements or mixes in shows which there are: + +```bash +codegraph query app.jsonl --file supertypes.sql +``` + +| supertype | relation | types | example | +|---|---|---|---| +| `java:com.megacorp.ledger/LedgerClient` | inheritance | 1 | `java:com.acme.order.adapter/LedgerAdapter` | +| `java:java.lang/RuntimeException` | inheritance | 1 | `java:com.acme.order/EmptyBasketException` | + +Read the list and keep the supertypes that mean "called from outside". The +entry points are then the operations of those types **that nothing in the +code calls**: the callbacks, not the helpers beside them. + +**3. Operations nothing in the code calls.** The structural fallback, which +needs no framework knowledge at all. Such an operation is one of five things: +an entry point the two layers above missed, a reflection target (a getter a +template reads, a property a binder sets), a handler passed to the framework +as a value, dead code, or library API offered to others. Four kinds of +operation are left out, because each has a caller the model does not draw: + +- a **constructor**: a container builds what it wires; +- an operation **written inside another** (a lambda, a local function): it + runs with the one that holds it; +- an operation **called through a type above its own**: a call to + `Priceable.price()` may run `Money.price()`. Same name, same number of + parameters, in a type that extends or implements the called one; +- a **name the language itself calls** (`toString`, `equals`, Ruby's + `initialize`): the `conventional` names of the + [language profile](/docs/reference/profiles/). + +### The stack table + +The names are data, not code: a **stack table**, one JSON file. Each of its +maps gives a name and the kind of stimulus it stands for. + +| Map | A key is | It finds | |---|---|---| -| inbound command | a request to change something | `PostMapping`, `PutMapping`, `DeleteMapping`, `[HttpPost]`, `CommandHandler`, a CLI verb | -| inbound query | a request to read something | `GetMapping`, `[HttpGet]`, GraphQL resolvers, `QueryHandler` | -| external event | something happened elsewhere | `KafkaListener`, `JmsListener`, `RabbitListener`, `SqsListener`, a webhook route | -| internal event | something happened here, and something else reacts | `EventListener`, `TransactionalEventListener`, `EventHandler` | -| temporal | time passed | `Scheduled`, Quartz `Job`, `TimerTask`, JobRunr | -| lifecycle | the process starts or stops (technical, not domain) | `main`, `ApplicationRunner`, `CommandLineRunner`, `PostConstruct` | -| framework callback | plumbing the framework calls (usually not domain) | `Filter`, `Interceptor`, `Converter`, `HealthIndicator` | +| `annotations` | an annotation's name | whatever carries it | +| `supertypes` | the name of a type the framework calls | the uncalled operations of every type below it | +| `types` | a pattern on a type's name (`*Controller`) | the uncalled operations of the types it matches | +| `operations` | an operation's name (`main`, `perform`) | the uncalled operations of that name | +| `entries` | an id | that entity: what a person said is an entry point | +| `conventional` | (a list) the names the language calls | nothing: those are left out of layer 3 | -```sql -SELECT n.id AS entry_point, a.name AS annotation, x.arguments - FROM edge x - JOIN edge_kind ek ON ek.id = x.kind_id - JOIN entity a ON a.id = x.to_id - JOIN node n ON n.ref = x.from_id - WHERE ek.name = 'annotationUse' - AND a.name IN ('GetMapping', 'PostMapping', 'PutMapping', 'DeleteMapping', - 'KafkaListener', 'JmsListener', 'RabbitListener', - 'EventListener', 'Scheduled') - ORDER BY a.name, n.id; -``` - -**2. Interfaces the framework calls.** A class implementing `Runnable`, -`Job`, `MessageListener` or `CommandLineRunner` is an entry point with no -annotation on it. The `interfaceImplementation` edges to a stub say so: +The kinds of stimulus are these eight. The last two are technical: they are +entry points, and rarely domain. -```sql -SELECT n.id AS implementation, t.id AS framework_interface - FROM dep d - JOIN node n ON n.ref = d.from_ref - JOIN node t ON t.ref = d.to_ref - WHERE d.kind = 'interfaceImplementation' AND t.is_stub = 1 - ORDER BY t.id, n.id; +| Stimulus | What it is, in domain words | Annotations and supertypes to look for | +|---|---|---| +| `inbound command` | a request to change something | `PostMapping`, `PutMapping`, `DeleteMapping`, `[HttpPost]`, `CommandHandler`, a CLI verb | +| `inbound query` | a request to read something | `GetMapping`, `[HttpGet]`, GraphQL resolvers, `QueryHandler` | +| `inbound request` | a request, and the name does not say whether it reads or changes | `RequestMapping`, `[Route]`, a Rails or MVC controller action, `MessagePattern` | +| `external event` | something happened elsewhere | `KafkaListener`, `JmsListener`, `RabbitListener`, `SqsListener`, a webhook route | +| `internal event` | something happened here, and something else reacts | `EventListener`, `TransactionalEventListener`, `EventHandler`, a background job | +| `temporal` | time passed | `Scheduled`, `Cron`, Quartz `Job`, `TimerTask` | +| `lifecycle` | the process starts or stops | `main`, `ApplicationRunner`, `CommandLineRunner`, `PostConstruct`, `Bean` | +| `framework callback` | plumbing the framework calls | `Filter`, `Interceptor`, `Converter`, `HealthIndicator`, `InitBinder` | + +Five tables ship with the plugin, in +[`plugin/references/stacks/`](https://github.com/defsquare/codegraph/tree/main/plugin/references/stacks). +Each was run on a real codebase and its rows read: + +| Table | Language | Checked on | It found | It does not find | +|---|---|---|---|---| +| `spring.json` | Java | spring-petclinic `500158f` | 32 by annotation, the 32 of `--report wiring`; 6 by supertype; `main` | a property a template or a binder reaches (16 rows left unclassified) | +| `aspnet.json` | C# | dotnet/eShop `ab10e4c`, OrchardCore `045b6d1` | eShop: 14 by attribute, 44 by supertype. OrchardCore: 399 and 587 | a minimal API route (`MapGet("/items", GetAllItems)`): the handler is passed as a value | +| `nestjs.json` | TypeScript | the 39 sample apps of nestjs/nest `94df49d` | 130 by decorator, 33 by supertype | a decorator whose package resolves to source outside the roots: it is then filed as that file, not by name | +| `phoenix.json` | Elixir | plausible/analytics `418da46` | 170 by type name (`*Controller`, `Mix.Tasks.*`), 253 by operation name (`mount`, `handle_event`, `perform`), 11 by behaviour | which controller function is routed: the router's macros are not edges. `use` is not a supertype without a compiler trace | +| `rails.json` | Ruby | mastodon `v4.3.0` | 1 543 by supertype: controllers, Sidekiq workers, serializers, mailers, Thor commands | which controller method is an action and which a filter: the model has no visibility. A Rake task: a block, not an operation | + +Any other framework is **not covered**: Jakarta EE and JAX-RS, Micronaut, +Quarkus, Azure Functions, Express, Fastify, Next.js, Sinatra, Grape, Hanami. +Build its table from the two censuses, and say it is yours. + +### The inventory + +Copy a table, add what the censuses and the people around you say, and run: + +```bash +codegraph query app.jsonl --file entry-points.sql --param-file stack=stack.json ``` -Read the list and keep the interfaces that mean "called from outside". +| entry_point | kind | layer | evidence | stimulus | calls | arguments | +|---|---|---|---|---|---|---| +| `java:com.acme.order/Order.discount(int)` | method | annotation | Audited | inbound command | 1 | `[{"name":"value","value":{"k":"unevaluated","source":"LedgerClient.AUDIT_TAG"}}]` | +| `java:com.acme.order/Reporting.max(java.util.List)` | method | annotation | Audited | inbound command | 1 | `[{"name":"value","value":{"k":"string","v":"monthly"}}]` | +| `java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)` | method | supertype | LedgerClient | external event | 1 | NULL | +| `java:com.acme.order/Notifications.notifyShipped(com.acme.order.Order)` | method | by hand | NULL | internal event | 1 | NULL | +| `java:com.acme.order/OrderService.bill(com.acme.order.Order)` | method | type name | `*Service` | inbound command | 3 | NULL | +| `java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)` | method | type name | `*Service` | inbound command | 2 | NULL | +| `java:com.acme.order/OrderService.archive(java.util.List)` | method | type name | `*Service` | inbound command | 2 | NULL | +| `java:com.acme.order/Batch.running()` | method | no caller | NULL | temporal | 2 | NULL | +| `java:com.acme.order/Reporting.join(java.lang.String[])` | method | no caller | NULL | NULL | 3 | NULL | + +That is the reference fixture, which uses no framework, with a table that +names what stands for one there: + +```json +{ + "annotations": { "Audited": "inbound command" }, + "supertypes": { "LedgerClient": "external event" }, + "types": { "*Service": "inbound command" }, + "operations": { "running": "temporal" }, + "conventional": ["toString", "equals", "hashCode", "compareTo", "main"], + "entries": { "java:com.acme.order/Notifications.notifyShipped(com.acme.order.Order)": "internal event" } +} +``` -**3. Methods nothing in the corpus calls.** The structural fallback, which -needs no framework knowledge at all. A method with no incoming invocation is -one of four things: an entry point the tables above missed, a reflection -target, dead code, or library API offered to others. Rank by fan-out so the -ones that *do* something come first: +**How to read it.** + +- `layer` is the evidence: `annotation` and `supertype` are written in the + source; `type name` is a convention you stated; `by hand` is what somebody + said; `no caller` is the absence of an edge. A row found by two layers is + shown under the stronger one. +- `stimulus` is the table's word. **`NULL` is unclassified**: found by + layer 3, named by no table. Rank those by `calls`, the calls the operation + makes: the ones that do something come first. An unclassified row is not an + entry point until someone says so; write it in `entries`, or its type in + `types`, and run again. +- A row whose `kind` is not an operation is a marker, not a stimulus: a + `@RequestMapping` on a class is a path prefix, a `@ModelAttribute` on a + parameter is a binding. It is listed because the annotation is there. +- An `entries` id that is not in the model comes back with `kind` `NULL`: a + typo shows instead of vanishing. +- Zero rows for a map is "this table found none here", never "there are + none". + +Step 3 separates two of the five cases of layer 3: dead code is stable (no +revisions), an entry point is worked on. + +Save the inventory (`--all --json > inventory.json`): the queries below read +it. The first one is the inventory **grouped by kind**, which is what you +write down: -```sql -SELECT n.id, count(d.ref) AS fan_out - FROM node n - LEFT JOIN dep d ON d.from_ref = n.ref AND d.kind = 'invocation' - WHERE n.kind = 'method' AND n.is_stub IS NOT 1 - AND NOT EXISTS (SELECT 1 FROM dep i - WHERE i.to_ref = n.ref AND i.kind = 'invocation') - GROUP BY n.ref ORDER BY fan_out DESC, n.id - LIMIT 50; +```bash +codegraph query app.jsonl --file entry-point-kinds.sql --param-file inventory=inventory.json ``` -| id | fan_out | -|---|---| -| `java:com.acme.order/OrderService.bill(com.acme.order.Order)` | 3 | -| `java:com.acme.order/Reporting.join(java.lang.String[])` | 3 | -| `java:com.acme.order/Basket.add(com.acme.order.Basket.Line)` | 2 | - -Step 3 separates two of the four cases: dead code is stable (no revisions), -an entry point is worked on. The model does not carry visibility modifiers -today, so `private` helpers reached only through a lambda can appear here; -they are recognisable by their name and their small fan-out. +| stimulus | layer | evidence | entry_points | example | +|---|---|---|---|---| +| external event | supertype | LedgerClient | 1 | `java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)` | +| inbound command | type name | `*Service` | 3 | `java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)` | +| inbound command | annotation | Audited | 2 | `java:com.acme.order/Order.discount(int)` | +| internal event | by hand | NULL | 1 | `java:com.acme.order/Notifications.notifyShipped(com.acme.order.Order)` | +| temporal | no caller | NULL | 1 | `java:com.acme.order/Batch.running()` | +| unclassified | no caller | NULL | 24 | `java:com.acme.order.legacy/List.length()` | ## Walk what each stimulus reaches From an entry point, follow the invocation and access edges forward. The -reachable set is everything that *can* run when the stimulus fires. SQLite -does this with a recursive query; paste the entry point's id on the first -line: +reachable set is everything that *can* run when the stimulus fires: -```sql -WITH RECURSIVE reach(ref, depth) AS ( - SELECT ref, 0 FROM node WHERE id = 'java:com.acme.order/Order.discount(int)' - UNION - SELECT d.to_ref, r.depth + 1 - FROM reach r JOIN dep d ON d.from_ref = r.ref - WHERE d.kind IN ('invocation', 'access') - AND d.provenance = 'declared' - AND r.depth < 20) -SELECT n.id, n.is_stub AS external, min(r.depth) AS depth - FROM reach r JOIN node n ON n.ref = r.ref - GROUP BY n.ref ORDER BY depth, n.id; +```bash +codegraph query app.jsonl --file reach.sql --param candidates=0 \ + --param id='java:com.acme.order/Order.discount(int)' ``` | id | external | depth | @@ -147,19 +228,41 @@ SELECT n.id, n.is_stub AS external, min(r.depth) AS depth | `java:com.acme.order/Money.times(int)` | 0 | 1 | | `java:com.megacorp.ledger/LedgerClient` | 1 | 1 | | `java:com.acme.order/Money.(long)` | 0 | 2 | +| `java:com.acme.order/Money.cents` | 0 | 2 | **How to read it.** The rows with `external = 1` are the **exit points**: the stubs the chain ends in. A database driver, an HTTP client, a message -producer, a clock. An entry point and its exit points are one end-to-end -flow: in domain words, a command, the operations it triggers and the outside -capabilities it needs. Write the chain down as a list of types in depth -order; that list is the reading order for the use case. - -Run it twice. With `d.provenance = 'declared'` you get the **facts-only lower -bound**. Remove that line and you add the `dynamic-candidate` edges (the -Spring wiring from `--report wiring`, for instance): the plausible upper -bound. A chain that doubles between the two runs goes through an interface -whose implementation is chosen at runtime, and a reader must know which one. +producer, a clock; skip the language's own library. An entry point and its +exit points are one end-to-end flow: in domain words, a command, the +operations it triggers and the outside capabilities it needs. + +Run it twice. With `candidates=0` you get the **facts-only lower bound**: +edges of provenance `declared`, and the operations written inside a reached +one. With `candidates=1` you add three things, each an inference: + +- every edge the extractor wrote with another provenance (`derived`, + `generated`, `dynamic-candidate`); +- the **candidates** a `dynamic-candidate` edge lists without choosing one: an + Elixir protocol call and its implementations; +- **dispatch**: a call to an operation of a type may run the operation of the + same name and the same number of parameters in any type of the code that + extends or implements it. + +A chain that doubles between the two runs goes through an interface whose +implementation is chosen at runtime, and a reader must know which one. On the +C# fixture, `MoneyExtensions.IsFree(IPriceable)` reaches 3 entities on facts +and 9 with the candidates: the three `Price()` behind `IPriceable`, and what +they reach. Where no type of the code implements the interface (a Spring Data +repository), the two runs are equal, and that says the implementation is not +in the source. + +{{< callout type="info" >}} +The candidate targets of `--report wiring` are **not** in the store: that +report derives them in memory and prints them. The second run does not need +them: dispatch reaches every implementation in the code, where the wiring +report would keep the ones a `@Primary` or a `@Qualifier` selects. It is the +upper bound. +{{< /callout >}} For a chain you want to *see* rather than list, the navigator does the same walk by hand: open the entry point in the **Navigate** tab of @@ -168,19 +271,113 @@ source line. Five hops in, you have read the use case. ## What the slices give you -Once you have a chain per entry point, three cheap observations follow: +One query walks the chain behind **every classified entry point** at once, and +folds what it reaches to types. It reads the saved inventory: + +```bash +codegraph query app.jsonl --file chains.sql --param-file inventory=inventory.json --param candidates=0 +``` + +| entry_point | type | external | depth | file | +|---|---|---|---|---| +| `java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)` | `java:com.acme.order.adapter/LedgerAdapter` | 0 | 0 | `com/acme/order/adapter/LedgerAdapter.java` | +| `java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)` | `java:com.acme.order.adapter/AuditTrail` | 1 | 1 | NULL | +| `java:com.acme.order/Batch.running()` | `java:com.acme.order/Batch` | 0 | 0 | `com/acme/order/Batch.java` | +| `java:com.acme.order/Batch.running()` | `java:com.acme.order/Money` | 0 | 1 | `com/acme/order/Money.java` | + +The rows of one entry point, in this order, are **the reading order for the +use case**: its types, the nearest first, then its exit points. Save the +result (`--all --json > chains.json`); three cheap observations read it. -- **Use cases, grouped.** Entry points whose chains overlap heavily belong - to the same feature; groups with little overlap are candidate bounded - contexts. Types present in almost every chain are the shared kernel or the - cross-cutting plumbing, and step 5 will say which. -- **The residue.** Everything no chain reaches. Stable residue (step 3: no - revisions) is deletion material. Actively changed residue is a detection - gap: reflection, a framework the name lists do not know. Report it as a - gap, not as dead code. -- **Which chain to read first.** Rank the chains by how many step 3 hotspots - they pass through. The chain through the biggest, most-changed, most-tangled - code is the one to read first, and the one to explain first in step 5. +**Which chain to read first.** Rank the chains by how many step 3 hotspots +they pass through. `:hotspots` is the joined hotspot report as step 3 saved +it; its first ten rows count. Here two files stand for it: + +```bash +codegraph query app.jsonl --file chain-ranking.sql --param-file chains=chains.json \ + --param hotspots='{"rows":[{"model":"com/acme/order/Money.java"},{"model":"com/acme/order/OrderService.java"}]}' +``` + +| entry_point | types | exits | depth | hotspots | +|---|---|---|---|---| +| `java:com.acme.order/Order.discount(int)` | 3 | 1 | 1 | 1 | +| `java:com.acme.order/Batch.running()` | 2 | 0 | 1 | 1 | +| `java:com.acme.order/OrderService.archive(com.acme.order.legacy.List)` | 2 | 1 | 1 | 1 | + +The chain through the biggest, most-changed, most-tangled code is the one to +read first, and the one to explain first in step 5. Read a command, a query, +a request or an event before a `lifecycle` entry or a `framework callback` of +the same rank: a callback runs for every request and is nobody's use case. +With no history, pass `'{"rows":[]}'`: the column is then 0 everywhere, and +the order is by size. + +**Use cases, grouped.** Entry points whose chains overlap heavily belong to +the same feature; groups with little overlap are candidate bounded contexts. +Two chains are put together when the types they share are at least `:min` +percent of all the types of the two; a group is whatever is near something +in it. The types that more than half the chains reach are left out of the +comparison: they would glue everything into one group. + +```bash +codegraph query app.jsonl --file chain-groups.sql --param-file chains=chains.json --param min=50 +``` + +| group_of | entry_points | entry_point | types | +|---|---|---|---| +| `java:com.acme.order/OrderService.archive(java.util.List)` | 2 | `java:com.acme.order/OrderService.archive(java.util.List)` | 2 | +| `java:com.acme.order/OrderService.archive(java.util.List)` | 2 | `java:com.acme.order/OrderService.bill(com.acme.order.Order)` | 2 | +| `java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)` | 1 | `java:com.acme.order.adapter/LedgerAdapter.post(java.lang.Object)` | 1 | + +A group is named after one of its members. Start at 50 and raise it when one +group swallows the rest. Group the facts-only chains: with candidates, every +chain that crosses a widely implemented interface reaches the same types. + +**The shared kernel.** Types present in almost every chain are the shared +kernel or the cross-cutting plumbing, and step 5 will say which: + +```bash +codegraph query app.jsonl --file shared-types.sql --param-file chains=chains.json +``` + +| type | chains | pct | +|---|---|---| +| `java:com.acme.order/AbstractOrder` | 3 | 37.5 | +| `java:com.acme.order/OrderService` | 3 | 37.5 | +| `java:com.acme.order/Money` | 2 | 25 | + +**The residue.** What nothing that starts at an entry point touches. A chain +follows what *runs*; a type that is only mentioned (a parameter's type, an +exception thrown, a class extended) is used all the same. So the residue is +measured wider: from the types of the classified entry points, through +**every** edge between types, any kind, any provenance. What is left is +mentioned by nothing reachable. + +```bash +codegraph query app.jsonl --file residue.sql --param-file inventory=inventory.json \ + --param activity='{"rows":[{"model":"com/acme/order/Basket.java","revisions":4}]}' +``` + +| type | kind | file | sloc | revisions | +|---|---|---|---|---| +| `java:com.acme.order/Basket` | class | `com/acme/order/Basket.java` | 34 | 4 | +| `java:com.acme.order/Basket.Line` | class | `com/acme/order/Basket.java` | 14 | 4 | +| `java:com.acme.order/Basket.Cursor` | class | `com/acme/order/Basket.java` | 6 | 4 | +| `java:com.acme.order/Basket.Line.Discount` | class | `com/acme/order/Basket.java` | 5 | 4 | +| `java:com.acme.order/StockGuard` | class | `com/acme/order/StockGuard.java` | 14 | 0 | +| `java:com.acme.order/EmptyBasketException` | class | `com/acme/order/EmptyBasketException.java` | 5 | 0 | + +`:activity` is step 3's joined hotspot report, saved for every file: + +```bash +codegraph history history.jsonl --report hotspots --model app.jsonl --top 100000 --json > activity.json +``` + +`revisions` is the file's, in the window step 3 mined. **Stable residue** (0) +is deletion material. **Actively changed residue** is a detection gap: +reflection, a framework the table does not know. Report it as a gap, not as +dead code. With no history (`'{"rows":[]}'`) the column is `NULL`: not +measured, which is not zero. The residue is only as good as the inventory: an +entry point the table missed takes everything behind it into the residue. ## Write down @@ -191,6 +388,455 @@ Once you have a chain per entry point, three cheap observations follow: Next: [Meaning](/docs/discover/meaning/). +## The statements + +One statement per file. A type is asked for by its trait (`TType`), an +operation by `TInvocable`, never by a list of kinds, so the same text runs on +every language. + +### supertypes.sql + +The external types the code extends, implements or mixes in, and how many of its types do. Parameters: none. + +```sql +SELECT t.id AS supertype, d.kind AS relation, + count(DISTINCT d.from_ref) AS types, min(n.id) AS example + FROM dep d + JOIN node t ON t.ref = d.to_ref + JOIN node n ON n.ref = d.from_ref + WHERE d.kind IN ('inheritance', 'interfaceImplementation', 'traitUsage') + AND t.is_stub AND NOT n.is_stub + GROUP BY t.ref, d.kind + ORDER BY types DESC, supertype, relation + LIMIT 40; +``` + +### entry-points.sql + +The entry-point inventory, each row with the layer that found it: an annotation, a supertype, a name, no caller. Parameters: :stack — a stack table as JSON: annotations, supertypes, types, operations, conventional, entries. + +```sql +WITH RECURSIVE +-- the stack table, read once +by_annotation(name, stimulus) AS MATERIALIZED ( + SELECT key, value FROM json_each(:stack, '$.annotations')), +by_supertype(name, stimulus) AS MATERIALIZED ( + SELECT key, value FROM json_each(:stack, '$.supertypes')), +by_type_name(pattern, stimulus) AS MATERIALIZED ( + SELECT key, value FROM json_each(:stack, '$.types')), +by_name(name, stimulus) AS MATERIALIZED ( + SELECT key, value FROM json_each(:stack, '$.operations')), +by_hand(id, stimulus) AS MATERIALIZED ( + SELECT key, value FROM json_each(:stack, '$.entries')), +conventional(name) AS MATERIALIZED ( + SELECT value FROM json_each(:stack, '$.conventional')), +operation AS ( -- what can be called, whatever its kind is named + SELECT m.trait_set_id + FROM trait_set_member m JOIN trait t ON t.id = m.trait_id + WHERE t.name = 'TInvocable'), +above(type, super) AS ( -- a type, with every type above it + SELECT d.from_ref, d.to_ref FROM dep d + WHERE d.kind IN ('inheritance', 'interfaceImplementation', 'traitUsage') + UNION + SELECT a.type, d.to_ref FROM above a JOIN dep d ON d.from_ref = a.super + WHERE d.kind IN ('inheritance', 'interfaceImplementation', 'traitUsage')), +called(ref) AS ( -- the target of a call, or one of its candidates + SELECT to_ref FROM dep WHERE kind = 'invocation' + UNION + SELECT candidate_id FROM edge_candidate), +arity(ref, n) AS ( + SELECT entity_id, count(*) FROM entity_parameter GROUP BY entity_id), +overriding(ref) AS ( -- called through a type above its own: same name, same number of parameters + SELECT o.id + FROM called c + JOIN entity s ON s.id = c.ref + JOIN above a ON a.super = s.parent_id + JOIN entity o ON o.parent_id = a.type AND o.name = s.name + LEFT JOIN arity sn ON sn.ref = s.id + LEFT JOIN arity om ON om.ref = o.id + WHERE coalesce(sn.n, 0) = coalesce(om.n, 0)), +uncalled(ref, type, name) AS MATERIALIZED ( + SELECT e.id, e.parent_id, e.name + FROM entity e + LEFT JOIN entity p ON p.id = e.parent_id + WHERE e.trait_set_id IN (SELECT trait_set_id FROM operation) + AND e.is_stub IS NOT 1 + AND e.name IS NOT NULL + AND e.kind_id NOT IN (SELECT id FROM kind WHERE name = 'constructor') + -- a lambda or a local function runs with the operation it is written in + AND (p.id IS NULL OR p.trait_set_id NOT IN (SELECT trait_set_id FROM operation)) + AND e.id NOT IN (SELECT ref FROM called) + AND e.id NOT IN (SELECT ref FROM overriding)), +found(ref, id, layer, evidence, stimulus, arguments) AS MATERIALIZED ( + SELECT x.from_id, NULL, 'annotation', a.name, w.stimulus, x.arguments + FROM by_annotation w + JOIN entity a ON a.name = w.name + JOIN edge x ON x.to_id = a.id + JOIN edge_kind ek ON ek.id = x.kind_id AND ek.name = 'annotationUse' + UNION ALL + SELECT u.ref, NULL, 'supertype', s.name, w.stimulus, NULL + FROM by_supertype w + JOIN entity s ON s.name = w.name + JOIN above a ON a.super = s.id + JOIN uncalled u ON u.type = a.type + UNION ALL + SELECT n.ref, w.id, 'by hand', NULL, w.stimulus, NULL + FROM by_hand w + LEFT JOIN node n ON n.id = w.id + UNION ALL + SELECT u.ref, NULL, 'type name', w.pattern, w.stimulus, NULL + FROM by_type_name w + JOIN entity t ON t.name GLOB w.pattern + JOIN uncalled u ON u.type = t.id + UNION ALL + SELECT u.ref, NULL, 'no caller', NULL, w.stimulus, NULL + FROM uncalled u + LEFT JOIN by_name w ON w.name = u.name + -- a name the language itself calls is not a stimulus, unless the table says so + WHERE w.name IS NOT NULL + OR u.name NOT IN (SELECT name FROM conventional)) +SELECT coalesce(n.id, f.id) AS entry_point, n.kind, f.layer, f.evidence, f.stimulus, + (SELECT count(*) FROM dep o + WHERE o.from_ref = f.ref AND o.kind = 'invocation') AS calls, + f.arguments + FROM found f + LEFT JOIN node n ON n.ref = f.ref + WHERE f.layer = 'annotation' + OR (f.layer = 'supertype' + AND f.ref NOT IN (SELECT ref FROM found WHERE layer = 'annotation')) + OR (f.layer = 'by hand' + AND (f.ref IS NULL OR f.ref NOT IN ( + SELECT ref FROM found WHERE layer IN ('annotation', 'supertype')))) + OR (f.layer = 'type name' + AND f.ref NOT IN (SELECT ref FROM found + WHERE layer IN ('annotation', 'supertype', 'by hand') + AND ref IS NOT NULL)) + OR (f.layer = 'no caller' + AND f.ref NOT IN (SELECT ref FROM found + WHERE layer <> 'no caller' AND ref IS NOT NULL)) + ORDER BY CASE f.layer WHEN 'annotation' THEN 1 WHEN 'supertype' THEN 2 + WHEN 'by hand' THEN 3 WHEN 'type name' THEN 4 ELSE 5 END, + f.stimulus IS NULL, calls DESC, entry_point, f.evidence; +``` + +### entry-point-kinds.sql + +The inventory grouped by kind of stimulus, with the layer and the name that found each group. Parameters: :inventory — the saved rows of entry-points.sql. + +```sql +WITH found(entry, layer, evidence, stimulus) AS ( + SELECT json_extract(r.value, '$[0]'), json_extract(r.value, '$[2]'), + json_extract(r.value, '$[3]'), json_extract(r.value, '$[4]') + FROM json_each(:inventory, '$.rows') r) +SELECT coalesce(f.stimulus, 'unclassified') AS stimulus, f.layer, f.evidence, + count(DISTINCT f.entry) AS entry_points, min(f.entry) AS example + FROM found f + GROUP BY f.stimulus, f.layer, f.evidence + -- what no table names comes last + ORDER BY f.stimulus IS NULL, f.stimulus, entry_points DESC, f.layer, f.evidence; +``` + +### reach.sql + +What one entry point reaches, hop by hop: on facts only, or with the candidates. Parameters: :id — the entry point's id, :candidates — 0 for declared facts only, 1 to add the candidates. + +```sql +WITH RECURSIVE +operation AS ( -- what can be called, whatever its kind is named + SELECT m.trait_set_id + FROM trait_set_member m JOIN trait t ON t.id = m.trait_id + WHERE t.name = 'TInvocable'), +above(type, super) AS ( -- a type, with every type above it + SELECT d.from_ref, d.to_ref FROM dep d + WHERE d.kind IN ('inheritance', 'interfaceImplementation', 'traitUsage') + UNION + SELECT a.type, d.to_ref FROM above a JOIN dep d ON d.from_ref = a.super + WHERE d.kind IN ('inheritance', 'interfaceImplementation', 'traitUsage')), +arity(ref, n) AS ( + SELECT entity_id, count(*) FROM entity_parameter GROUP BY entity_id), +step(src, dst) AS ( + -- a call or an access, as written + SELECT d.from_ref, d.to_ref FROM dep d + WHERE d.kind IN ('invocation', 'access') + AND (:candidates = 1 OR d.provenance = 'declared') + UNION + -- an operation written inside another runs with it: a lambda, a local function + SELECT c.parent_id, c.id FROM entity c JOIN entity p ON p.id = c.parent_id + WHERE c.trait_set_id IN (SELECT trait_set_id FROM operation) + AND p.trait_set_id IN (SELECT trait_set_id FROM operation) + UNION + -- candidates: the targets an edge lists without choosing one + SELECT x.from_id, c.candidate_id FROM edge_candidate c JOIN edge x ON x.id = c.edge_id + WHERE :candidates = 1 + UNION + -- candidates: a call may run the operation of the same name in any type below + SELECT s.id, o.id + FROM above a + JOIN entity s ON s.parent_id = a.super + JOIN entity o ON o.parent_id = a.type AND o.name = s.name + LEFT JOIN arity sn ON sn.ref = s.id + LEFT JOIN arity om ON om.ref = o.id + WHERE :candidates = 1 + AND s.trait_set_id IN (SELECT trait_set_id FROM operation) + AND o.trait_set_id IN (SELECT trait_set_id FROM operation) + AND coalesce(sn.n, 0) = coalesce(om.n, 0)), +reach(ref, depth) AS ( + SELECT ref, 0 FROM node WHERE id = :id + UNION + SELECT s.dst, r.depth + 1 FROM reach r JOIN step s ON s.src = r.ref + WHERE r.depth < 20) +SELECT n.id, n.is_stub AS external, min(r.depth) AS depth + FROM reach r JOIN node n ON n.ref = r.ref + GROUP BY n.ref ORDER BY depth, n.id; +``` + +### chains.sql + +The chain behind every classified entry point at once: the types it reaches, the nearest first. Parameters: :inventory — the saved rows of entry-points.sql, :candidates — 0 for declared facts only, 1 to add the candidates. + +```sql +WITH RECURSIVE +operation AS ( -- what can be called, whatever its kind is named + SELECT m.trait_set_id + FROM trait_set_member m JOIN trait t ON t.id = m.trait_id + WHERE t.name = 'TInvocable'), +types AS ( + SELECT m.trait_set_id + FROM trait_set_member m JOIN trait t ON t.id = m.trait_id + WHERE t.name = 'TType'), +above(type, super) AS ( -- a type, with every type above it + SELECT d.from_ref, d.to_ref FROM dep d + WHERE d.kind IN ('inheritance', 'interfaceImplementation', 'traitUsage') + UNION + SELECT a.type, d.to_ref FROM above a JOIN dep d ON d.from_ref = a.super + WHERE d.kind IN ('inheritance', 'interfaceImplementation', 'traitUsage')), +arity(ref, n) AS ( + SELECT entity_id, count(*) FROM entity_parameter GROUP BY entity_id), +step(src, dst) AS ( + -- a call or an access, as written + SELECT d.from_ref, d.to_ref FROM dep d + WHERE d.kind IN ('invocation', 'access') + AND (:candidates = 1 OR d.provenance = 'declared') + UNION + -- an operation written inside another runs with it: a lambda, a local function + SELECT c.parent_id, c.id FROM entity c JOIN entity p ON p.id = c.parent_id + WHERE c.trait_set_id IN (SELECT trait_set_id FROM operation) + AND p.trait_set_id IN (SELECT trait_set_id FROM operation) + UNION + -- candidates: the targets an edge lists without choosing one + SELECT x.from_id, c.candidate_id FROM edge_candidate c JOIN edge x ON x.id = c.edge_id + WHERE :candidates = 1 + UNION + -- candidates: a call may run the operation of the same name in any type below + SELECT s.id, o.id + FROM above a + JOIN entity s ON s.parent_id = a.super + JOIN entity o ON o.parent_id = a.type AND o.name = s.name + LEFT JOIN arity sn ON sn.ref = s.id + LEFT JOIN arity om ON om.ref = o.id + WHERE :candidates = 1 + AND s.trait_set_id IN (SELECT trait_set_id FROM operation) + AND o.trait_set_id IN (SELECT trait_set_id FROM operation) + AND coalesce(sn.n, 0) = coalesce(om.n, 0)), +classified(id) AS MATERIALIZED ( -- the inventory's rows that have a stimulus + SELECT json_extract(r.value, '$[0]') + FROM json_each(:inventory, '$.rows') r + WHERE json_extract(r.value, '$[4]') IS NOT NULL), +seed(ref) AS ( -- those of them that are operations + SELECT n.ref FROM node n + WHERE n.id IN (SELECT id FROM classified) + AND n.trait_set_id IN (SELECT trait_set_id FROM operation)), +reach(entry, ref, depth) AS ( + SELECT ref, ref, 0 FROM seed + UNION + SELECT r.entry, s.dst, r.depth + 1 FROM reach r JOIN step s ON s.src = r.ref + WHERE r.depth < 20), +climb(ref, at) AS ( -- from what is reached up to the nearest type around it + SELECT DISTINCT ref, ref FROM reach + UNION ALL + SELECT c.ref, e.parent_id FROM climb c JOIN entity e ON e.id = c.at + WHERE e.parent_id IS NOT NULL + AND e.trait_set_id NOT IN (SELECT trait_set_id FROM types)), +owner(ref, type) AS ( + SELECT c.ref, c.at FROM climb c JOIN entity e ON e.id = c.at + WHERE e.parent_id IS NULL + OR e.trait_set_id IN (SELECT trait_set_id FROM types)) +SELECT s.id AS entry_point, t.id AS type, t.is_stub AS external, + min(r.depth) AS depth, f.path AS file + FROM reach r + JOIN owner o ON o.ref = r.ref + JOIN node s ON s.ref = r.entry + JOIN node t ON t.ref = o.type + JOIN entity e ON e.id = o.type + LEFT JOIN file f ON f.id = e.anchor_file_id + GROUP BY r.entry, o.type + ORDER BY entry_point, depth, type; +``` + +### chain-ranking.sql + +One row per chain: how much it reaches, and how many of step 3's hotspots it passes through. Parameters: :chains — the saved rows of chains.sql, :hotspots — step 3's joined hotspot report as saved, or {"rows":[]}. + +```sql +WITH member(entry, external, depth, file) AS ( + SELECT json_extract(r.value, '$[0]'), json_extract(r.value, '$[2]'), + json_extract(r.value, '$[3]'), json_extract(r.value, '$[4]') + FROM json_each(:chains, '$.rows') r), +hot(file) AS ( -- the first ten rows of the report, by the file the model knows + SELECT json_extract(h.value, '$.model') + FROM json_each(:hotspots, '$.rows') h + WHERE h.key < 10) +SELECT m.entry AS entry_point, + sum(m.external = 0) AS types, + sum(m.external = 1) AS exits, + max(m.depth) AS depth, + count(DISTINCT CASE WHEN m.file IN (SELECT file FROM hot) THEN m.file END) AS hotspots + FROM member m + GROUP BY m.entry + ORDER BY hotspots DESC, types DESC, entry_point; +``` + +### chain-groups.sql + +The entry points grouped by what their chains share: one group, one candidate use case. Parameters: :chains — the saved rows of chains.sql, :min — the share of types two chains must have in common, in percent. + +```sql +WITH RECURSIVE +member(entry, type) AS MATERIALIZED ( -- the code's own types only + SELECT DISTINCT json_extract(r.value, '$[0]'), json_extract(r.value, '$[1]') + FROM json_each(:chains, '$.rows') r + WHERE json_extract(r.value, '$[2]') = 0), +entries(entry) AS MATERIALIZED ( + SELECT DISTINCT entry FROM member), +plumbing(type) AS MATERIALIZED ( -- what more than half the chains reach tells no two apart + SELECT type FROM member GROUP BY type + HAVING 2 * count(*) > (SELECT count(*) FROM entries)), +own(entry, type) AS MATERIALIZED ( + SELECT entry, type FROM member + WHERE type NOT IN (SELECT type FROM plumbing)), +size(entry, n) AS MATERIALIZED ( + SELECT entry, count(*) FROM own GROUP BY entry), +near(a, b) AS MATERIALIZED ( -- shared types over all the types of the two chains + SELECT x.entry, y.entry + FROM own x + JOIN own y ON y.type = x.type AND y.entry <> x.entry + JOIN size sx ON sx.entry = x.entry + JOIN size sy ON sy.entry = y.entry + GROUP BY x.entry, y.entry + HAVING 100.0 * count(*) / (max(sx.n) + max(sy.n) - count(*)) >= :min), +spread(entry, label) AS ( -- a group is whatever is near something in it + SELECT entry, entry FROM entries + UNION + SELECT n.b, s.label FROM spread s JOIN near n ON n.a = s.entry), +grouped(entry, label) AS ( + SELECT entry, min(label) FROM spread GROUP BY entry) +SELECT g.label AS group_of, + count(*) OVER (PARTITION BY g.label) AS entry_points, + g.entry AS entry_point, + (SELECT count(*) FROM member m WHERE m.entry = g.entry) AS types + FROM grouped g + ORDER BY entry_points DESC, group_of, entry_point; +``` + +### shared-types.sql + +The types of the code that the most chains pass through: the shared kernel, or the plumbing. Parameters: :chains — the saved rows of chains.sql. + +```sql +WITH member(entry, type) AS ( + SELECT DISTINCT json_extract(r.value, '$[0]'), json_extract(r.value, '$[1]') + FROM json_each(:chains, '$.rows') r + WHERE json_extract(r.value, '$[2]') = 0) +SELECT m.type, count(*) AS chains, + round(100.0 * count(*) / (SELECT count(DISTINCT entry) FROM member), 1) AS pct + FROM member m + GROUP BY m.type + ORDER BY chains DESC, m.type + LIMIT 20; +``` + +### residue.sql + +The types nothing that starts at an entry point mentions, with the revisions of their file. Parameters: :inventory — the saved rows of entry-points.sql, :activity — step 3's joined hotspot report for every file, or {"rows":[]}. + +```sql +WITH RECURSIVE +types AS ( + SELECT m.trait_set_id + FROM trait_set_member m JOIN trait t ON t.id = m.trait_id + WHERE t.name = 'TType'), +operation AS ( + SELECT m.trait_set_id + FROM trait_set_member m JOIN trait t ON t.id = m.trait_id + WHERE t.name = 'TInvocable'), +climb(ref, at) AS ( -- from each entity up to the nearest type around it + SELECT id, id FROM entity + UNION ALL + SELECT c.ref, e.parent_id FROM climb c JOIN entity e ON e.id = c.at + WHERE e.parent_id IS NOT NULL + AND e.trait_set_id NOT IN (SELECT trait_set_id FROM types)), +owner(ref, type) AS MATERIALIZED ( + SELECT c.ref, c.at FROM climb c JOIN entity e ON e.id = c.at + WHERE e.parent_id IS NULL + OR e.trait_set_id IN (SELECT trait_set_id FROM types)), +uses(a, b) AS MATERIALIZED ( -- type a mentions type b: any edge, any provenance + SELECT f.type, t.type FROM edge x + JOIN owner f ON f.ref = x.from_id JOIN owner t ON t.ref = x.to_id + UNION + SELECT f.type, t.type FROM edge_candidate c JOIN edge x ON x.id = c.edge_id + JOIN owner f ON f.ref = x.from_id JOIN owner t ON t.ref = c.candidate_id + UNION -- the declared type of a field or a parameter + SELECT f.type, t.type FROM entity e + JOIN owner f ON f.ref = e.id JOIN owner t ON t.ref = e.declared_type_id + UNION -- a part written elsewhere and the type it belongs to, both ways + SELECT f.type, t.type FROM entity e + JOIN owner f ON f.ref = e.id JOIN owner t ON t.ref = e.attached_to_id + UNION + SELECT t.type, f.type FROM entity e + JOIN owner f ON f.ref = e.id JOIN owner t ON t.ref = e.attached_to_id + UNION -- a type and a type written inside it, both ways + SELECT p.id, e.id FROM entity e JOIN entity p ON p.id = e.parent_id + WHERE e.trait_set_id IN (SELECT trait_set_id FROM types) + AND p.trait_set_id IN (SELECT trait_set_id FROM types) + UNION + SELECT e.id, p.id FROM entity e JOIN entity p ON p.id = e.parent_id + WHERE e.trait_set_id IN (SELECT trait_set_id FROM types) + AND p.trait_set_id IN (SELECT trait_set_id FROM types)), +classified(id) AS MATERIALIZED ( -- the inventory's rows that have a stimulus + SELECT json_extract(r.value, '$[0]') + FROM json_each(:inventory, '$.rows') r + WHERE json_extract(r.value, '$[4]') IS NOT NULL), +touched(type) AS ( -- from the classified entry points, through every mention + SELECT o.type + FROM node n JOIN owner o ON o.ref = n.ref + WHERE n.id IN (SELECT id FROM classified) + UNION + SELECT u.b FROM touched t JOIN uses u ON u.a = t.type), +activity(file, revisions) AS MATERIALIZED ( + SELECT json_extract(h.value, '$.model'), json_extract(h.value, '$.revisions') + FROM json_each(:activity, '$.rows') h) +SELECT n.id AS type, n.kind, f.path AS file, + (SELECT em.value FROM entity_metric em + WHERE em.entity_id = n.ref AND em.key = 'sloc') AS sloc, + -- no history given: not measured, which is not zero + CASE WHEN (SELECT count(*) FROM activity) = 0 THEN NULL + ELSE coalesce(a.revisions, 0) END AS revisions + FROM node n + JOIN entity e ON e.id = n.ref + LEFT JOIN file f ON f.id = e.anchor_file_id + LEFT JOIN activity a ON a.file = f.path + WHERE NOT n.is_stub + AND n.ref NOT IN (SELECT type FROM touched) + -- a type; or, where functions are written straight in a file, that file + AND (n.trait_set_id IN (SELECT trait_set_id FROM types) + OR (e.parent_id IS NULL + AND EXISTS (SELECT 1 FROM entity c + WHERE c.parent_id = n.ref AND c.is_stub IS NOT 1 + AND c.trait_set_id IN (SELECT trait_set_id FROM operation) + AND c.trait_set_id NOT IN (SELECT trait_set_id FROM types)))) + ORDER BY revisions DESC, sloc DESC, type; +``` + ## Related - [Colour a Spring codebase by role](/docs/how-to/spring-roles/) diff --git a/website/content/docs/discover/structure.md b/website/content/docs/discover/structure.md index b4e0818b..dbb3d9e6 100644 --- a/website/content/docs/discover/structure.md +++ b/website/content/docs/discover/structure.md @@ -91,7 +91,7 @@ How many of each kind of element, stubs excluded: SELECT k.name AS kind, count(*) AS n FROM entity e JOIN kind k ON k.id = e.kind_id WHERE e.is_stub IS NOT 1 - GROUP BY k.name ORDER BY n DESC; + GROUP BY k.name ORDER BY n DESC, kind; ``` | kind | n | @@ -101,8 +101,13 @@ SELECT k.name AS kind, count(*) AS n | attribute | 21 | | constructor | 19 | | class | 14 | +| lambda | 6 | +| localVariable | 6 | | package | 3 | | interface | 2 | +| annotation | 1 | +| enum | 1 | +| record | 1 | This is the reference fixture, a deliberately small corpus. On a real system expect thousands of methods and hundreds of types; the shape of the table is @@ -112,42 +117,67 @@ carriers; one with many `lambda` rows is functional in style; a single ## Measure size and find the outliers -Size per module, with the share of the whole. Only type-level `sloc` is -summed, because the extractor also measures each method and adding both would -count every line twice: +Size per module, with the share of the whole. A module that is a file (in +TypeScript, Elixir and Ruby) carries its own `sloc`. A package or a namespace +carries none, and gets the sum of the types written directly in it. Only +those: a method's lines and a nested type's lines are already inside the type +around them, and adding them would count every line twice. ```sql -WITH type_sloc AS ( - SELECT e.module_id, em.value AS sloc - FROM entity_metric em - JOIN entity e ON e.id = em.entity_id - JOIN kind k ON k.id = e.kind_id +WITH types AS ( + SELECT m.trait_set_id + FROM trait_set_member m JOIN trait t ON t.id = m.trait_id + WHERE t.name = 'TType'), +top_type AS ( + SELECT e.parent_id AS module_id, em.value AS sloc + FROM entity_metric em JOIN entity e ON e.id = em.entity_id WHERE em.key = 'sloc' - AND k.name IN ('class', 'interface', 'enum', 'record', 'annotation')) -SELECT m.symbol AS module, - sum(t.sloc) AS sloc, - count(*) AS types, - round(100.0 * sum(t.sloc) / (SELECT sum(sloc) FROM type_sloc), 1) AS pct - FROM type_sloc t JOIN entity m ON m.id = t.module_id - GROUP BY m.symbol ORDER BY sloc DESC; + AND e.parent_id = e.module_id + AND e.trait_set_id IN (SELECT trait_set_id FROM types)), +module_size AS ( + SELECT m.symbol AS module, + coalesce((SELECT em.value FROM entity_metric em + WHERE em.entity_id = m.id AND em.key = 'sloc'), + (SELECT sum(t.sloc) FROM top_type t WHERE t.module_id = m.id)) AS sloc, + (SELECT count(*) FROM top_type t WHERE t.module_id = m.id) AS types + FROM entity m + WHERE m.id = m.module_id AND m.is_stub IS NOT 1) +SELECT module, sloc, types, + round(100.0 * sloc / (SELECT sum(sloc) FROM module_size), 1) AS pct + FROM module_size + WHERE sloc IS NOT NULL + ORDER BY sloc DESC, module; ``` +| module | sloc | types | pct | +|---|---|---|---| +| `com.acme.order` | 221 | 14 | 90.9 | +| `com.acme.order.legacy` | 14 | 1 | 5.8 | +| `com.acme.order.adapter` | 8 | 1 | 3.3 | + +The `types` CTE is how a query says "a type" in any language: it asks for the +trait `TType`, not for a list of kinds. A Java class, a C# struct, a Ruby +module and an Elixir protocol all carry it. + The largest types, which is where an outlier shows up first: ```sql -SELECT n.id, em.value AS sloc +SELECT n.id, n.kind, em.value AS sloc FROM entity_metric em JOIN node n ON n.ref = em.entity_id WHERE em.key = 'sloc' - AND n.kind IN ('class', 'interface', 'enum', 'record', 'annotation') + AND n.trait_set_id IN ( + SELECT m.trait_set_id + FROM trait_set_member m JOIN trait t ON t.id = m.trait_id + WHERE t.name = 'TType') ORDER BY em.value DESC, n.id LIMIT 20; ``` -| id | sloc | -|---|---| -| `java:com.acme.order/Basket` | 34 | -| `java:com.acme.order/Batch` | 29 | -| `java:com.acme.order/Reporting` | 28 | +| id | kind | sloc | +|---|---|---| +| `java:com.acme.order/Basket` | class | 34 | +| `java:com.acme.order/Batch` | class | 29 | +| `java:com.acme.order/Reporting` | class | 28 | **How to read it.** Size follows a power law in every codebase: a handful of types hold a large share of the lines. That is normal. What you are looking @@ -163,43 +193,62 @@ counting it as empty. ## Measure branching -Cyclomatic complexity is measured per method. Summed per type it says how much -decision logic a class carries; the maximum says whether one method carries -most of it: +Cyclomatic complexity is measured per operation: a method, a constructor, a +function, a lambda. Summed per type it says how much decision logic a class +carries; the maximum says whether one operation carries most of it. Each +operation is counted in the nearest type around it, so a lambda counts in the +class of the method that holds it. That is the sum the city draws as a +building's height. A function written outside any type is counted in its +module, and the `kind` column says so: ```sql -SELECT p.id AS type, +WITH RECURSIVE types AS ( + SELECT m.trait_set_id + FROM trait_set_member m JOIN trait t ON t.id = m.trait_id + WHERE t.name = 'TType'), +climb(op, at) AS ( + SELECT em.entity_id, e.parent_id + FROM entity_metric em JOIN entity e ON e.id = em.entity_id + WHERE em.key = 'cyclomatic' + UNION ALL + SELECT c.op, e.parent_id + FROM climb c JOIN entity e ON e.id = c.at + WHERE e.parent_id IS NOT NULL + AND e.trait_set_id NOT IN (SELECT trait_set_id FROM types)) +SELECT o.id AS owner, o.kind, sum(em.value) AS cyclomatic, - max(em.value) AS worst_method, - count(*) AS methods - FROM entity_metric em - JOIN node n ON n.ref = em.entity_id - JOIN node p ON p.ref = n.parent_ref - WHERE em.key = 'cyclomatic' - GROUP BY p.ref ORDER BY cyclomatic DESC, p.id + max(em.value) AS worst, + count(*) AS operations + FROM climb c + JOIN entity e ON e.id = c.at + JOIN node o ON o.ref = c.at + JOIN entity_metric em ON em.entity_id = c.op AND em.key = 'cyclomatic' + WHERE e.parent_id IS NULL + OR e.trait_set_id IN (SELECT trait_set_id FROM types) + GROUP BY o.ref ORDER BY cyclomatic DESC, o.id LIMIT 20; ``` -| type | cyclomatic | worst_method | methods | -|---|---|---|---| -| `java:com.acme.order/Reporting` | 11 | 4 | 6 | -| `java:com.acme.order/Notifications` | 7 | 1 | 7 | -| `java:com.acme.order/Batch` | 5 | 1 | 5 | - -**How to read it.** `Reporting` has one method at 4 and five simpler ones: a -type with one branchy centre. `Notifications` is at 7 across seven methods of -complexity 1: many small straight-line methods, probably dispatch or -notification glue. A type with `worst_method` above 15 has a method nobody can -test exhaustively, and that method is where bugs are fixed repeatedly (step 3 -will confirm or deny). Compare this table with the size table: a type that is -high on both is the classic outlier; a type that is small but branchy is the -one lines of code would have hidden. +| owner | kind | cyclomatic | worst | operations | +|---|---|---|---|---| +| `java:com.acme.order/Notifications` | class | 12 | 1 | 12 | +| `java:com.acme.order/Reporting` | class | 11 | 4 | 6 | +| `java:com.acme.order/Batch` | class | 8 | 1 | 8 | + +**How to read it.** `Reporting` has one operation at 4 and five simpler ones: +a type with one branchy centre. `Notifications` is at 12 across twelve +operations of complexity 1: many small straight-line methods and lambdas, +probably dispatch or notification glue. A type with `worst` above 15 has an +operation nobody can test exhaustively, and that operation is where bugs are +fixed repeatedly (step 3 will confirm or deny). Compare this table with the +size table: a type that is high on both is the classic outlier; a type that is +small but branchy is the one lines of code would have hidden. With the [metrics pass](/docs/how-to/measure-metrics/) run over the model, the -same query with `em.key = 'cognitive'` ranks by **cognitive** complexity — -branching weighted by how deep it nests, which is closer to how hard a method -is to read than to how many tests it needs — and `'mi'` gives each method's -maintainability index. The pass joins its measures to the entities the +same query with `'cognitive'` in place of `'cyclomatic'` ranks by +**cognitive** complexity — branching weighted by how deep it nests, which is +closer to how hard a method is to read than to how many tests it needs — and +`'mi'` gives each method's maintainability index. The pass joins its measures to the entities the extractor already wrote, so the queries above do not change. ## Find the tangles @@ -211,8 +260,14 @@ codebase: ```bash codegraph analyze app.jsonl --report cycles --level module --internal-only +codegraph analyze app.jsonl --report cycles --level type --internal-only ``` +`--internal-only` drops the stubs, so the cycles you see are between code you +own. Run it at `--level module` first (packages tangled with packages) and +then at `--level type`. The reference fixture has no cycle between its three +packages; between its types it has two, and this is the first: + ```text cycles: 2 strongly connected components, ranked by component size descending, ties by weight then first member tangle: 40.0% overall — feedback weight 2 of 5 cyclic references (minimum feedback set) @@ -222,17 +277,14 @@ cycle 1 — 2 nodes, 3 edges, weight 8, tangle 50.0% java:com.acme.order/Money java:com.acme.order/Priceable edges: + java:com.acme.order/Money -> java:com.acme.order/Money weight=6 kinds=access,invocation,reference provenance=declared (self) java:com.acme.order/Money -> java:com.acme.order/Priceable weight=1 kinds=interfaceImplementation provenance=declared java:com.acme.order/Priceable -> java:com.acme.order/Money weight=1 kinds=reference provenance=declared [feedback] ``` -`--internal-only` drops the stubs, so the cycles you see are between code you -own. Run it at `--level module` first (packages tangled with packages) and -then at `--level type`. - **How to read it.** Three numbers per cycle: -- **members** is how many modules are locked together. One cycle of 500 +- **members** is how many modules (or types) are locked together. One cycle of 500 packages is a ball of mud with a thin shell; ten cycles of two packages each are ten local mistakes. - **weight** is how many base dependencies are involved: how strongly the @@ -258,11 +310,15 @@ codegraph analyze app.jsonl --report coupling --level type --internal-only --top Ce = efferent (distinct nodes this one depends on) = fan-out I = Ce / (Ca + Ce); 0 when nothing touches the node. Self-loops excluded. - NODE FAN-IN FAN-OUT CA CE I - java:com.acme.order.legacy 1 0 1 0 0.000 - java:com.acme.order 0 1 0 1 1.000 + NODE FAN-IN FAN-OUT CA CE I + java:com.acme.order/Money 7 1 7 1 0.125 + java:com.acme.order/Priceable 5 1 5 1 0.167 + java:com.acme.order/Order 2 4 2 4 0.667 ``` +The rows are ranked by total coupling, fan-in plus fan-out, so read the +`FAN-IN` column for what is most depended on. + **How to read it.** High fan-in and low instability (`I` near 0) is a **load-bearing wall**: many things depend on it and it depends on little, so it is stable by construction and a change to it is expensive. High fan-in *and* @@ -299,7 +355,8 @@ it is actually worked on. ## Write down - The resolution rate and the stub count, and the commit the model was - extracted from (the model header carries it). + extracted from (the header carries it when the extractor was given + `--repo-commit`; otherwise note `git rev-parse HEAD` beside it). - The size and complexity tables, with the break in each curve marked and the generated or test code marked as such. - The cycles report: how many components, the size of the largest, and its diff --git a/website/content/docs/how-to/history-joins.md b/website/content/docs/how-to/history-joins.md index 05d5e49f..bb647a82 100644 --- a/website/content/docs/how-to/history-joins.md +++ b/website/content/docs/how-to/history-joins.md @@ -105,7 +105,33 @@ the model must come from a directory inside the repository you mined. An ambiguous suffix joins nothing and is counted rather than guessed. `--model FILE` is required for `hidden` and `deadweight`; without it the command -falls back to this directory's default model. +falls back to this directory's default model. A file that is not a model is a +finding, exit `3`: no report is printed over an empty join. + +## Rank the hotspots by effort times complexity + +The same join gives `hotspots` the model's measures, and `summary` the share of +commits that cross a top-level directory. Both do it only when `--model` names +a model: + +```bash +codegraph history codegraph-history.jsonl --report hotspots --model codegraph.jsonl --rank fragile --top 3 +``` + +```text +hotspots of codegraph, joined with the model (top 3 of 428 files, by fragile rank): + REVISIONS SLOC CYCLOMATIC CYCLE FIXES DENSITY AUTHORS OWNER CLASSIC BRANCHY TANGLED FRAGILE PATH + 14 161 - 0 4 0.29 3 89% #1 29 - - 1 packages/core/src/profiles/java.ts + 22 10 - 0 3 0.14 2 99% #1 208 - - 2 packages/viz/src/main.ts + 15 919 241 0 3 0.20 2 89% #1 2 2 - 3 packages/cli/test/explain.test.ts +ranks: classic = revisions x sloc, branchy = revisions x cyclomatic, tangled = revisions of a file in a dependency cycle (CYCLE = its files), fragile = revisions x density = fixes; - = not ranked. OWNER = the share of the file's added lines its main author wrote, and that author's row in --report authors. +``` + +The four right-hand columns are ranks, one per family; `--rank` chooses which +one orders the rows (`branchy` by default). A `-` under `CYCLOMATIC` is a file +with no measured operation, here a file of data: it is not ranked as branchy, +which is not the same as being simple. [Activity](/docs/discover/activity/) +says how to read the four families. {{< callout type="info" >}} Co-change is an inference about people, not a fact about code. It never enters diff --git a/website/content/docs/how-to/query-model-db.md b/website/content/docs/how-to/query-model-db.md index 6a200a31..ba6d9fd8 100644 --- a/website/content/docs/how-to/query-model-db.md +++ b/website/content/docs/how-to/query-model-db.md @@ -37,7 +37,8 @@ assumes them. CREATE TEMP VIEW node AS SELECT e.id AS ref, (SELECT value FROM meta WHERE key = 'lang') || ':' || m.symbol - || CASE WHEN e.id = e.module_id THEN '' ELSE '/' || e.symbol END + -- no '/' for a module (it names itself) nor for an empty symbol (an anonymous function) + || CASE WHEN e.id = e.module_id OR e.symbol = '' THEN '' ELSE '/' || e.symbol END || CASE WHEN e.disambiguator IS NULL THEN '' ELSE '#' || e.disambiguator END AS id, k.name AS kind, diff --git a/website/content/docs/reference/cli/_index.md b/website/content/docs/reference/cli/_index.md index 274a0229..ef9d049c 100644 --- a/website/content/docs/reference/cli/_index.md +++ b/website/content/docs/reference/cli/_index.md @@ -35,6 +35,7 @@ global options: | [`validate`](/docs/reference/cli/validate/) | Check models against their language profile and the graph invariants. | | [`analyze`](/docs/reference/cli/analyze/) | Report dependencies, cycles, coupling or framework wiring over the loaded models. | | [`import`](/docs/reference/cli/import/) | Build the SQLite analysis store (`model.db`) beside a `model.jsonl`. | +| [`query`](/docs/reference/cli/query/) | Run one read-only SQL statement over a model's store, with the `node` and `dep` views. | | [`export`](/docs/reference/cli/export/) | Write the folded graph as DOT, JSON, CSV or PlantUML. | | [`city`](/docs/reference/cli/city/) | Write the code city: modules as districts, types as buildings. | | [`navigator`](/docs/reference/cli/navigator/) | Explore the model: a searchable tree with per-node dependency detail. | diff --git a/website/content/docs/reference/cli/history.md b/website/content/docs/reference/cli/history.md index 83e7ad39..e5fbbada 100644 --- a/website/content/docs/reference/cli/history.md +++ b/website/content/docs/reference/cli/history.md @@ -8,7 +8,7 @@ Report churn, hotspots and authorship over a mined history.jsonl. ## Synopsis ``` -codegraph history [history.jsonl] [--report ] [--top N] [--model FILE] [--min-support N] [--min-confidence PCT] [--serve] [--port N] [--host ADDR] [--city FILE] [--json] +codegraph history [history.jsonl] [--report ] [--top N] [--model FILE] [--rank ] [--min-support N] [--min-confidence PCT] [--serve] [--port N] [--host ADDR] [--city FILE] [--json] ``` ## Arguments @@ -23,7 +23,8 @@ codegraph history [history.jsonl] [--report ` | Which report to print. | `summary` | | `--top N` | Show only the N highest-ranked rows (hotspots defaults to 20). | — | -| `--model FILE` | Model for the cross-graph reports (hidden, deadweight); defaults to this directory's default model. | — | +| `--model FILE` | A model to join on file paths. hidden and deadweight need one (default: this directory's default model). Given to hotspots, each file gains its lines, its cyclomatic complexity, its dependency cycle and its rank in four families; given to summary, the share of commits that cross a top-level directory of the model. | — | +| `--rank ` | hotspots with --model: the family the rows are ordered by — classic (revisions x lines), branchy (revisions x cyclomatic; the default), tangled (revisions of a file in a dependency cycle), fragile (revisions x fix density). | — | | `--min-support N` | Coupling: pairs must co-change in at least N commits. | `3` | | `--min-confidence PCT` | Coupling: support over the rarer file's revisions, as a percent. | `50` | | `--serve` | Serve the file-level city REPLAY of this history — buildings are files, a timeline scrubs the commits (stdout stays empty; Ctrl-C stops it). | — | @@ -37,7 +38,8 @@ codegraph history [history.jsonl] [--report