GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Kuiper, cosmos and drawing engines / cosmic / tools/explore/ci

CI Newcode

A Python command-line tool in the explore folder of Cosmic that reads units and build graph, using haversine and SHA-256.

666 lines of Python from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1091 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. CI Newcode automation · cosmic / tools/explore/ci/newcode.py lines 1–666

CI Newcode

A Python command-line tool in the explore folder of Cosmic that reads units and build graph, using haversine and SHA-256.

automationcosmic / tools/explore/ci/newcode.py · lines 1–666 of 666 · Entry point · pattern _strip_comments (shared by 2 files)

What it does
It loads units and build graph. Defines 31 functions or classes, including first, git, sha, make_key, Extractor. Uses libraries argparse, hashlib, json, os, re. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: Parquet file units.parquet; JSON file build_graph.json; command-line arguments. Out: JSON file. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
Used directly by 1 file: Test CI (cosmic).
What it achieves
It makes key (`make_key`), loads Parquet (`load_parquet`) and finds bng (`find_bng`). New-code hunter: lists only the files and functions that are new or changed since the last deployed commit, and flags each new function as unique, a duplicate (exact or near, with the key of the original). It accepts `--repo`, `--name` and `--base`.
Why it matters
Checked by Test CI.
Application
cosmic · tools/explore/ci · Python CLI
Uses
argparse, hashlib, json, os, re, subprocess, sys, extract
Used by
imported by Test CI (import)
Produces
first, git, sha, make_key, Extractor, lite_rows, Index, tree_files, text_hash, file_units, load_parquet, engine_reference
Defines here
first, git, sha, make_key, Extractor, __init__, vedic, rows, _strip_comments, _lite_hashes, _lite_minhash, lite_rows, Index, __init__, add, _best, _other, match, tree_files, text_hash, file_units, load_parquet, engine_reference, find_bng, resolve_base, changed_files, engine_flag, hunt, summarise, report
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
cosmic@51bebf892d63a617408bc5e25b270b9f893e9c03 tools/explore/ci/newcode.py:1-666 · blob a4764417991743e5f60f1e05e69b67b1b984e3c5 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""New-code hunter: lists only the files and functions that are new or changed since the last deployed commit,
and flags each new function as unique, a duplicate (exact or near, with the key of the original), or engine maths
that should import Ventus Grid Engine / bng.mjs instead of copying it.

    python tools/explore/ci/newcode.py [--repo DIR] [--base SHA] [--head REV] [--graph build_graph.json]
        [--units units.parquet] [--engine DIR] [--bng FILE] [--estate SRC] [--out ci-newcode.md] [--json FILE]

Advisory: exit 0 unless a new function is an EXACT duplicate of more than 20 lines (exit 1). Exit 2 = usage error.

Base commit (first that applies, recorded in the report):
  1. --base SHA (in CI: github.event.before);
  2. build_graph.json repos[<repo name>].commit, i.e. the commit the last deployed Explore Code cut read,
     if it exists locally and is an ancestor of --head;
  3. `git log` parent of --head (HEAD~1).

Units (functions, methods, classes, arrows) come from the VEDIC fingerprint extractor (vedic-/fingerprints/
extract.py, schema vedic-fingerprint-units-v1: exact_hash, struct_hash, 64-value MinHash) when it can be imported
(--vedic DIR, $VEDIC_FINGERPRINTS, or ../vedic-/fingerprints next to the repo). Without it a small built-in
extractor is used (Python ast; JS `function name(`, `name = function`, `name = (..) =>`, brace matched); its hashes
are not comparable with units.parquet, so the estate index is then skipped and the report says so.

