Skip to content

Latest commit

 

History

History
261 lines (214 loc) · 20.1 KB

usage.md

File metadata and controls

261 lines (214 loc) · 20.1 KB

Usage

The quick start on the shipped sample, what you get from the graph, family packs, configuration, the vault it exports, the rules block setup writes and the Rust library.

Quick start on the shipped sample

The example family pack (families/) and the sample repositories (fixtures/) ship in the repository, not in the binary, so the first command downloads a copy of it, even if you installed the binary another way. Run the commands in any folder; they make two folders side by side, comparegraph (the copy) and cg-try (your workspace, where the store lives). The sample is fixtures/typescript (three files) against the ten-feature example pack:

git clone --depth 1 https://github.com/MassRelayAI/comparegraph
mkdir cg-try && cd cg-try
comparegraph add ../comparegraph/fixtures/typescript --name tsfix   # register a clone (read, never run)
comparegraph build tsfix                                   # parse it: one run, one store hash
comparegraph family add ../comparegraph/families/example-code-graph-tools
comparegraph relate                                        # related | adjacent | unrelated
comparegraph map tsfix example-code-graph-tools            # candidates per feature, writes nothing
comparegraph claim tsfix symbols.extraction has --author me --at src/util.ts:11-11
comparegraph claim tsfix search.embeddings none --author me  # no --searched: the graph check runs
comparegraph matrix example-code-graph-tools               # features x clones, prevalence, gaps
comparegraph export vault --out ./vault                    # open ./vault in Obsidian

Every command prints one JSON envelope (add --pretty to indent it). Real output from the steps above, trimmed:

build   {"run":1,"nodes":13,"edges":21,"files_parsed":3,"communities":1,
         "store_hash":"8a64f321...","reused":false}
relate  {"repo":"tsfix","family":"example-code-graph-tools","score":0.0,"band":"unrelated"}
claim   {"feature":"symbols.extraction","verdict":"has","confidence":"derived",
         "locations":[{"path":"src/util.ts","line_start":11,"line_end":11,"stale":false}]}
