GLOBALGRID2050 / EXPLORE CODE

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

Describe (part 2)

A Python command-line tool in the explore folder of Cosmic that maps build graph, overhead lines (OHL) and the Renewable Energy Planning Database (REPD) register, using G99/1 and IEC 60287.

700 lines of Python from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1098 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. Describe render · cosmic / tools/explore/describe.py lines 701–1400

Describe

A Python command-line tool in the explore folder of Cosmic that maps build graph, overhead lines (OHL) and the Renewable Energy Planning Database (REPD) register, using G99/1 and IEC 60287.

rendercosmic / tools/explore/describe.py · lines 701–1400 of 1758 (continued from section 1097) · Entry point · pattern clean_comment (shared by 2 files)

What it does
It maps build graph, overhead lines (OHL), the REPD register and battery storage (BESS). Defines 67 functions or classes, including _strip_markers, _is_heading, _codeish, _quote, code_quote. Uses libraries argparse, collections, json, os, posixpath. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Why it exists in the grid workflow
Domain terms in the code: overhead lines (OHL), the REPD register, battery storage (BESS).
Inputs & outputs
In: JSON file build_graph.json; DuckDB queries; command-line arguments. Out: JSON file; interactive map; SVG drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857.
Downstream impact
Used directly by 11 files: Feeder 47 (cosmic); Arena (cosmic); Describe Bigbang (cosmic); Judge (cosmic); and 7 more. Reached from 5 other entry points, including Extras (cosmic); Ship (cosmic); Test Build (cosmic).
What it achieves
It cleans comment (`clean_comment`), joins words (`join_words`) and cleans objects (`clean_objects`). Careful one-line descriptions for Explore Code, from evidence only. It accepts `--graph`, `--src` and `--sample`.
Why it matters
Imported by 8 files, including Feeder 47, Arena and Describe Bigbang. Checked by 3 tests, including Test Cadastre 27.
Application
cosmic · tools/explore · Python CLI
Uses
argparse, collections, json, os, posixpath, re, sys
Used by
imported by Feeder 47 (sys.path import), imported by Arena (sys.path import), imported by Describe Bigbang (sys.path import), imported by Judge (sys.path import), imported by Cadastre 27 (sys.path import), imported by Primer 48 (sys.path import), imported by Baseline (sys.path import), imported by Test Cadastre 27 (sys.path import), and 3 more
Produces
code_quote, clean_comment, leading_comment, config_summary, workflow_facts, main_only, readme_sentences, readme_match, fix_case, article, join_words, dedupe_words
Defines here
ident_words, _shown, code_facts, in_title, specifics, generic_synopsis, _synopsis, repo_name, _folder, _where, _defines_phrase, _name_says, _achieves, _restates, _why, describe, _status, bb_verb_clause, bb_function_clauses, bb_helper_clause, bb_source_facts, first, _bigbang
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/describe.py:701-1400 · blob bb0a99ba93b52a7fa06c65b18da866bbb292e359 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
                  highlight='highlights', reconcile='reconciles', resample='resamples', aggregate='aggregates',
                  rotate='rotates', scale='scales', convert='converts', to='converts to', bin='bins', clip='clips',
                  buffer='buffers', simplify='simplifies', reproject='reprojects', geocode='geocodes', size='sizes',
                  derate='derates', route='routes', trace='traces', sum='sums', mean='averages', average='averages',
                  get='gets', set='sets', hide='hides', run='runs', open='opens', close='closes', send='sends',
                  post='posts', bind='binds', attach='attaches', mount='mounts', select='selects', project='projects',
                  start='starts', stop='stops', step='steps', reset='resets', paint='paints', label='labels',
                  mark='marks', join='joins', mask='masks', query='queries', lookup='looks up', serve='serves',
                  emit='emits', append='appends', insert='inserts', delete='deletes', replace='replaces', wrap='wraps',
                  clamp='clamps', integrate='integrates', translate='translates', describe='describes',
                  explain='explains', compare='compares', diff='compares', pick='picks', fit='fits', zoom='zooms',
                  store='stores', cache='caches', print='prints', dump='dumps', strip='strips', split='splits',
                  hash='hashes', tile='tiles', judge='judges', rate='rates', is_=None, has=None, on=None, handle=None,
                  init=None, setup=None, test=None, assert_=None, expect=None, log=None)
CODE_STOP = {'data', 'value', 'values', 'it', 'all', 'one', 'item', 'items', 'list', 'obj', 'fn', 'x', 'y', 'z', 'info',
             'el', 'node', 'thing', 'stuff', 'result', 'results', 'args', 'arg', 'opts', 'options', 'state', 'cb', 'e',
             'evt', 'event', 'str', 'string', 'num', 'number', 'text', 'json', 'html', 'id', 'ids', 'key', 'keys', 'out',
             'in', 'of', 'the', 'a', 'an', 'and', 'or', 'by', 'for', 'from', 'with', 'on', 'at', 'is', 'as', 'all', 'if',
             'tmp', 'temp', 'helper', 'helpers', 'util', 'utils', 'impl', 'internal', 'safe', 'raw', 'new', 'old', 'v',
             'el', 'els', 'dom', 'ui', 'main', 'init', 'self', 'this', 'that', 'once', 'now', 'test', 'tests', 'case'}
