GLOBALGRID2050 / EXPLORE CODE

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

Review Page and 2 more files

A Python command-line tool in the fingerprints folder of VEDIC that reads units modular, rules, clusters summary and modular join summary.

427 lines of Python from vedic-, in 3 files. Topic: AI agents and coordination. Section 1668 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. Extract render · vedic- / fingerprints/extract.py lines 1135–1142
  2. Modular Join storage · vedic- / fingerprints/modular_join.py lines 1–198
  3. Review Page storage · vedic- / fingerprints/review_page.py lines 1–221

Extract

A Python command-line tool in the fingerprints folder of VEDIC that draws units, extract summary, cables and substations, using SHA-256 and haversine.

rendervedic- / fingerprints/extract.py · lines 1135–1142 of 1142 (continued from section 1666) · Entry point · pattern file_rows (shared by 2 files)

What it does
It draws units, extract summary, cables and substations. Defines 40 functions or classes, including TokenizeFailure, _lex, js_tokenize, bracket_match, _is. Uses libraries argparse, ast, bisect, collections, hashlib. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; 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). Domain terms in the code: cables, substations, 11kV. README: "Better evidence from extraction: add `unit_terms` or side-effect patterns in `extract.py` together with a test in `test_extract.py`"
Inputs & outputs
In: Parquet file units.parquet; JSON file extract-summary.json; browser IndexedDB; command-line arguments. Out: JSON file. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326. Voltage levels named: 11kV.
Downstream impact
Used directly by 2 files: Test Extract (vedic-); VEDIC Fingerprints Workflow (vedic-).
What it achieves
It cleans doc (`clean_doc`) and is built from the tokenize failure class (`TokenizeFailure`) and the js tokenize helper (`js_tokenize`). One row per code unit (function, method, class, arrow) of the Ventusltd estate. Its code works with 11 kV. It accepts `--src`, `--out` and `--repos`.
Why it matters
Run by VEDIC Fingerprints Workflow. Checked by Test Extract.
Application
vedic- · fingerprints · Python CLI
Uses
argparse, ast, bisect, collections, hashlib, io, json, keyword
Used by
imported by Test Extract (import), run by VEDIC Fingerprints Workflow (workflow run)
Produces
TokenizeFailure, js_tokenize, bracket_match, js_params, js_units, minhash, jaccard, sha, unit_terms, side_effects, clean_doc, LineIndex
Defines here
none
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/extract.py:1135-1142 · blob 6aa04263ba9350b49ddf2bf51bc250e47adbb02c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: agent_infra · users: ai_agent · canonical: unknown
        json.dump(summary, fh, indent=2, sort_keys=False)
        fh.write('\n')
    print(json.dumps({k: v for k, v in summary.items() if k != 'repo_names'}, indent=2))
    return 0


if __name__ == '__main__':
    sys.exit(main())

Modular Join

A Python command-line tool in the fingerprints folder of VEDIC that reads units modular. It loads elements (`load_elements`), loads lines (`load_lines`) and writes summary (`write_summary`).

storagevedic- / fingerprints/modular_join.py · lines 1–198 of 198 · Entry point · pattern load_elements (shared by 3 files)

