GLOBALGRID2050 / EXPLORE CODE

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

VEDIC Family Similarity and 2 more files

A Python command-line tool in the tools folder that reads features (`read_features`), using SHA-256.

602 lines of Python and JavaScript from vedic-, in 3 files. Topic: AI agents and coordination. Section 1676 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. VEDIC Family Similarity render · vedic- / tools/family_similarity.py lines 1–339
  2. VEDIC Family Similarity Review storage · vedic- / tools/family_similarity_review.py lines 1–187
  3. VEDIC Family Similarity Witness render · vedic- / tools/family_similarity_witness.mjs lines 1–76

VEDIC Family Similarity

A Python command-line tool in the tools folder that reads features (`read_features`), using SHA-256.

rendervedic- / tools/family_similarity.py · lines 1–339 of 339 · Entry point · pattern projection (shared by 3 files)

What it does
It loads data. Defines 12 functions or classes, including sha256_file, read_features, projection, representations, device_score. Uses libraries argparse, collections, functools, hashlib, json. Side effects: changes the web page (DOM); 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).
Inputs & outputs
In: command-line arguments.
Downstream impact
Used directly by 1 file: VEDIC Family Similarity Review (vedic-).
What it achieves
It is built from the sha256 file helper (`sha256_file`), the projection step (`projection`) and the representations step (`representations`). Compute bounded, source-ID-preserving similarity leads for existing Stars families. It accepts `--dimensions`, `--tile` and `--top-k`.
Why it matters
Imported by VEDIC Family Similarity Review.
Application
vedic- · tools · Python CLI
Uses
argparse, collections, functools, hashlib, json, os, pathlib, tempfile
Used by
imported by VEDIC Family Similarity Review (import)
Produces
sha256_file, read_features, projection, representations, device_score, ranked_neighbors, benchmark, matrix_scan, sparse_components, neighbor_table, analyse, main
Defines here
sha256_file, read_features, projection, representations, device_score, ranked_neighbors, benchmark, matrix_scan, sparse_components, neighbor_table, analyse, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/family_similarity.py:1-339 · blob 09f48f96a34aa20052d15f128d48c8ec1bae3750 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Compute bounded, source-ID-preserving similarity leads for existing Stars families."""

import argparse
from collections import Counter, defaultdict
import functools
import hashlib
import json
import os
from pathlib import Path
import tempfile
from time import perf_counter

import numpy as np
import pyarrow as pa
import pyarrow.parquet as pq
from scipy.sparse import coo_matrix
from scipy.sparse.csgraph import connected_components


THRESHOLDS = (0.85, 0.90, 0.92, 0.95, 0.99)
POLICY = "vedic-family-signed-hash-tfidf-v1"
COSINE_CUDA = r"""
extern "C" __global__ void cosine(
    const float* features, float* result, int n, int d, int begin, int rows
) {
    const int tx = threadIdx.x, ty = threadIdx.y;
    const int local_row = blockIdx.y * 16 + ty;
    const int row = begin + local_row, col = blockIdx.x * 16 + tx;
    const int load_col = blockIdx.x * 16 + ty;
    __shared__ float a[16][17], b[16][17];
    float acc = 0.0f;
    for (int offset = 0; offset < d; offset += 16) {
        a[ty][tx] = local_row < rows ? features[row*d + offset + tx] : 0.0f;
        b[ty][tx] = load_col < n ? features[load_col*d + offset + tx] : 0.0f;
        __syncthreads();
        #pragma unroll
        for (int i = 0; i < 16; ++i) acc = fmaf(a[ty][i], b[tx][i], acc);
        __syncthreads();
    }
    if (local_row < rows && col < n) result[local_row*n+col] = acc;
}
"""


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


def read_features(path):
    """Aggregate supplied existing element occurrences by their permanent family."""

    table = pq.read_table(path)
    required = {"family_id", "element_id", "tokens"}
    if not required.issubset(table.column_names):
        raise ValueError(f"Feature file must contain {sorted(required)}")
    allowed = required | {"counts", "lang", "language", "repo", "path", "symbol"}
    groups = defaultdict(list)
    seen_elements = set()
    for row in table.select([col for col in table.column_names if col in allowed]).to_pylist():
        family, element, tokens = (row[k] for k in ("family_id", "element_id", "tokens"))
        if type(family) is not int or type(element) is not int or family <= 0 or element <= 0:
            raise ValueError("Expected existing positive integer family and element IDs")
        if element in seen_elements:
            raise ValueError(f"Repeated element ID in feature input: {element}")
        seen_elements.add(element)
        if not isinstance(tokens, list) or any(not isinstance(value, str) or not value for value in tokens):
            raise ValueError(f"Invalid token array for element {element}")
        counts = row.get("counts")
        if counts is None:
            features = Counter(tokens)
        else:
            if len(tokens) != len(counts) or any(type(count) is not int or count <= 0 for count in counts):
                raise ValueError(f"Invalid positive token counts for element {element}")
            features = Counter()
            for token, count in zip(tokens, counts, strict=True):
                features[token] += count
        groups[family].append((element, features))
    if not groups:
        raise ValueError("No computational families were supplied")
    return groups, len(seen_elements)


@functools.lru_cache(maxsize=200_000)
def projection(token):
    raw = hashlib.blake2b(token.encode(), digest_size=8, person=b"VEDIC-v1").digest()
    return int.from_bytes(raw[:4], "little"), (1 if raw[4] & 1 else -1)


def representations(groups, dimension):
    ids = np.asarray(sorted(groups), dtype=np.int64)
    docs = []
    document_frequency = Counter()
    for family in ids:
        # Same-logic element variants keep their shared family identity.
        document = Counter()
        for _, features in sorted(groups[family]):
            document |= features
        docs.append(document)
        document_frequency.update(document.keys())
    idf = {k: np.log((1 + len(ids)) / (1 + frequency)) + 1
           for k, frequency in document_frequency.items()}
    matrix = np.zeros((len(ids), dimension), dtype=np.float32)
    metadata = []
    for index, (family, document) in enumerate(zip(ids, docs, strict=True)):
        terms = sorted(document.items())
        fingerprint = hashlib.sha256(json.dumps(terms, separators=(",", ":"), ensure_ascii=False)
                                      .encode()).hexdigest() if terms else None
        for term, count in terms:
            bucket, sign = projection(term)
            matrix[index, bucket % dimension] += sign * (1 + np.log(count)) * idf[term]
        metadata.append({
            "family_id": int(family),
            "representative_element_id": min(element for element, _ in groups[family]),
            "element_count": len(groups[family]),
            "term_count": len(terms),
            "unprojected_feature_sha256": fingerprint,
        })
    norms = np.linalg.norm(matrix, axis=1)
    active = norms > 0
    matrix[active] /= norms[active, None]
    return ids, matrix, active, metadata, len(document_frequency)


def device_score(cp, kernel, data, begin, rows):
    n, dimension = data.shape
    scores = cp.empty((rows, n), dtype=cp.float32)
    kernel(((n + 15) // 16, (rows + 15) // 16), (16, 16),
           (data, scores, np.int32(n), np.int32(dimension), np.int32(begin), np.int32(rows)))
    return scores


def ranked_neighbors(cp, scores, index, active, top_k):
    count = scores.shape[1]
    scores[~active[index], :] = -cp.inf
    scores[:, ~active] = -cp.inf
    rows = cp.arange(len(index), dtype=cp.int32)
    scores[rows, index] = -cp.inf
    # Preserve score order, then resolve exact float32 ties by existing ascending ID order.
    bits = scores.view(cp.uint32)
    ordered = bits ^ cp.where(bits & cp.uint32(0x80000000),
                              cp.uint32(0xFFFFFFFF), cp.uint32(0x80000000))
    priority = (ordered.astype(cp.uint64) << 32) | (np.uint64(count) - cp.arange(count, dtype=cp.uint64))
    indices = cp.empty((len(index), top_k), dtype=cp.int32)
    values = cp.empty((len(index), top_k), dtype=cp.float32)
    for rank in range(top_k):
        chosen = cp.argmax(priority, axis=1)
        indices[:, rank] = chosen
        values[:, rank] = scores[rows, chosen]
        priority[rows, chosen] = 0
    return indices.get(), values.get()


def benchmark(cp, kernel, matrix):
    rows = min(2048, len(matrix))
    sample = np.ascontiguousarray(matrix[np.linspace(0, len(matrix) - 1, rows, dtype=int)])
    cp.cuda.Stream.null.synchronize()
    bench_started = perf_counter()
    device = cp.asarray(sample)
    start, finish = cp.cuda.Event(), cp.cuda.Event()
    start.record()
    values = device_score(cp, kernel, device, 0, rows)
    finish.record()
    finish.synchronize()
    gpu_ms = cp.cuda.get_elapsed_time(start, finish)
    observed = values.get()
    gpu_total = perf_counter() - bench_started
    cpu_started = perf_counter()
    expected = sample @ sample.T
    cpu_seconds = perf_counter() - cpu_started
    error = np.abs(expected - observed)
    close = bool(np.allclose(expected, observed, atol=2e-5, rtol=2e-5))
    if not close:
        raise RuntimeError("GPU cosine failed NumPy parity")
    return {
        "families": rows, "score_cells": rows**2, "numpy_score_seconds": cpu_seconds,
        "gpu_kernel_seconds": gpu_ms / 1000, "gpu_transfer_inclusive_seconds": gpu_total,
        "numpy_over_transfer_inclusive_ratio": cpu_seconds / gpu_total,
        "max_absolute_score_difference": float(error.max()), "numpy_parity": close,
        "threshold_mask_disagreements": {
            str(t): int(np.count_nonzero((expected >= t) != (observed >= t))) for t in THRESHOLDS
        },
    }


def matrix_scan(cp, kernel, matrix, active, tile_rows, top_k):
    n = len(matrix)
    memory = cp.get_default_memory_pool()
    uploaded = cp.asarray(matrix)
    gpu_active = cp.asarray(active)
    live_columns = cp.arange(n, dtype=cp.int32)
    ranks = np.empty((n, top_k), dtype=np.int32)
    values = np.empty((n, top_k), dtype=np.float32)
    totals = np.zeros(len(THRESHOLDS), dtype=np.int64)
    score_seconds = 0.0
    peak_pool = memory.total_bytes()
    for begin in range(0, n, tile_rows):
        step = min(tile_rows, n - begin)
        index = cp.arange(begin, begin + step, dtype=cp.int32)
        start, finish = cp.cuda.Event(), cp.cuda.Event()
        start.record()
        scores = device_score(cp, kernel, uploaded, begin, step)
        finish.record()
        cp.clip(scores, -1, 1, out=scores)
        upper = gpu_active[index, None] & gpu_active[None, :] & (index[:, None] < live_columns)
        counts = cp.stack([cp.count_nonzero((scores >= threshold) & upper) for threshold in THRESHOLDS])
        totals += counts.get()
        ranks[begin:begin+step], values[begin:begin+step] = ranked_neighbors(
            cp, scores, index, gpu_active, top_k)
        score_seconds += cp.cuda.get_elapsed_time(start, finish) / 1000
        peak_pool = max(peak_pool, memory.total_bytes())
        del scores, upper, counts
    return ranks, values, totals, score_seconds, peak_pool


def sparse_components(ids, target, values, limit):
    count, top_k = target.shape
    start = np.repeat(np.arange(count), top_k)
    end = target.ravel()
    good = np.isfinite(values.ravel()) & (values.ravel() >= limit)
    graph = coo_matrix((np.ones(np.count_nonzero(good), dtype=np.uint8),
                       (start[good], end[good])), shape=(count, count)).tocsr()
    _, components = connected_components(graph, directed=False)
    size = np.bincount(components)
    rep = np.full(len(size), np.iinfo(np.int64).max, dtype=np.int64)
    np.minimum.at(rep, components, ids)
    return (pa.table({
        "family_id": ids, "component_representative_family_id": rep[components],
        "component_size": size[components],
    }), {"threshold": limit, "non_singleton_components": int((size > 1).sum()),
         "families_in_non_singleton_components": int(size[size > 1].sum()),
         "retained_directed_edges": int(good.sum())})


def neighbor_table(ids, target, values):
    count, top_k = target.shape
    row = np.repeat(ids, top_k)
    cols = ids[target.ravel()]
    scores = values.ravel()
    order = np.tile(np.arange(1, top_k + 1, dtype=np.int16), count)
    enabled = np.isfinite(scores)
    return pa.table({"family_id": row[enabled], "neighbor_family_id": cols[enabled],
                     "cosine": scores[enabled], "rank": order[enabled]})


def analyse(input_path, output, dimension, tile_rows, requested_top):
    import cupy as cp

    if output.exists():
        raise ValueError("Choose a new immutable output directory")
    if not (dimension % 16 == 0 and 16 <= dimension <= 4096
            and 16 <= tile_rows <= 512 and 1 <= requested_top <= 64):
        raise ValueError("Invalid feature dimension, tile size or neighbor count")
    digest = sha256_file(input_path)
    started = perf_counter()
    groups, elements = read_features(input_path)
    ids, matrix, active, metadata, unique_terms = representations(groups, dimension)
    if len(ids) < 2 or np.count_nonzero(active) < 2:
        raise ValueError("At least two nonempty families are required")
    encode_seconds = perf_counter() - started
    if digest != sha256_file(input_path):
        raise ValueError("Feature input changed during processing")
    memory_free, memory_total = cp.cuda.runtime.memGetInfo()
    estimated_memory = matrix.nbytes + tile_rows * len(ids) * 40
    if estimated_memory > memory_free // 2:
        raise MemoryError("Tile and feature estimate exceeds half available VRAM")
    kernel = cp.RawKernel(COSINE_CUDA, "cosine")
    warm = cp.asarray(matrix[:16])
    device_score(cp, kernel, warm, 0, len(warm))
    cp.cuda.Stream.null.synchronize()
    bench = benchmark(cp, kernel, matrix)
    cp.get_default_memory_pool().free_all_blocks()
    top_k = min(requested_top, len(ids) - 1)
    start = perf_counter()
    ranks, values, totals, score_seconds, pool_peak = matrix_scan(
        cp, kernel, matrix, active, tile_rows, top_k)
    wall_scan = perf_counter() - start
    clusters, cluster_counts = sparse_components(ids, ranks, values, 0.92)
    neighbors = neighbor_table(ids, ranks, values)
    counts = Counter(row["unprojected_feature_sha256"] for row in metadata
                     if row["unprojected_feature_sha256"] is not None)
    n = len(ids)
    evaluated = int(np.count_nonzero(active))
    summary = {
        "schema": "vedic.family-similarity.v1", "feature_method": POLICY,
        "feature_sha256": digest, "families": n, "nonempty_families": evaluated, "elements": elements,
        "unique_input_terms": unique_terms, "dimensions": dimension, "tile_rows": tile_rows,
        "neighbors_per_family_cap": top_k, "neighbor_rows": neighbors.num_rows,
        "computed_gpu_score_cells_including_diagonal_and_empty": n * n,
        "ordered_nonself_nonempty_comparisons": evaluated * (evaluated - 1),
        "unique_nonself_nonempty_pairs": evaluated * (evaluated - 1) // 2,
        "threshold_totals_unique_unordered": {str(k): int(v) for k, v in zip(THRESHOLDS, totals, strict=True)},
        "families_with_multiple_producer_elements": sum(len(rows) > 1 for rows in groups.values()),
        "equal_unprojected_feature_buckets": sum(count > 1 for count in counts.values()),
        "families_in_equal_unprojected_feature_buckets": sum(count for count in counts.values() if count > 1),
        "feature_and_normalization_seconds": encode_seconds, "gpu_score_kernel_seconds": score_seconds,
        "scan_wall_seconds": wall_scan,
        "ordered_valid_comparisons_per_scan_second": evaluated * (evaluated - 1) / wall_scan,
        "observed_cupy_pool_bytes_including_cached_blocks": pool_peak,
        "gpu_vram_free_before_bytes": memory_free, "gpu_vram_total_bytes": memory_total,
        "benchmark": bench, "graph": cluster_counts,
        "limits": [
            "Family IDs come from input. Equal token/count fingerprints are not equal source bytes.",
            "All dot products are exhaustive at the chosen projected float32 representation.",
            "Projection collisions and recorded runtime context can change relationships.",
            "Sparse connected components use retained neighbors, and transitive membership is not equivalence.",
            "Benchmarked fixed feature scoring, not source extraction, English, or program execution.",
        ],
    }
    output.parent.mkdir(parents=True, exist_ok=True)
    with tempfile.TemporaryDirectory(prefix=".family-sim-", dir=output.parent) as temp:
        staged = Path(temp) / "release"
        staged.mkdir()
        tables = {"families": pa.Table.from_pylist(metadata),
                  "neighbors": neighbors, "clusters": clusters}
        for name, table in tables.items():
            pq.write_table(table, staged / f"{name}.parquet", compression="zstd")
        summary["artifacts"] = {
            path.name: {"sha256": sha256_file(path), "bytes": path.stat().st_size}
            for path in sorted(staged.glob("*.parquet"))
        }
        (staged / "manifest.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
        os.rename(staged, output)
    return summary


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("input", type=Path)
    parser.add_argument("output", type=Path)
    parser.add_argument("--dimensions", type=int, default=1024)
    parser.add_argument("--tile", type=int, default=192)
    parser.add_argument("--top-k", type=int, default=12)
    args = parser.parse_args()
    print(json.dumps(analyse(args.input, args.output, args.dimensions, args.tile, args.top_k), indent=2))


if __name__ == "__main__":
    main()

VEDIC Family Similarity Review

A Python command-line tool in the tools folder that reads repeat elements and drift leads, using SHA-256.

storagevedic- / tools/family_similarity_review.py · lines 1–187 of 187 · Entry point · pattern scores (shared by 2 files)

What it does
It loads repeat elements and drift leads. Defines 7 functions or classes, including audit_index, sparse_reviews, scores, weighted, drift_leads. Uses libraries argparse, collections, hashlib, json, math. 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).
Inputs & outputs
In: Parquet file repeat-elements.parquet; Parquet file drift-leads.parquet; SQLite database; command-line arguments.
Downstream impact
It is itself an entry point (Python CLI); no other file was found loading it.
What it achieves
It audits index (`audit_index`) and is built from the sparse reviews helper (`sparse_reviews`) and the scores step (`scores`). Verify source-index totals and audit selected cosine leads in the original sparse feature space. It accepts `--database`, `--library` and `--features`.
Why it matters
No other file in the estate was found to import it; it is an entry point.
Application
vedic- · tools · Python CLI
Uses
VEDIC Family Similarity (import), argparse, collections, hashlib, json, math, pathlib, re, sqlite3
Used by
none found
Produces
audit_index, sparse_reviews, drift_leads, cpu_threshold_replay, main
Defines here
audit_index, sparse_reviews, scores, weighted, drift_leads, cpu_threshold_replay, main
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/family_similarity_review.py:1-187 · blob 646b5462d36afd552e44aeb7c78df0ae525199bf · 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
"""Verify source-index totals and audit selected cosine leads in the original sparse feature space."""

import argparse
from collections import Counter, defaultdict
import hashlib
import json
import math
from pathlib import Path
import re
import sqlite3

import pyarrow as pa
import pyarrow.parquet as pq


LEXICAL = {"pair", "op", "id", "literal", "symbol"}
STRUCTURAL = {"ast", "kind", "lang", "need", "needs", "dep", "signature", "param", "refusal"}
STAMP = re.compile(r"(^|[^0-9])\d{8}(\d{4})?(?=[^0-9]|$)")


def audit_index(database, library, repeat_output):
    with sqlite3.connect(database.resolve().as_uri() + "?mode=ro&immutable=1", uri=True) as db:
        counts = {table: db.execute(f'SELECT count(*) FROM "{table}"').fetchone()[0]
                  for table in ("line", "scan", "commit_info", "element", "family", "tablet", "occurrence")}
        counts["repos_with_occurrence_rows"] = db.execute(
            "SELECT count(DISTINCT repo) FROM occurrence").fetchone()[0]
        counts["families_with_elements"] = db.execute(
            "SELECT count(DISTINCT family) FROM element").fetchone()[0]
        lineages = defaultdict(set)
        elements = defaultdict(set)
        occurrences = Counter()
        places = db.execute("""
          SELECT e.family,e.n,te.first,o.repo,o.path FROM tablet_element te
          JOIN element e ON e.n=te.element JOIN occurrence o ON o.tablet=te.tablet
          JOIN scan s ON s.repo=o.repo AND s.commit_sha=o.commit_sha
        """)
        element_counts = Counter()
        for family, element, _, repo, path in places:
            lineage = (repo, STAMP.sub(r"\1{stamp}", path))
            lineages[family].add(lineage)
            elements[family, element].add(lineage)
            occurrences[family] += 1
            element_counts[family, element] += 1
        counts["current_head_families_with_places"] = len(lineages)
        counts["families_across_multiple_current_file_lineages"] = sum(
            len(paths) >= 2 for paths in lineages.values())
        counts["only_same_lineage_multiple_current_places"] = sum(
            occurrences[family] >= 2 and len(paths) == 1 for family, paths in lineages.items())
        rows = [{"family_id": family, "element_id": element, "current_file_lineages": len(paths),
                 "current_places": element_counts[family,element]}
                for (family,element),paths in sorted(elements.items()) if len(paths) >= 2]
        counts["exact_producer_element_ids_across_multiple_current_file_lineages"] = len(rows)
        pq.write_table(pa.Table.from_pylist(rows), repeat_output, compression="zstd")
    text = library.read_text(encoding="utf-8")
    counts["compiled_function_candidates_in_library"] = len(re.findall(r"(?m)^// Family #\d+ · element #\d+", text))
    counts["compiled_js_exports_behind_family_comments"] = len(re.findall(r"(?m)^export const f\d+_", text))
    return counts


def sparse_reviews(feature_file, neighbors, witness):
    families = defaultdict(Counter)
    for batch in pq.ParquetFile(feature_file).iter_batches(columns=["family_id", "tokens"]):
        for row in batch.to_pylist():
            families[row["family_id"]] |= Counter(row["tokens"])
    source = json.loads(witness.read_bytes())
    pairs = {(x["families"][0], x["families"][1]) for x in source["pairs"]}
    ids = sorted({item for pair in pairs for item in pair})
    df = Counter(term for doc in families.values() for term in doc)
    presence = defaultdict(lambda: None)
    edge = pq.read_table(neighbors, filters=[("family_id", "in", ids)],
                         columns=["family_id", "neighbor_family_id", "cosine", "rank"])
    for row in edge.to_pylist():
        presence[row["family_id"],row["neighbor_family_id"]] = (
            row["cosine"], row["rank"])

    def scores(left, right, prefixes=None):
        def weighted(doc):
            return {term: (1 + math.log(count)) * (1 + math.log((1+len(families))/(1+df[term])))
                    for term,count in doc.items()
                    if prefixes is None or term.split(":",1)[0] in prefixes}
        a, b = weighted(families[left]), weighted(families[right])
        denominator = math.sqrt(sum(x*x for x in a.values()) * sum(x*x for x in b.values()))
        return sum(a[k]*b[k] for k in a.keys() & b.keys()) / denominator if denominator else None

    return [{**row,
             "projected_retained_forward_score_rank": presence[*row["families"]],
             "projected_retained_reverse_score_rank": presence[*reversed(row["families"])],
             "exact_sparse_all_terms_tfidf": scores(*row["families"]),
             "exact_sparse_lexical_tfidf": scores(*row["families"], LEXICAL),
             "exact_sparse_structural_tfidf": scores(*row["families"], STRUCTURAL)}
            for row in source["pairs"]]


def drift_leads(feature_file, neighbors, output):
    labels = defaultdict(set)
    broad = {"default", "constructor", "anonymous", "render", "update", "start", "main", "init",
             "getvalue", "callback", "cleanup", "normalize", "normalise", "validate"}
    for batch in pq.ParquetFile(feature_file).iter_batches(columns=["family_id", "symbol"]):
        for row in batch.to_pylist():
            name = (row["symbol"] or "").casefold()
            if name not in broad and re.fullmatch(r"[a-z_$][a-z0-9_$]{3,}", name):
                labels[row["family_id"]].add(name)
    candidates = {}
    for row in pq.read_table(neighbors, filters=[("cosine", ">=", 0.92)],
                             columns=["family_id", "neighbor_family_id", "cosine"]).to_pylist():
        left, right = sorted((row["family_id"], row["neighbor_family_id"]))
        matching = labels[left] & labels[right]
        if matching:
            candidates[left, right] = max(candidates.get((left, right), 0), row["cosine"])
    rows = [{"family_a": left, "family_b": right, "shared_symbol": sorted(labels[left] & labels[right]),
             "cosine": score} for (left, right), score in sorted(candidates.items())]
    schema = pa.schema([("family_a", pa.int64()), ("family_b", pa.int64()),
                        ("shared_symbol", pa.list_(pa.string())), ("cosine", pa.float32())])
    pq.write_table(pa.Table.from_pylist(rows, schema=schema), output, compression="zstd")
    return len(rows)


def cpu_threshold_replay(features, dimension=1024, tile=256):
    import os
    from time import perf_counter
    import numpy as np
    from family_similarity import THRESHOLDS, read_features, representations

    start = perf_counter()
    groups, _ = read_features(features)
    ids, matrix, active, _, _ = representations(groups, dimension)
    prep = perf_counter() - start
    counts = np.zeros(len(THRESHOLDS), dtype=np.int64)
    labels = np.arange(len(ids))
    seconds = 0.0
    outer = perf_counter()
    for begin in range(0, len(ids), tile):
        stop = min(begin + tile, len(ids))
        started = perf_counter()
        scores = matrix[begin:stop] @ matrix.T
        seconds += perf_counter() - started
        eligible = active[begin:stop, None] & active[None, :] & (labels[begin:stop, None] < labels)
        for index, limit in enumerate(THRESHOLDS):
            counts[index] += np.count_nonzero((scores >= limit) & eligible)
    return {
        "families": len(ids), "dimension": dimension, "row_tile": tile, "score_cells": len(ids)**2,
        "observed_openblas_threads_setting": os.environ.get("OPENBLAS_NUM_THREADS"),
        "feature_prep_seconds": prep, "score_only_seconds": seconds,
        "scoring_and_threshold_reduction_seconds": perf_counter() - outer,
        "threshold_totals_unique_unordered": {str(t): int(c) for t,c in zip(THRESHOLDS, counts, strict=True)},
        "scope": "Same float32 feature representation and threshold reduction. CPU replay omits top-k sorting.",
    }


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--database", type=Path, required=True)
    parser.add_argument("--library", type=Path, required=True)
    parser.add_argument("--features", type=Path, required=True)
    parser.add_argument("--neighbors", type=Path, required=True)
    parser.add_argument("--witness", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    parser.add_argument("--cpu-replay", action="store_true")
    args = parser.parse_args()
    args.output.mkdir(parents=True, exist_ok=False)
    repeat_output = args.output / "repeat-elements.parquet"
    values = audit_index(args.database, args.library, repeat_output)
    pairs = sparse_reviews(args.features, args.neighbors, args.witness)
    drift_output = args.output / "drift-leads.parquet"
    drift_count = drift_leads(args.features, args.neighbors, drift_output)
    with repeat_output.open("rb") as stream:
        digest = hashlib.file_digest(stream, "sha256").hexdigest()
    report = {
        "inventory": values, "canonical_relationships_checked": len(pairs), "relationships": pairs,
        "repeat_elements_sha256": digest, "repeat_elements_bytes": repeat_output.stat().st_size,
        "same_symbol_different_family_drift_leads_at_0_92": drift_count,
        "drift_leads_bytes": drift_output.stat().st_size,
        "drift_leads_sha256": hashlib.sha256(drift_output.read_bytes()).hexdigest(),
        "cpu_replay": cpu_threshold_replay(args.features) if args.cpu_replay else None,
        "notes": [
            "Repeated elements represent the same existing producer element identity across separately normalised current file lineages.",
            "The compiled-library count is source availability and parse admission, separate from verified executions.",
            "Sparse exact here means no hash projection in the selected feature vectors. Tokenisation can still omit or truncate context.",
            "Null projected score means the pair was outside the retained directed top-k; it does not imply a zero score.",
        ],
    }
    (args.output / "manifest.json").write_text(json.dumps(report, indent=2)+"\n", encoding="utf-8")
    print(json.dumps(report, indent=2))


if __name__ == "__main__":
    main()

VEDIC Family Similarity Witness

A JavaScript module in the tools folder using data from the GlobalGrid2050 repository. It is built from the git raw helper (`gitRaw`) and the git blob helper (`gitBlob`).

rendervedic- / tools/family_similarity_witness.mjs · lines 1–76 of 76 · Not reached from any entry point (candidate for review) · pattern extract (shared by 8 files)

What it does
It fetches data. Defines gitRaw, gitBlob, extract. Uses libraries node:assert/strict, node:child_process, node:crypto, node:vm. Side effects: changes the web page (DOM); makes network requests; starts processes.
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).
Inputs & outputs
In: data source: globalgrid2050 data.
What it achieves
Defines `gitRaw`, `gitBlob` and `extract`.
Why it matters
No other file in the estate was found to import it.
Application
vedic- · tools · JavaScript module
Uses
node:assert/strict, node:child_process, node:crypto, node:vm
Used by
none found
Produces
gitRaw, gitBlob, extract
Defines here
gitRaw, gitBlob, extract
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
vedic-@1c95ee78c2dd3f1f72c0fd5a5f6e247aaf1624e0 tools/family_similarity_witness.mjs:1-76 · blob 5ad41d8722141434d6efd248cf5598da2c7d9b1c · GitHub at these lines
State
achieves: name · context: readme_derived · stage: output · effects: dom, network, process · domain stage: agent_infra · users: ai_agent · canonical: unreached_review
import assert from 'node:assert/strict';
import {execFileSync} from 'node:child_process';
import {createHash} from 'node:crypto';
import vm from 'node:vm';

const atlas='afffa9781f6130529ae93052604cd3d98d172a35';
const engine='7c2a7b42905674fdcd3aa4bb50af14bc352a7747';
const a='E:/VEDIC/offline/gridatlas', e='E:/VEDIC/offline/ventus-grid-engine';
const modulePath='atlas/modules/202609011950-geodesy.js';
const sandboxPath='atlas/cartridges/202609012045-sld-sandbox-v9-8.js';
function gitRaw(repo,commit,path) {
 return execFileSync('git',['--no-replace-objects','-C',repo,'cat-file','blob',commit+':'+path]);
}
const gitBlob=r=>createHash('sha1').update('blob '+r.length+'\0').update(r).digest('hex');
function extract(raw,start,end,name,constants={}){
 const code=raw.toString('utf8').split(/\r?\n/).slice(start-1,end).join('\n').replace(/^export /,'');
 assert.match(code,new RegExp('function\\s+'+name+'\\('));
 return vm.runInNewContext(code+'\n'+name,constants,{timeout:1000});
}
const canonical=gitRaw(a,atlas,modulePath), sandbox=gitRaw(a,atlas,sandboxPath);
const oldEngine=gitRaw(e,engine,'engine/v9-geodesy.js');
const constants={DEG:Math.PI/180,EARTH_RADIUS_KM:6378.137,R_ATLAS:6378.137};
const pairs=[];
const dist=extract(canonical,24,42,'distanceKm',constants);
const historicalDist=extract(sandbox,36,42,'distanceKm',constants);
let diff;
for(let i=1;i<100&&!diff;i++){
 const args=[-2,53,-2+i/2048,53+i/4096];
 const x=dist(...args),y=historicalDist(...args);
 if(!Object.is(x,y))diff={coordinates:args,canonical_km:x,variant_km:y};
}
assert.ok(diff);
pairs.push({families:[511,32987],classification:'numerical_drift',evidence:diff});
const dest=extract(oldEngine,121,131,'destinationPoint',constants);
const oldDest=extract(sandbox,3631,3641,'destinationPoint',constants);
const templateCases=[[0,0,0,0],[-2,53,115,45],[178,30,350,90]];
for(const args of templateCases)assert.deepEqual(Array.from(dest(...args)),Array.from(oldDest(...args)));
pairs.push({families:[8769,33124],classification:'bounded_sample_parity',cases:templateCases.length,
            evidence:'Equal constants and same observed outputs on zero-distance, ordinary and date-line cases.'});
const ref='2f4b7cb82ee154fa3c684cba634d45f2183c6e7d';
const remotePath='pipelinenews_intelligence/202608311558/assets/202608311558-grid-proximity.mjs';
const remote=await fetch('https://raw.githubusercontent.com/Ventusltd/globalgrid2050/'+ref+'/'+remotePath);
assert.ok(remote.ok);
const proximity=Buffer.from(await remote.arrayBuffer());
assert.equal(gitBlob(proximity),'c275c42a00b0ea40c33b4e03440f1b97c0c0bd54');
const bearing=extract(canonical,128,134,'initialBearingDeg',constants);
const other=extract(proximity,591,597,'bearingDeg');
for(const args of [[-2,53,-1,54],[0,0,-1,0],[178,31,-179,31],[1,2,1,2]])assert.equal(bearing(...args),other(...args));
pairs.push({families:[8770,1936],classification:'bounded_sample_parity',cases:4,
            evidence:'Same degree convention and equal tested ordinary, westward, date-line and coincident results.'});
const byFamilyFiles=[
 [80283, 'engine/electrification-demand.js',126,136,'averagePowerGw'],
 [80271, 'engine/diversified-demand.js',134,153,'averageOverWindowGw'],
 [80284, 'engine/electrification-demand.js',144,158,'peakFromLoadFactorGw'],
 [80285, 'engine/electrification-demand.js',166,182,'loadFactorFromPeak']
];
const modules={};
for(const name of new Set(byFamilyFiles.map(x=>x[1]))){
 const raw=gitRaw(e,engine,name);
 assert.ok(!/^\s*import\s/m.test(raw.toString()));
 modules[name]=await import('data:text/javascript;base64,'+raw.toString('base64'));
}
const demand=modules['engine/electrification-demand.js'],window=modules['engine/diversified-demand.js'];
assert.equal(demand.averagePowerGw({annualTwh:8.76}).value,window.averageOverWindowGw({annualTwh:8.76,windowHoursPerDay:24}).value);
assert.equal(window.averageOverWindowGw({annualTwh:8.76,windowHoursPerDay:12}).value,2);
pairs.push({families:[80283,80271],classification:'conditional_variant',cases:2, evidence:'Equal when the window is 24 hours, distinct at 12 hours.'});
assert.equal(demand.peakFromLoadFactorGw({averageGw:7,loadFactor:.5}).value,14);
assert.equal(demand.loadFactorFromPeak({averageGw:7,peakGw:14}).value,.5);
pairs.push({families:[80284,80285],classification:'distinct_inverse_contracts',cases:2, evidence:'One returns peak power in GW, the other returns a dimensionless load factor.'});
const c=[-2,53,-1,54];
assert.ok(dist(...c)>0 && bearing(...c)>=0 && bearing(...c)<360);
pairs.push({families:[511,8770],classification:'complementary_not_interchangeable',
            evidence:'Same two positions yield two distinct quantities, distance in kilometres and initial bearing in degrees.'});
console.log(JSON.stringify({snapshot:"family-similarity canonical witness v1",pairs,
          blob_map:{[modulePath]:gitBlob(canonical),[sandboxPath]:gitBlob(sandbox),
            'engine/v9-geodesy.js':gitBlob(oldEngine),[remotePath]:gitBlob(proximity)}},null,2));