GLOBALGRID2050 / EXPLORE CODE

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

Extract and 1 more file

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

700 lines of Python from vedic-, in 2 files. Topic: AI agents and coordination. Section 1666 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. Enrich storage · vedic- / fingerprints/enrich.py lines 1–266
  2. Extract render · vedic- / fingerprints/extract.py lines 1–434

Enrich

A Python command-line tool in the fingerprints folder of VEDIC that reads functions, units, enrich summary and dictionary.

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

What it does
It loads functions, units, enrich summary and dictionary. Defines 12 functions or classes, including bare_repo, mask, pieces_of, load_elements, ElementIndex. Uses libraries argparse, collections, json, pathlib, re. 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 `--elements`, `enrich.py` still proposes periodic categories from the dictionary and writes the review page."
Inputs & outputs
In: JSON file functions.json; Parquet file candidates.parquet; Parquet file units.parquet; JSON file dictionary.json; command-line arguments. Out: JSON file enrich-summary.json.
Downstream impact
Used directly by 2 files: Test Enrich (vedic-); VEDIC Fingerprints Workflow (vedic-).
What it achieves
It loads elements (`load_elements`) and is built from the bare repo helper (`bare_repo`) and the mask step (`mask`). Attach Elements catalogue keys and a proposed Periodic Table category to fingerprint candidates. It reads `units.parquet`. It accepts `--out`, `--dictionary` and `--elements`.
Why it matters
Run by VEDIC Fingerprints Workflow. Checked by Test Enrich.
Application
vedic- · fingerprints · Python CLI
Uses
Candidates (import), Review Page (import), argparse, collections, json, pathlib, re, sys, time, pyarrow
Used by
imported by Test Enrich (import), run by VEDIC Fingerprints Workflow (workflow run)
Produces
bare_repo, mask, pieces_of, load_elements, ElementIndex, entry_features, propose_category, enrich, main
Defines here
bare_repo, mask, pieces_of, load_elements, ElementIndex, __init__, match, add, entry_features, propose_category, enrich, 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/enrich.py:1-266 · blob cfa494acc80498c885e5d734f66efa53492134f7 · 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
"""Attach Elements catalogue keys and a proposed Periodic Table category to fingerprint candidates.

Optional step after candidates.py (and after modular_join.py when a Modular Star database is at hand).
Everything it adds is a PROPOSAL for review, like the candidates themselves: nothing is accepted into
data/dictionary.json, and VEDIC reuses existing identities (Elements block keys, Modular Star family
numbers, the dictionary's periodic categories) without inventing or renumbering any.

Elements catalogue keys (Ventusltd/elements, catalogue/elements.json), strongest evidence first:
  family       the candidate's Modular Star families (ms_families, from modular_join.py) appear in the
               element's function_keys (`family:N`): identical logic, exact identity
  path+name    a member's repo and path equal one of the element's files and its name is one of the
               element's function names (catalogue/functions.json)
  path         a member's repo and path equal one of the element's files
  path-family  the same once a 20YYMMDD[hhmm] timestamp folder or prefix is masked in both paths
  name         a member name equals the name of one of the element's function_keys
               (names from catalogue/functions.json); names of one word piece are too common and skipped

Proposed periodic category, from the existing dictionary only:
  already_vedic   the category of the dictionary entry the candidate already matches by name
  nearest         otherwise a vote of the (up to) three dictionary entries whose word, translation_ref
                  name, inputs and output share most name pieces with the candidate's names, suggested
                  word and units found (Jaccard of singularised pieces, at least MIN_SIMILARITY, and at
                  least one shared piece from the names or word, not only unit terms); empty otherwise
Proposed periodic block: the already_vedic entry's block, else the nearest entries' block, else the
symbol of an element matched by family or path+name; never 'Unresolved', empty when unknown.

Columns added to out/candidates.parquet (rewritten; rerunning replaces them):
  elements_keys (list<string>), elements_evidence (list<string>, one per key),
  periodic_category_proposed, periodic_block_proposed, periodic_basis, enrichment_state = 'PROPOSAL'
Also writes out/enrich-summary.json and, unless --no-html, out/candidates.html (review_page.py).

Usage:
  python fingerprints/enrich.py --out fingerprints/out --dictionary data/dictionary.json \
    --elements ../elements/catalogue/elements.json
"""
import argparse
from collections import Counter, defaultdict
import json
from pathlib import Path
import re
import sys
import time

import pyarrow as pa
import pyarrow.parquet as pq

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
from candidates import load_dictionary_entries, name_pieces, singular  # noqa: E402