FORMULAS = [  # (all of these regular expressions match the code, phrase); phrase verb is "calculates"
    ((r'\b(?:sin|cos)\(', r'\b(?:atan2|asin)\(', r'\b637[18](?:\.\d+)?\b|earth_?radius|r_earth'), 'great-circle distances'),
    ((r'\bhypot\(|sqrt\(\s*\(?\s*(d[\w.]*)\s*\*\s*\1\s*\+\s*(d[\w.]*)\s*\*\s*\2\b|'
      r'sqrt\(\s*\(?\s*(d[\w.]*)\s*\*\*\s*2\s*\+\s*(d[\w.]*)\s*\*\*\s*2',), 'planar distances'),
    ((r'\batan2\(', r'pi\s*/\s*180|180\s*/\s*(?:math\.)?pi|\btorad|\bradians\(|deg2rad|\btodeg|\bdegrees\('), 'angles'),
    ((r'\b[Ii](?:_\w+)?\s*\*\*\s*2\s*\*\s*[Rr]\b|\b[Ii]\s*\*\s*[Ii]\s*\*\s*[Rr]\b|pow\(\s*[Ii]\w*\s*,\s*2\s*\)\s*\*\s*[Rr]\b',),
     'resistive (I²R) losses'),
    ((r'(?:sqrt\(\s*3\s*\)|\b1\.732\d*|\bsqrt_?3)\s*\*\s*\(?\s*(?:\w+\.)?(?:kv|volt|voltage|current|amps?|i|v|vll|u)\b|'
      r'\b(?:kv|volt|voltage|current|amps?|i|v|vll|u)\s*\*\s*(?:math\.)?(?:sqrt\(\s*3\s*\)|1\.732\d*|sqrt_?3\b)',),
     'three-phase power'),
]
DRAWING = [  # (regular expression, phrase)
    (r"getcontext\(\s*['\"]2d|\b(?:ctx|context|g)\.(?:arc|lineto|fillrect|strokerect|filltext|beginpath)\(", 'draws on a canvas'),
    (r"createelementns\([^)]*svg|<svg\b|\bd3\.select", 'draws SVG graphics'),
    (r"getcontext\(\s*['\"]webgl", 'renders with WebGL'),
]
UNIT_WORDS = {'kv': 'kV', 'kva': 'kVA', 'mva': 'MVA', 'mvar': 'MVAr', 'mw': 'MW', 'kw': 'kW', 'mwh': 'MWh', 'kwh': 'kWh',
              'ohm': 'Ω', 'ohms': 'Ω', 'mm2': 'mm²', 'sqmm': 'mm²', 'degc': '°C', 'celsius': '°C'}
INPUT_ID = re.compile(r"getElementById\(\s*['\"]([\w-]+)['\"]\s*\)\.(?:value|valueAsNumber|checked)|"
                      r"querySelector\(\s*['\"]#([\w-]+)['\"]\s*\)\.(?:value|valueAsNumber|checked)|"
                      r"<(?:input|select|textarea)\b[^>]*?\b(?:id|name)\s*=\s*[\"']([\w-]+)", re.I)
WEB_KINDS = {'script', 'JavaScript module', 'TypeScript module', 'page', 'component'}  # drawing and form evidence
CODE_KINDS = {'script', 'JavaScript module', 'TypeScript module', 'Python module', 'Python CLI', 'page', 'component',
              'shell script', 'shader'}


def ident_words(name):
    """'trefoilSpacingMm2' -> ['trefoil', 'spacing', 'mm2']; snake, kebab and acronyms split; lower case."""
    n = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', name)
    n = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1 \2', n)
    return [w.lower() for w in re.split(r'[\s_\-.$]+', n) if w]


def _shown(w):
    if w in UNITS:
        return UNITS[w]
    if w in GLOSSARY and w not in CASE_SKIP:
        return GLOSSARY[w][0]
    return w