Reference ("existing code") = units of the base tree of the repo (or the units.parquet rows of that repo at that
same commit), units.parquet rows of every other estate repo, Ventus Grid Engine engine/*.js and bng.mjs, plus new
units earlier in path order (a function pasted twice in one push is a duplicate of the first paste).

Classes, in this order:
  engine-maths     exact/structural/near (MinHash >= 0.8) match to a Grid Engine or bng.mjs unit, or the name of
                   an engine export with trig/maths calls, or an earth-radius constant (6371, 6378.137, 6378137)
                   used with trig. Not flagged where the file already imports the engine or bng.
  duplicate-exact  same exact_hash (tokens equal, comments and whitespace ignored) as a reference unit.
  duplicate-near   same struct_hash or MinHash Jaccard >= 0.8 (VEDIC rules.json cluster.near_jaccard), 25+ tokens.
  unique           anything else.
Keys follow clean/CONTRACT.md: <repo>@<commit> <path>:<first>-<last> <blob>.
"""
import argparse
import hashlib
import json
import os
import re
import subprocess
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
COSMIC = os.path.abspath(os.path.join(HERE, '..', '..', '..'))
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)
MAX_BYTES = 1 << 20
NEAR = 0.8
NEAR_MIN_TOKENS = 25
BANDS, ROWS = 16, 4
FAIL_LINES = 20
EARTH = re.compile(r'(?<![\d.])(6371(?:\.0+)?|6371\.0088|6378\.137|6378137|6371000|6371008\.8)(?![\d])')
TRIG = re.compile(r'\b(?:Math\.|math\.|np\.)?(?:sin|cos|atan2|asin|acos|tan|sqrt|hypot)\s*\(')
# A real import statement (ES import / dynamic import / require) of an engine module or bng.mjs; a credit comment
# naming the engine is a copy, not an import.
IMPORTS_ENGINE = re.compile(r"(?m)^\s*(?:import\b[^;\n]*\bfrom\s*|.*\bimport\s*\(\s*|.*\brequire\s*\(\s*)['\"]"
                            r"[^'\"]*(?:ventus-grid-engine[^'\"]*|/engine/[\w-]+\.js|bng\.mjs)['\"]")
# Name matches count only for maths-specific export names (not generic ones such as index, at, within, record).
MATHS_NAME = re.compile(r'dist|km|bearing|haversine|^tm|bng|wgs|gridref|area|perimeter|circle|destination|voltage|'
                        r'current|power|kva|kvar|mva|loss|drop|capacity', re.I)
TEST_PATH = re.compile(r'(^|/)(test_[^/]*\.py|[^/]*_test\.py|[^/]*\.(test|spec)\.[jt]sx?|tests?/)')
DEFAULT_PATHS = {
    'vedic': [os.environ.get('VEDIC_FINGERPRINTS', ''), os.path.join(COSMIC, '..', 'vedic-', 'fingerprints'),
              os.path.join(COSMIC, '..', 'clones', 'vedic-', 'fingerprints'), '/home/claude/vedic-/fingerprints'],
    'units': [os.environ.get('VEDIC_UNITS', ''), os.path.join(COSMIC, '..', 'vedic-', 'fingerprints', 'out', 'units.parquet'),
              '/home/claude/vedic-/fingerprints/out/units.parquet'],
    'engine': [os.environ.get('GRID_ENGINE', ''), os.path.join(COSMIC, '..', 'clones', 'ventus-grid-engine'),
               os.path.join(COSMIC, '..', 'ventus-grid-engine'), '/home/claude/src/ventus-grid-engine'],
    'graph': [os.environ.get('EXPLORE_GRAPH', ''), os.path.join(COSMIC, '..', '_site', 'explore-code', 'build_graph.json'),
              '/tmp/site8/explore-code/build_graph.json'],
}
# Exported maths of ventus-grid-engine@ad56635 engine/*.js and bng.mjs, used only when the clone is absent (CI
# without it): a new function with one of these names and trig/maths calls is flagged engine-maths by name.
ENGINE_NAMES_FALLBACK = {
    'distancekm', 'haversine', 'haversineuk', 'initialbearingdeg', 'destinationpoint', 'destinationcirclepoints',
    'circlevertexcount', 'circlecapareakm2', 'polygonareakm2', 'polylineperimeterkm', 'voltagedropvolts',
    'droppercent', 'currenta', 'currentfrommvaatkv', 'apparentpowerkva', 'apparentpowermva', 'reactivepowerkvar',
    'correctionkvar', 'losseswatts', 'annuallosskwh', 'firmcapacitymva', 'tmforward', 'tminverse', 'bngtowgs84',
    'wgs84tobng', 'parsegridref', 'gridref'}


def first(paths, isdir=False):
    for p in paths:
        if p and (os.path.isdir(p) if isdir else os.path.exists(p)):
            return os.path.abspath(p)
    return None


def git(repo, *args, binary=False, check=True):
    r = subprocess.run(['git', '-C', repo] + list(args), capture_output=True)
    if check and r.returncode:
        raise RuntimeError('git %s: %s' % (' '.join(args), r.stderr.decode(errors='replace').strip()))
    return r.stdout if binary else r.stdout.decode('utf-8', 'replace')


def sha(s):
    return hashlib.sha256(s.encode('utf-8', 'replace')).hexdigest()


def make_key(repo, commit, path, a, b, blob):
    return '%s@%s %s:%d-%d %s' % (repo, commit, path, a, b, blob or '-')


# ----------------------------------------------------------------------------------------------- extractors
class Extractor:
    """VEDIC extract.py when importable, else the built-in lite extractor. rows(path, text) -> unit dicts with
    name, kind, line_from, line_to, n_lines, n_tokens, exact_hash, struct_hash, minhash, calls."""

    def __init__(self, vedic_dir=None):
        self.X, self.name = None, 'builtin-lite'
        d = vedic_dir or first(DEFAULT_PATHS['vedic'], isdir=True)
        if d and os.path.exists(os.path.join(d, 'extract.py')):
            try:
                sys.path.insert(0, d)
                import extract as X  # noqa: E402
                self.X, self.name = X, 'vedic-extract (%s)' % X.SCHEMA
            except Exception as e:  # numpy/pyarrow missing etc.
                print('newcode: VEDIC extractor unavailable (%s); using builtin-lite' % e, file=sys.stderr)
            finally:
                sys.path.remove(d)

    @property
    def vedic(self):
        return self.X is not None

    def rows(self, path, text):
        if not PARSE_EXT.search(path) or SKIP.search(path):
            return []
        if text.count('\n') and len(text) / (text.count('\n') + 1) > 400:
            return []  # minified, same rule as VEDIC
        try:
            if self.X:
                rows, _ = self.X.file_rows(path, text)
                out = self.X.finish_rows(rows, {'repo': '', 'commit': '', 'path': path, 'blob': ''})
                for r in out:
                    r['minhash'] = [int(v) for v in r['minhash']]
                return out
            return lite_rows(path, text)
        except Exception:
            return []


_TOK = re.compile(r'"(?:\\.|[^"\\\n])*"|\'(?:\\.|[^\'\\\n])*\'|`(?:\\.|[^`\\])*`|[A-Za-z_$][\w$]*|\d[\w.]*|'
                  r'==+|!=+|<=|>=|=>|&&|\|\||\*\*|[^\s\w]')
_KW = set('''if else for while do return function var let const new class this typeof instanceof in of try catch
finally throw switch case break continue default async await yield import export from def lambda and or not is
None True False null undefined true false pass elif with as global nonlocal raise del self'''.split())


def _strip_comments(text, py):
    if py:
        return re.sub(r'(?m)#.*$', '', text)
    return re.sub(r'/\*.*?\*/|(?<![:\\])//[^\n]*', '', text, flags=re.S)


