Analytical metrics about code quality for git history
code-crime AGENTS.md
11 kB · 90 lines
Markdown
at main

AGENTS.md — Code Crime #

Code Crime parses Git history and change data with Rust, libgit2 (the git2 crate), and DuckDB to construct analytical metrics about code quality and change impacts. It implements the behavioral code-analysis methodology from Adam Tornhill's Software Design X-Rays (The Pragmatic Bookshelf, 2018): version control is treated as a behavioral log of the organization, and analysis targets the intersection of what code is changed often with what that change costs.

This file steers work in this repository. It summarizes the concepts each part of the system must respect; the two context documents in .agents/context/ hold the full book summary and the metric-by-metric reference behind these conclusions.

Git and commits #

  • Never commit on the current checkout branch directly (including main/master). Committing outside a feature branch is prohibited. Before making any edits that will be committed, create a branch first (git checkout -b <descriptive-branch-name>), do the work, and commit there.
  • Use Conventional Commits for all commit messages. Follow the format and types defined in the cheat sheet: https://gist.github.com/qoomon/5dfcdf8eec66a051ecd85625518cfd13 (e.g. feat:, fix:, docs:, refactor:, chore: with optional scopes).
  • Commit message body is required for non-trivial changes and must contain:
    • the model used to make the change
    • a concise reasoning about why the change was necessary.

Core ideas (required background) #

  • Technical debt is defined by interest, not by quality. Code is debt only if it is actually modified or read often. Prioritization therefore needs a time dimension that static analysis cannot provide; change frequency is the interest-rate proxy.
  • Change frequency follows a power law in every codebase analyzed: most code sits untouched in a long tail while a small hot area absorbs development. Improving the hot 20% is where productivity gains concentrate.
  • Hotspots = change frequency × lines of code. Complicated code that you must work with often. They persist for years and usually indicate low cohesion — too many responsibilities attracting the changes.
  • Change coupling reveals what static analysis cannot see — files that repeatedly change together without a source-level dependency. It surfaces hidden dependencies, missing abstractions, and shotgun surgery.
  • Code age has three generations. Recent code has a fresh mental model; stable old code works as a black box; mid-aged code — forgotten yet still revisited — is where "ignorant surgery" happens and where fault density concentrates.
  • Social structure predicts defects better than code metrics. Diffused ownership, many minor contributors, and congested parallel work correlate with defects; a clear main developer lowers risk.
  • The metrics are heuristics that focus expert attention. They are not verdicts and are never a replacement for human judgment.

Architecture #

The system is an extract → materialize → analyze pipeline. Raw history is mined once; every metric is a SQL view or query over the same materialized layer.

  1. Ingest (libgit2). Walk the commit graph in-process. Per commit extract:
    • what: files changed with added/removed line counts (numstat diff), later mapped to functions for method-level analysis;
    • when: author and commit dates;
    • who: author identity, normalized through the repository's .mailmap. Write these as raw provenance tables into DuckDB. No analysis decisions happen here.
  2. Materialize (DuckDB). Pre-aggregate per-file change counts, per-pair shared-commit counts, logical-component groupings (files mapped to architecturally meaningful components via glob/regex patterns supplied in a configuration file), and per-author contributed lines. Materialization exists because pair-level coupling is expensive and its thresholds must be uniform across analyses.
  3. Analyze (SQL). Each metric below is a view or query over the materialized tables, emitted as CSV/JSON or explored in the DuckDB CLI. Prefer adding a view over a new Rust code path: metrics live in SQL so they stay inspectable, composable, and user-extensible without a recompile.

Stack reasoning (binding for implementation choices) #

  • Rust (edition 2024). History mining is CPU- and memory-bound over long revision walks; a garbage-collector-free, single-binary implementation with predictable ownership fits this. The crate name is code-crime under code-crime/.
  • libgit2 via git2. Structured in-process data — revision iterator, diff stats, blame, blob content at arbitrary historic revisions — replaces parsing git CLI text and removes dependence on an installed git version. Historic blob access is what enables complexity-trend and method-level analysis, so the retrieval layer is shared by ingest and trend metrics.
  • DuckDB, embedded. Every metric is an OLAP aggregation (joins, windows, medians, pair co-occurrence) over the same raw layer. DuckDB's single-file, columnar engine expresses hotspots, coupling predicates, and fractal values as plain SQL, supports time-sliced window required by trend/rising-hotspot analyses, and lets users add metric queries without touching Rust.

Metric catalog #