What it does
It loads units modular. Defines 8 functions or classes, including load_elements, unpack, load_lines, first_line, match. Uses libraries argparse, collections, json, os, sqlite3. 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: "Without `--db`, `modular_join.py` records that nothing was joined"
Inputs & outputs
In: JSON file modular-join-summary.json; Parquet file units.parquet; Parquet file units-modular.parquet; Parquet file candidates.parquet; SQLite database; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 2 files: Test Modular Join (vedic-); VEDIC Fingerprints Workflow (vedic-).
What it achieves
Join fingerprint units to Modular Star's permanent element and family numbers. It accepts `--db`, `--out` and `--min-overlap`.
Why it matters
Run by VEDIC Fingerprints Workflow. Checked by Test Modular Join.
Application
vedic- · fingerprints · Python CLI
Uses
Testcode — Wafer Development Environment Page (estate URL), argparse, collections, json, os, sqlite3, struct, time, pyarrow
Used by
imported by Test Modular Join (import), run by VEDIC Fingerprints Workflow (workflow run)
Produces
load_elements, unpack, load_lines, first_line, match, write_summary, run, main
Defines here
load_elements, unpack, load_lines, first_line, match, write_summary, run, 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 fingerprints/modular_join.py:1-198 · blob 3b5bf1332239ddc1287c8b2b162ee2a2cf435409 · 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
#!/usr/bin/env python3
"""Join fingerprint units to Modular Star's permanent element and family numbers.

VEDIC reuses Modular Star identities and never renumbers them (docs/VEDIC-LANGUAGE.md, Invariants).
Modular Star (Ventusltd/stars, release `modular-star`, asset `modular.sqlite.gz`) stores every file
version as a tablet keyed by its git blob, and every function or class inside it as an element with
its first and last line (1-based, inclusive) and the numbered family of elements with the same logic.
A fingerprint unit carries the same blob and line range, so the join is exact:

    unit.blob = tablet.git_blob  and  tablet_element.first = unit.line_from
    (or, failing that, the element whose line range overlaps the unit's by at least --min-overlap)

Each tablet also stores `lines`: the permanent line number of every physical line of the file, packed
as unsigned 32-bit little-endian integers, 4 bytes per line, in file order (stars/modular-star/lib.mjs,
`pack`/`unpack`). A unit's first permanent line is therefore unpack(tablet.lines)[line_from - 1].

Outputs, beside the inputs:
  out/units-modular.parquet   unit_id, ms_element, ms_family, ms_match ('exact', 'overlap' or 'none'),
                              ms_line (int64, the unit's first permanent line number, null if unknown)
  out/candidates.parquet      rewritten with ms_families (list<int64>, most common first),
                              ms_family_main (int64, null if none), ms_lines (list<int64>: first line of
                              up to 5 members, in member order) and underground_url (the wafer's
                              underground reader at the top member's first line, '' if none)
  out/modular-join-summary.json

Without a database the script records that nothing was joined and leaves the candidates unchanged.
Fingerprint clusters may be wider than one family: Modular Star joins identical logic only, while
fingerprints also gather near copies. A cluster listing several families is the evidence of that.

Usage:
  gh release download modular-star --repo Ventusltd/stars --pattern modular.sqlite.gz --dir /tmp/ms
  gunzip /tmp/ms/modular.sqlite.gz
  python fingerprints/modular_join.py --db /tmp/ms/modular.sqlite --out fingerprints/out
"""
import argparse
import collections
import json
import os
import sqlite3
import struct
import time

import pyarrow as pa
import pyarrow.parquet as pq


def load_elements(db, blobs):
    """Map git_blob -> list of (first, last, element, family) for the blobs we need."""
    con = sqlite3.connect('file:%s?mode=ro' % db, uri=True)
    out = collections.defaultdict(list)
    blobs = sorted(blobs)
    for i in range(0, len(blobs), 500):
        chunk = blobs[i:i + 500]
        rows = con.execute(
            'SELECT t.git_blob, te.first, te.last, te.element, e.family '
            'FROM tablet t JOIN tablet_element te ON te.tablet = t.n JOIN element e ON e.n = te.element '
            'WHERE t.git_blob IN (%s)' % ','.join('?' * len(chunk)), chunk).fetchall()
        for blob, first, last, element, family in rows:
            out[blob].append((first, last, element, family))
    con.close()
    return out


UNDERGROUND = ('https://globalgrid2050.com/testcode/wafer-development-environment/'
               '202609180205-underground/?line=%d')
MAX_LINES_PER_CANDIDATE = 5


def unpack(blob):
    """Permanent line numbers of a tablet, exactly as lib.mjs unpacks them (uint32 little-endian)."""
    blob = bytes(blob or b'')
    n = len(blob) // 4
    return list(struct.unpack('<%dI' % n, blob[:n * 4]))