def _lite_hashes(body, py):
    toks = _TOK.findall(_strip_comments(body, py))
    struct = []
    for t in toks:
        if t[0] in '"\'`':
            struct.append('STR')
        elif t[0].isdigit():
            struct.append('NUM')
        elif re.match(r'[A-Za-z_$]', t):
            struct.append(t if t in _KW else 'ID')
        else:
            struct.append(t)
    return toks, struct


def _lite_minhash(struct):
    sh = {' '.join(struct[i:i + 5]) for i in range(max(1, len(struct) - 4))}
    return [min(int.from_bytes(hashlib.blake2b(s.encode(), digest_size=4, person=b'lite%04d' % k).digest(), 'big')
                for s in sh) for k in range(64)]


def lite_rows(path, text):
    lines = text.split('\n')
    py = path.lower().endswith('.py')
    spans = []
    if py:
        import ast
        try:
            tree = ast.parse(text)
        except SyntaxError:
            return []
        for node in ast.walk(tree):
            if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
                a = min([node.lineno] + [d.lineno for d in node.decorator_list])
                spans.append((node.name, 'class' if isinstance(node, ast.ClassDef) else 'function', a, node.end_lineno))
    else:
        pat = re.compile(r'(?:\bfunction\s+([A-Za-z_$][\w$]*)\s*\(|\b([A-Za-z_$][\w$]*)\s*[=:]\s*(?:async\s+)?'
                         r'(?:function\b[^(]*\(|\([^()]*\)\s*=>\s*\{))')
        offs = [0]
        for ln in lines:
            offs.append(offs[-1] + len(ln) + 1)
        import bisect
        for m in pat.finditer(text):
            name = m.group(1) or m.group(2)
            o = text.find('{', m.end() - 1)
            if o < 0:
                continue
            depth, i = 0, o
            while i < len(text):
                c = text[i]
                if c == '{':
                    depth += 1
                elif c == '}':
                    depth -= 1
                    if depth == 0:
                        break
                i += 1
            a = bisect.bisect_right(offs, m.start())
            b = bisect.bisect_right(offs, i)
            spans.append((name, 'function', a, b))
    out = []
    for name, kind, a, b in spans:
        body = '\n'.join(lines[a - 1:b])
        toks, struct = _lite_hashes(body, py)
        if b - a + 1 < 3 or len(toks) < 12:
            continue
        calls = sorted(set(re.findall(r'([A-Za-z_$][\w$.]*)\s*\(', body)))[:50]
        out.append({'name': name, 'kind': kind, 'line_from': a, 'line_to': b, 'n_lines': b - a + 1,
                    'n_tokens': len(toks), 'exact_hash': sha(' '.join(toks)), 'struct_hash': sha(' '.join(struct)),
                    'minhash': _lite_minhash(struct), 'calls': calls})
    return out