claim   {"feature":"search.embeddings","verdict":"none","confidence":"inferred",
         "note":"graph-absent (names, paths, community terms, kinds; not strings, flags or config keys):
                 terms=embedding,embeddings,search; stems=embedd; channels=symbols:0,paths:0,communities:0,kinds:0"}
claim   a bad citation is refused: "src/nope.ts: file does not exist in the clone"  (error invalid_arguments)
matrix  symbols.extraction -> has (prevalence 1.0);  search.embeddings -> none;  the other eight cells "-"
check   {"repos":1,"runs_done":1,"stale_locations":0,"drifted_runs":0,"schema_ok":true,"problems":[]}
export  {"written":"./vault","repos":1,"files":27,"communities":1,"symbols":10}

check reads each cited location from the git objects of the commit its claim's run read, never from the clone's working HEAD, so fetching a newer upstream never reddens it; cited_commit_differs_from_head counts the live locations read at a commit that is not the clone's HEAD (the re-score backlog). A cited commit missing from the clone (shallow, pruned) is clone_unavailable with reason commit_unavailable, never a pass; a run that records no head (one that predates the column) is read from the working tree and counted in unpinned_runs, so a green there is not pinned; comparegraph backfill-head (dry run first; --apply also adds the run.head_source column to an older store and says so) pins such a run by hash equivalence, only when every cited location matches at the repo's recorded head. A shallow clone that lacks the cited commit is commit_unavailable (fetch it, or git fetch --unshallow); claim hashes at the same commit and refuses a file with uncommitted changes. check notes a run pinned this way (head_source equivalent-by-hash). Runs whose cited spans already mismatch at the recorded head (for example massrelay runs 102, 106 and 107, 761 locations) stay unpinned: the remedy is a re-claim or a rebuild, not the backfill. A run head is stored as a 7-character prefix (a known limit: an ambiguous prefix resolves to nothing and reads as commit_unavailable). claim on a run whose commit is not in the clone is refused (clone_unavailable, reason commit_unavailable), never read from the working tree.

relate says unrelated, as it should: a three-file fixture is not a code-graph tool, and map finds no candidates. The matrix has two claimed cells and eight unclaimed - cells.

What you get

Four levels. Each answer says how it knows.

Level Example Where
Repo surface licence, licence lane, head commit, role (root or comparator) repos, show
Structure module communities with label, keywords, cohesion, size communities
Symbols callers, callees, blast radius, tests that reach a symbol, entry points, dead-code candidates show, traverse, impact, tests-for, entry-points, dead-code
Health cycles, dead imports, duplicate bodies, size and coupling outliers, boundary rules, with a baseline ratchet health
Claims verdict, citation, author, trail of superseded rows claim, claims, matrix

A real show answer from the quick start (trimmed):

{"ok":true,"verb":"show","schema":1,
 "data":{"repo":"tsfix","lane":"study",
  "node":{"kind":"method","qualified_name":"src/util.ts::bump","path":"src/util.ts",
          "line_start":11,"line_end":11,"language":"typescript"},
  "community":"src","callers":[],"callees":["src/util.ts::add"],"stale":false,"confidence":"observed"},
 "evidence":{"confidence":"observed","limitations":[]}}

Envelope fields: ok, verb, schema, data, evidence, page, cost, error. The exit code is 0 when ok and 1 otherwise. List verbs take --limit (default 50, maximum 500) and --cursor. Error codes (from docs/catalog.json): below_floor, catalog_stale, check_failed, empty, invalid_arguments, io_error, none_refused, not_found, provider_unavailable, store_error. A none_refused error also carries error.data: the exact searched and the full hits_read list a re-claim needs (see claim in commands.md).

Judging a branch against its base

delta answers "what did this branch introduce since it left its base, and does the base have it now", from builds of the same clone at three refs: the base, the head and their merge base. The clone is only read (raw blobs through git ls-tree and git cat-file, no filter of the clone runs); its checkout, index and working tree never change.

comparegraph delta myrepo --base origin/main --head origin/feature-x --build-missing --pretty
# summary.branch_symbols: symbols the branch added, changed or removed since the merge base
# summary.branch_items: those rows plus the branch's work outside symbols (branch.residue: a hunk of top-level code, a
#   touched .sql or config file), each residue item one unknown
# every row answers on_base: yes (base holds the branch's change; `via` says how), no, or unknown (`why` says why)
# summary.share_on_base_exact: yes over branch_items (1.0 = all); unknown counts AGAINST it
# summary.unknown: {count, by_why}: what could not be told, and why
# summary.share_already_on_base: the same number as share_on_base_exact (kept for older readers)
# summary.near_on_base: rows base holds only nearly (J >= 0.9, nearer the branch than the merge base), each with its
#   j_head and j_merge_base: unknown (why near), never landed, for a person to read
# summary.stale_conflicts: symbols the branch changed that base changed differently, removed or moved (not on base)
# base_files.deleted: files base deleted that the branch touched
comparegraph delta myrepo --base origin/main --head origin/feature-x --refresh   # after either ref moved: rebuilds only what moved
comparegraph repos --stale                  # ref runs whose ref moved or is gone
comparegraph gc --refs                      # dry run: gone, superseded and old ref runs; add --apply --by me to remove them
comparegraph show myrepo src/a.py::bar --ref origin/feature-x    # a graph read verb answers from a ref's run (and says `stale` if the ref moved)

The fields are facts; whether to restack, take parts or retire the branch is the reader's call. A verdict reads the exact share (share_on_base_exact), in which only a yes counts: no and unknown both count against it. A branch with any unknown row or residue item (summary.unknown.count above 0) is read by a person before it is retired: unknown means the model could not tell (a copy of code the merge base already had, one base copy for several branch rows, a near match, equal tokens in other text, a file a run could not read or outside the subset, a submodule, a change no row accounts for), never that base has it. The near_on_base rows are among them. A null share (the branch has no item at all) is read by a person too: nothing was judged. Every line the branch changed is accounted for by a judged row or is an unknown item (branch.residue): a re-indent, whitespace inside a string, a .sql file, a submodule bump. Every yes is then checked against git's own merge (git merge-tree, git 2.38 or newer, read-only): a yes in a file the merge would change, or that conflicts, is unknown (merge_changes_file, with model_via saying how the model had it), and a share of 1.0 also needs the merged tree to be base's tree, and no conflict (else every yes is merge_conflict). A 1.0 means git's merge of the branch into base would change nothing on base, and every change is accounted for. It does not prove base never reverted earlier branch work: a fast-forward of base to the branch, or a merge that keeps the branch as its first parent (a foxtrot merge, e.g. git pull on the branch then a push to base), followed by a revert is undetectable (the graph cannot tell it from base reverting its own commit). A squash or a cherry-pick of the branch then a revert is not a limit: it reads below 1.0. Any branch base ever merged before (a merge on base's first-parent chain took its work), and joined or shallow histories, always carry one unknown item for a person, merged_into_base_before (its reason: merged_before, no_first_parent_fork, shallow_history); the merged_into_base_before_paths limitation lists the paths that hold work base no longer holds, when it can tell. A person confirms before a branch is deleted, a deleted branch is always bundled first, and a null share (no item at all) is read by a person too. --whole-tree's share_identical is how much of head base holds as it is: it has none of these checks and is never a retirement signal.

How a row is answered (docs/decisions.md, "Plan 14: the delta model"): copies of each body (kind + normalised body hash) are counted over the whole tree of the merge base (m), head (h) and base (b). An added or changed row is yes, same_symbol when base holds the very symbol with the branch's body, tokens and text (unknown, text_differs when only the tokens agree); unknown, trivial_body under 8 body tokens; unknown, body_on_merge_base when the branch made no new copy of the body (h - m <= 0: a copy, move or swap of old code); else base's new copies (b - m) credit the branch's new ones one to one: enough for every row of the body is yes, body_hash, none is no, some is unknown, shared_credit. A removed row is no while base keeps the symbol or as many copies of its body as the merge base had, unknown when base keeps fewer, a near copy, or the branch only moved it, and yes, absent_on_base only when base holds no copy AND base's run read every file the merge base's did not (no new unread file, no new submodule). A path that holds the same blob on head and base makes every row in it yes, same_file.

From a branch to a verdict to a deleted branch

comparegraph build myrepo --ref origin/feature-x               # the branch's tree, read as raw git blobs
comparegraph delta myrepo --base origin/main --head origin/feature-x --build-missing
comparegraph decide myrepo reject --why "already on main as bar2" --by me --ref origin/feature-x --commit <sha> --summary-from-delta --base origin/main --bundle D:/bundles/feature-x.bundle
# the record keeps the exact share, the unknown count and the near rows; the verdict is read off the exact share, every
# unknown by a person; --base must name the base the stored delta used
git bundle create D:/bundles/feature-x.bundle origin/feature-x   # outside CompareGraph: the only archive of the branch
git branch -D feature-x                                          # then the branch can go
comparegraph gc --refs                                           # dry run: what is gone, superseded or old
comparegraph gc --refs --apply --by me                           # deletes that ref's runs and extracted trees; the verdict stays
comparegraph decisions --ref origin/feature-x                    # the verdict, by ref and commit

A ref run is only for delta: claim refuses --ref (claims record a repository's head), so no claim ever cites one and gc --refs is never blocked by a citation. A branch verdict names its ref and commit by value, so it outlives the data.

Revisiting a deleted branch (only when asked)

Nothing in CompareGraph reads a deleted branch on its own, and it keeps no copy. To look again: restore the branch from its git bundle (the path is in the decide --ref record, decisions --ref <ref>), build --ref it, run delta, then delete the branch and run gc --refs --apply --by <who> again.

Family packs

A family is a directory with a rows.md: front matter with family: and description:, then a table with id, group, feature, definition, counts_as_has, tier (basics, common, extra or candidate) and weight, plus an optional eighth column synonyms (comma-separated words that also name the feature, e.g. reattempt, backoff). Synonyms are terms of map and of the absent check, and a claim none --searched that uses one counts as naming the feature; an undeclared unrelated word is still refused. A header with any other ninth column is refused. A feature id is <group>.<slug>: lowercase [a-z0-9-], exactly one dot, and the group column must equal the id's group (symbols.extraction has group symbols); a row that breaks it is refused when the pack loads. Two packs ship: families/example-code-graph-tools (10 features, the quick start) and families/code-graph-tools (30 features, the mapping gold). family propose <name> --repos a,b,c drafts a pack from the terms the clones share, with no model. The tier names and band thresholds (related at 0.5 or more, adjacent at 0.2 or more) are provisional, and a relatedness score is vocabulary overlap, not evidence (design notes).

The vault

comparegraph export vault --out ./vault regenerates the whole vault from the store.

vault/
  index.md      llms.txt      AGENTS.md     entry point, a short map, the short workflow for an agent
  repos/        one note per clone
  communities/  symbols/      one folder per clone
  families/     features/     one note per family; one folder per family with a note per feature and its cells
  history/      one note per clone: the dated claim and decision trail, superseded rows marked

Every note starts with a front-matter description: built from stored facts by a template, not by a model, for example function pkg/core.py::add in pkg/core.py:1-2, 3 callers, 0 callees. An agent reads the descriptions first and opens a note only when the line is not enough. At 4.4k files the vault is one file per symbol (66,970 files, 275 MB in the proof report), too large to open as one vault in a note tool.

Configuration

Setting Where Meaning
--root <dir> every command (default .) the workspace; the store is <root>/.comparegraph/comparegraph.db
COMPAREGRAPH_THREADS environment build: cap on per-file analysis threads, 1 to 64 (default 8, also bounded by the CPU count); 0 or an unparsable value is ignored
COMPAREGRAPH_PROFILE environment build: 1 prints one stderr line per pass with its wall time and a count
COMPAREGRAPH_PLUGIN_TIMEOUT environment an external provider's run limit in whole seconds (default 1800; 0 or unparsable is refused)
COMPAREGRAPH_PLUGIN_CAPS_TIMEOUT environment the deadline of a capabilities probe in whole seconds (default 10)
COMPAREGRAPH_PLUGIN_OUTPUT_CAP environment the plugin stdout cap (default 256 MiB)
COMPAREGRAPH_ALLOW_UNVERIFIED environment 1 is the same as --allow-unverified
COMPAREGRAPH_ROOT_MAP environment the same as --root-map: FROM=TO pairs separated by ;, applied at a path boundary on read; the store is not written
COMPAREGRAPH_BIN environment the command setup registers, when --bin is not given
COMPAREGRAPH_NO_PIDNS environment 1 skips the PID-namespace test runner, for contributors (docs/dev/pid-namespaces.md)
COMPAREGRAPH_NOW environment a fixed clock for tests; do not set it in real use
--min-confidence traverse, impact, tests-for, entry-points, dead-code 0.5 (default, includes guessed hops) or 1.0
--max-file-bytes, --max-files, --full build skip files over this size (1048576); keep the first N files by sorted path (50000); bypass the per-file parse cache

The rules block and the hook

The table of clients and their files is in the README.

Besides the entry, setup writes a CompareGraph block, between <!-- comparegraph --> and <!-- /comparegraph -->, into the agent's instruction file in the workspace root (--root, default the current directory; the Rules file column; only once .comparegraph/ exists there, so run comparegraph add first; skip it with --no-rules), and for Claude Code a SessionStart hook in .claude/settings.json (project scope) or ~/.claude/settings.json (user scope; skip it with --no-hook). The hook runs comparegraph doctor --brief, which prints nothing outside a workspace with a store. A block from an older release is refreshed in place; a block you edited by hand is left alone unless you pass --force. Markers quoted inside a fenced code block, or a second block, count as the block (the first marker pair wins); a close marker alone is ignored and a block is appended.

Library usage

The crate is comparegraph. Each verb is a function in comparegraph::application::* taking the workspace root; the CLI and MCP server are thin adapters over them.

use comparegraph::application::{add, build, matrix};
use comparegraph::providers::BuildOptions;
use std::path::Path;

let root = Path::new(".");
add::add_repo(root, Path::new("../comparegraph/fixtures/typescript"), Some("tsfix"), false)?;
let report = build::build_repo(root, "tsfix", "reference", &BuildOptions::default())?;
let m = matrix::matrix(root, "example-code-graph-tools")?;
println!("{} nodes, {} comparators", report.nodes, m.comparators);

The stable contracts: the JSON envelope (export json, every CLI answer), and crates/comparegraph/src/store/schema.sql for read-only SQL on .comparegraph/comparegraph.db. claim and decision rows are append-only: read them, do not update them.

Health: findings and a ratchet

comparegraph health myrepo                       # counts per kind, the first 50 findings of each, every one with path:line
comparegraph health myrepo --baseline health.json   # write the finding keys of today (sorted)
comparegraph health myrepo --check health.json      # exit 1 only on a finding that is not in the baseline

A fixed finding does not fail the check; the answer says 3 finding(s) now clean, shrink the baseline, and rerunning with --baseline shortens the file. Limits and architecture rules live in the workspace's comparegraph.toml:

[health]
max_file_lines = 800
min_lines = 10                  # shortest duplicated body

[[health.boundary]]
from  = "apps/web/**"           # no file here may import ...
never = "apps/api/src/db/**"    # ... any file there

Back to README