def load_lines(db, blobs):
    """Map git_blob -> list of permanent line numbers (index 0 = file line 1)."""
    con = sqlite3.connect('file:%s?mode=ro' % db, uri=True)
    out = {}
    blobs = sorted(blobs)
    for i in range(0, len(blobs), 500):
        chunk = blobs[i:i + 500]
        for blob, lines in con.execute('SELECT git_blob, lines FROM tablet WHERE git_blob IN (%s)'
                                       % ','.join('?' * len(chunk)), chunk):
            out[blob] = unpack(lines)
    con.close()
    return out


def first_line(lines, line_from):
    """Permanent number of 1-based file line `line_from`, or None when the tablet does not reach it."""
    if lines and 1 <= line_from <= len(lines):
        return lines[line_from - 1]
    return None


def match(unit_from, unit_to, elements, min_overlap):
    """Exact start line first; otherwise the largest overlap covering at least min_overlap of both."""
    exact = [e for e in elements if e[0] == unit_from]
    if exact:
        best = min(exact, key=lambda e: (abs(e[1] - unit_to), e[2]))
        return best[2], best[3], 'exact'
    best, best_share = None, 0.0
    for first, last, element, family in elements:
        ov = min(last, unit_to) - max(first, unit_from) + 1
        if ov <= 0:
            continue
        share = min(ov / (last - first + 1), ov / (unit_to - unit_from + 1))
        if share > best_share or (share == best_share and best and element < best[2]):
            best, best_share = (first, last, element, family), share
    if best and best_share >= min_overlap:
        return best[2], best[3], 'overlap'
    return None, None, 'none'


def write_summary(out, summary):
    with open(os.path.join(out, 'modular-join-summary.json'), 'w', encoding='utf-8') as f:
        json.dump(summary, f, indent=1)


def run(db, out, min_overlap=0.8):
    t0 = time.time()
    path = os.path.join(out, 'units.parquet')
    cols = ['unit_id', 'blob', 'line_from', 'line_to']
    have = pq.read_schema(path).names
    cols += [c for c in ('repo', 'path', 'name') if c in have]
    units = pq.read_table(path, columns=cols).to_pylist()
    summary = {'database': os.path.basename(db) if db else None, 'units': len(units), 'min_overlap': min_overlap}
    if not db or not os.path.isfile(db):
        summary.update({'joined': 0, 'note': 'no Modular Star database given; nothing joined'})
        write_summary(out, summary)
        print(summary['note'])
        return summary
    elements = load_elements(db, {u['blob'] for u in units})
    tablet_lines = load_lines(db, {u['blob'] for u in units})
    rows, counts = [], collections.Counter()
    fam_of, line_of, hint_of = {}, {}, {}
    for u in units:
        el, fam, how = match(u['line_from'], u['line_to'], elements.get(u['blob'], []), min_overlap)
        counts[how] += 1
        fam_of[u['unit_id']] = fam
        line_of[u['unit_id']] = first_line(tablet_lines.get(u['blob']), u['line_from'])
        hint_of[u['unit_id']] = '%s/%s::%s' % (u.get('repo'), u.get('path'), u.get('name'))
        rows.append({'unit_id': u['unit_id'], 'ms_element': el, 'ms_family': fam, 'ms_match': how,
                     'ms_line': line_of[u['unit_id']]})
    pq.write_table(pa.Table.from_pylist(rows, schema=pa.schema([
        ('unit_id', pa.string()), ('ms_element', pa.int64()), ('ms_family', pa.int64()), ('ms_match', pa.string()),
        ('ms_line', pa.int64())])),
        os.path.join(out, 'units-modular.parquet'), compression='zstd')

    cpath = os.path.join(out, 'candidates.parquet')
    if os.path.isfile(cpath):
        cand = pq.read_table(cpath)
        hints = (cand.column('import_hint').to_pylist() if 'import_hint' in cand.column_names
                 else [None] * cand.num_rows)
        fams, mains, ms_lines, urls = [], [], [], []
        for members, hint in zip(cand.column('members').to_pylist(), hints):
            c = collections.Counter(fam_of.get(m) for m in members if fam_of.get(m) is not None)
            ordered = [f for f, _ in sorted(c.items(), key=lambda x: (-x[1], x[0]))]
            fams.append(ordered)
            mains.append(ordered[0] if ordered else None)
            with_line = [m for m in members if line_of.get(m) is not None]
            ms_lines.append([line_of[m] for m in with_line[:MAX_LINES_PER_CANDIDATE]])
            # Top member: the import_hint member when it has a line, else the first member that has one.
            top = next((m for m in with_line if hint and hint_of.get(m) == hint), None)
            top = top or (with_line[0] if with_line else None)
            urls.append(UNDERGROUND % line_of[top] if top else '')
        for name in ('ms_families', 'ms_family_main', 'ms_lines', 'underground_url'):
            if name in cand.column_names:
                cand = cand.drop_columns([name])
        cand = cand.append_column('ms_families', pa.array(fams, pa.list_(pa.int64())))
        cand = cand.append_column('ms_family_main', pa.array(mains, pa.int64()))
        cand = cand.append_column('ms_lines', pa.array(ms_lines, pa.list_(pa.int64())))
        cand = cand.append_column('underground_url', pa.array(urls, pa.string()))
        pq.write_table(cand, cpath, compression='zstd')
        summary['candidates_with_family'] = sum(1 for m in mains if m is not None)
        summary['candidates_with_line'] = sum(1 for u in urls if u)
        summary['candidates'] = len(mains)
    summary['units_with_line'] = sum(1 for v in line_of.values() if v is not None)
    summary.update({'joined': counts['exact'] + counts['overlap'], 'exact': counts['exact'],
                    'overlap': counts['overlap'], 'unmatched': counts['none'],
                    'runtime_s': round(time.time() - t0, 2)})
    write_summary(out, summary)
    print(json.dumps(summary))
    return summary