STATE = "PROPOSAL"
MAX_KEYS = 8
MIN_SIMILARITY = 0.1
EVIDENCE_RANK = {"family": 0, "path+name": 1, "path": 2, "path-family": 3, "name": 4}
# Pieces too common in dictionary inputs/outputs to show likeness on their own.
WEAK = {"record", "result", "optional", "list", "and", "or", "the", "of", "to", "in", "with", "value",
        "data", "summary", "string", "object", "boolean", "callable", "null", "get", "set", "is", "has",
        "make", "compute", "calc", "calculate", "create", "build", "new", "from", "by", "for", "same",
        "unit", "type", "typed", "fn", "func", "util", "helper", "init", "update"}
TIMESTAMP = re.compile(r"20\d{6}(\d{4})?")
NEW_COLUMNS = (("elements_keys", pa.list_(pa.string())), ("elements_evidence", pa.list_(pa.string())),
               ("periodic_category_proposed", pa.string()), ("periodic_block_proposed", pa.string()),
               ("periodic_basis", pa.string()), ("enrichment_state", pa.string()))


def bare_repo(repo):
    return (repo or "").rsplit("/", 1)[-1]


def mask(path):
    return TIMESTAMP.sub("20YYMMDD", path or "")


def pieces_of(texts):
    out = set()
    for text in texts:
        for p in name_pieces(str(text or "")):
            if p.isalpha() and len(p) >= 2 and p not in WEAK:
                out.add(singular(p))
    return out


def load_elements(path, functions_path=None):
    """Elements catalogue entries plus a family-key -> function name map (if functions.json exists)."""
    if not path or not Path(path).is_file():
        return [], {}
    elements = json.loads(Path(path).read_text(encoding="utf-8"))
    if isinstance(elements, dict):
        elements = elements.get("elements", [])
    functions_path = Path(functions_path) if functions_path else Path(path).with_name("functions.json")
    names = {}
    if functions_path.is_file():
        for f in json.loads(functions_path.read_text(encoding="utf-8")):
            if f.get("key") and f.get("name"):
                names[f["key"]] = f["name"]
    return sorted(elements, key=lambda e: (e.get("number") or 0, e.get("key") or "")), names


class ElementIndex:
    def __init__(self, elements, function_names):
        self.by_key = {e["key"]: e for e in elements}
        self.by_family = defaultdict(set)
        self.by_path = defaultdict(set)
        self.by_masked = defaultdict(set)
        self.by_name = defaultdict(set)
        self.names_of = defaultdict(set)
        for e in elements:
            for fk in e.get("function_keys") or []:
                self.by_family[fk].add(e["key"])
                name = function_names.get(fk)
                if name:
                    self.names_of[e["key"]].add(name)
                if name and len({p for p in name_pieces(name) if p.isalpha()}) >= 2:
                    self.by_name[name].add(e["key"])
            for f in e.get("files") or []:
                repo, path = bare_repo(f.get("repo")), f.get("path") or ""
                self.by_path[(repo, path)].add(e["key"])
                self.by_masked[(repo, mask(path))].add(e["key"])

    def match(self, members, names, families):
        """[(key, evidence)]: strongest evidence first, then most members matched, then the most
        specific element (fewest files), then element number."""
        found, hits = {}, Counter()

        def add(keys, evidence):
            for k in keys:
                if k not in found or EVIDENCE_RANK[evidence] < EVIDENCE_RANK[found[k]]:
                    found[k] = evidence

        for fam in families or []:
            add(self.by_family.get(f"family:{fam}", ()), "family")
        for u in members:
            repo, path = bare_repo(u["repo"]), u["path"]
            exact = self.by_path.get((repo, path), set())
            add({k for k in exact if u.get("name") in self.names_of[k]}, "path+name")
            add(exact, "path")
            masked = self.by_masked.get((repo, mask(path)), set())
            add(masked, "path-family")
            hits.update(exact | masked)
        for n in names:
            add(self.by_name.get(n, ()), "name")
        ordered = sorted(found.items(), key=lambda kv: (
            EVIDENCE_RANK[kv[1]], -hits[kv[0]], len(self.by_key[kv[0]].get("files") or []),
            self.by_key[kv[0]].get("number") or 0, kv[0]))
        return ordered[:MAX_KEYS]


def entry_features(entry):
    ref = (entry.get("translation_ref") or "").rsplit(":", 1)[-1]
    return pieces_of([entry["word"], ref, entry.get("output") or ""] + list(entry.get("inputs") or []))