def code_facts(text, kind='', defines=(), title=''):
    """{'phrase': 'computes trefoil spacing and bend radius (`trefoilSpacing`, `bendRadius`) and draws on a canvas',
    'terms': [every identifier and word the phrase used]} or {} when the code gives nothing to say. Evidence only:
    defined names led by a CODE_VERBS verb (one clause per name in file order, at most three names, each shown as
    `code` after its plain words; consecutive names with the same verb share it; Big Bang rule R1); with none, up to two multi-word noun names as "works with ..."),
    FORMULAS (sin/cos with atan2/asin and an earth radius -> great-circle distances; hypot, or sqrt(dx*dx + dy*dy) or
    sqrt(dx**2 + dy**2) over d-named differences -> planar distances; atan2 with a degree/radian conversion -> angles;
    I**2*R -> resistive losses; sqrt(3) times a voltage or current -> three-phase power), DRAWING calls (canvas 2D,
    SVG, WebGL) and form inputs read by id (their words) in JavaScript
    family files and pages only, and units named in
    identifiers or strings (UNIT_WORDS, two mentions or more). A name whose phrase repeats the title is skipped."""
    if kind not in CODE_KINDS or not text:
        return {}
    low = text.lower()
    tl = re.sub(r'[^a-z0-9]+', ' ', polish_title(title).lower()).strip() if title else ''

    def in_title(ph):
        p = re.sub(r'[^a-z0-9]+', ' ', ph.lower()).strip()
        return bool(tl) and (p in tl or tl in p)
    terms, parts, used, seen = [], [], [], set()
    for name in defines or []:  # Big Bang R1: one verb-led clause per defined name, in file order, at most three
        if name.startswith('_') or len(name) < 5 or name in ('constructor', 'main') or name.isupper():
            continue
        ws = ident_words(name)
        if len(ws) < 2 or not CODE_VERBS.get(ws[0]):
            continue
        obj = [w for w in ws[1:] if w not in CODE_STOP and not w.isdigit() and len(w) > 1]
        if not obj or len(obj) > 3:
            continue
        phrase = ' '.join(_shown(w) for w in obj)
        verb = CODE_VERBS[ws[0]]
        if in_title(phrase) or in_title(' '.join(ws)) or (verb, phrase.lower()) in seen:
            continue
        seen.add((verb, phrase.lower()))
        same = parts and parts[-1].startswith(verb + ' ') and ' and ' not in parts[-1]
        if same:  # "computes trefoil spacing (`a`) and bend radius (`b`)": the verb is said once
            parts[-1] += ' and %s (`%s`)' % (phrase, name)
        else:
            parts.append('%s %s (`%s`)' % (verb, phrase, name))
        terms += [name, phrase]
        if len(terms) >= 6:
            break
    if not parts:  # no verb-led names: the first two multi-word noun names, as "works with ..."
        nouns = []
        for name in defines or []:
            ws = [w for w in ident_words(name) if w not in CODE_STOP and not w.isdigit() and len(w) > 1]
            if name.startswith('_') or len(ws) < 2 or len(ws) > 3 or len(ws) != len(ident_words(name)) or \
                    name.isupper() or ws[0] in CODE_VERBS or ws[0] in ('get', 'set', 'is', 'has', 'on', 'handle', 'make'):
                continue
            ph = ' '.join(_shown(w) for w in ws)
            if in_title(ph):
                continue
            if ph not in (x for x, _ in nouns):
                nouns.append((ph, name))
            if len(nouns) == 2:
                break
        if nouns:
            parts.append('works with %s' % join_words('%s (`%s`)' % (x, n) for x, n in nouns))
            terms += [n for _, n in nouns] + [x for x, _ in nouns]
    formulas = [ph for rxs, ph in FORMULAS if all(re.search(rx, text if 'I' in rx else low) for rx in rxs)]
    if formulas:
        terms += formulas
        parts.append('calculates %s' % join_words(formulas[:2]))
    web = kind in WEB_KINDS
    if web and not any(p.startswith(('draws', 'renders', 'plots')) for p in parts):
        for rx, ph in DRAWING:
            if re.search(rx, low):
                parts.append(ph)
                terms.append(ph)
                break
    ids = []
    for m in (INPUT_ID.finditer(text) if web else ()):
        i = next(x for x in m.groups() if x)
        ws = [w for w in ident_words(i) if w not in CODE_STOP and not w.isdigit() and len(w) > 1
              and w not in ('input', 'select', 'field', 'btn', 'button', 'box', 'val', 'q', 'search', 'file')]
        p = ' '.join(_shown(w) for w in ws)
        if p and p not in ids:
            ids.append(p)
            terms.append(i)
    if ids:
        parts.append('reads inputs for %s' % join_words(ids[:3]))
    if not parts:
        return {}
    phrase = join_words(parts[:4])
    units = collections.Counter()
    for w in re.findall(r'[A-Za-z][A-Za-z0-9]*', text[:200000]):
        for x in ident_words(w):
            if x in UNIT_WORDS:
                units[UNIT_WORDS[x]] += 1
    for ch, u in (('Ω', 'Ω'), ('mm²', 'mm²'), ('°C', '°C')):
        units[u] += text.count(ch)
    us = [u for u, c in units.most_common() if c >= 2][:3]
    if us:
        phrase += ' (units: %s)' % ', '.join(us)
        terms += us
    return {'phrase': phrase, 'terms': terms}


# Big Bang rule R4: standards and named methods, said only when the source itself names them.
STD_RX = re.compile(r'\b(?:IEC|IEEE|ISO|ENA)\s?\d{3,5}(?:-\d+)*\b|\bBS\s?(?:EN\s?)?\d{3,5}(?:-\d+)*\b|'
                    r'\bG(?:59|83|98|99|100)/\d\b|\bEPSG:\d{4,5}\b')
METHODS = [('haversine', 'haversine'), ('vincenty', 'Vincenty'), ('newton-raphson', 'Newton-Raphson'),
           ('newton_raphson', 'Newton-Raphson'), ('gauss-seidel', 'Gauss-Seidel'), ('pagerank', 'PageRank'),
           ('dijkstra', 'Dijkstra'), ('louvain', 'Louvain'), ('bradley-terry', 'Bradley-Terry'),
           ('douglas-peucker', 'Douglas-Peucker'), ('delaunay', 'Delaunay'), ('voronoi', 'Voronoi'),
           ('k-means', 'k-means'), ('kmeans', 'k-means'), ('monte carlo', 'Monte Carlo'), ('kalman', 'Kalman'),
           ('sha-256', 'SHA-256'), ('sha256', 'SHA-256'), ('helmert', 'Helmert'), ('ostn15', 'OSTN15'),
           ('web mercator', 'Web Mercator'), ('levenshtein', 'Levenshtein'), ('topological sort', 'topological sort'),
           ('point in polygon', 'point in polygon'), ('ray casting', 'ray casting'), ('least squares', 'least squares')]


def specifics(text):
    """Standards (IEC/IEEE/ISO/ENA/BS numbers, G99/1-style, EPSG codes) and named methods that occur in the source,
    first seen first, at most three: ['IEC 60287', 'haversine']."""
    if not text:
        return []
    out = []
    for m in STD_RX.finditer(text[:200000]):
        k = re.sub(r'\s+', ' ', m.group(0))
        if k not in out:
            out.append(k)
    low = text[:200000].lower()
    hits = sorted((m.start(), shown) for key, shown in METHODS
                  for m in [re.search(r'(?<![\w])' + re.escape(key) + r'(?![\w])', low)] if m)
    for _, shown in hits:
        if shown not in out:
            out.append(shown)
    return out[:3]


GENERIC_SYN = re.compile(r'^An? [\w\- ]+?(?: in [^.]*?)?(?:,? covering [^.]*)?\.\s*$')


def generic_synopsis(synopsis):
    """True when a synopsis says only kind + repository (+ topic nouns): 'A JavaScript file in X covering cables.'"""
    core = re.sub(r'\s*(?:Published at|Served with|Runs) .*$', '', synopsis).strip()
    return bool(GENERIC_SYN.match(core)) and ' that ' not in core and ' using data ' not in core