def main():
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--db', help='path to modular.sqlite (unzipped)')
    ap.add_argument('--out', default=os.path.join(os.path.dirname(os.path.abspath(__file__)), 'out'))
    ap.add_argument('--min-overlap', type=float, default=0.8)
    a = ap.parse_args()
    run(a.db, a.out, a.min_overlap)


if __name__ == '__main__':
    main()

Review Page

A Python command-line tool in the fingerprints folder of VEDIC that reads units modular, rules, clusters summary and modular join summary.

storagevedic- / fingerprints/review_page.py · lines 1–221 of 221 · Entry point · pattern github_url (shared by 2 files)

What it does
It loads units modular, rules, clusters summary and modular join summary. Defines 8 functions or classes, including esc, github_url, proposed_entry, member_item, render. Uses libraries argparse, html, json, pathlib, pyarrow.parquet. 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: "Committed: `extract.py`, `candidates.py`, `modular_join.py`, `enrich.py`, `review_page.py`, their tests, `rules.json`, `CONTRACT.md`, this README, `runs.tsv` (the small ledger showing how each run and rules change moved the results) and `LATEST.md` (top 25 of the latest run)."
Inputs & outputs
In: Parquet file candidates.parquet; Parquet file units.parquet; Parquet file units-modular.parquet; JSON file rules.json; JSON file clusters-summary.json; JSON file modular-join-summary.json; JSON file enrich-summary.json; command-line arguments.
Downstream impact
Used directly by 2 files: Enrich (vedic-); Test Enrich (vedic-). Reached from 1 other entry point, including VEDIC Fingerprints Workflow (vedic-).
What it achieves
It is built from the esc step (`esc`), the GitHub URL helper (`github_url`) and the proposed entry helper (`proposed_entry`). Write `out/candidates.html`: a static review page of fingerprint candidates (no JavaScript). It reads `candidates.parquet`. It accepts `--out`, `--rules` and `--limit`.
Why it matters
Imported by Enrich. Checked by Test Enrich.
Application
vedic- · fingerprints · Python CLI
Uses
Testcode — Wafer Development Environment Page (estate URL), argparse, html, json, pathlib, pyarrow.parquet
Used by
imported by Enrich (import), imported by Test Enrich (import)
Produces
esc, github_url, proposed_entry, member_item, render, write, main
Defines here
esc, github_url, proposed_entry, member_item, render, field, write, 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 fingerprints/review_page.py:1-221 · blob e74e517b9d14aec9c38b5e66e02f116203b99e78 · 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
#!/usr/bin/env python3
"""Write out/candidates.html: a static review page of fingerprint candidates (no JavaScript).

Reads out/candidates.parquet (with the optional columns added by modular_join.py and enrich.py),
out/units.parquet for member locations and, when present, out/units-modular.parquet for each member's
Modular Star family and first permanent line. Generated, so it lives in out/ and is never committed.
Colours: the GlobalGrid2050 / Pipeline News palette.

Usage: python fingerprints/review_page.py --out fingerprints/out [--rules fingerprints/rules.json]
"""
import argparse
import html
import json
from pathlib import Path