def propose_category(row, entries, features, by_word):
    """(category, block, basis) proposed from existing dictionary entries; '' where unknown."""
    if row.get("already_vedic") and row["already_vedic"] in by_word:
        e = by_word[row["already_vedic"]]
        block = e.get("periodic_block_candidate") or ""
        return (e.get("periodic_category") or "", "" if block == "Unresolved" else block,
                f"already_vedic {e['word']} (#{e.get('number')})")
    named = pieces_of(list(row.get("names") or [])[:3] + [row.get("suggested_word") or ""])
    mine = named | pieces_of(row.get("units_found") or [])
    scored = []
    for e in entries:
        theirs = features[id(e)]
        # Shared unit terms alone (kv, lat) say little about role: a name piece must be shared too.
        if not (named & theirs) or not e.get("periodic_category"):
            continue
        sim = len(mine & theirs) / len(mine | theirs)
        if sim >= MIN_SIMILARITY:
            scored.append((sim, e))
    scored.sort(key=lambda se: (-se[0], se[1].get("number") or 0))
    top = scored[:3]
    if not top:
        return "", "", ""
    votes = Counter()
    for sim, e in top:
        votes[e["periodic_category"]] += sim
    category = sorted(votes.items(), key=lambda kv: (-kv[1], kv[0]))[0][0]
    block = next((e.get("periodic_block_candidate") for _, e in top
                  if e["periodic_category"] == category
                  and e.get("periodic_block_candidate") not in (None, "", "Unresolved")), "")
    basis = "nearest " + ", ".join(f"#{e.get('number')} {e['word']} {sim:.2f}" for sim, e in top)
    return category, block or "", basis


def enrich(out_dir, dictionary_path, elements_path=None, functions_path=None, html=True):
    started = time.time()
    out = Path(out_dir)
    cpath = out / "candidates.parquet"
    cand = pq.read_table(cpath)
    rows = cand.to_pylist()
    units = {u["unit_id"]: u for u in pq.read_table(out / "units.parquet",
                                                     columns=["unit_id", "repo", "path", "name"]).to_pylist()}
    entries = load_dictionary_entries(dictionary_path)
    features = {id(e): entry_features(e) for e in entries}
    by_word = {}
    for e in entries:
        by_word.setdefault(e["word"], e)
    elements, function_names = load_elements(elements_path, functions_path)
    index = ElementIndex(elements, function_names)

    added = {name: [] for name, _ in NEW_COLUMNS}
    evidence_counts = Counter()
    for row in rows:
        members = [units[m] for m in row["members"] if m in units]
        matched = index.match(members, row.get("names") or [], row.get("ms_families") or [])
        evidence_counts.update(ev for _, ev in matched)
        category, block, basis = propose_category(row, entries, features, by_word)
        strong = [k for k, ev in matched if ev in ("family", "path+name")]
        if not block and strong:
            symbol = index.by_key[strong[0]].get("symbol") or ""
            if symbol:
                block, basis = symbol, (basis + "; " if basis else "") + f"block from element {strong[0]}"
        values = {"elements_keys": [k for k, _ in matched], "elements_evidence": [ev for _, ev in matched],
                  "periodic_category_proposed": category, "periodic_block_proposed": block,
                  "periodic_basis": basis, "enrichment_state": STATE}
        for name, _ in NEW_COLUMNS:
            added[name].append(values[name])
            row[name] = values[name]
    for name, typ in NEW_COLUMNS:
        if name in cand.column_names:
            cand = cand.drop_columns([name])
        cand = cand.append_column(name, pa.array(added[name], typ))
    pq.write_table(cand, cpath, compression="zstd")

    summary = {
        "schema": "vedic-fingerprint-enrich-summary-v1",
        "state": STATE,
        "candidates": len(rows),
        "elements_catalogue": str(elements_path) if elements else None,
        "elements_loaded": len(elements),
        "function_names_loaded": len(function_names),
        "candidates_with_elements": sum(1 for k in added["elements_keys"] if k),
        "element_matches_by_evidence": dict(sorted(evidence_counts.items())),
        "candidates_with_category": sum(1 for c in added["periodic_category_proposed"] if c),
        "candidates_with_block": sum(1 for b in added["periodic_block_proposed"] if b),
        "runtime_seconds": round(time.time() - started, 3),
        "limits": [
            "Every added field is a proposal for review, never an accepted classification.",
            "Path and name matches show where code lives or what it is called, not that it is the same logic; "
            "only family matches (Modular Star) are identity.",
            "Categories come from name and unit likeness to existing dictionary entries, not from execution.",
        ],
    }
    (out / "enrich-summary.json").write_text(json.dumps(summary, indent=2) + "\n", encoding="utf-8")
    if html:
        import review_page
        review_page.write(out)
    return summary


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--out", type=Path, default=HERE / "out")
    ap.add_argument("--dictionary", type=Path, default=HERE.parent / "data" / "dictionary.json")
    ap.add_argument("--elements", type=Path, help="Elements catalogue elements.json (optional)")
    ap.add_argument("--functions", type=Path, help="catalogue functions.json (default: beside --elements)")
    ap.add_argument("--no-html", action="store_true", help="do not write out/candidates.html")
    a = ap.parse_args()
    s = enrich(a.out, a.dictionary, a.elements, a.functions, html=not a.no_html)
    print(json.dumps({k: v for k, v in s.items() if k != "limits"}, indent=2))