# ---------------------------------------------------------------- the four texts
def _synopsis(ev, title):
    kind = ev.get('kind', '')
    noun = KIND_NOUN.get(kind, (kind or 'file').lower() if kind.isupper() is False else kind)
    if kind == 'page' and ev.get('has_map'):
        noun = 'map page'
    objects = clean_objects(ev.get('objects'), title, kind, ev.get('role', ''))
    sources = clean_sources(ev.get('sources'), ev.get('repo', ''), ev.get('repo_titles'))
    verb = ev.get('verb') or ''
    role = ev.get('role', '')
    if verb == 'draws' and not (role in ('render', 'interaction') or kind in ('page', 'component')):
        verb = ''  # drawing evidence in a formula library or a test harness is not its job
    if verb == 'lists and searches' and not (role == 'interaction' or kind == 'page'):
        verb = ''
    if verb == 'calculates' and not any(DOMAIN_OBJ.match(o) for o in objects):
        verb = ''
    if verb == 'tests' and kind != 'test' and role != 'test':
        verb = ''
    if kind == 'workflow':
        objects = []
    if verb == 'draws' and objects and all(DOMAIN_OBJ.match(o) for o in objects):
        verb = ''  # domain nouns are counted words, not drawn layers: say "covering"

    repo_t = repo_name(ev)
    where = _where(ev, title, repo_t)
    s = '%s %s%s' % (article(noun).capitalize(), noun, where)
    with_v, alone = VERBS.get(verb, (verb, None)) if verb else ('', None)
    if kind == 'test':
        imps = [polish_title(i['title']) for i in ev.get('imports') or [] if i.get('title') and i['title'] != title][:2]
        if imps:
            s += ' that checks %s' % join_words(imps)
            objects = []
    cf = (ev.get('code') or {}).get('phrase', '') if not sources and kind not in ('test', 'workflow') else ''
    if objects and with_v and kind != 'test':
        s += ' that %s %s' % (with_v, join_words(objects))
    elif cf and not (kind == 'test' and ' that checks ' in s):
        s += ' that %s' % cf  # code evidence (code_facts) instead of kind + repository + topic alone
        if objects and len(cf.split()) < 14:
            s += ', covering %s' % join_words(objects)
    elif objects:
        s += ' covering %s' % join_words(objects)
    elif alone:
        s += ' that %s' % alone
    elif not sources and ev.get('_fold'):
        s += ' that %s' % ev['_fold']  # the file's own imperative first sentence, said once (not again in achieves)
    sp = [x for x in ev.get('specifics') or [] if x.lower() not in s.lower()][:2]
    if sp and kind not in ('workflow', 'configuration'):
        s += (', using %s' if (' that ' in s or ' covering ' in s) else ' that uses %s') % join_words(sp)
    if sources:
        if objects and with_v in ('fetches', 'reads'):
            s += ' from %s' % _repo_list(sources)
        elif objects:
            s += '%s and uses data from %s' % (',' if len(objects) > 1 else '', _repo_list(sources))
        else:
            s += ' using data from %s' % _repo_list(sources)
    s = _finish(s)
    extra = []
    wf = ev.get('workflow') or {}
    if wf.get('triggers'):
        extra.append('Runs %s.' % join_words([TRIGGER_WORDS[t] for t in wf['triggers']][:3]))
    url = ev.get('published', '')
    if url:
        if kind == 'page':
            extra.append('Published at %s.' % url)
        elif kind in ('style sheet', 'script', 'JavaScript module', 'TypeScript module', 'component', 'shader'):
            extra.append('Served with the page at %s.' % url)
    s = ' '.join([s] + extra)
    if len(expand_once(s, title, (repo_t,)).split()) > 30:
        cf0 = (ev.get('code') or {}).get('phrase', '')
        if cf0 and ' (units: ' in cf0:
            return _synopsis(dict(ev, code=dict(ev['code'], phrase=re.sub(r' \(units: [^)]*\)', '', cf0))), title)
        if cf0 and ' (`' in cf0:
            return _synopsis(dict(ev, code=dict(ev['code'], phrase=re.sub(r' \(`[^)]*\)', '', cf0))), title)
        if len(objects) > 1:
            return _synopsis(dict(ev, objects=objects[:-1]), title)
        if len(ev.get('sources') or []) > 1:
            return _synopsis(dict(ev, sources=(ev.get('sources') or [])[:1]), title)
        if ev.get('specifics'):
            return _synopsis(dict(ev, specifics=[]), title)
        if FOLDER_PLACE and not ev.get('_no_folder') and _folder(ev, title, repo_t):
            return _synopsis(dict(ev, _no_folder=True), title)
        if not ev.get('_no_where'):
            return _synopsis(dict(ev, _no_where=True), title)
    return s


def repo_name(ev):
    """The repository as a name: repo_title when it reads as a name, else the slug in words. A descriptor sentence
    ('GlobalGrid2050 is being built as ...') is README context, never pasted into every synopsis."""
    rt = (ev.get('repo_title') or '').strip()
    if rt and len(rt.split()) <= 7 and not re.search(r'[.!?:;]$|\b(is|are|was|does|this|that)\b', rt, re.I):
        return rt
    slug = ev.get('repo') or ''
    ws = [w for w in re.split(r'[-_\s]+', slug) if w]
    return ' '.join(w[0].upper() + w[1:] if w.islower() else w for w in ws) or rt