# ----------------------------------------------------------------------------------------------- reference index
class Index:
    """Reference units: exact/struct hash maps and MinHash LSH buckets. Lower `prio` wins as the original."""

    def __init__(self):
        self.units, self.exact, self.struct, self.buckets = [], {}, {}, {}

    def add(self, u, prio):
        u = dict(u, prio=prio)
        i = len(self.units)
        self.units.append(u)
        self.exact.setdefault(u['exact_hash'], []).append(i)
        if u.get('text_hash'):
            self.exact.setdefault(u['text_hash'], []).append(i)
        if u['n_tokens'] >= NEAR_MIN_TOKENS:
            self.struct.setdefault(u['struct_hash'], []).append(i)
            mh = u['minhash']
            for b in range(BANDS):
                self.buckets.setdefault((b, tuple(mh[b * ROWS:(b + 1) * ROWS])), []).append(i)

    @staticmethod
    def _best(cands):
        return min(cands, key=lambda u: (u['prio'], u['repo'], u['path'], u['line_from']))

    @staticmethod
    def _other(u, r):
        """False when r is u itself or nests with it (same file, overlapping line ranges)."""
        return not (r['repo'] == u['repo'] and r['commit'] == u['commit'] and r['path'] == u['path']
                    and r['line_from'] <= u['line_to'] and u['line_from'] <= r['line_to'])

    def match(self, u):
        """-> (relation, original unit, jaccard) or None."""
        hits = list(self.exact.get(u['exact_hash'], ())) + list(self.exact.get(u.get('text_hash') or '-', ()))
        ex = [self.units[i] for i in dict.fromkeys(hits) if self._other(u, self.units[i])]
        if ex:
            return 'exact', self._best(ex), 1.0
        if u['n_tokens'] < NEAR_MIN_TOKENS:
            return None
        st = [self.units[i] for i in self.struct.get(u['struct_hash'], ()) if self._other(u, self.units[i])]
        if st:
            return 'structural', self._best(st), 1.0
        mh = u['minhash']
        seen = set()
        for b in range(BANDS):
            seen.update(self.buckets.get((b, tuple(mh[b * ROWS:(b + 1) * ROWS])), ()))
        best = None
        for i in seen:
            r = self.units[i]
            if not self._other(u, r):
                continue
            j = sum(1 for x, y in zip(mh, r['minhash']) if x == y) / 64.0
            if j >= NEAR and (best is None or (-j, r['prio'], r['repo'], r['path']) < (-best[1], best[0]['prio'],
                                                                                     best[0]['repo'], best[0]['path'])):
                best = (r, j)
        return ('near', best[0], best[1]) if best else None


def tree_files(repo, rev):
    """[(path, blob, text)] of parseable code files at rev (VEDIC selection: <= 1 MB, no vendor/dist/min)."""
    out = []
    raw = git(repo, 'ls-tree', '-r', '-l', '-z', rev, binary=True)
    items = []
    for rec in raw.split(b'\0'):
        if not rec:
            continue
        meta, path = rec.split(b'\t', 1)
        mode, typ, blob, size = meta.split()
        path = path.decode('utf-8', 'replace')
        if typ != b'blob' or not PARSE_EXT.search(path) or SKIP.search(path):
            continue
        if size == b'-' or not 0 < int(size) <= MAX_BYTES:
            continue
        items.append((path, blob.decode()))
    if not items:
        return out
    p = subprocess.run(['git', '-C', repo, 'cat-file', '--batch'], input=''.join(b + '\n' for _, b in items).encode(),
                       capture_output=True, check=True)
    data, pos = p.stdout, 0
    for path, blob in items:
        nl = data.index(b'\n', pos)
        size = int(data[pos:nl].split()[2])
        body = data[nl + 1:nl + 1 + size]
        pos = nl + 1 + size + 1
        if b'\0' in body[:8000]:
            continue
        out.append((path, blob, body.decode('utf-8', 'replace')))
    return out


def text_hash(path, text, a, b):
    """Context-free exact hash of lines a..b: comments stripped, whitespace collapsed. (VEDIC's Python exact_hash
    also carries DEDENT tokens of the block before the unit, so one function pasted after different code can
    get two exact_hash values; this hash does not.)"""
    body = '\n'.join(text.split('\n')[a - 1:b])
    return 't:' + sha(' '.join(_strip_comments(body, path.lower().endswith('.py')).split()))