if __name__ == "__main__":
    main()

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 1–434 of 1142 · 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
TokenizeFailure, _lex, js_tokenize, bracket_match, _is, _ident, _skip_generic, _find_body, js_params, _expr_end, js_units
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:1-434 · 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
#!/usr/bin/env python3
r"""fingerprints/extract.py - one row per code unit (function, method, class, arrow) of the Ventusltd estate.

Writes out/units.parquet exactly as fingerprints/CONTRACT.md (schema vedic-fingerprint-units-v1) and
out/extract-summary.json. Python 3.12 stdlib + pyarrow + numpy only.

  python fingerprints/extract.py --src /home/claude/src --out fingerprints/out [--repos a,b]

File selection is the Explore Code rule (cosmic tools/explore/build.py scan()): clones whose
remote.origin.url is https://github.com/Ventusltd/..., blobs at HEAD read with `git ls-tree -r -l -z`
and `git cat-file --batch`, code extensions only, no vendor/dist/build/node_modules/third_party/*.min.*,
0 < size <= 1 MB, not binary, not minified (avg > 400 bytes/line), each blob once (first repo in
case-insensitive order wins), newest of each timestamp family (paths equal once 20YYMMDD[hhmm] is
masked). Of those, only Python (.py) and JavaScript/TypeScript (.js .mjs .cjs .ts .jsx .tsx and inline
<script> blocks in .html/.htm) are parsed into units.

Units
  python      `ast`: def / async def (kind function, or method when directly inside a class), class.
              Ranges from lineno/end_lineno; decorators are included in the range.
  javascript  a small tokenizer (comments, '..' ".." and `..${..}..` strings, heuristic regex literals,
              numbers, identifiers, punctuators) and brace matching on the token stream:
              `[async] function name(..) {..}`                         kind function
              `class Name {..}`                                         kind class
              `name(..) {..}` / `name = (..) => ..` in a class body      kind method
              `const|let|var name = [async] function (..) {..}`         kind function
              `const|let|var name = [async] (..) => ..` / `x => ..`     kind arrow (block or expression body)
              `name: function (..) {..}`, `X.prototype.name = function`  kind method
              `X.name = function (..) {..}`                              kind function
              Anonymous callbacks are not units (they belong to the unit that contains them).
              Any tokenizer problem (unterminated string, comment or template) skips the whole file.
  Units under 3 lines or 12 tokens are skipped. Units may nest (a class row and its method rows).

Hashes
  exact_hash   sha256 of the unit's tokens (comments dropped) joined by one space: any whitespace or
               comment-only change keeps it. Python INDENT/DEDENT/NEWLINE are kept as markers.
  struct_hash  sha256 of the structural stream: identifiers -> ID, numbers -> NUM, strings and template
               literals -> STR (JS regex literals -> REGEX), language keywords and operators kept.
               Python uses the `tokenize` module; f-strings collapse to one STR on every Python version.
  minhash      64 x uint32. Each structural token is hashed with blake2b(digest 8, person b'vedic-tok');
               each 5-token shingle s = t0..t4 is combined as v = ((((t0*P+t1)*P+t2)*P+t3)*P+t4) mod 2^64
               (P = 0x100000001b3) then mixed with the splitmix64 finaliser; function i (0..63) is
               h_i(v) = ((A_i * v + B_i) mod 2^64) >> 32 with A_i (odd), B_i taken from
               blake2b(f"{MINHASH_SEED}/{i}/a|b", digest 8). MINHASH_SEED = "vedic-minhash-v1".
               minhash[i] = min over shingles. Fewer than 5 tokens: the whole stream is one shingle.
               Estimated Jaccard of two units = share of equal positions.
"""
import argparse
import ast
import bisect
import collections
import hashlib
import io
import json
import keyword
import os
import re
import subprocess
import sys
import time
import tokenize
import warnings

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

SCHEMA = 'vedic-fingerprint-units-v1'
MINHASH_SEED = 'vedic-minhash-v1'
N_HASH = 64
SHINGLE = 5
MIN_LINES, MIN_TOKENS = 3, 12
MAX_CALLS, MAX_DOC = 50, 300

EXT = re.compile(r'\.(py|js|mjs|cjs|ts|tsx|jsx|html|htm|css|sh|ps1|bat|yml|yaml|sql|rs|go|c|cc|cpp|h|hpp|'
                 r'java|kt|swift|rb|php|r|jl|lua|toml|glsl|wgsl|vue|svelte)$', re.I)