FOLDER_SKIP = {'src', 'lib', 'libs', 'dist', 'js', 'css', 'web', 'www', 'app', 'apps', 'workflows', 'github', 'code',
               'files', 'misc', 'tmp', 'old', 'new', 'public', 'static', 'site', 'docs', 'releases', 'release',
               'versions', 'version', 'archive', 'preview', 'build', 'out', 'mod', 'modules', 'pkg', 'main'}


def _folder(ev, title, repo_t=''):
    """The nearest folder that names something ('spider', 'solar billion'): letters only (no stamps, versions or
    hashes), not a generic container, and not already said by the title or the repository name."""
    tw = {w.lower() for w in re.findall(r'[A-Za-z]+', title + ' ' + repo_t + ' ' + (ev.get('repo') or ''))}
    for d in reversed((ev.get('path') or '').split('/')[:-1]):
        if not re.match(r'^[a-z][a-z\-_]{2,24}$', d) or d in FOLDER_SKIP:
            continue
        ws = [w for w in re.split(r'[-_]', d) if w]
        if all(w in tw for w in ws) or any(len(w) < 3 for w in ws) and len(ws) == 1:
            continue
        return ' '.join(ws)
    return ''


def _where(ev, title, repo_t):
    """' in the spider folder of Stars' / ' in the spider folder' / ' in Stars' / ''."""
    repo_ok = bool(repo_t) and repo_t.lower() not in title.lower() and not ev.get('_no_where')
    fold = '' if ev.get('_no_folder') or not FOLDER_PLACE else _folder(ev, title, repo_t)
    if fold and repo_ok:
        return ' in the %s folder of %s' % (fold, repo_t)
    if fold:
        return ' in the %s folder' % fold
    return ' in %s' % repo_t if repo_ok else ''


def _defines_phrase(defs, n=3):
    names = [d for d in (defs or []) if not d.startswith('_') and d not in ('__init__', 'main', 'constructor')
             and len(d) > 2][:n]
    if not names:
        return ''
    more = len([d for d in defs if not d.startswith('_') and d not in ('__init__', 'main', 'constructor')
                and len(d) > 2]) - len(names)
    return 'Defines %s%s.' % (join_words('`%s`' % d for d in names) if more <= 0 else
                              ', '.join('`%s`' % d for d in names), ' and %d more' % more if more > 0 else '')


def _name_says(title, kind):
    """'Fetch NESO DNO Boundaries' -> 'Its name says it fetches NESO DNO boundaries.' (verb-led names only)."""
    core = re.sub(r'\s*\(.*?\)|\s+Workflow$', '', collapse_expansions(title.split(' — ')[-1]))
    ws = core.split()
    if len(ws) < 2:
        return ''
    v = VERB_LEAD.get(ws[0].lower())
    if not v:
        return ''
    rest = ' '.join(w if (w.isupper() or re.search(r'\d|[A-Z].*[A-Z]', w)) else w.lower() for w in ws[1:])
    rest = re.sub(r'\b[vV]\s?\d+(\.\d+)*\b|\b\d+\b', '', rest).strip()
    if not re.search(r'[A-Za-z]{3,}', rest):
        return ''
    return 'Its name says it %s %s.' % (v, rest) if rest else ''


def _achieves(ev, title):
    kind = ev.get('kind', '')
    path = ev.get('path', '')
    names = [ev.get('repo_title', ''), ev.get('repo', ''), title]
    c = ev.get('comment') or ''
    folded = ev.get('_folded') or ''
    if c:
        cc = clean_comment(c, path, names, title=title)
        if folded and cc.startswith(folded):
            cc = cc[len(folded):].strip()  # its first sentence is already the synopsis
        if cc and not _restates(cc, title):
            return cc, 'comment', 'comment'
    if ev.get('config'):
        cc = clean_comment(ev['config'], path, names, title=title)
        if folded and cc.startswith(folded):
            cc = cc[len(folded):].strip()
        if cc and not _restates(cc, title):
            return cc, 'comment', 'config'
    wf = ev.get('workflow') or {}
    if wf and (wf.get('name') or wf.get('runs') or wf.get('publishes')):
        bits = []
        nm = STATUS_PREFIX.sub('', re.sub(r'\s+', ' ', STAMP.sub('', wf.get('name', ''))).strip())
        if nm and not _restates(nm, title):
            bits.append('Named “%s”' % nm)
        if wf.get('runs'):
            rt = wf.get('run_titles') or {}
            bits.append('runs %s' % join_words(('%s (`%s`)' % (rt[r], r)) if rt.get(r) else '`%s`' % r
                                               for r in wf['runs'][:3]))
        if wf.get('publishes'):
            bits.append('publishes to GitHub Pages')
        if bits:
            return _finish('; '.join(bits)), 'comment', 'workflow'
    if ev.get('main_only'):
        mod = ev['main_only']
        return ('Entry point only: it runs `main()`%s.' % (' from `%s`' % mod if mod != 'main' else '')), 'code', 'entry'
    vd = ev.get('vedic')
    if vd and vd.get('function'):
        out = str(vd.get('output') or '').replace('_', ' ').strip().rstrip('.')
        ins = [re.sub(r'^(.+?) optional$', r'optional \1', str(x).replace('_', ' ')) for x in vd.get('inputs') or []]
        s = 'Its `%s` function gives %s' % (vd['function'], out[:1].lower() + out[1:] if out else 'a result')
        if len(ins) == 2 and ins[0] == ins[1]:
            ins = ['two %ss' % ins[0]]
        if ins:
            s += ' from %s' % join_words(ins[:3])
        s = _cap_words(_finish(s), 32)
        if vd.get('word'):
            s = s.rstrip('.') + ' (VEDIC: %s).' % vd['word'].lower()
        return fix_case(s), 'code', 'vedic'
    for sent in ev.get('readme') or []:
        hit = readme_match([sent], path)
        if hit:
            cc = clean_comment(hit, path, names, max_words=36)
            if cc and not _restates(cc, title):
                return 'The README says: %s' % cc, 'readme', 'readme'
    said = _name_says(title, kind)
    d = _defines_phrase(ev.get('defines')) if kind not in ('workflow', 'configuration', 'style sheet') else ''
    out = ' '.join(x for x in (said, d) if x)
    return out, 'name', 'name' if out else 'none'


