GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / AI agents and coordination / vedic- / fingerprints

Candidates

A Python command-line tool in the fingerprints folder of VEDIC that reads clusters summary, dictionary, units and rules, using SHA-256.

649 lines of Python from vedic-, in 1 file. Topic: AI agents and coordination. Section 1665 of 2044.

Cut 2026-12-06T03:07:51+00:00. A copy for reading; the repository at the stated commit is the source.

In the State lines below, domain stage, users and canonical status are rule-based first approximations from code and path evidence (rules explore-agent-rules-v1), not observed facts: the rules.

In this section

  1. Candidates storage · vedic- / fingerprints/candidates.py lines 1–649

Candidates

A Python command-line tool in the fingerprints folder of VEDIC that reads clusters summary, dictionary, units and rules, using SHA-256.

storagevedic- / fingerprints/candidates.py · lines 1–649 of 649 · Entry point · pattern cluster_units (shared by 2 files)

What it does
It loads clusters summary, dictionary, units and rules. Defines 39 functions or classes, including sha256_file, load_rules, load_units, load_dictionary_entries, load_dictionary. Uses libraries argparse, collections, datetime, hashlib, json. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain stage agent_infra (repository name word 'vedic'): AI-agent memory, coordination and code audit (the multi-agent journey named in Ventus Ltd's brief). README: "`candidates.py` does the following, with every threshold and weight taken from `rules.json`:"
Inputs & outputs
In: Parquet file candidates.parquet; JSON file dictionary.json; Parquet file units.parquet; JSON file rules.json; command-line arguments. Out: JSON file clusters-summary.json.
Downstream impact
Used directly by 3 files: Enrich (vedic-); Test Candidates (vedic-); VEDIC Fingerprints Workflow (vedic-). Reached from 1 other entry point, including Test Enrich (vedic-).
What it achieves
It loads rules (`load_rules`), loads units (`load_units`) and loads dictionary entries (`load_dictionary_entries`). Propose VEDIC word candidates from recurring code units (never accepted automatically). It accepts `--units`, `--rules` and `--dictionary`.
Why it matters
Imported by Enrich. Run by VEDIC Fingerprints Workflow. Checked by Test Candidates.
Application
vedic- · fingerprints · Python CLI
Uses
argparse, collections, datetime, hashlib, json, math, pathlib, re
Used by
imported by Enrich (import), imported by Test Candidates (import), run by VEDIC Fingerprints Workflow (workflow run)
Produces
sha256_file, load_rules, load_units, load_dictionary_entries, load_dictionary, name_pieces, stop_matcher, singular, entry_pieces, is_noun, dictionary_word, suggest_word
Defines here
sha256_file, load_rules, load_units, load_dictionary_entries, load_dictionary, name_pieces, stop_matcher, singular, entry_pieces, is_noun, dictionary_word, suggest_word, first_sentence, UnionFind, __init__, find, union, lsh_pairs, cluster_units, medoid_average, tighten, cluster_id, size_sanity, useful_doc, useful_terms, name_specificity, score_parts, weighted_score, most_common_sorted, capability_draft
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 fingerprints/candidates.py:1-649 · blob 97fe80a1239107edb354bd558f85c7f98ee1b0d9 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: agent_infra · users: ai_agent · canonical: supporting_data
"""Propose VEDIC word candidates from recurring code units (never accepted automatically).

Reads out/units.parquet (see CONTRACT.md), clusters exact and near-duplicate units, scores each
cluster with the weights in rules.json, gates them with its thresholds and writes
candidates.parquet, candidates.md, clusters-summary.json, plus one ledger line in runs.tsv.
"""

import argparse
from collections import Counter, defaultdict
from datetime import datetime, timezone
import hashlib
import json
import math
from pathlib import Path
import re
from time import perf_counter

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq


HERE = Path(__file__).resolve().parent
POLICY = "vedic-fingerprint-minhash-lsh-v1"
STATE = "CANDIDATE"
RUNS_HEADER = ("utc_time_with_offset", "rules_version", "rules_sha256", "units", "clusters",
               "candidates", "top_candidate")
UNIT_COLUMNS = ("unit_id", "repo", "commit", "path", "lang", "kind", "name", "params", "line_from",
                "line_to", "n_lines", "n_tokens", "struct_hash", "minhash", "doc", "calls",
                "unit_terms", "side_effects", "pure")
CANDIDATE_SCHEMA = pa.schema([
    ("cluster_id", pa.string()), ("score", pa.float64()), ("struct_hash", pa.string()),
    ("size", pa.int32()), ("repos", pa.list_(pa.string())), ("n_repos", pa.int32()),
    ("names", pa.list_(pa.string())), ("suggested_word", pa.string()),
    ("already_vedic", pa.string()), ("capability_draft", pa.string()),
    ("units_found", pa.list_(pa.string())), ("pure_share", pa.float64()),
    ("import_hint", pa.string()), ("members", pa.list_(pa.string())),
    ("rules_version", pa.string()), ("state", pa.string()),
    ("sibling_clusters", pa.list_(pa.string())),
])


# ---------------------------------------------------------------- rules and inputs

def sha256_file(path):
    with Path(path).open("rb") as file:
        return hashlib.file_digest(file, "sha256").hexdigest()


def load_rules(path):
    rules = json.loads(Path(path).read_text(encoding="utf-8"))
    for key in ("rules_version", "cluster", "candidate", "weights", "scales", "verb_lexicon",
                "stop_names"):
        if key not in rules:
            raise ValueError(f"rules.json is missing {key!r}")
    cluster = rules["cluster"]
    if cluster["lsh_bands"] * cluster["lsh_rows"] > 64:
        raise ValueError("lsh_bands * lsh_rows must not exceed the 64 MinHash values")
    return rules


def load_units(path):
    table = pq.read_table(path)
    missing = [c for c in UNIT_COLUMNS if c not in table.column_names]
    if missing:
        raise ValueError(f"units.parquet is missing columns {missing}")
    return table.select(list(UNIT_COLUMNS)).to_pylist()


def load_dictionary_entries(path):
    """Dictionary entries sorted by number (empty list if there is no dictionary)."""
    if path is None or not Path(path).exists():
        return []
    data = json.loads(Path(path).read_text(encoding="utf-8"))
    entries = data.get("entries", data) if isinstance(data, dict) else data
    return sorted((e for e in entries if e.get("word")),
                  key=lambda e: (e.get("number") or 0, e.get("word") or ""))


def load_dictionary(path):
    """Map a translation_ref's last segment to the existing VEDIC word (lowest number wins)."""
    by_name = {}
    for entry in load_dictionary_entries(path):
        ref = entry.get("translation_ref")
        if ref:
            by_name.setdefault(ref.rsplit(":", 1)[-1], entry["word"])
    return by_name


# ---------------------------------------------------------------- names and words

def name_pieces(name):
    """Split camelCase, PascalCase, snake_case, kebab-case and digits into lower-case pieces."""
    pieces = []
    for part in re.split(r"[^A-Za-z0-9]+", name or ""):
        pieces += re.findall(r"[A-Z]+(?=[A-Z][a-z]|\d|$)|[A-Z]?[a-z]+|[A-Z]+|\d+", part)
    return [p.lower() for p in pieces if p]


def stop_matcher(rules):
    """Return a predicate: True for names never worth a word (stop_names, stop_name_regex)."""
    stops = {s.lower() for s in rules["stop_names"]}
    patterns = [re.compile(r) for r in rules.get("stop_name_regex", [])]
    return lambda name: (name or "").lower() in stops or any(p.search(name or "") for p in patterns)


def singular(piece):
    return piece[:-1] if len(piece) > 3 and piece.endswith("s") and not piece.endswith("ss") else piece


def entry_pieces(entry):
    """Name pieces of a dictionary entry's translation_ref name, inputs and output (singularised)."""
    ref = (entry.get("translation_ref") or "").rsplit(":", 1)[-1]
    words = [ref] + [str(x) for x in entry.get("inputs") or []] + [str(entry.get("output") or "")]
    return {singular(p) for w in words for p in name_pieces(w) if p.isalpha() and len(p) >= 2}


def is_noun(word, rules):
    return word.upper() in {w.upper() for w in rules.get("noun_words", [])}


def dictionary_word(names, entries):
    """Existing dictionary word for these member names, or ''.

    1. An entry whose translation_ref name equals a member name of two or more word pieces (names in
       order, lowest number wins).
    2. Otherwise an entry whose word pieces all appear in the top name and whose translation_ref name,
       inputs or output share the most pieces with the top name (at least two shared pieces; ties go
       to the lower dictionary number). A lead for review, not proof of identity."""
    if not entries:
        return ""
    by_ref = {}
    for entry in entries:
        ref = entry.get("translation_ref")
        if ref:
            by_ref.setdefault(ref.rsplit(":", 1)[-1], entry["word"])
    for name in names:
        # Bare one-piece names (apply, load, index) are too common to identify an entry by name alone.
        if name in by_ref and len({p for p in name_pieces(name) if p.isalpha()}) >= 2:
            return by_ref[name]
    pieces = {singular(p) for p in name_pieces(names[0] if names else "")}
    best, best_overlap = "", 1
    for entry in entries:
        word_pieces = {singular(p) for p in name_pieces(entry["word"])}
        if not word_pieces or not word_pieces <= pieces:
            continue
        overlap = len(pieces & (entry_pieces(entry) | word_pieces))
        if overlap > best_overlap:
            best, best_overlap = entry["word"], overlap
    return best


def suggest_word(name, rules, names=None, entries=None):
    """(word, known): an existing dictionary word that fits (see dictionary_word); else the verb_lexicon
    word of the top name: a leading verb, else the first noun (noun_words), else the first hit; else
    UPPER of the first non-generic word piece of 3+ letters; else ''."""
    word = dictionary_word(names or [name], entries or [])
    if word:
        return word, True
    lexicon = {k.lower(): v for k, v in rules["verb_lexicon"].items()}
    generic = {g.lower() for g in rules.get("generic_pieces", [])}
    pieces = name_pieces(name)
    hits = [(i, lexicon[p]) for i, p in enumerate(pieces) if p in lexicon]
    if hits:
        # A verb in leading position (after generic pieces such as get/compute) names the action:
        # drawCircle -> PRESENT. Later in a name a lexicon verb is usually a noun (lossLoadFactor,
        # heightStore), so a noun hit is preferred there; otherwise the first hit.
        lead = next((i for i, p in enumerate(pieces) if p not in generic), None)
        if hits[0][0] == lead and not is_noun(hits[0][1], rules):
            return hits[0][1], True
        nouns = [w for _, w in hits if is_noun(w, rules)]
        return (nouns or [hits[0][1]])[0], True
    for piece in pieces:
        if piece not in generic and piece.isalpha() and len(piece) >= 3:
            return piece.upper(), False
    return "", False


def first_sentence(text):
    text = " ".join((text or "").split())
    if not text:
        return ""
    match = re.search(r"^(.+?[.!?])(\s|$)", text)
    return (match.group(1) if match else text).strip()


# ---------------------------------------------------------------- clustering

class UnionFind:
    def __init__(self, n):
        self.parent = list(range(n))

    def find(self, x):
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x

    def union(self, a, b):
        ra, rb = self.find(a), self.find(b)
        if ra != rb:
            # Smaller index becomes root: result is independent of pair order.
            self.parent[max(ra, rb)] = min(ra, rb)


def lsh_pairs(signatures, bands, rows, max_bucket):
    """Candidate pairs (i < j) of rows sharing any LSH band. Deterministic in input order."""
    n = len(signatures)
    pairs = set()
    if n < 2:
        return pairs
    for band in range(bands):
        block = signatures[:, band * rows:(band + 1) * rows]
        buckets = defaultdict(list)
        for i in range(n):
            buckets[block[i].tobytes()].append(i)
        for members in buckets.values():
            if len(members) < 2:
                continue
            if len(members) <= max_bucket:
                pairs.update((a, b) for x, a in enumerate(members) for b in members[x + 1:])
            else:
                # Oversized bucket (usually boilerplate): compare each member with the first only.
                head = members[0]
                pairs.update((head, b) for b in members[1:])
    return pairs


def cluster_units(units, rules):
    """Exact groups by struct_hash, then near-duplicate merge by MinHash LSH. Returns clusters
    as sorted lists of unit indices, plus counts."""
    cfg = rules["cluster"]
    groups = defaultdict(list)
    for index, unit in enumerate(units):
        groups[unit["struct_hash"]].append(index)
    keys = sorted(groups)
    stats = {"exact_groups": len(keys), "lsh_candidate_pairs": 0, "near_pairs_verified": 0}
    if not keys:
        return [], stats
    width = cfg["lsh_bands"] * cfg["lsh_rows"]
    signatures = np.zeros((len(keys), 64), dtype=np.uint32)
    for row, key in enumerate(keys):
        values = units[groups[key][0]]["minhash"] or []
        if len(values) != 64:
            raise ValueError(f"minhash must hold 64 values (unit {units[groups[key][0]]['unit_id']})")
        signatures[row] = values
    pairs = lsh_pairs(signatures[:, :width], cfg["lsh_bands"], cfg["lsh_rows"],
                      cfg.get("lsh_max_bucket", 400))
    stats["lsh_candidate_pairs"] = len(pairs)
    uf = UnionFind(len(keys))
    edges = defaultdict(set)
    for a, b in sorted(pairs):
        if float(np.mean(signatures[a] == signatures[b])) >= cfg["near_jaccard"]:
            stats["near_pairs_verified"] += 1
            uf.union(a, b)
            edges[a].add(b)
            edges[b].add(a)
    components = defaultdict(list)
    for row in range(len(keys)):
        components[uf.find(row)].append(row)
    floor = cfg["near_jaccard"] - cfg.get("split_margin", 0.1)
    weights = [len(groups[key]) for key in keys]
    stats["clusters_split"] = 0
    stats["clusters_from_splits"] = 0
    out = []
    for rows in components.values():
        parts = tighten(sorted(rows), signatures, weights, edges, cfg["near_jaccard"], floor)
        if len(parts) > 1:
            stats["clusters_split"] += 1
            stats["clusters_from_splits"] += len(parts)
        for part in parts:
            out.append(sorted(i for row in part for i in groups[keys[row]]))
    return out, stats


def medoid_average(rows, signatures, weights):
    """Medoid of exact groups `rows` (largest weighted sum of estimated Jaccard to the others; lowest
    row on ties) and the unit-weighted average estimated Jaccard of the other groups' units to it."""
    sig = signatures[rows]
    sim = (sig[:, None, :] == sig[None, :, :]).mean(axis=2)
    w = np.array([weights[r] for r in rows], dtype=float)
    totals = (sim * w[None, :]).sum(axis=1) - w  # exclude self
    m = int(np.argmax(totals))  # argmax returns the first maximum: deterministic
    others = [j for j in range(len(rows)) if j != m]
    if not others:
        return m, 1.0, sim
    avg = float(sum(w[j] * sim[m, j] for j in others) / sum(w[j] for j in others))
    return m, avg, sim


def tighten(rows, signatures, weights, edges, near, floor):
    """Split a union-find component whose members drifted away from its medoid (LSH chaining).

    If the average estimated Jaccard of the other members to the medoid is below `floor`, the medoid
    keeps the groups within `near` of it; the rest are re-joined by their own verified pairs only,
    and each of those parts is tightened again. Returns a list of row lists."""
    if len(rows) < 3:
        return [rows]
    m, avg, sim = medoid_average(rows, signatures, weights)
    if avg >= floor:
        return [rows]
    core = [rows[j] for j in range(len(rows)) if j == m or sim[m, j] >= near]
    rest = [r for r in rows if r not in set(core)]
    parts, seen = [core], set()
    restset = set(rest)
    for start in rest:
        if start in seen:
            continue
        comp, stack = [], [start]
        seen.add(start)
        while stack:
            x = stack.pop()
            comp.append(x)
            for y in sorted(edges[x]):
                if y in restset and y not in seen:
                    seen.add(y)
                    stack.append(y)
        parts.extend(tighten(sorted(comp), signatures, weights, edges, near, floor))
    return parts


def cluster_id(unit_ids):
    return hashlib.sha256("\n".join(sorted(unit_ids)).encode()).hexdigest()[:12]


# ---------------------------------------------------------------- scoring

def size_sanity(median_lines, scales):
    low, high = scales["ideal_lines_min"], scales["ideal_lines_max"]
    if median_lines < low:
        return max(0.0, median_lines / low)
    if median_lines <= high:
        return 1.0
    return max(0.0, 1.0 - math.log(median_lines / high) / math.log(scales["huge_lines_factor"]))


def useful_doc(doc, patterns):
    """The doc, unless empty or matching doc_ignore_regex (generated annotations, banners)."""
    doc = " ".join((doc or "").split())
    return "" if not doc or any(p.search(doc) for p in patterns) else doc


def useful_terms(terms, rules):
    ignore = {t.lower() for t in rules.get("unit_terms_ignore", [])}
    return [t for t in terms or [] if t.lower() not in ignore]


def name_specificity(name, rules):
    """Share of up to two distinctive (non-generic, 2+ letter) pieces in the name."""
    generic = {g.lower() for g in rules.get("generic_pieces", [])}
    pieces = [p for p in name_pieces(name) if p.isalpha() and len(p) >= 2 and p not in generic]
    return min(1.0, len(set(pieces)) / 2)


def score_parts(members, n_callers, verb_known, rules, doc_patterns=()):
    """Each part is in [0, 1]; the score is the weighted sum scaled so full marks = 100."""
    s = rules["scales"]
    size = len(members)
    per_repo = Counter(u["repo"] for u in members)
    repos = set(per_repo)
    # Copies within one repository count up to recurrence_per_repo_cap towards recurrence.
    cap = s.get("recurrence_per_repo_cap") or size
    effective = sum(min(cap, c) for c in per_repo.values())
    names = Counter(u["name"] for u in members)
    terms = {t for u in members for t in useful_terms(u["unit_terms"], rules)}
    lines = sorted(u["n_lines"] for u in members)
    return {
        "recurrence": (min(1.0, math.log(effective) / math.log(s["recurrence_size_cap"]))
                       if effective > 1 else 0.0),
        "spread": min(1.0, (len(repos) - 1) / max(1, s["spread_repos_cap"] - 1)),
        "purity": sum(bool(u["pure"]) for u in members) / size,
        "unit_terms": min(1.0, len(terms) / s["unit_terms_cap"]),
        "doc": 1.0 if any(useful_doc(u["doc"], doc_patterns) for u in members) else 0.0,
        "called_by": min(1.0, math.log1p(n_callers) / math.log1p(s["called_by_cap"])),
        "name_consensus": names.most_common(1)[0][1] / size,
        "size_sanity": size_sanity(lines[len(lines) // 2], s),
        "verb_known": 1.0 if verb_known else 0.0,
        "name_specificity": name_specificity(names.most_common(1)[0][0], rules),
    }


def weighted_score(parts, weights):
    total = sum(weights.values())
    if total <= 0:
        return 0.0
    return round(100.0 * sum(weights[k] * parts.get(k, 0.0) for k in weights) / total, 3)


# ---------------------------------------------------------------- drafting from evidence

def most_common_sorted(counter):
    return [k for k, _ in sorted(counter.items(), key=lambda kv: (-kv[1], kv[0]))]


def capability_draft(members, top_name, doc_patterns=()):
    docs = Counter(first_sentence(useful_doc(u["doc"], doc_patterns)) for u in members)
    docs.pop("", None)
    if docs:
        return sorted(docs.items(), key=lambda kv: (-kv[1], -len(kv[0]), kv[0]))[0][0]
    named = [u for u in members if u["name"] == top_name] or members
    params = Counter(tuple(u["params"] or []) for u in named)
    best = sorted(params.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]
    subject = " ".join(p for p in name_pieces(top_name) if p.isalpha()) or top_name
    kind = Counter(u["kind"] for u in named).most_common(1)[0][0]
    if kind == "class":
        return f"Defines {subject} (draft from name only; no docstring)"
    where = f"from {', '.join(best)}" if best else "with no parameters"
    return f"Computes {subject} {where} (draft from name and parameters; no docstring)"


def github_url(unit, owner):
    repo = unit["repo"] if "/" in unit["repo"] else f"{owner}/{unit['repo']}"
    return (f"https://github.com/{repo}/blob/{unit['commit']}/{unit['path']}"
            f"#L{unit['line_from']}-L{unit['line_to']}")


# ---------------------------------------------------------------- pipeline

def analyse(units_path, rules_path, dictionary_path, out_dir, ledger=None, latest=None):
    started = perf_counter()
    rules = load_rules(rules_path)
    rules_sha = sha256_file(rules_path)
    cfg, gate, weights = rules["cluster"], rules["candidate"], rules["weights"]
    all_units = load_units(units_path)
    entries = load_dictionary_entries(dictionary_path)
    vedic = load_dictionary(dictionary_path)

    is_stop = stop_matcher(rules)
    doc_patterns = [re.compile(r, re.IGNORECASE) for r in rules.get("doc_ignore_regex", [])]
    kept, dropped_small, dropped_stop = [], 0, 0
    for unit in all_units:
        if (unit["n_tokens"] or 0) < cfg["min_tokens"]:
            dropped_small += 1
        elif is_stop(unit["name"]):
            dropped_stop += 1
        else:
            kept.append(unit)
    kept.sort(key=lambda u: u["unit_id"])
    clusters, cluster_stats = cluster_units(kept, rules)

    # Pre-gate on cheap facts so caller evidence is only gathered for plausible clusters.
    plausible = []
    for indices in clusters:
        members = [kept[i] for i in indices]
        if len(members) < gate["min_units"] or len({u["repo"] for u in members}) < gate["min_repos"]:
            continue
        if sum(bool(u["pure"]) for u in members) / len(members) < gate["require_pure_share"]:
            continue
        plausible.append(members)
    wanted = {u["name"] for members in plausible for u in members}
    callers = defaultdict(set)
    for unit in all_units:
        for called in unit["calls"] or []:
            if called in wanted:
                callers[called].add(unit["unit_id"])

    rows, parts_by_id, links = [], {}, {}
    for members in plausible:
        members.sort(key=lambda u: (u["repo"], u["path"], u["line_from"], u["unit_id"]))
        member_ids = [u["unit_id"] for u in members]
        own = set(member_ids)
        names = most_common_sorted(Counter(u["name"] for u in members))
        caller_ids = set().union(*(callers[n] for n in set(names))) - own
        word, known = suggest_word(names[0], rules, names, entries)
        parts = score_parts(members, len(caller_ids), known, rules, doc_patterns)
        score = weighted_score(parts, weights)
        if score < gate.get("min_score", 0):
            continue
        per_name = {n: len(callers[n] - own) for n in names}
        hinted = sorted(members, key=lambda u: (-per_name[u["name"]], u["repo"], u["path"],
                                                u["line_from"]))[0]
        cid = cluster_id(member_ids)
        rows.append({
            "cluster_id": cid,
            "score": score,
            "struct_hash": most_common_sorted(Counter(u["struct_hash"] for u in members))[0],
            "size": len(members),
            "repos": sorted({u["repo"] for u in members}),
            "n_repos": len({u["repo"] for u in members}),
            "names": names,
            "suggested_word": word,
            "already_vedic": next((vedic[n] for n in names if n in vedic), ""),
            "capability_draft": capability_draft(members, names[0], doc_patterns),
            "units_found": most_common_sorted(Counter(
                t for u in members for t in set(useful_terms(u["unit_terms"], rules)))),
            "pure_share": round(sum(bool(u["pure"]) for u in members) / len(members), 4),
            "import_hint": f"{hinted['repo']}/{hinted['path']}::{hinted['name']}",
            "members": member_ids,
            "rules_version": rules["rules_version"],
            "state": STATE,
        })
        parts_by_id[cid] = parts
        # Three examples from distinct repos first.
        seen, examples = set(), []
        for u in members:
            if u["repo"] not in seen:
                seen.add(u["repo"])
                examples.append(u)
        examples = (examples + [u for u in members if u not in examples])[:3]
        links[cid] = [(f"{u['repo']}:{u['path']}", github_url(u, rules.get("github_owner", ""))) for u in examples]

    rows.sort(key=lambda r: (-r["score"], r["cluster_id"]))
    mark_siblings(rows)
    if gate.get("max_candidates"):
        rows = rows[:gate["max_candidates"]]

    out = Path(out_dir)
    out.mkdir(parents=True, exist_ok=True)
    pq.write_table(pa.Table.from_pylist(rows, schema=CANDIDATE_SCHEMA), out / "candidates.parquet",
                   compression="zstd")
    (out / "candidates.md").write_text(render_markdown(rows[:100], parts_by_id, links, rules, rules_sha),
                                       encoding="utf-8")
    runtime = round(perf_counter() - started, 3)
    top = rows[0] if rows else None
    top_text = f"{top['suggested_word'] or '?'}:{top['names'][0]}:{top['score']}" if top else ""
    summary = {
        "schema": "vedic-fingerprint-clusters-summary-v1",
        "policy": POLICY,
        "rules_version": rules["rules_version"],
        "rules_sha256": rules_sha,
        "units_sha256": sha256_file(units_path),
        "units_total": len(all_units),
        "units_dropped_below_min_tokens": dropped_small,
        "units_dropped_stop_names": dropped_stop,
        "units_clustered": len(kept),
        "clusters": len(clusters),
        "clusters_with_2plus_units": sum(len(c) > 1 for c in clusters),
        **cluster_stats,
        "clusters_passing_size_repo_purity": len(plausible),
        "candidates": len(rows),
        "candidates_already_vedic": sum(bool(r["already_vedic"]) for r in rows),
        "thresholds": {"cluster": cfg, "candidate": gate},
        "weights": weights,
        "top_candidate": top_text,
        "runtime_seconds": runtime,
        "limits": [
            "Candidates are proposals for review; none is accepted into dictionary.json automatically.",
            "Near-duplicate merging is transitive (union-find): members of one cluster need not all be near each other.",
            "Structural similarity is not semantic equivalence; equal structure can compute different things.",
            "Called-by evidence matches names only, not resolved imports; common names inflate it.",
            "suggested_word and capability_draft come from names, parameters and docstrings, not from execution.",
        ],
    }
    (out / "clusters-summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
    append_run(Path(ledger) if ledger else HERE / "runs.tsv",
               (datetime.now(timezone.utc).isoformat(timespec="seconds"), rules["rules_version"],
                rules_sha, len(all_units), len(clusters), len(rows), top_text))
    if latest is not False:
        Path(latest or HERE / "LATEST.md").write_text(
            render_latest(rows[:25], summary), encoding="utf-8")
    return summary


def mark_siblings(rows):
    """Clusters sharing a top name and the same already_vedic word (or both none) stay separate (their
    structure differs) but each lists the others, in rank order, in sibling_clusters, so a reviewer
    reads them together (describe x3, createGeoJSONCircle x2)."""
    by_key = defaultdict(list)
    for r in rows:
        by_key[(r["names"][0], r["already_vedic"])].append(r["cluster_id"])
    for r in rows:
        group = by_key[(r["names"][0], r["already_vedic"])]
        r["sibling_clusters"] = [c for c in group if c != r["cluster_id"]]


def append_run(path, values):
    path.parent.mkdir(parents=True, exist_ok=True)
    new = not path.exists() or path.stat().st_size == 0
    with path.open("a", encoding="utf-8") as file:
        if new:
            file.write("\t".join(RUNS_HEADER) + "\n")
        file.write("\t".join(str(v).replace("\t", " ").replace("\n", " ") for v in values) + "\n")


def cell(text):
    return str(text).replace("|", "\\|").replace("\n", " ")


def names_cell(r):
    text = ", ".join(r["names"][:3])
    sib = r.get("sibling_clusters") or []
    return text + (f" (+{len(sib)} sibling{'s' if len(sib) > 1 else ''})" if sib else "")


def render_markdown(rows, parts_by_id, links, rules, rules_sha):
    lines = [
        "# VEDIC fingerprint candidates",
        "",
        f"Rules `{rules['rules_version']}` (sha256 `{rules_sha[:12]}`). State of every row: `{STATE}`.",
        "Nothing here is accepted automatically: each row needs human or AI review before any",
        "entry is added to `data/dictionary.json`. Structural likeness is not semantic equivalence.",
        "",
        "| # | word | names | already VEDIC | repos | units | score | pure | units found | capability draft | examples |",
        "|---|---|---|---|---|---|---|---|---|---|---|",
    ]
    for rank, r in enumerate(rows, 1):
        examples = "<br>".join(f"[{cell(label)}]({url})" for label, url in links[r["cluster_id"]])
        lines.append("| " + " | ".join(cell(v) for v in (
            rank, r["suggested_word"] or "-", names_cell(r), r["already_vedic"] or "-",
            r["n_repos"], r["size"], f"{r['score']:.1f}", f"{r['pure_share']:.2f}",
            ", ".join(r["units_found"][:5]) or "-", r["capability_draft"][:140])) + f" | {examples} |")
    lines += ["", "## Score parts (0-1) for the rows above", "",
              "| # | cluster | " + " | ".join(rules["weights"]) + " |",
              "|---|---|" + "---|" * len(rules["weights"])]
    for rank, r in enumerate(rows, 1):
        p = parts_by_id[r["cluster_id"]]
        lines.append(f"| {rank} | `{r['cluster_id']}` | " +
                     " | ".join(f"{p.get(k, 0.0):.2f}" for k in rules["weights"]) + " |")
    return "\n".join(lines) + "\n"


def render_latest(rows, summary):
    lines = [
        "# Latest fingerprint candidates (summary)",
        "",
        f"Rules `{summary['rules_version']}` (sha256 `{summary['rules_sha256'][:12]}`): "
        f"{summary['units_total']} units, {summary['clusters']} clusters, "
        f"{summary['candidates']} candidates. All are `{STATE}`; none is accepted automatically.",
        "Regenerated by `fingerprints/candidates.py`; full table in `fingerprints/out/candidates.md`.",
        "",
        "| # | word | names | already VEDIC | repos | units | score |",
        "|---|---|---|---|---|---|---|",
    ]
    for rank, r in enumerate(rows, 1):
        lines.append("| " + " | ".join(cell(v) for v in (
            rank, r["suggested_word"] or "-", names_cell(r), r["already_vedic"] or "-",
            r["n_repos"], r["size"], f"{r['score']:.1f}")) + " |")
    return "\n".join(lines) + "\n"


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--units", type=Path, default=HERE / "out" / "units.parquet")
    parser.add_argument("--rules", type=Path, default=HERE / "rules.json")
    parser.add_argument("--dictionary", type=Path, default=HERE.parent / "data" / "dictionary.json")
    parser.add_argument("--out", type=Path, default=HERE / "out")
    parser.add_argument("--ledger", type=Path, default=HERE / "runs.tsv",
                        help="runs ledger to append one line to (default fingerprints/runs.tsv)")
    parser.add_argument("--latest", type=Path, default=HERE / "LATEST.md",
                        help="small committed summary of the top candidates")
    args = parser.parse_args()
    summary = analyse(args.units, args.rules, args.dictionary, args.out, args.ledger, args.latest)
    print(json.dumps({k: summary[k] for k in ("rules_version", "units_total", "units_clustered",
                                              "clusters", "candidates", "top_candidate",
                                              "runtime_seconds")}, indent=2))


if __name__ == "__main__":
    main()