import pyarrow.parquet as pq

HERE = Path(__file__).resolve().parent
UNDERGROUND = ("https://globalgrid2050.com/testcode/wafer-development-environment/"
               "202609180205-underground/?line=%d")
MEMBERS_SHOWN = 3
MEMBERS_MAX = 40

CSS = """
:root{--bg:#000;--panel:#0b0e14;--line:#2f343d;--text:#fff;--muted:#a6adbb;--link:#66ccff;--accent:#00ffff}
*{box-sizing:border-box}
body{margin:0;background:var(--bg);color:var(--text);font:14px/1.45 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace}
main{max-width:1200px;margin:0 auto;padding:20px}
h1{color:var(--accent);font-size:20px;margin:0 0 6px;letter-spacing:.04em}
h2{font-size:16px;margin:0;color:var(--text)}
a{color:var(--link)}
.muted{color:var(--muted)}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:4px;padding:12px 14px;margin:12px 0}
.note{border-left:3px solid var(--accent)}
.cand header{display:flex;flex-wrap:wrap;gap:6px 14px;align-items:baseline}
.rank{color:var(--muted)}
.word{color:var(--accent);font-weight:bold}
.score{margin-left:auto;color:var(--accent)}
.tag{border:1px solid var(--line);border-radius:3px;padding:0 5px;color:var(--muted);font-size:12px}
.tag.vedic{color:var(--accent);border-color:var(--accent)}
dl{display:grid;grid-template-columns:max-content 1fr;gap:3px 12px;margin:8px 0 0}
dt{color:var(--muted)}
dd{margin:0;overflow-wrap:anywhere}
ul{margin:4px 0;padding-left:18px}
details{margin-top:6px}
summary{color:var(--muted);cursor:pointer}
pre{background:var(--bg);border:1px solid var(--line);padding:8px;overflow:auto;white-space:pre-wrap}
nav a{margin-right:8px}
"""


def esc(value):
    return html.escape(str(value if value is not None else ""), quote=True)


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']}")


def proposed_entry(row, units, owner):
    """A draft dictionary entry for a reviewer to copy; no number or gg_id is invented here."""
    hint_repo, _, rest = (row.get("import_hint") or "").partition("/")
    name = rest.rsplit("::", 1)[-1] if "::" in rest else (row["names"][0] if row["names"] else "")
    first = next((units[m] for m in row["members"] if m in units and units[m]["name"] == name), None)
    first = first or next((units[m] for m in row["members"] if m in units), None)
    repo = hint_repo if "/" in hint_repo else f"{owner}/{hint_repo}"
    entry = {
        "number": "ASSIGNED AT REVIEW (next_number)",
        "word": row.get("suggested_word") or "",
        "kind": "FUNCTION",
        "translation_ref": f"fingerprint:{repo}:{name}",
        "inputs": list(first["params"] or []) if first else [],
        "output": None,
        "purpose": row.get("capability_draft") or "",
        "state": "CANDIDATE",
        "periodic_category": row.get("periodic_category_proposed") or None,
        "periodic_block_candidate": row.get("periodic_block_proposed") or "Unresolved",
        "source": github_url(first, owner) if first else None,
        "fingerprint_cluster": row["cluster_id"],
        "family_id": row.get("ms_family_main"),
    }
    return json.dumps(entry, indent=1, ensure_ascii=False)