PARSE_EXT = re.compile(r'\.(py|js|mjs|cjs|ts|tsx|jsx|html|htm)$', re.I)
SKIP = re.compile(r'(^|/)(node_modules|vendor|third_party|dist|build|\.git)/|\.min\.(js|css)$', re.I)
STAMP = re.compile(r'(?<!\d)(20\d{6}(?:T?\d{4,6}Z?)?)(?!\d)')

# ------------------------------------------------------------------ vocabularies (extend freely)
# Domain and unit terms. Matched, lower-cased, against camelCase/snake_case pieces of the unit's
# identifiers (name, params and every identifier in the body) and against words in its strings.
# Terms in AMBIGUOUS (single letters and very short words) only count as a non-first identifier piece
# or right after a number in a string ("11 kV", "5 m"); single letters need more, see unit_terms().
UNIT_TERMS = {
    'geodesy': ['lat', 'lon', 'lng', 'latitude', 'longitude', 'bearing', 'azimuth', 'heading', 'deg', 'degrees',
                'rad', 'radians', 'km', 'm', 'metre', 'metres', 'meter', 'meters', 'mi', 'miles', 'haversine',
                'geodesic', 'wgs84', 'epsg', 'utm', 'osgb', 'bng', 'easting', 'northing', 'elevation', 'altitude',
                'crs', 'geojson', 'distance'],
    'electrical': ['v', 'kv', 'volt', 'volts', 'voltage', 'a', 'amp', 'amps', 'ampere', 'amperes', 'ka', 'current',
                   'ohm', 'ohms', 'impedance', 'resistance', 'reactance', 'hz', 'frequency', 'phase', 'cable',
                   'cables', 'conductor', 'mm2', 'xlpe', 'derating', 'earthing', 'fault'],
    'power': ['w', 'kw', 'mw', 'gw', 'va', 'kva', 'mva', 'kvar', 'mvar', 'pf', 'power', 'reactive', 'apparent'],
    'energy': ['wh', 'kwh', 'mwh', 'gwh', 'twh', 'energy', 'joule', 'joules'],
    'solar_storage': ['solar', 'pv', 'irradiance', 'ghi', 'dni', 'inverter', 'mppt', 'kwp', 'mwp', 'wp', 'battery',
                      'bess', 'soc', 'storage', 'charge', 'discharge'],
    'grid': ['grid', 'substation', 'substations', 'transformer', 'feeder', 'busbar', 'switchgear', 'breaker',
             'dno', 'tso', 'dso', 'interconnector', 'sld', 'kv33', 'kv132'],
    'time': ['ms', 's', 'sec', 'secs', 'second', 'seconds', 'minute', 'minutes', 'h', 'hr', 'hrs', 'hour', 'hours',
             'day', 'days', 'utc', 'timestamp', 'epoch'],
    'money': ['gbp', 'usd', 'eur', 'price', 'prices', 'cost', 'costs', 'tariff', 'capex', 'opex', 'revenue',
              'pence', 'pounds'],
}
TERM_GROUP = {t: g for g, ts in UNIT_TERMS.items() for t in ts}
AMBIGUOUS = {t for t in TERM_GROUP if len(t) == 1} | {'mi', 'ms', 'hr', 'va', 'wp', 'pf', 'ka', 'deg', 'rad', 'sec'}