def _restates(text, title):
    """True when text says no more than the title (same content words)."""
    tw = {w.lower() for w in re.findall(r'[A-Za-z0-9]+', title)} | {'the', 'a', 'an', 'for', 'of', 'and', 'page',
                                                                    'script', 'module', 'workflow', 'file', 'tool'}
    xw = [w.lower() for w in re.findall(r'[A-Za-z0-9]+', text)]
    return bool(xw) and sum(w not in tw for w in xw) < 2


def _why(ev, title):
    kind = ev.get('kind', '')
    deps = [dict(d, title=polish_title(d['title'])) for d in ev.get('dependents') or [] if d.get('title')]
    repo = ev.get('repo', '')
    if not deps:
        if kind == 'test':
            imps = [polish_title(i['title']) for i in ev.get('imports') or [] if i.get('title')]
            if imps:
                return 'Guards the behaviour of %s.' % join_words(imps[:3]), 'imports'
        return '', ''
    tests = [d for d in deps if d.get('kind') == 'test' or d.get('role') == 'test']
    pages = [d for d in deps if d.get('kind') == 'page' and d not in tests]
    # a dependent that runs this file (workflow run, script call) is said so, not "imported by"
    runners = [d for d in deps if d not in tests and d not in pages and d.get('edge') in ('workflow-run', 'script-call')]
    others = [d for d in deps if d not in tests and d not in pages and d not in runners]
    sents = []
    if pages:
        p = pages[0]
        name = _page_name(p['title'])
        same = name.lower() == _page_name(title).lower()
        label = 'the page of the same name' if same else 'the %s %s' % (name, 'map page' if p.get('is_map') else 'page')
        if p.get('repo') and p['repo'] != repo:
            label += ' in %s' % (ev.get('repo_titles') or {}).get(p['repo'], p['repo'])
        objs = [o for o in clean_objects(ev.get('objects'), title) if DOMAIN_OBJ.match(o)][:2]
        if p.get('is_map') and objs:
            s = 'Feeds %s (%s)' % (label, join_words(objs))
        else:
            s = 'Loaded by %s' % label
        if p.get('published'):
            s += ' at %s' % p['published']
        if len(pages) > 1:
            s += ' and %d other page%s' % (len(pages) - 1, '' if len(pages) == 2 else 's')
        sents.append(s + '.')
    if others:
        names = []
        for d in others:
            t = d['title'] if d['title'] != title else 'a file of the same name'
            if t not in names:
                names.append(t)
        lead = 'Also imported by' if pages else 'Imported by'
        if len(others) <= 3:
            s = '%s %s' % (lead, join_words(names[:3]))
        else:
            s = '%s %d files, including %s' % (lead, len(others), join_words(names[:3]))
        xr = sorted({d['repo'] for d in others if d.get('repo') and d['repo'] != repo})
        if xr:
            rt = ev.get('repo_titles') or {}
            s += ', from %s' % join_words([rt.get(r, r) for r in xr[:3]] + (['others'] if len(xr) > 3 else []))
        sents.append(s + '.')
    if runners:
        rn = list(dict.fromkeys(d['title'] for d in runners))
        sents.append('Run by %s.' % (join_words(rn) if len(rn) <= 3 else '%d workflows and scripts, including %s'
                                     % (len(rn), join_words(rn[:3]))))
    if tests:
        tn = [d['title'] for d in tests]
        sents.append('Checked by %s.' % (tn[0] if len(tn) == 1 else '%d tests, including %s' % (len(tn), tn[0])))
    return ' '.join(sents), 'dependents'


def describe(ev):
    """Evidence -> {'title', 'synopsis', 'achieves', 'why', 'provenance'}. Pure and deterministic."""
    title = polish_title(ev.get('title') or '')
    clause, first = _imperative(ev, title)
    syn = _synopsis(dict(ev, _fold=clause) if clause else ev, title)
    folded = bool(clause) and (' that %s' % clause) in syn
    ach, prov, detail = _achieves(dict(ev, _folded=first) if folded else ev, title)
    why, why_src = _why(ev, title)
    status = _status(ev, title)
    if status and status not in why:
        why = (why + ' ' + status).strip()
        why_src = (why_src + '+context') if why_src else 'context'
    prot = tuple(p for p in (ev.get('repo_title'),) if p)
    syn = fix_case(dedupe_words(expand_once(syn, title, prot)))
    ach = fix_case(dedupe_words(expand_once(ach, title + ' ' + syn, prot))) if ach else ''
    why = fix_case(dedupe_words(why))
    if ach and syn and ach.rstrip('.').lower() == syn.rstrip('.').lower():
        ach = ''
    syn2, ach2 = _bigbang(ev, title, syn, ach)
    from_code = (syn2, ach2) != (syn, ach)
    syn, ach = syn2, ach2
    syn_prov = [k for k in ('verb', 'objects', 'sources', 'published', 'workflow', 'code', 'specifics') if ev.get(k)]
    if prov == 'name' and not syn_prov and not folded and not from_code:
        note = NAME_ONLY  # LAWS K1: a description with no key behind it says it is a candidate (shown beside achieves)
    else:
        note = ''
    return {'title': title, 'synopsis': syn, 'achieves': ach, 'why': why, 'note': note,
            'provenance': {'achieves': prov, 'achieves_detail': detail, 'why': why_src,
                           'synopsis': [k for k in ('verb', 'objects', 'sources', 'published', 'workflow', 'code',
                                                    'specifics') if ev.get(k)] + (['comment'] if folded else []),
                           'bigbang': from_code, 'candidate': bool(note),
                           'version': GENERATOR_VERSION}}