def member_item(unit, owner, ms):
    label = f"{unit['repo']}:{unit['path']}#L{unit['line_from']}-L{unit['line_to']} {unit['name']}"
    extra = ""
    info = ms.get(unit["unit_id"]) or {}
    if info.get("ms_family") is not None:
        extra += f" <span class='tag'>family {esc(info['ms_family'])}</span>"
    if info.get("ms_line") is not None:
        extra += (f" <a class='tag' href='{esc(UNDERGROUND % info['ms_line'])}'>line {esc(info['ms_line'])}</a>")
    return f"<li><a href='{esc(github_url(unit, owner))}'>{esc(label)}</a>{extra}</li>"


def render(rows, units, ms, owner, summary=None, limit=None):
    shown = rows[:limit] if limit else rows
    rules_version = rows[0]["rules_version"] if rows else ""
    out = [
        "<!doctype html><html lang='en'><head><meta charset='utf-8'>",
        "<meta name='viewport' content='width=device-width,initial-scale=1'>",
        "<title>VEDIC fingerprint candidates</title>",
        f"<style>{CSS}</style></head><body><main>",
        "<h1>VEDIC FINGERPRINT CANDIDATES</h1>",
        f"<p class='muted'>{len(rows)} candidates, rules <code>{esc(rules_version)}</code>, "
        f"generated by <code>fingerprints/review_page.py</code> (deterministic: same inputs, same page). "
        f"Every row is <b>CANDIDATE</b>; nothing here is accepted automatically.</p>",
        "<section class='panel note'><h2>How to accept a candidate</h2><ol>",
        "<li>Open the member links and read the source: same structure is not the same meaning, "
        "and a shared name is a lead, not proof.</li>",
        "<li>If it is a real reusable capability, copy the proposed entry below it into "
        "<code>data/dictionary.json</code> through the normal review process (a pull request "
        "reviewed by a human or AI reviewer). Assign the number from <code>next_number</code> "
        "there; never renumber existing entries or invent Modular Star IDs.</li>",
        "<li>Replace the drafted fields with evidence: output with units, purpose, limits, "
        "and the Modular Star family, element and line IDs once resolved.</li>",
        "<li>Fields marked <i>proposed</i> (Elements keys, periodic category and block) are "
        "suggestions from likeness, not classifications.</li></ol></section>",
    ]
    if summary:
        out.append(f"<p class='muted'>Pipeline: {esc(summary)}</p>")
    for rank, r in enumerate(shown, 1):
        members = [units[m] for m in r["members"] if m in units]
        vedic = (f"<span class='tag vedic'>already VEDIC: {esc(r['already_vedic'])}</span>"
                 if r.get("already_vedic") else "")
        sib = r.get("sibling_clusters") or []
        sib_html = (" <span class='tag'>siblings: " + ", ".join(
            f"<a href='#c-{esc(c)}'>{esc(c)}</a>" for c in sib) + "</span>") if sib else ""
        out.append(f"<article class='panel cand' id='c-{esc(r['cluster_id'])}'><header>"
                   f"<span class='rank'>#{rank}</span><span class='word'>{esc(r['suggested_word'] or '-')}</span>"
                   f"<h2>{esc(', '.join(r['names'][:4]))}</h2>{vedic}{sib_html}"
                   f"<span class='score'>score {r['score']:.1f}</span></header><dl>")

        def field(label, value):
            out.append(f"<dt>{esc(label)}</dt><dd>{value}</dd>")

        field("capability", esc(r.get("capability_draft")))
        field("size", f"{r['size']} units in {r['n_repos']} repos, pure share {r['pure_share']:.2f}")
        field("repos", esc(", ".join(r["repos"])))
        if r.get("units_found"):
            field("units found", esc(", ".join(r["units_found"][:8])))
        field("import hint", esc(r.get("import_hint")))
        fams = r.get("ms_families") or []
        if fams:
            field("Modular Star families", esc(", ".join(str(f) for f in fams[:8])))
        lines = r.get("ms_lines") or []
        if lines:
            field("Modular Star lines", esc(", ".join(str(n) for n in lines)))
        if r.get("underground_url"):
            field("underground", f"<a href='{esc(r['underground_url'])}'>open top member in the wafer "
                                 f"underground reader</a>")
        keys = r.get("elements_keys") or []
        if keys:
            ev = r.get("elements_evidence") or [""] * len(keys)
            field("Elements keys (proposed)", esc(", ".join(f"{k} ({e})" for k, e in zip(keys, ev))))
        if r.get("periodic_category_proposed") or r.get("periodic_block_proposed"):
            field("periodic (proposed)", esc(f"{r.get('periodic_category_proposed') or '?'} / "
                                             f"{r.get('periodic_block_proposed') or 'Unresolved'}")
                  + f" <span class='muted'>{esc(r.get('periodic_basis'))}</span>")
        field("cluster", f"<code>{esc(r['cluster_id'])}</code>")
        out.append("</dl><ul>")
        out += [member_item(u, owner, ms) for u in members[:MEMBERS_SHOWN]]
        out.append("</ul>")
        if len(members) > MEMBERS_SHOWN:
            out.append(f"<details><summary>{len(members) - MEMBERS_SHOWN} more members</summary><ul>")
            out += [member_item(u, owner, ms) for u in members[MEMBERS_SHOWN:MEMBERS_MAX]]
            if len(members) > MEMBERS_MAX:
                out.append(f"<li class='muted'>and {len(members) - MEMBERS_MAX} more in candidates.parquet</li>")
            out.append("</ul></details>")
        out.append("<details><summary>proposed dictionary entry (copy after review)</summary>"
                   f"<pre>{esc(proposed_entry(r, units, owner))}</pre></details></article>")
    if limit and len(rows) > limit:
        out.append(f"<p class='muted'>{len(rows) - limit} lower-ranked candidates are in "
                   f"candidates.parquet.</p>")
    out.append("</main></body></html>")
    return "\n".join(out) + "\n"