# Side effects: regexes over a compact token text (strings replaced by "", comments gone, tokens joined
# with nothing except one space between two word tokens: `new Date()`, `document.title`, `fetch(url)`).
_B = r'(?<![\w.$])'  # not part of a longer name and not a property of something else
SIDE_EFFECTS = {
    'dom': {'javascript': [r'\bdocument\.', r'\bwindow\.', r'\bquerySelector(All)?\(', r'\.(innerHTML|outerHTML|innerText|textContent)\b',
                           r'\baddEventListener\(', r'\bremoveEventListener\(', r'\bcreateElement(NS)?\(',
                           r'\bgetElementById\(', r'\bgetElementsBy\w+\(', r'\.(appendChild|removeChild|insertBefore|replaceChildren)\(',
                           r'\.classList\.', r'\.setAttribute\(', r'\.style\.'],
            'python': [r'\bjs\.document\b']},
    'network': {'javascript': [_B + r'fetch\(', r'\bXMLHttpRequest\b', r'\bWebSocket\b', r'\baxios\b',
                               r'\bnavigator\.sendBeacon\(', r'\bEventSource\b'],
                'python': [r'\brequests\.(get|post|put|delete|patch|head|request|Session)\b', r'\burllib\.', r'\burlopen\(',
                           r'\bhttp\.client\b', r'\bhttpx\.', r'\baiohttp\.', r'\bsocket\.', r'\bsmtplib\.']},
    'storage': {'javascript': [r'\blocalStorage\b', r'\bsessionStorage\b', r'\bindexedDB\b', r'\bcaches\.', r'\bdocument\.cookie\b'],
                'python': [r'\bsqlite3\b', r'\bduckdb\b', r'\bpickle\.(dump|load)', r'\bshelve\.', r'\bpsycopg2?\b', r'\bsqlalchemy\b']},
    'filesystem': {'javascript': [r'\bfs\.', r'\bfsPromises\.', r'\b(readFileSync|writeFileSync|readdirSync|mkdirSync|existsSync)\(',
                                  r'\bDeno\.(readTextFile|writeTextFile|readFile|writeFile)', r'\bshow(Save|Open)FilePicker\(',
                                  r'\bFileReader\b'],
                   'python': [_B + r'open\(', r'\.(write_text|read_text|write_bytes|read_bytes|mkdir|unlink|rmdir|touch)\(',
                              r'\bos\.(remove|unlink|rename|replace|makedirs|mkdir|rmdir|listdir|walk|scandir)\b', r'\bshutil\.',
                              r'\bglob\.', r'\bpq\.(write_table|read_table)\(', r'\.to_(csv|parquet|json|excel)\(',
                              r'\bpd\.read_\w+\(', r'\bjson\.(dump|load)\(', r'\bnp\.(save|load|savez|loadtxt|savetxt)\(']},
    'process': {'javascript': [r'\bchild_process\b', r'\bprocess\.(exit|env|argv|on|kill|stdout|stderr|cwd)\b',
                               _B + r'(execSync|spawnSync|spawn|exec|execFile)\(', r'\bnew Worker\('],
                'python': [r'\bsubprocess\.', r'\bos\.(system|popen|exec\w*|spawn\w*|kill|_exit|environ|getenv)\b',
                           r'\bsys\.exit\(', r'\bmultiprocessing\.']},
    'console': {'javascript': [r'\bconsole\.', _B + r'(alert|prompt|confirm)\('],
                'python': [_B + r'print\(', r'\blogging\.', r'\blogger\.', r'\blog\.(debug|info|warning|warn|error|exception)\(',
                           r'\bsys\.(stdout|stderr)\.']},
    'random': {'javascript': [r'\bMath\.random\(', r'\bcrypto\.(getRandomValues|randomUUID|randomBytes)\('],
               'python': [r'\brandom\.', r'\bnp\.random\.', r'\bnumpy\.random\.', r'\buuid\.uuid4\(', r'\bsecrets\.', r'\bos\.urandom\(']},
    'time': {'javascript': [r'\bDate\.now\(', r'\bnew Date\(\)', r'\bperformance\.now\(', _B + r'(setTimeout|setInterval|requestAnimationFrame)\('],
             'python': [r'\btime\.(time|monotonic|perf_counter|sleep|localtime|gmtime|strftime|time_ns)\(',
                        r'\b(datetime|date)\.(now|utcnow|today)\(']},
}
SIDE_RX = {lang: [(cat, re.compile('|'.join(d[lang]))) for cat, d in SIDE_EFFECTS.items() if d.get(lang)]
           for lang in ('python', 'javascript')}

JS_KEYWORDS = frozenset('''break case catch class const continue debugger default delete do else export extends finally
for function if import in instanceof let new return super switch this throw try typeof var void while with yield async
await of static true false null'''.split())
REGEX_AFTER = frozenset('''return typeof instanceof in of new delete void throw case do else yield await'''.split())
NONCALL = frozenset('''if for while switch catch return typeof function class new delete void throw case do else
with yield await import super in of instanceof'''.split())
CLASS_MODS = frozenset('static async get set public private protected readonly abstract override declare accessor'.split())


class TokenizeFailure(Exception):
    pass


# ------------------------------------------------------------------ JavaScript tokenizer
_JS_TOKEN = re.compile(r'''
 (?P<ws>\s+)
|(?P<lc>//[^\n]*)
|(?P<bc>/\*[\s\S]*?\*/)
|(?P<str>"(?:[^"\\\n]|\\[\s\S])*"|'(?:[^'\\\n]|\\[\s\S])*')
|(?P<num>0[xX][0-9a-fA-F_]+n?|0[bB][01_]+n?|0[oO][0-7_]+n?|(?:\d[\d_]*(?:\.[\d_]*)?|\.\d[\d_]*)(?:[eE][+-]?\d+)?n?)
|(?P<id>\#?[^\W\d][\w$]*|\#?\$[\w$]*)
|(?P<punc>>>>=|\.\.\.|===|!==|\*\*=|<<=|>>=|>>>|&&=|\|\|=|\?\?=|=>|==|!=|<=|>=|&&|\|\||\?\?|\?\.(?!\d)|\+\+|--|\+=|-=|\*=|%=|&=|\|=|\^=|\*\*|<<|>>|[{}()\[\];,<>+\-*%&|^!~?:=.@])
''', re.X)
_JS_REGEX = re.compile(r'/(?![*/])(?:[^/\\\[\n]|\\.|\[(?:[^\]\\\n]|\\.)*\])+/[a-zA-Z]*')
_TMPL_CHUNK = re.compile(r'(?:[^`\\$]|\\[\s\S]|\$(?!\{))*')