def _status(ev, title):
    """One sentence from the estate experiments (ev['context'], see attach_context), or ''."""
    c = ev.get('context') or {}
    if not c:
        return ''
    tw = c.get('twin') or {}
    tname = tw.get('title') or ('`%s`' % tw['path'] if tw.get('path') else '')
    if tname and tw.get('repo') and tw['repo'] != ev.get('repo'):
        tname += ' in %s' % repo_name({'repo': tw['repo']})
    sa = c.get('set_aside')
    if sa == 'noise-generated':
        return 'Written by a tool, so the cleaned view sets it aside.'
    if sa == 'near-copy-of' or c.get('verdict') == 'near-copy-of':
        if tname:
            return 'A near copy of %s%s.' % (tname, '; the cleaned view keeps that one' if sa else '')
        return 'A near copy of another file.' if not sa else 'A near copy of another file; the cleaned view sets it aside.'
    if sa == 'unit-duplicate-of':
        return 'All of its code also lives in other files, so the cleaned view sets it aside.'
    if c.get('clarity') == 'unreached' and not ev.get('dependents') and not ev.get('entry'):
        return 'No entry point reaches it.'
    if c.get('verdict') == 'family-shared' and tname and (tw.get('shared') or 0) >= 3:
        return 'Shares %d functions with %s.' % (tw['shared'], tname)
    return ''

FOLD_VERBS = dict(VERB_LEAD, register='registers', read='reads', write='writes', show='shows', serve='serves',
                  turn='turns', keep='keeps', give='gives', draw='draws', run='runs', wire='wires', hold='holds',
                  record='records', store='stores', send='sends', map='maps', sort='sorts', filter='filters',
                  normalise='normalises', resolve='resolves', compare='compares', rank='ranks', score='scores',
                  list='lists', emit='emits', write_='writes', convert='converts', copy='copies', mirror='mirrors',
                  guard='guards', prove='proves', replay='replays', serialise='serialises', index='indexes')


# ---------------------------------------------------------------- describe-3: distilled Big Bang rules
# Adopted one rule at a time from bigbang/describe_bigbang.py (DISTILLED.md), each kept only when the Big Bang judge
# (bigbang/judge.py) shows a win with invented() == 0; scores in CHANGELOG.md. EXPLORE_DESCRIBE_BIGBANG=0 turns them off.
NAME_ONLY = 'Described from its file name only (a candidate, not yet checked against the code).'  # LAWS K1 template
BIGBANG = os.environ.get('EXPLORE_DESCRIBE_BIGBANG', '1') != '0'
BB_VERBS = dict(FOLD_VERBS, get='gets', save='saves', hide='hides', add='adds', remove='removes', set='sets',
                format='formats', normalize='normalizes', group='groups', count='counts', solve='solves',
                simulate='simulates', select='selects', open='opens', close='closes', post='posts', bind='binds',
                attach='attaches', toggle='toggles', make='makes', search='searches', match='matches', snap='snaps',
                zoom='zooms', fit='fits', pick='picks', place='places', route='routes', size='sizes', rate='rates',
                classify='classifies', encode='encodes', decode='decodes', hash='hashes', append='appends',
                insert='inserts', delete='deletes', replace='replaces', wrap='wraps', clamp='clamps',
                interpolate='interpolates', integrate='integrates', aggregate='aggregates', summarise='summarises',
                translate='translates', describe='describes', explain='explains', reset='resets', start='starts',
                stop='stops', animate='animates', paint='paints', highlight='highlights', label='labels',
                mark='marks', join='joins', split='splits', reproject='reprojects', query='queries',
                lookup='looks up', dump='dumps', cache='caches')
for _k in ('handle', 'on', 'is', 'has', 'to', 'init', 'setup', 'test', 'assert', 'expect', 'log', 'write_'):
    BB_VERBS.pop(_k, None)
BB_HELPERS = BIGBANG
BB_UNITS = BIGBANG
BB_IO = BIGBANG
BB_STOP = {'the', 'a', 'an', 'of', 'to', 'for', 'and', 'or', 'by', 'from', 'with', 'in', 'on', 'at', 'it', 'all',
           'data', 'value', 'values', 'item', 'items', 'obj', 'fn', 'cb', 'el', 'tmp', 'impl', 'helper', 'async'}


def bb_verb_clause(name):
    """R1: a verb-led defined name in its own words: 'computeRating' -> 'computes rating (`computeRating`)'."""
    ws = ident_words(name)
    if len(ws) < 2 or name.startswith('_') or name.isupper():
        return ''
    v = BB_VERBS.get(ws[0])
    obj = [w for w in ws[1:] if w not in BB_STOP and not w.isdigit() and len(w) > 1]
    if not v or not obj or len(obj) > 4:
        return ''
    return '%s %s (`%s`)' % (v, ' '.join(_shown(w) for w in obj), name)


def bb_function_clauses(defines, title='', n=3):
    """R1: up to n verb-led clauses for public defined names, in file order, de-duplicated by phrase."""
    out, seen, tl = [], set(), title.lower()
    for d in defines or []:
        if d.startswith('test') or d in ('main', 'constructor') or len(d) < 3:
            continue
        c = bb_verb_clause(d)
        ph = c.split(' (`')[0]
        if not c or ph in seen or ph.split(' ', 1)[-1] == tl:
            continue
        seen.add(ph)
        out.append(c)
        if len(out) == n:
            break
    return out