Implement in this order; each entry notes what drives the implementation.

  1. Change frequency — distinct commits touching each entity, scopeable with --after date filters and path filters. Power-law behavior is expected; the distribution itself is a sanity check that mining is correct.
  2. Lines of code — language-neutral complexity proxy per file (blob content at HEAD) and per-period deltas from numstat. No per-language parsers in the core path.
  3. Hotspots and logical components — change frequency × LOC, ranked; components defined by user-supplied glob/regex mappings so every aggregate metric can be computed at file, component, or subsystem level consistently. Hotspot output is for improving code, not judging authors — the original work happened under time pressure no static snapshot shows.
  4. Complexity trends — historic revision snapshots of hotspot files, indentation-based complexity per snapshot, aggregated per component and sampled monthly. Complexity grows steeply early in a file's bad code's life; trends per component reveal tipping points and track whether refactorings worked. Indentation-style reformatting spikes must be discounted.
  5. Change coupling — co-change pairs over shared commits with the methodology's false-positive thresholds as the default SQL predicate: at least 20 shared commits and at least 50% of the total commits to either file. Pairs are then filtered by surprise: test-with-code-under-test coupling is expected and excluded; test-with-unrelated-test or cross-component coupling is the signal. Architectural variant: percentage of commits cutting across components/layers.
  6. Code age — last-modification age per file from commit dates relative to a reference date, plus median age via blame. Exclude autogenerated content. Old tests are an exception to the "stable is good" rule — test suites that no longer grow with application code are candidates for deletion.
  7. Social metrics — author counts per component, knowledge maps, and fractal (fragmentation) values. All computed from contributed lines of code (numstat), never commit counts, because deep knowledge transcends the current structure. Team mapping is a user-supplied author-to-team file.
  8. Clone similarity — similarity percentages among methods in co-changing regions (the pairs surfaced by coupling), text-based first. Clones are a hazard when they evolve together; a conditional in one clone but not the other is a latent-bug signal to investigate with blame and the owning author.
  9. Multi-repository analyses — concatenate per-repo datasets with a virtual repository-name root; group cross-repo changes into logical change sets by same-author/same-day sliding window or, preferably, ticket ids parsed from commit messages; compute a technology-sprawl index by feeding per-language line counts into the fractal-value formula (0.0 = one language, 1.0 = maximal sprawl).
  10. Predictive metrics — complexity-growth warnings against a reference state (branch-point commit or one-month window, using the lowest complexity in the range, ~10% growth threshold for files beyond a minimum size); rising hotspots by diffing rankings across time windows; expected-co-change checks suitable for CI or pre-commit hooks; knowledge-loss simulation splitting authors into staying/leaving virtual teams.

Hard rules and constraints #

  • Minimum history: 150–200 commits before analyses are meaningful. The tool must refuse or clearly warn below that rather than emit confident-looking numbers.
  • .mailmap is mandatory for all social metrics. Distrust author-based analysis on migrated histories, copy-paste repos without migrated history, and squashed multi-author commits — degrade to technical metrics in those cases.
  • Report trends, not absolute values. Absolute complexity or LOC numbers are not comparable across codebases or tools; only trajectory comparisons are sanctioned output.
  • Exclude autogenerated content from hotspot, age, and sprawl analyses — it pollutes every ranking.
  • Social metric output is never for individual performance evaluation. People optimize what is measured; the data source and team dynamics both get destroyed. The tool's documentation and help text must repeat this wherever ownership data is exposed.
  • Test code gets the same treatment as application code. No special-casing that filters tests out of hotspots or coupling — the methodology's recurring finding is that the worst problems live in tests.

Repo layout #

  • code-crime/ — the Rust crate.
  • .agents/skills/ — mounted agent skills; not part of the tool.
  • Dockerfile, .devcontainer/ — dev environment: Rust stable (minimal profile), DuckDB CLI, uv/Vibe, Herdr.

Build and test #

cargo build
cargo test
cargo clippy -- -D warnings
cargo fmt --check

Dev container rebuild from repo root: podman build -t vibe-sandbox-rust:latest .

Conventions #

  • Rust 2024 edition; keep the crate name consistent (code-crime/Cargo.toml).
  • Metrics are SQL, not Rust control flow: when a new metric is needed, first check whether it is expressible as a view over existing materialized tables. Extend the materialization layer only when a metric genuinely needs new raw data.
  • Number formats in metric output follow the CLI conventions of the inputs (dates as YYYY-MM-DD, paths relative to the analyzed repository root, repository prefix for multi-repo datasets).
  • When a new metric or threshold is added, document it in the README metrics section and, if it encodes a claim from the book, keep the claim traceable by recording chapter/page in .agents/context/ notes rather than in code comments.
  • Keep the ethical constraint and reliability warnings visible in any user-facing surface (--help, README, generated report headers).