def _lex(src, pos, out, comments, nested, depth):
    """Tokenize src from pos. Appends (type, text, start) to out: type i(dentifier/keyword) n s t(emplate)
    r(egex) p(unctuator). nested: stop after the '}' that closes a template ${ and return its end."""
    if depth > 40:
        raise TokenizeFailure('template nesting too deep')
    n = len(src)
    brace = 0
    match = _JS_TOKEN.match
    prev_t = prev_x = None
    while pos < n:
        c = src[pos]
        if c == '`':
            start = pos
            pos += 1
            while True:
                pos = _TMPL_CHUNK.match(src, pos).end()
                if pos >= n:
                    raise TokenizeFailure('unterminated template')
                if src[pos] == '`':
                    pos += 1
                    break
                pos = _lex(src, pos + 2, [], comments if not nested else [], True, depth + 1)
            if out is not None:
                out.append(('t', src[start:pos], start))
            prev_t, prev_x = 't', None
            continue
        if c == '/':
            nx = src[pos + 1:pos + 2]
            if nx == '*':
                end = src.find('*/', pos + 2)
                if end < 0:
                    raise TokenizeFailure('unterminated comment')
                comments.append((pos, end + 2, src[pos:end + 2]))
                pos = end + 2
                continue
            if nx == '/':
                end = src.find('\n', pos)
                end = n if end < 0 else end
                comments.append((pos, end, src[pos:end]))
                pos = end
                continue
            regex_ok = prev_t is None or (prev_t == 'p' and prev_x not in (')', ']', '}')) or \
                (prev_t == 'i' and prev_x in REGEX_AFTER)
            if regex_ok:
                m = _JS_REGEX.match(src, pos)
                if m:
                    out.append(('r', m.group(), pos))
                    prev_t, prev_x = 'r', None
                    pos = m.end()
                    continue
            if nx == '=':
                out.append(('p', '/=', pos))
                pos += 2
            else:
                out.append(('p', '/', pos))
                pos += 1
            prev_t, prev_x = 'p', '/'
            continue
        m = match(src, pos)
        if m is None:
            if c in '"\'':
                raise TokenizeFailure('unterminated string')
            # unknown character (e.g. stray unicode punctuation): keep it as a punctuator
            out.append(('p', c, pos))
            prev_t, prev_x = 'p', c
            pos += 1
            continue
        k = m.lastgroup
        end = m.end()
        if k == 'ws':
            pos = end
            continue
        text = m.group()
        if k == 'punc':
            if text == '{':
                brace += 1
            elif text == '}':
                if nested and brace == 0:
                    return end
                brace -= 1
            out.append(('p', text, pos))
            prev_t, prev_x = 'p', text
        elif k == 'id':
            out.append(('i', text, pos))
            prev_t, prev_x = 'i', text
        elif k == 'str':
            out.append(('s', text, pos))
            prev_t, prev_x = 's', None
        elif k == 'num':
            out.append(('n', text, pos))
            prev_t, prev_x = 'n', None
        else:  # lc / bc handled above; defensive
            comments.append((pos, end, text))
        pos = end
    if nested:
        raise TokenizeFailure('unterminated template expression')
    return pos


def js_tokenize(src):
    toks, comments = [], []
    _lex(src, 0, toks, comments, False, 0)
    return toks, comments


def bracket_match(toks):
    """match[i] = index of the partner bracket, -1 if none. Tolerates mismatches."""
    match = [-1] * len(toks)
    stack = []
    pair = {')': '(', ']': '[', '}': '{'}
    for i, (t, x, _) in enumerate(toks):
        if t != 'p':
            continue
        if x in '([{' and len(x) == 1:
            stack.append(i)
        elif x in pair and len(x) == 1:
            want = pair[x]
            for d in range(len(stack) - 1, max(-1, len(stack) - 4), -1):
                if toks[stack[d]][1] == want:
                    j = stack[d]
                    del stack[d:]
                    match[i], match[j] = j, i
                    break
    return match


def _is(toks, i, x):
    return 0 <= i < len(toks) and toks[i][1] == x and toks[i][0] == 'p'