def file_units(ex, repo_name, commit, path, blob, text):
    return [dict(u, repo=repo_name, commit=commit, path=path, blob=blob,
                 text_hash=text_hash(path, text, u['line_from'], u['line_to'])) for u in ex.rows(path, text)]


def load_parquet(path, skip_repos=()):
    import pyarrow.parquet as pq
    cols = ['repo', 'commit', 'path', 'blob', 'name', 'kind', 'line_from', 'line_to', 'n_lines', 'n_tokens',
            'exact_hash', 'struct_hash', 'minhash']
    t = pq.read_table(path, columns=cols).to_pydict()
    out = []
    for k in range(len(t['repo'])):
        if t['repo'][k] in skip_repos:
            continue
        out.append({c: t[c][k] for c in cols})
    return out


def engine_reference(ex, engine_dir, bng_path):
    """Units of ventus-grid-engine engine/*.js (exported maths) and bng.mjs, plus their exported names."""
    units, names = [], set()
    if engine_dir and os.path.isdir(os.path.join(engine_dir, 'engine')):
        try:
            commit = git(engine_dir, 'rev-parse', 'HEAD').strip()
        except RuntimeError:
            commit = '-'
        for fn in sorted(os.listdir(os.path.join(engine_dir, 'engine'))):
            if not fn.endswith('.js'):
                continue
            path = 'engine/' + fn
            text = open(os.path.join(engine_dir, path), encoding='utf-8', errors='replace').read()
            blob = git(engine_dir, 'hash-object', path, check=False).strip() or '-'
            names.update(n.lower() for n in re.findall(r'export\s+(?:async\s+)?function\s+([\w$]+)', text))
            units += file_units(ex, 'ventus-grid-engine', commit, path, blob, text)
    if bng_path and os.path.isfile(bng_path):
        text = open(bng_path, encoding='utf-8', errors='replace').read()
        d = os.path.dirname(bng_path)
        top = git(d, 'rev-parse', '--show-toplevel', check=False).strip()
        repo = os.path.basename(top) if top else 'bng'
        commit = git(d, 'rev-parse', 'HEAD', check=False).strip() or '-'
        rel = os.path.relpath(bng_path, top) if top else os.path.basename(bng_path)
        blob = git(d, 'hash-object', bng_path, check=False).strip() or '-'
        names.update(n.lower() for n in re.findall(r'export\s+(?:async\s+)?function\s+([\w$]+)', text))
        units += file_units(ex, repo, commit, rel, blob, text)
    return units, names


def find_bng():
    for p in (os.environ.get('BNG_MJS', ''),
              os.path.join(COSMIC, '..', 'clones', 'energy-transition-simulator', 'prototype', 'mod', 'engine', 'bng.mjs'),
              '/home/claude/src/energy-transition-simulator/prototype/mod/engine/bng.mjs',
              '/home/claude/lic/energy-transition-simulator/prototype/mod/engine/bng.mjs'):
        if p and os.path.isfile(p):
            return os.path.abspath(p)
    return None


# ----------------------------------------------------------------------------------------------- the hunt
def resolve_base(repo, repo_name, head, base, graph):
    if base and not re.fullmatch(r'0+', base):
        return git(repo, 'rev-parse', base + '^{commit}').strip(), '--base'
    if graph:
        for r in graph.get('repos', []):
            c = r.get('commit')
            if r.get('repo') == repo_name and c:
                ok = subprocess.run(['git', '-C', repo, 'merge-base', '--is-ancestor', c, head],
                                    capture_output=True).returncode == 0
                if ok:
                    return c, 'build_graph cut %s repos[%s].commit' % (graph.get('cut'), repo_name)
    parent = git(repo, 'rev-parse', head + '~1', check=False).strip()
    if parent:
        return parent, 'git log parent of %s' % head
    return None, 'no base (first commit)'


def changed_files(repo, base, head):
    """[(status, old_path, path)] for code files added/modified/renamed between base and head."""
    raw = git(repo, 'diff', '--name-status', '-z', '-M', base, head, binary=True).decode('utf-8', 'replace')
    parts = raw.split('\0')
    out, i = [], 0
    while i < len(parts) and parts[i]:
        st = parts[i]
        if st[0] in 'RC':
            out.append((st[0], parts[i + 1], parts[i + 2]))
            i += 3
        else:
            out.append((st[0], parts[i + 1], parts[i + 1]))
            i += 2
    return out


