GLOBALGRID2050 / EXPLORE CODE

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

Test Candidates and 1 more file

A test in the fingerprints folder of VEDIC that checks Candidates, using SHA-256 and haversine. It writes units (`write_units`), sets up (`setUp`) and runs pipeline (`run_pipeline`).

474 lines of Python from vedic-, in 2 files. Topic: AI agents and coordination. Section 1669 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. Test Candidates test · vedic- / fingerprints/test_candidates.py lines 1–295
  2. Test Enrich test · vedic- / fingerprints/test_enrich.py lines 1–179

Test Candidates

A test in the fingerprints folder of VEDIC that checks Candidates, using SHA-256 and haversine. It writes units (`write_units`), sets up (`setUp`) and runs pipeline (`run_pipeline`).

testvedic- / fingerprints/test_candidates.py · lines 1–295 of 295 · Entry point · pattern run_pipeline (shared by 2 files)

What it does
It tests its inputs. Defines 21 functions or classes, including minhash, near, unit, synthetic, write_units. Uses libraries copy, hashlib, json, pathlib, random. 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: JSON file rules.json; Parquet file units.parquet; JSON file dictionary.json; Parquet file candidates.parquet; JSON file clusters-summary.json.
Downstream impact
Used directly by 1 file: VEDIC Fingerprints Workflow (vedic-).
What it achieves
Offline tests for `candidates.py` on a small synthetic units table. It reads `candidates.parquet`.
Why it matters
Run by VEDIC Fingerprints Workflow.
Application
vedic- · fingerprints · test
Uses
Candidates (import), copy, hashlib, json, pathlib, random, sys, tempfile, unittest
Used by
run by VEDIC Fingerprints Workflow (workflow run)
Produces
minhash, near, unit, synthetic, write_units, CandidatesTest
Defines here
minhash, near, unit, synthetic, write_units, CandidatesTest, setUp, tearDown, run_pipeline, by_name, test_exact_and_near_clustering, test_gating_from_rules, test_stop_names_and_min_tokens_excluded, test_verb_suggestion, test_already_vedic_and_drafts, test_noise_filters, test_lsh_determinism_and_cluster_ids, test_runs_ledger_appended_once_per_run, test_dictionary_word_preferred, test_chained_cluster_is_split, test_sibling_clusters
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/test_candidates.py:1-295 · blob afd0b23dd052edf161e7cb72f65ebf885241a999 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""Offline tests for candidates.py on a small synthetic units table."""

import copy
import hashlib
import json
from pathlib import Path
import random
import sys
import tempfile
import unittest

import pyarrow as pa
import pyarrow.parquet as pq

sys.path.insert(0, str(Path(__file__).resolve().parent))
import candidates as C  # noqa: E402

RULES_PATH = Path(__file__).resolve().parent / "rules.json"


def minhash(seed):
    rng = random.Random(seed)
    return [rng.randrange(2**32) for _ in range(64)]


def near(values, changed, seed=99):
    """Copy of a MinHash with `changed` positions replaced (estimated Jaccard = 1 - changed/64)."""
    rng = random.Random(seed)
    out = list(values)
    for pos in rng.sample(range(64), changed):
        out[pos] = (out[pos] + 1 + rng.randrange(1000)) % 2**32
    return out


def unit(repo, name, mh, struct, line=1, **extra):
    uid = hashlib.sha256(f"{repo}@{'a' * 40}:src/{name}.js:{line}-{line + 9}".encode()).hexdigest()[:16]
    row = {
        "schema": "vedic-fingerprint-units-v1", "unit_id": uid, "repo": repo, "commit": "a" * 40,
        "path": f"src/{name}.js", "blob": "b" * 40, "lang": "javascript", "kind": "function",
        "name": name, "params": ["lat1", "lon1", "lat2", "lon2"], "line_from": line,
        "line_to": line + 9, "n_lines": 10, "n_tokens": 80, "exact_hash": "e" * 64,
        "struct_hash": struct, "minhash": mh, "doc": "", "calls": [], "unit_terms": ["km", "lat"],
        "side_effects": [], "pure": True,
    }
    row.update(extra)
    return row


HAV = minhash(1)
CLAMP = minhash(2)


def synthetic():
    rows = [
        # Exact group (same struct_hash) across three repos.
        unit("gridatlas", "distanceKm", HAV, "s-hav", doc="Great-circle distance in km. Uses haversine."),
        unit("satnav", "distanceKm", HAV, "s-hav", line=20),
        unit("engine", "haversine", HAV, "s-hav", line=40),
        # Near duplicate of the haversine group (60/64 equal -> 0.94).
        unit("pipelinenews", "distanceKm", near(HAV, 4), "s-hav2"),
        # Clamp group: three units, two repos, no doc, no unit terms.
        unit("gridatlas", "clampValue", CLAMP, "s-clamp", line=60, params=["v", "lo", "hi"], unit_terms=[]),
        unit("satnav", "clampValue", near(CLAMP, 2, 5), "s-clamp2", line=60, params=["v", "lo", "hi"], unit_terms=[]),
        unit("satnav", "clampValue", CLAMP, "s-clamp", line=80, params=["v", "lo", "hi"], unit_terms=[]),
        # Far from everything (only 50% equal to HAV): must stay separate.
        unit("engine", "distanceMiles", near(HAV, 32, 7), "s-far", line=90),
        # Stop names and too small units.
        unit("a", "main", minhash(3), "s-main"), unit("b", "main", minhash(3), "s-main"),
        unit("c", "main", minhash(3), "s-main"),
        unit("a", "tiny", minhash(4), "s-tiny", n_tokens=10), unit("b", "tiny", minhash(4), "s-tiny", n_tokens=10),
        unit("c", "tiny", minhash(4), "s-tiny", n_tokens=10),
        # Single-repo recurrence: fails min_repos.
        unit("solo", "solo", minhash(6), "s-solo", line=1), unit("solo", "solo", minhash(6), "s-solo", line=30),
        unit("solo", "solo", minhash(6), "s-solo", line=60),
        # Impure group: fails require_pure_share.
        *[unit(r, "fetchJson", minhash(8), "s-fetch", side_effects=["network"], pure=False)
          for r in ("a", "b", "c")],
        # Callers of distanceKm.
        unit("ui", "showRoute", minhash(10), "s-ui", calls=["distanceKm", "format"]),
    ]
    return rows


def write_units(rows, directory):
    path = Path(directory) / "units.parquet"
    pq.write_table(pa.Table.from_pylist(rows), path)
    return path


DICTIONARY = {"schema": "vedic.dictionary.v1", "entries": [
    {"number": 1, "word": "MEASURE", "translation_ref": "geodesy:distanceKm"},
    {"number": 2, "word": "ORIENT", "translation_ref": None},
    {"number": 3, "word": "OTHER", "translation_ref": "x:clampNumber"},
]}


class CandidatesTest(unittest.TestCase):
    def setUp(self):
        self.temp = tempfile.TemporaryDirectory()
        self.dir = Path(self.temp.name)
        self.rules = C.load_rules(RULES_PATH)
        self.dictionary = self.dir / "dictionary.json"
        self.dictionary.write_text(json.dumps(DICTIONARY))

    def tearDown(self):
        self.temp.cleanup()

    def run_pipeline(self, rows=None, rules=None):
        units = write_units(rows or synthetic(), self.dir)
        rules_path = RULES_PATH
        if rules is not None:
            rules_path = self.dir / "rules.json"
            rules_path.write_text(json.dumps(rules))
        out = self.dir / "out"
        summary = C.analyse(units, rules_path, self.dictionary, out, ledger=self.dir / "runs.tsv",
                            latest=self.dir / "LATEST.md")
        return summary, pq.read_table(out / "candidates.parquet").to_pylist()

    def by_name(self, rows):
        return {r["names"][0]: r for r in rows}

    def test_exact_and_near_clustering(self):
        _, rows = self.run_pipeline()
        found = self.by_name(rows)
        hav = found["distanceKm"]
        self.assertEqual(hav["size"], 4)  # 3 exact + 1 near duplicate
        self.assertEqual(hav["n_repos"], 4)
        self.assertEqual(hav["names"], ["distanceKm", "haversine"])
        self.assertEqual(found["clampValue"]["size"], 3)
        all_names = {n for r in rows for n in r["names"]}
        self.assertNotIn("distanceMiles", all_names)

    def test_gating_from_rules(self):
        _, rows = self.run_pipeline()
        names = {r["names"][0] for r in rows}
        self.assertNotIn("solo", names)       # min_repos
        self.assertNotIn("fetchJson", names)  # require_pure_share
        self.assertEqual(names, {"distanceKm", "clampValue"})
        rules = copy.deepcopy(self.rules)
        rules["candidate"]["min_units"] = 4
        _, rows = self.run_pipeline(rules=rules)
        self.assertEqual([r["names"][0] for r in rows], ["distanceKm"])
        rules["candidate"]["require_pure_share"] = 0.0
        rules["candidate"]["min_units"] = 3
        _, rows = self.run_pipeline(rules=rules)
        self.assertIn("fetchJson", {r["names"][0] for r in rows})

    def test_stop_names_and_min_tokens_excluded(self):
        summary, rows = self.run_pipeline()
        names = {n for r in rows for n in r["names"]}
        self.assertNotIn("main", names)
        self.assertNotIn("tiny", names)
        self.assertEqual(summary["units_dropped_stop_names"], 3)
        self.assertEqual(summary["units_dropped_below_min_tokens"], 3)
        is_stop = C.stop_matcher(self.rules)
        self.assertTrue(is_stop("__init__"))
        self.assertTrue(is_stop("testHaversine"))
        self.assertTrue(is_stop("onClick"))
        self.assertFalse(is_stop("distanceKm"))
        self.assertFalse(is_stop("testament"))

    def test_verb_suggestion(self):
        self.assertEqual(C.name_pieces("voltageDropVolts"), ["voltage", "drop", "volts"])
        self.assertEqual(C.name_pieces("parse_XMLHeader2"), ["parse", "xml", "header", "2"])
        cases = {"distanceKm": "MEASURE", "getBearing": "BEARING", "voltage_drop": "DROP",
                 "clampValue": "CLAMP", "kmToMiles": "CONVERT", "computeWidget": "WIDGET",
                 "get": ""}
        for name, word in cases.items():
            self.assertEqual(C.suggest_word(name, self.rules)[0], word, name)
        _, rows = self.run_pipeline()
        self.assertEqual(self.by_name(rows)["distanceKm"]["suggested_word"], "MEASURE")

    def test_already_vedic_and_drafts(self):
        _, rows = self.run_pipeline()
        found = self.by_name(rows)
        self.assertEqual(found["distanceKm"]["already_vedic"], "MEASURE")
        self.assertEqual(found["clampValue"]["already_vedic"], "")
        self.assertEqual(found["distanceKm"]["capability_draft"], "Great-circle distance in km.")
        self.assertTrue(found["clampValue"]["capability_draft"].startswith("Computes clamp value from v, lo, hi"))
        self.assertEqual(found["distanceKm"]["import_hint"].split("::")[-1], "distanceKm")
        self.assertEqual(found["distanceKm"]["state"], "CANDIDATE")
        self.assertEqual(found["distanceKm"]["rules_version"], self.rules["rules_version"])
        self.assertGreater(found["distanceKm"]["score"], found["clampValue"]["score"])
        for r in rows:
            self.assertTrue(0 <= r["score"] <= 100)

    def test_noise_filters(self):
        patterns = [__import__("re").compile(r, 2) for r in self.rules["doc_ignore_regex"]]
        self.assertEqual(C.useful_doc("Family #8770 · element #8770 · 40 places", patterns), "")
        self.assertEqual(C.useful_doc("── Geometry ──────────", patterns), "")
        self.assertEqual(C.useful_doc("Great-circle distance.", patterns), "Great-circle distance.")
        self.assertEqual(C.useful_terms(["amp", "km", "a"], self.rules), ["km"])
        one_repo = [unit("r1", "f", HAV, "s", line=i) for i in range(50)]
        spread = [unit(f"r{i}", "f", HAV, "s") for i in range(3)]
        rec = lambda m: C.score_parts(m, 0, False, self.rules)["recurrence"]
        self.assertEqual(rec(one_repo), rec(spread))

    def test_lsh_determinism_and_cluster_ids(self):
        rows = synthetic()
        _, first = self.run_pipeline(rows)
        shuffled = list(rows)
        random.Random(3).shuffle(shuffled)
        _, second = self.run_pipeline(shuffled)
        self.assertEqual(first, second)
        hav = self.by_name(first)["distanceKm"]
        expected = hashlib.sha256("\n".join(sorted(hav["members"])).encode()).hexdigest()[:12]
        self.assertEqual(hav["cluster_id"], expected)
        import numpy as np
        sig = np.array([HAV, near(HAV, 4), CLAMP], dtype=np.uint32)
        self.assertEqual(C.lsh_pairs(sig, 16, 4, 400), C.lsh_pairs(sig, 16, 4, 400))
        self.assertIn((0, 1), C.lsh_pairs(sig, 16, 4, 400))

    def test_runs_ledger_appended_once_per_run(self):
        self.run_pipeline()
        ledger = self.dir / "runs.tsv"
        lines = ledger.read_text().splitlines()
        self.assertEqual(lines[0].split("\t"), list(C.RUNS_HEADER))
        self.assertEqual(len(lines), 2)
        self.run_pipeline()
        lines = ledger.read_text().splitlines()
        self.assertEqual(len(lines), 3)
        fields = lines[2].split("\t")
        self.assertEqual(len(fields), len(C.RUNS_HEADER))
        self.assertEqual(fields[1], self.rules["rules_version"])
        self.assertTrue(fields[0].endswith("+00:00"))
        self.assertTrue((self.dir / "out" / "candidates.md").exists())
        summary = json.loads((self.dir / "out" / "clusters-summary.json").read_text())
        self.assertEqual(summary["rules_sha256"], C.sha256_file(RULES_PATH))

    # ---- v2: dictionary words, chain splitting, siblings
    def test_dictionary_word_preferred(self):
        entries = [
            {"number": 24, "word": "DROP", "translation_ref": "engine:voltage-drop:voltageDropVolts",
             "inputs": ["current_a", "length_m"], "output": "voltage_drop_record"},
            {"number": 25, "word": "PERCENT", "translation_ref": "engine:voltage-drop:dropPercent",
             "inputs": ["drop_volts", "nominal_volts"], "output": "drop_percent"},
        ]
        # Exact translation_ref name wins over the lexicon's first piece.
        self.assertEqual(C.suggest_word("dropPercent", self.rules, ["dropPercent"], entries)[0], "PERCENT")
        # Without an exact name, the entry whose ref/inputs/output share most pieces wins.
        self.assertEqual(C.suggest_word("percentDropVolts", self.rules, None, entries)[0], "PERCENT")
        self.assertEqual(C.suggest_word("voltage_drop", self.rules, None, entries)[0], "DROP")
        # One shared piece is not enough evidence.
        self.assertEqual(C.dictionary_word(["percentile"], entries), "")
        # Bare one-piece names do not identify an entry by name alone.
        self.assertEqual(C.dictionary_word(["apply"], [{"number": 1, "word": "FILTER PROJECTS",
                                                         "translation_ref": "x:apply"}]), "")
        # A leading verb names the action; later lexicon verbs are usually nouns.
        self.assertEqual(C.suggest_word("drawCircle", self.rules)[0], "PRESENT")
        self.assertEqual(C.suggest_word("getDrawCircle", self.rules)[0], "PRESENT")
        self.assertEqual(C.suggest_word("lossLoadFactor", self.rules)[0], "LOSS")
        self.assertEqual(C.suggest_word("heightStore", self.rules)[0], "HEIGHT")
        self.assertEqual(C.suggest_word("kmToMiles", self.rules)[0], "CONVERT")

    def test_chained_cluster_is_split(self):
        base = minhash(21)
        chain = []
        for step in range(7):  # each step changes 10 more positions: neighbours 0.84, two apart 0.69
            sig = list(base)
            for pos in range(10 * step):
                sig[pos] = (base[pos] + 7) % 2**32
            chain.append(sig)
        rows = [unit(f"r{i}", f"chain{i}", sig, f"s-chain{i}", line=1) for i, sig in enumerate(chain)]
        units = [dict(r) for r in rows]
        clusters, stats = C.cluster_units(sorted(units, key=lambda u: u["unit_id"]), self.rules)
        sizes = sorted(len(c) for c in clusters)
        self.assertEqual(stats["clusters_split"], 1)
        self.assertEqual(sizes, [2, 2, 3])
        loose = copy.deepcopy(self.rules)
        loose["cluster"]["split_margin"] = 1.0
        clusters, stats = C.cluster_units(sorted(units, key=lambda u: u["unit_id"]), loose)
        self.assertEqual([len(c) for c in clusters], [7])
        self.assertEqual(stats["clusters_split"], 0)

    def test_sibling_clusters(self):
        other = minhash(31)
        rows = synthetic() + [
            unit(r, "distanceKm", other, "s-other", line=200, params=["a", "b"]) for r in ("x1", "x2", "x3")]
        _, out = self.run_pipeline(rows)
        dist = [r for r in out if r["names"][0] == "distanceKm"]
        self.assertEqual(len(dist), 2)
        self.assertEqual(dist[0]["sibling_clusters"], [dist[1]["cluster_id"]])
        self.assertEqual(dist[1]["sibling_clusters"], [dist[0]["cluster_id"]])
        self.assertEqual(self.by_name(out)["clampValue"]["sibling_clusters"], [])
        # Same top name without a dictionary word: siblings too; a different vedic word: not.
        rows = synthetic() + [
            unit(r, "clampValue", other, "s-other", line=200, params=["a", "b"]) for r in ("x1", "x2", "x3")]
        _, out = self.run_pipeline(rows)
        clamps = [r for r in out if r["names"][0] == "clampValue"]
        self.assertEqual([len(r["sibling_clusters"]) for r in clamps], [1, 1])
        self.assertEqual(self.by_name(out)["distanceKm"]["sibling_clusters"], [])


if __name__ == "__main__":
    unittest.main()

Test Enrich

A test in the fingerprints folder of VEDIC that checks Enrich and Review Page, using haversine.

testvedic- / fingerprints/test_enrich.py · lines 1–179 of 179 · Entry point · pattern tearDown (shared by 38 files)

What it does
It tests its inputs. Defines 11 functions or classes, including cand, EnrichTests, setUp, tearDown, rows. Uses libraries json, os, pathlib, sys, tempfile. 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 units.parquet; Parquet file candidates.parquet; JSON file elements.json; JSON file dictionary.json. Out: JSON file elements.json; JSON file functions.json.
Downstream impact
Used directly by 1 file: VEDIC Fingerprints Workflow (vedic-).
What it achieves
It sets up (`setUp`) and is built from the cand step (`cand`) and the enrich tests class (`EnrichTests`). `enrich.py` and `review_page.py` on small fixtures: proposals only, evidence-ranked, static page. It reads `candidates.parquet`.
Why it matters
Run by VEDIC Fingerprints Workflow.
Application
vedic- · fingerprints · test
Uses
Enrich (import), Review Page (import), json, os, pathlib, sys, tempfile, unittest, pyarrow, pyarrow.parquet
Used by
run by VEDIC Fingerprints Workflow (workflow run)
Produces
cand, EnrichTests
Defines here
cand, EnrichTests, setUp, tearDown, rows, test_elements_keys_by_evidence, test_path_and_name_without_families, test_periodic_proposals, test_without_catalogue_and_rerun, test_review_page, test_review_page_modular_star
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/test_enrich.py:1-179 · blob 8c52851a0826f61e0564614f123c4a76f20949bd · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
"""enrich.py and review_page.py on small fixtures: proposals only, evidence-ranked, static page."""
import json
import os
from pathlib import Path
import sys
import tempfile
import unittest

import pyarrow as pa
import pyarrow.parquet as pq

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import enrich as E  # noqa: E402
import review_page as R  # noqa: E402

C40 = "c" * 40
UNITS = [
    {"unit_id": "u1", "repo": "ventus-grid-engine", "commit": C40, "path": "engine/geo-core.js",
     "name": "distanceKm", "params": ["a", "b"], "line_from": 10, "line_to": 30},
    {"unit_id": "u2", "repo": "gridatlas", "commit": C40, "path": "atlas/parts/202609040400-geo.js",
     "name": "distanceKm", "params": ["a", "b"], "line_from": 5, "line_to": 25},
    {"unit_id": "u3", "repo": "satnav", "commit": C40, "path": "src/nav.js",
     "name": "haversine", "params": ["a", "b"], "line_from": 1, "line_to": 20},
    {"unit_id": "u4", "repo": "engine", "commit": C40, "path": "x/drop.js",
     "name": "voltageDropPercent", "params": ["v", "n"], "line_from": 3, "line_to": 9},
    {"unit_id": "u5", "repo": "other", "commit": C40, "path": "y/drop.js",
     "name": "voltageDropPercent", "params": ["v", "n"], "line_from": 3, "line_to": 9},
    {"unit_id": "u6", "repo": "z1", "commit": C40, "path": "a.js", "name": "legality", "params": [],
     "line_from": 1, "line_to": 9},
    {"unit_id": "u7", "repo": "z2", "commit": C40, "path": "a.js", "name": "legality", "params": [],
     "line_from": 1, "line_to": 9},
]


def cand(cid, members, names, word, vedic="", units_found=(), fams=None, score=90.0):
    row = {"cluster_id": cid, "score": score, "size": len(members), "repos": ["r"], "n_repos": 2,
           "names": names, "suggested_word": word, "already_vedic": vedic,
           "capability_draft": "Great-circle <distance> & more", "units_found": list(units_found),
           "pure_share": 1.0, "import_hint": f"{UNITS[0]['repo']}/{UNITS[0]['path']}::distanceKm",
           "members": members, "rules_version": "test-rules", "state": "CANDIDATE",
           "sibling_clusters": []}
    if fams is not None:
        row["ms_families"] = fams
    return row


ELEMENTS = [
    {"key": "block:Gc", "number": 13, "symbol": "Gc", "category": "geodesy", "kind": "engine",
     "function_keys": ["family:80299"], "repos": ["Ventusltd/ventus-grid-engine"],
     "files": [{"repo": "Ventusltd/ventus-grid-engine", "path": "engine/geo-core.js", "commit": C40}]},
    {"key": "block:Ss", "number": 40, "symbol": "Ss", "category": "cartridges", "kind": "cartridge",
     "function_keys": [], "files": [{"repo": "Ventusltd/gridatlas", "path": "atlas/parts/202501010000-geo.js",
                                     "commit": C40}]},
    {"key": "block:Vd", "number": 50, "symbol": "Vd", "category": "network", "kind": "engine",
     "function_keys": ["family:7"], "files": []},
    {"key": "block:Hx", "number": 60, "symbol": "Hx", "category": "geodesy", "kind": "engine",
     "function_keys": ["family:9"], "files": []},
    {"key": "block:Dz", "number": 70, "symbol": "Dz", "category": "other", "kind": "auto",
     "function_keys": ["family:10"], "files": []},
]
FUNCTIONS = [{"key": "family:80299", "name": "distanceKm"}, {"key": "family:7", "name": "voltageDropPercent"},
             {"key": "family:9", "name": "haversineKm"}, {"key": "family:10", "name": "describe"}]
DICTIONARY = {"entries": [
    {"number": 1, "word": "MEASURE", "translation_ref": "geodesy:distanceKm", "inputs": ["coordinate_pair"],
     "output": "distance_km", "periodic_category": "geodesy", "periodic_block_candidate": "Vg"},
    {"number": 24, "word": "DROP", "translation_ref": "engine:voltage-drop:voltageDropVolts",
     "inputs": ["current_a", "length_m"], "output": "voltage_drop_record",
     "periodic_category": "electrical engineering", "periodic_block_candidate": "Unresolved"},
    {"number": 25, "word": "PERCENT", "translation_ref": "engine:voltage-drop:dropPercent",
     "inputs": ["drop_volts", "nominal_volts"], "output": "drop_percent",
     "periodic_category": "electrical engineering", "periodic_block_candidate": "Unresolved"},
    {"number": 3, "word": "VOLTAGE", "translation_ref": "geodesy:voltagesKv", "inputs": ["voltage_properties"],
     "output": "kilovolt_list", "periodic_category": "geodesy", "periodic_block_candidate": "Vg"},
]}


class EnrichTests(unittest.TestCase):
    def setUp(self):
        self.tmp = tempfile.TemporaryDirectory()
        self.out = Path(self.tmp.name)
        pq.write_table(pa.Table.from_pylist(UNITS), self.out / "units.parquet")
        pq.write_table(pa.Table.from_pylist([
            cand("c1", ["u1", "u2", "u3"], ["distanceKm", "haversineKm", "describe"], "MEASURE", "MEASURE", ["km"], [80299]),
            cand("c2", ["u4", "u5"], ["voltageDropPercent"], "PERCENT", "", ["v"], [], score=70.0),
            cand("c3", ["u6", "u7"], ["legality"], "LEGALITY", "", ["kv", "voltage"], [], score=50.0),
        ]), self.out / "candidates.parquet")
        cat = self.out / "catalogue"
        cat.mkdir()
        (cat / "elements.json").write_text(json.dumps(ELEMENTS))
        (cat / "functions.json").write_text(json.dumps(FUNCTIONS))
        self.elements = cat / "elements.json"
        self.dictionary = self.out / "dictionary.json"
        self.dictionary.write_text(json.dumps(DICTIONARY))

    def tearDown(self):
        self.tmp.cleanup()

    def rows(self):
        return {r["cluster_id"]: r for r in pq.read_table(self.out / "candidates.parquet").to_pylist()}

    def test_elements_keys_by_evidence(self):
        s = E.enrich(self.out, self.dictionary, self.elements, html=False)
        rows = self.rows()
        c1 = rows["c1"]
        # Family identity first, then the path-family (timestamp-masked) cartridge, then name only;
        # a one-piece name (describe) is too common to match an element by name.
        self.assertEqual(list(zip(c1["elements_keys"], c1["elements_evidence"])),
                         [("block:Gc", "family"), ("block:Ss", "path-family"), ("block:Hx", "name")])
        self.assertEqual(list(zip(rows["c2"]["elements_keys"], rows["c2"]["elements_evidence"])),
                         [("block:Vd", "name")])
        self.assertEqual(rows["c3"]["elements_keys"], [])
        self.assertEqual(s["candidates_with_elements"], 2)
        for r in rows.values():
            self.assertEqual(r["enrichment_state"], "PROPOSAL")
            self.assertEqual(r["state"], "CANDIDATE")

    def test_path_and_name_without_families(self):
        rows = [cand("c1", ["u1"], ["distanceKm"], "MEASURE")]
        pq.write_table(pa.Table.from_pylist(rows), self.out / "candidates.parquet")
        E.enrich(self.out, self.dictionary, self.elements, html=False)
        c1 = self.rows()["c1"]
        self.assertEqual(c1["elements_keys"][0], "block:Gc")
        self.assertEqual(c1["elements_evidence"][0], "path+name")

    def test_periodic_proposals(self):
        E.enrich(self.out, self.dictionary, self.elements, html=False)
        rows = self.rows()
        self.assertEqual((rows["c1"]["periodic_category_proposed"], rows["c1"]["periodic_block_proposed"]),
                         ("geodesy", "Vg"))
        self.assertIn("already_vedic MEASURE", rows["c1"]["periodic_basis"])
        # Nearest entries by name pieces; 'Unresolved' is never proposed as a block.
        self.assertEqual(rows["c2"]["periodic_category_proposed"], "electrical engineering")
        self.assertTrue(rows["c2"]["periodic_basis"].startswith("nearest #25 PERCENT"))
        self.assertNotEqual(rows["c2"]["periodic_block_proposed"], "Unresolved")
        # Unit terms alone (kv, voltage) are not enough: missing evidence stays empty.
        self.assertEqual(rows["c3"]["periodic_category_proposed"], "")
        self.assertEqual(rows["c3"]["periodic_basis"], "")

    def test_without_catalogue_and_rerun(self):
        E.enrich(self.out, self.dictionary, None, html=False)
        self.assertEqual(self.rows()["c1"]["elements_keys"], [])
        E.enrich(self.out, self.dictionary, self.elements, html=False)
        first = self.rows()
        E.enrich(self.out, self.dictionary, self.elements, html=False)
        self.assertEqual(first, self.rows())

    def test_review_page(self):
        E.enrich(self.out, self.dictionary, self.elements, html=True)
        page = (self.out / "candidates.html").read_text()
        self.assertIn("background:var(--bg)", page)
        for colour in ("#000", "#0b0e14", "#2f343d", "#fff", "#a6adbb", "#66ccff", "#00ffff"):
            self.assertIn(colour, page)
        self.assertNotIn("<script", page.lower())
        self.assertIn(f"https://github.com/Ventusltd/ventus-grid-engine/blob/{C40}/engine/geo-core.js#L10-L30",
                      page)
        self.assertIn("block:Gc (family)", page)
        self.assertIn("How to accept", page)
        self.assertIn("data/dictionary.json", page)
        self.assertIn("Great-circle &lt;distance&gt; &amp; more", page)  # escaped
        self.assertIn("ASSIGNED AT REVIEW", page)                         # no invented number
        # Same inputs, same page.
        again = R.render(pq.read_table(self.out / "candidates.parquet").to_pylist(),
                         {u["unit_id"]: u for u in UNITS}, {}, "Ventusltd")
        self.assertEqual(again, R.render(pq.read_table(self.out / "candidates.parquet").to_pylist(),
                                         {u["unit_id"]: u for u in UNITS}, {}, "Ventusltd"))

    def test_review_page_modular_star(self):
        rows = pq.read_table(self.out / "candidates.parquet").to_pylist()
        rows[0]["ms_families"], rows[0]["ms_lines"] = [80299], [1004, 2000]
        rows[0]["underground_url"] = R.UNDERGROUND % 1004
        ms = {"u1": {"unit_id": "u1", "ms_family": 80299, "ms_line": 1004}}
        page = R.render(rows, {u["unit_id"]: u for u in UNITS}, ms, "Ventusltd")
        self.assertIn("202609180205-underground/?line=1004", page)
        self.assertIn("family 80299", page)
        self.assertIn("1004, 2000", page)


if __name__ == "__main__":
    unittest.main()