def _ident(toks, i):
    return 0 <= i < len(toks) and toks[i][0] == 'i'


def _skip_generic(toks, j, limit=40):
    """Skip a TypeScript <...> generic list starting at j; return index after it (or j)."""
    if not _is(toks, j, '<'):
        return j
    d = 0
    for k in range(j, min(len(toks), j + limit)):
        x = toks[k][1]
        if toks[k][0] == 'p':
            if x == '<':
                d += 1
            elif x == '>':
                d -= 1
            elif x == '>>':
                d -= 2
            elif x in ('{', ';', ')'):
                return j
            if d <= 0:
                return k + 1
    return j


def _find_body(toks, match, p, limit=40):
    """After a parameter list: skip a TS return type up to the '{' that opens the body."""
    n = len(toks)
    end = min(n, p + limit)
    while p < end:
        t, x, _ = toks[p]
        if t == 'p':
            if x == '{':
                if p > 0 and toks[p - 1][1] == ':' and toks[p - 1][0] == 'p':  # `): {a: T} {`
                    m = match[p]
                    if m > 0:
                        p = m + 1
                        continue
                return p
            if x in (';', '=>', '}', ')', ',', '='):
                return -1
            if x in ('(', '[') and match[p] > 0:
                p = match[p] + 1
                continue
        p += 1
    return -1


def js_params(toks, match, o, c):
    out, seg_start, k = [], o + 1, o + 1
    segs = []
    while k < c:
        t, x, _ = toks[k]
        if t == 'p' and x in ('(', '[', '{') and match[k] > k:
            k = match[k] + 1
            continue
        if t == 'p' and x == ',':
            segs.append((seg_start, k))
            seg_start = k + 1
        k += 1
    if seg_start < c:
        segs.append((seg_start, c))
    for a, b in segs:
        while a < b and (toks[a][1] in ('...', '@') or (toks[a][0] == 'i' and toks[a][1] in CLASS_MODS and
                                                         a + 1 < b and toks[a + 1][0] == 'i')):
            a += 1
        if a >= b:
            continue
        t, x, _ = toks[a]
        if t == 'i' and x != 'this':
            out.append(x)
        elif t == 'p' and x in ('{', '['):
            e = match[a] if match[a] > a else b
            for q in range(a + 1, e):
                if toks[q][0] == 'i' and q + 1 <= e and toks[q + 1][1] in (',', '}', ']', '=') and toks[q - 1][1] != '=':
                    out.append(toks[q][1])
    return out


def _expr_end(toks, match, b):
    """Last token index of an arrow function's expression body starting at b."""
    n = len(toks)
    k, last = b, b
    while k < n:
        t, x, _ = toks[k]
        if t == 'p':
            if x in ('(', '[', '{'):
                m = match[k]
                if m < 0:
                    return last
                last = k = m
                k += 1
                continue
            if x in (')', ']', '}', ';', ','):
                return last
        if k > b and t in ('i', 's', 'n', 't') and toks[last][0] in ('i', 's', 'n', 't', 'r') or \
                (k > b and t in ('i', 's', 'n', 't') and toks[last][1] in (')', ']', '}') and toks[last][0] == 'p'):
            if not (t == 'i' and x in ('in', 'of', 'instanceof')):
                return last
        last = k
        k += 1
    return last


def js_units(toks, match):
    """Return list of (kind, name, params, start_idx, end_idx, name_idx)."""
    n = len(toks)
    units = []
    fn_override = {}  # index of `function` keyword -> (name, start, kind)
    for i in range(n):
        t, x, _ = toks[i]
        if t != 'i':
            continue
        if i > 0 and toks[i - 1][1] in ('.', '?.') and toks[i - 1][0] == 'p':
            continue  # property named like a keyword
        if x in ('const', 'let', 'var'):
            j = i + 1
            if not (_ident(toks, j) and toks[j][1] not in JS_KEYWORDS):
                continue
            name, k = toks[j][1], j + 1
            if _is(toks, k, ':'):  # TS type annotation
                q = k + 1
                while q < min(n, k + 30) and not _is(toks, q, '=') and not _is(toks, q, ';'):
                    q = match[q] + 1 if toks[q][1] in ('(', '[', '{') and match[q] > q else q + 1
                k = q
            if not _is(toks, k, '='):
                continue
            k += 1
            if _ident(toks, k) and toks[k][1] == 'async' and k + 1 < n and toks[k + 1][1] in ('function', '(') or \
                    (_ident(toks, k) and toks[k][1] == 'async' and _ident(toks, k + 1) and _is(toks, k + 2, '=>')):
                k += 1
            if _ident(toks, k) and toks[k][1] == 'function':
                fn_override[k] = (name, i, 'function')