def bb_helper_clause(name):
    """R1b: a defined name that is not verb-led, said by its own words: 'segDist' -> 'the seg dist helper (`segDist`)'."""
    ws = ident_words(name)
    if name.startswith('_') or not ws or len(ws) > 4 or name.isupper() or len(name) < 3:
        return ''
    words = ' '.join(_shown(w) for w in ws)
    if name[:1].isupper():
        return 'the %s class (`%s`)' % (words, name)
    return 'the %s %s (`%s`)' % (words, 'step' if len(ws) == 1 else 'helper', name)


BB_UNIT_NUM = re.compile(r'(?<![\w.,])(\d+(?:\.\d+)?)\s?(kV|kVA|MVA|MW|GW|kW|MWh|GWh|kWh|kA|Hz)\b')
BB_READS = [re.compile(r"fetch\(\s*[`'\"]([\w./\-]+\.(?:json|geojson|csv|parquet|txt|pmtiles|topojson|xml))[`'\"]"),
            re.compile(r"read(?:File|FileSync|_text|_csv|_json|_parquet)?\w*\(\s*[^,)]*?['\"`]([\w./\-]+\.(?:json|"
                       r"geojson|csv|parquet|txt|tsv|ya?ml))['\"`]"),
            re.compile(r"open\(\s*[^,)]*?['\"]([\w./\-]+\.(?:json|geojson|csv|txt|tsv|ya?ml))['\"]\s*\)")]
BB_WRITES = [re.compile(r"write(?:File|FileSync|_text)?\w*\(\s*[^,)]*?['\"`]([\w./\-]+\.(?:json|geojson|csv|html|md|"
                        r"txt|parquet|svg|png))['\"`]"),
             re.compile(r"open\(\s*[^,)]*?['\"]([\w./\-]+\.(?:json|geojson|csv|html|md|txt|svg))['\"]\s*,\s*['\"][wa]")]
BB_FLAGS = re.compile(r"add_argument\(\s*['\"](--[\w\-]+)")
BB_EVENTS = re.compile(r"addEventListener\(\s*['\"](\w+)")


def bb_source_facts(text, kind=''):
    """Literal source facts for the Big Bang rules (R4b ratings with their numbers, R7 files read and written,
    flags and events), from source patterns only. build.py's evidence_from_build adds them to the evidence."""
    head = (text or '')[:200000]
    out = {}
    c = collections.Counter('%s %s' % m.groups() for m in BB_UNIT_NUM.finditer(head))
    units = [k for k, _ in sorted(c.items(), key=lambda kv: (-kv[1], kv[0]))][:3]
    if units:
        out['bb_units'] = units

    def first(rxs, n):
        got = []
        for rx in rxs:
            for m in rx.finditer(head):
                v = m.group(1)
                if v not in got and '${' not in v:
                    got.append(v)
        return got[:n]
    io = {'reads': first(BB_READS, 2), 'writes': first(BB_WRITES, 2), 'flags': first([BB_FLAGS], 3),
          'events': first([BB_EVENTS], 3) if kind in WEB_KINDS else []}
    io = {k: v for k, v in io.items() if v}
    if io:
        out['bb_io'] = io
    return out


def _bigbang(ev, title, syn, ach):
    """Apply the adopted Big Bang rules to describe-2's synopsis and achieves. Every added sentence must pass
    invented() against the evidence, or it is dropped."""
    if not BIGBANG or ev.get('kind') in ('workflow', 'configuration'):
        return syn, ach
    evt = evidence_text(ev)
    low = (syn + ' ' + ach).lower()
    cl = [c for c in bb_function_clauses(ev.get('defines'), title) if '`%s`' % c.split('`')[1] not in low]
    s = 'It %s.' % join_words(cl) if cl else ''
    if BB_HELPERS and len(cl) < 2:  # R1b: when verbs are scarce, name the main helpers by their own words
        used = {c.split('`')[1] for c in cl}
        hl = []
        for d in ev.get('defines') or []:
            if d in used or d.startswith('test') or d in ('main', 'constructor') or '`%s`' % d in low:
                continue
            h = '' if bb_verb_clause(d) else bb_helper_clause(d)
            if h and h not in hl:
                hl.append(h)
            if len(hl) + len(cl) >= 3:
                break
        if hl:
            s = ('It %s and is built from %s.' % (join_words(cl), join_words(hl)) if cl
                 else 'It is built from %s.' % join_words(hl))
    if s:
        test = re.sub(r'`[^`]*`', '', s)
        if not invented(test, evt):
            if len(syn.split()) + len(s.split()) <= 30:  # synopsis cap (test_describe)
                syn = (syn.rstrip() + ' ' + s).strip()
            else:
                ach = (s + ' ' + ach).strip()
    more = []
    units = [u for u in ev.get('bb_units') or [] if u.lower() not in (syn + ' ' + ach).lower()]
    if BB_UNITS and units:  # R4b: ratings exactly as the source writes them
        more.append('Its code works with %s.' % join_words(units))
    io = ev.get('bb_io') or {}
    if BB_IO and io:  # R7: what it reads, writes, accepts and responds to, from literal source patterns
        low = (syn + ' ' + ach).lower()
        acts = []
        if io.get('reads') and io['reads'][0].lower() not in low:
            acts.append('reads `%s`' % io['reads'][0])
        if io.get('writes') and io['writes'][0].lower() not in low:
            acts.append('writes `%s`' % io['writes'][0])
        if acts:
            more.append('It %s.' % join_words(acts))
        fl = [f for f in io.get('flags') or [] if f.lower() not in low]
        if fl:
            more.append('It accepts %s.' % join_words('`%s`' % f for f in fl))
        if io.get('events'):