def write(out_dir, rules_path=None, limit=None):
    out = Path(out_dir)
    rows = pq.read_table(out / "candidates.parquet").to_pylist()
    cols = ["unit_id", "repo", "commit", "path", "name", "params", "line_from", "line_to"]
    units = {u["unit_id"]: u for u in pq.read_table(out / "units.parquet", columns=cols).to_pylist()}
    ms = {}
    if (out / "units-modular.parquet").is_file():
        ms = {u["unit_id"]: u for u in pq.read_table(out / "units-modular.parquet").to_pylist()}
    rules_path = Path(rules_path) if rules_path else HERE / "rules.json"
    owner = "Ventusltd"
    if rules_path.is_file():
        owner = json.loads(rules_path.read_text(encoding="utf-8")).get("github_owner", owner)
    parts = []
    for name in ("clusters-summary.json", "modular-join-summary.json", "enrich-summary.json"):
        p = out / name
        if p.is_file():
            s = json.loads(p.read_text(encoding="utf-8"))
            if name.startswith("clusters"):
                parts.append(f"{s.get('units_total')} units, {s.get('clusters')} clusters "
                             f"({s.get('clusters_split', 0)} split)")
            elif name.startswith("modular"):
                parts.append(s.get("note") or f"Modular Star joined {s.get('joined')} units")
            else:
                parts.append(f"{s.get('candidates_with_elements')} with Elements keys, "
                             f"{s.get('candidates_with_category')} with a proposed category")
    path = out / "candidates.html"
    path.write_text(render(rows, units, ms, owner, "; ".join(parts), limit), encoding="utf-8")
    return path


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--out", type=Path, default=HERE / "out")
    ap.add_argument("--rules", type=Path, default=HERE / "rules.json")
    ap.add_argument("--limit", type=int, default=0, help="only the top N candidates (0 = all)")
    a = ap.parse_args()
    print(write(a.out, a.rules, a.limit or None))


if __name__ == "__main__":
    main()