def engine_flag(u, text, eng_index, eng_names, imports_engine):
    if imports_engine or TEST_PATH.search(u['path']):
        return None
    if eng_index is not None:
        m = eng_index.match(u)
        if m:
            return {'by': m[0] + (' %.2f' % m[2] if m[0] == 'near' else ''), 'original': m[1]}
    body = '\n'.join(text.split('\n')[u['line_from'] - 1:u['line_to']])
    has_trig = bool(TRIG.search(body))
    nm = u['name'].lower().lstrip('_')
    if nm in eng_names and has_trig and MATHS_NAME.search(nm):
        return {'by': 'name of an engine export with trig/maths', 'original': None, 'name': nm}
    if has_trig and EARTH.search(body):
        guess = 'destinationpoint' if 'dest' in nm else 'initialbearingdeg' if 'bear' in nm else 'distancekm'
        return {'by': 'earth radius constant %s with trig' % EARTH.search(body).group(1), 'original': None,
                'name': guess}
    return None


def hunt(repo, repo_name, base, head, ex, ref_units, eng_units, eng_names):
    """Analyse one repo between base and head. ref_units: estate reference (other repos). Returns a result dict."""
    head_sha = git(repo, 'rev-parse', head + '^{commit}').strip()
    files = changed_files(repo, base, head_sha)
    code = [(s, o, p) for s, o, p in files if PARSE_EXT.search(p) and not SKIP.search(p)]
    idx = Index()
    for u in eng_units:
        idx.add(u, 0)
    for u in ref_units:
        idx.add(u, 2 if u['repo'] != repo_name else 1)
    eng_idx = Index()
    for u in eng_units:
        eng_idx.add(u, 0)
    eng_by_name = {}
    for u in eng_units:
        eng_by_name.setdefault(u['name'].lower(), u)
    blobs = {}
    if code:
        for line in git(repo, 'ls-tree', '-r', head_sha, '--', *[p for _, _, p in code]).splitlines():
            meta, path = line.split('\t', 1)
            blobs[path] = meta.split()[2]
    out_files, out_units = [], []
    for st, old, path in sorted(code, key=lambda x: x[2]):
        text = git(repo, 'show', '%s:%s' % (head_sha, path), check=False)
        units = file_units(ex, repo_name, head_sha, path, blobs.get(path, '-'), text)
        old_units = {}
        if st in 'MRC':
            otext = git(repo, 'show', '%s:%s' % (base, old), check=False)
            for ou in ex.rows(old, otext):
                old_units.setdefault(ou['name'], set()).add(ou['exact_hash'])
        imp = bool(IMPORTS_ENGINE.search(text))
        n_new = 0
        for u in sorted(units, key=lambda u: u['line_from']):
            if u['name'] in old_units and u['exact_hash'] in old_units[u['name']]:
                continue
            change = 'changed' if u['name'] in old_units else 'new'
            rec = {'path': path, 'name': u['name'], 'kind': u['kind'], 'change': change,
                   'lines': [u['line_from'], u['line_to']], 'n_lines': u['n_lines'], 'n_tokens': u['n_tokens'],
                   'key': make_key(repo_name, head_sha, path, u['line_from'], u['line_to'], u['blob'])}
            ef = engine_flag(u, text, eng_idx if eng_units else None, eng_names, imp)
            m = idx.match(u)
            if ef:
                orig = ef['original'] or eng_by_name.get(ef.get('name', ''))
                rec.update(cls='engine-maths', by=ef['by'],
                           original=make_key(orig['repo'], orig['commit'], orig['path'], orig['line_from'],
                                             orig['line_to'], orig['blob']) if orig else 'engine export ' + ef['name'])
                rec['exact'] = bool(m and m[0] == 'exact')
            elif m and m[0] == 'exact':
                rec.update(cls='duplicate-exact', by='exact', exact=True)
            elif m:
                rec.update(cls='duplicate-near', by=m[0] + (' %.2f' % m[2] if m[0] == 'near' else ''), exact=False)
            else:
                rec.update(cls='unique', exact=False)
            if m and 'original' not in rec:
                o = m[1]
                rec['original'] = make_key(o['repo'], o['commit'], o['path'], o['line_from'], o['line_to'], o['blob'])
            out_units.append(rec)
            n_new += 1
            idx.add(u, 3)  # later pastes in this push match this one
        out_files.append({'status': st, 'path': path, 'old_path': old if old != path else None,
                          'lines': text.count('\n') + (1 if text and not text.endswith('\n') else 0),
                          'units': len(units), 'new_or_changed_units': n_new})
    other = [{'status': s, 'path': p} for s, o, p in files if (s, o, p) not in code]
    return {'repo': repo_name, 'dir': repo, 'base': base, 'head': head_sha, 'code_files': out_files,
            'other_files': other, 'units': out_units}


def summarise(res):
    c = {}
    for u in res['units']:
        c[u['cls']] = c.get(u['cls'], 0) + 1
    fails = [u for u in res['units'] if u.get('exact') and u['n_lines'] > FAIL_LINES]
    return c, fails


def report(results, meta):
    L = ['# New code since the last deploy (ci-newcode)', '',
         'Generated by tools/explore/ci/newcode.py. Advisory: fails only on exact duplicates of more than %d lines.'
         % FAIL_LINES, '',
         '- extractor: %s' % meta['extractor'],
         '- estate index: %s' % meta['units'],
         '- Grid Engine reference: %s' % meta['engine'],
         '- bng.mjs reference: %s' % meta['bng'],
         '- estate clones: %s' % meta.get('estate', 'not requested'), '']
    total_fail = 0
    for res in results:
        c, fails = summarise(res)
        total_fail += len(fails)
        L += ['## %s %s..%s' % (res['repo'], res['base'][:7], res['head'][:7]), '',
              'Base from: %s.' % res['base_from'], '',
              '| files changed (code) | files changed (other) | new/changed functions | unique | exact dup | near dup | engine maths | exact dup > %d lines |' % FAIL_LINES,
              '|---|---|---|---|---|---|---|---|',
              '| %d | %d | %d | %d | %d | %d | %d | %d |' % (
                  len(res['code_files']), len(res['other_files']), len(res['units']), c.get('unique', 0),
                  c.get('duplicate-exact', 0), c.get('duplicate-near', 0), c.get('engine-maths', 0), len(fails)), '']
        if fails:
            L += ['### Blocking: exact duplicates over %d lines' % FAIL_LINES, '']
            L += ['- `%s` %s (%d lines) duplicates `%s`' % (u['path'], u['name'], u['n_lines'], u['original'])
                  for u in fails[:40]]
            L.append('')
        eng = [u for u in res['units'] if u['cls'] == 'engine-maths']
        if eng:
            L += ['### Maths that should import Ventus Grid Engine or bng.mjs', '']
            L += ['- `%s:%d` %s (%s) -> `%s`' % (u['path'], u['lines'][0], u['name'], u['by'], u['original'])
                  for u in eng[:40]]
            L.append('')
        dup = sorted([u for u in res['units'] if u['cls'].startswith('duplicate')],
                     key=lambda u: (-u['n_lines'], u['path'], u['lines'][0]))
        if dup:
            L += ['### Largest duplicates (top 25 of %d)' % len(dup), '']
            L += ['- %s `%s:%d` %s (%d lines, %s) = `%s`' % (u['cls'][10:], u['path'], u['lines'][0], u['name'],
                                                         u['n_lines'], u['by'], u['original']) for u in dup[:25]]
            L.append('')
        top = {}
        for f in res['code_files']:
            d = os.path.dirname(f['path']) or '.'
            t = top.setdefault(d, [0, 0])
            t[0] += 1
            t[1] += f['new_or_changed_units']
        L += ['### New code by folder', '', '| folder | files | new/changed functions |', '|---|---|---|']
        L += ['| %s | %d | %d |' % (d, v[0], v[1]) for d, v in sorted(top.items(), key=lambda x: (-x[1][1], x[0]))[:30]]
        L.append('')
    L.append('Result: %s' % ('FAIL (%d exact duplicates over %d lines)' % (total_fail, FAIL_LINES) if total_fail
                             else 'PASS (advisory findings only)'))
    return '\n'.join(L) + '\n', total_fail


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.split('\n')[0])
    ap.add_argument('--repo', default=COSMIC, help='git checkout to hunt in (default: this cosmic checkout)')
    ap.add_argument('--name', default=None, help='repo name as in build_graph (default: folder name)')
    ap.add_argument('--base', default=None)
    ap.add_argument('--head', default='HEAD')
    ap.add_argument('--graph', default=None)
    ap.add_argument('--units', default=None, help="VEDIC units.parquet ('' to skip)")
    ap.add_argument('--vedic', default=None, help='vedic-/fingerprints folder (extract.py)')
    ap.add_argument('--engine', default=None, help="ventus-grid-engine checkout ('' to skip)")
    ap.add_argument('--bng', default=None, help="bng.mjs path ('' to skip)")
    ap.add_argument('--estate', default=None, help='also hunt every clone in this folder (base from build_graph)')
    ap.add_argument('--out', default='ci-newcode.md')
    ap.add_argument('--json', default=None, help='also write the full result as JSON')
    a = ap.parse_args(argv)
    if not os.path.isdir(os.path.join(a.repo, '.git')) and not os.path.isfile(os.path.join(a.repo, '.git')):
        print('newcode: %s is not a git checkout' % a.repo, file=sys.stderr)
        return 2
    graph_path = a.graph if a.graph is not None else first(DEFAULT_PATHS['graph'])
    graph = None
    if graph_path and os.path.isfile(graph_path):
        with open(graph_path, encoding='utf-8') as fh:
            graph = json.load(fh)
    ex = Extractor(a.vedic)
    engine_dir = a.engine if a.engine is not None else first(DEFAULT_PATHS['engine'], isdir=True)
    bng = a.bng if a.bng is not None else find_bng()
    eng_units, eng_names = engine_reference(ex, engine_dir, bng)
    if not eng_names:
        eng_names = set(ENGINE_NAMES_FALLBACK)
    units_path = a.units if a.units is not None else first(DEFAULT_PATHS['units'])
    use_parquet = bool(units_path and os.path.isfile(units_path) and ex.vedic)
    parquet = []
    if use_parquet:
        try:
            parquet = load_parquet(units_path)
        except Exception as e:
            print('newcode: cannot read %s (%s)' % (units_path, e), file=sys.stderr)
            use_parquet = False
    parquet_commits = {(u['repo'], u['commit']) for u in parquet}

    targets = [(os.path.abspath(a.repo), a.name or os.path.basename(os.path.abspath(a.repo)), a.base)]
    if a.estate:
        for d in sorted(os.listdir(a.estate)):
            p = os.path.join(a.estate, d)
            if os.path.isdir(os.path.join(p, '.git')) and os.path.abspath(p) != targets[0][0]:
                targets.append((os.path.abspath(p), d, None))
    results = []
    estate = {'checked': 0, 'at_cut': 0, 'no_cut': 0}
    for repo, name, base_arg in targets:
        head = a.head if repo == targets[0][0] else 'HEAD'
        try:
            head_sha = git(repo, 'rev-parse', head + '^{commit}').strip()
            base, base_from = resolve_base(repo, name, head_sha, base_arg, graph if (base_arg is None) else None)
        except RuntimeError as e:
            print('newcode: %s: %s' % (name, e), file=sys.stderr)
            continue
        if repo != targets[0][0]:
            estate['checked'] += 1
            if not base_from.startswith('build_graph'):
                estate['no_cut'] += 1
                continue  # estate clones: only against a deployed cut
            if base == head_sha:
                estate['at_cut'] += 1
        if not base or base == head_sha:
            if repo == targets[0][0]:
                results.append({'repo': name, 'dir': repo, 'base': base or head_sha, 'head': head_sha,
                                'base_from': base_from, 'code_files': [], 'other_files': [], 'units': []})
            continue
        # reference: other repos from parquet; this repo's base tree from parquet if same commit, else extracted
        ref = [u for u in parquet if u['repo'] != name]
        if (name, base) in parquet_commits:
            ref += [u for u in parquet if u['repo'] == name and u['commit'] == base]
        else:
            for path, blob, text in tree_files(repo, base):
                ref += file_units(ex, name, base, path, blob, text)
        res = hunt(repo, name, base, head_sha, ex, ref, eng_units, eng_names)
        res['base_from'] = base_from
        results.append(res)
    meta = {'extractor': ex.name,
            'units': ('%s (%d units)' % (units_path, len(parquet))) if use_parquet else
                     ('skipped (%s)' % ('builtin-lite hashes are not comparable' if units_path and not ex.vedic
                                        else 'no units.parquet')),
            'engine': ('%s (%d units)' % (engine_dir, sum(1 for u in eng_units if u['repo'] == 'ventus-grid-engine'))
                       if engine_dir else 'absent; export-name list used (%d names)' % len(ENGINE_NAMES_FALLBACK)),
            'bng': bng or 'absent',
            'graph': graph_path if graph else None,
            'estate': ('%d clones checked: %d unchanged since the cut, %d not in the cut, %d with new code'
                       % (estate['checked'], estate['at_cut'], estate['no_cut'],
                          estate['checked'] - estate['at_cut'] - estate['no_cut'])) if a.estate else 'not requested'}
    md, fails = report(results, meta)
    with open(a.out, 'w', encoding='utf-8') as fh:
        fh.write(md)
    if a.json:
        with open(a.json, 'w', encoding='utf-8') as fh:
            json.dump({'schema': 'ci-newcode-v1', 'meta': meta, 'results': [
                {k: v for k, v in r.items() if k != 'dir'} for r in results]}, fh, indent=1)
    print('newcode: %d repo(s), %d new/changed functions, %d blocking -> %s' % (
        len(results), sum(len(r['units']) for r in results), fails, a.out))
    return 1 if fails else 0


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