GLOBALGRID2050 / EXPLORE CODE

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

Describe (part 3)

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.

358 lines of Python from cosmic, in 1 file. Topic: Kuiper, cosmos and drawing engines. Section 1099 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 1401–1758

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 1401–1758 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
_imperative, evidence_from_build, invented, _split_list, parse_synopsis, _readme_chain, evidence_from_graph, evidence_text, flags, _main
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:1401-1758 · 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
            more.append('It responds to %s events.' % join_words(io['events']))
    for m in more:
        if not invented(re.sub(r'`[^`]*`', '', m), evt):
            ach = (ach.rstrip() + ' ' + m).strip()
    return syn, ach


def _imperative(ev, title):
    """(clause, first sentence) when the file's own cleaned comment opens with an imperative ('Register the graphs
    this repository publishes ...'): the synopsis says it once in the third person ('that registers the graphs ...')
    and achieves moves on to the next sentence. ('', '') otherwise."""
    names = [ev.get('repo_title', ''), ev.get('repo', ''), title]
    raw = ev.get('comment') or ev.get('config') or ''
    if not raw or ev.get('kind') in ('workflow', 'test'):
        return '', ''
    cc = clean_comment(raw, ev.get('path', ''), names, title=title)
    ss = _sentences(cc)
    if not ss:
        return '', ''
    first = ss[0]
    ws = first.rstrip('.!?…').split()
    if not (4 <= len(ws) <= 22) or first.endswith('…') or not re.match(r'^[A-Z][a-z]+$', ws[0]):
        return '', ''
    v = FOLD_VERBS.get(ws[0].lower())
    if not v or (len(ws) > 1 and ws[1].lower() in ('is', 'are', 'was', 'of', 'for', 'and', 'or', 'by')):
        return '', ''
    return '%s %s' % (v, ' '.join(ws[1:])), first


# ---------------------------------------------------------------- build.py adapter
MAP_EVIDENCE = re.compile(r'maplibregl\.|\bL\.map\(|addLayer\(|new\s+ol\.Map|mapboxgl\.|leaflet', re.I)


def evidence_from_build(i, files, imported_by, metas, repo_title, titles_by_path=None, leaks=lambda s: 0):
    """Evidence dict for build.py's files[i]. Call after synopsis_of() has run for every file (it sets
    f['syn_parts'] and f['published'], which this reads for the file and for its dependents).
    repo_title: build.py's repo_title function; titles_by_path: {(repo, path): title}; leaks: Kuiper's
    non-public check, applied to every name and sentence taken from the file or its READMEs."""
    f = files[i]
    text = f.get('text') or '\n'.join(f.get('lines') or [])
    meta = metas.get(f['repo'], {})
    verb, objects, sources = (f.get('syn_parts') or ('', [], []))
    rs, d = [], posixpath.dirname(f['path'])
    while True:
        rs.extend(x for x in meta.get('readme_sentences', {}).get(d, []) if not leaks(x))
        if not d:
            break
        d = posixpath.dirname(d)
    comment = leading_comment(f['path'], text)
    ev = {'title': f['title'], 'kind': f['kind'], 'role': f.get('role', ''), 'repo': f['repo'], 'path': f['path'],
          'repo_title': repo_title(f['repo']), 'comment': '' if leaks(comment) else comment, 'readme': rs,
          'defines': [n for n, k, _ in f.get('defs') or [] if k != 'workflow' and not leaks(n)],
          'verb': verb, 'objects': list(objects), 'sources': list(sources), 'published': f.get('published', ''),
          'has_map': f['kind'] == 'page' and bool(MAP_EVIDENCE.search(text)), 'entry': f.get('entry')}
    cf = code_facts(text, f['kind'], ev['defines'], f['title'])
    if cf and not any(leaks(t) for t in cf['terms']):
        ev['code'] = cf
    sp = [x for x in specifics(text) if not leaks(x)]
    if sp:
        ev['specifics'] = sp
    if f['kind'] == 'configuration' or f['path'].endswith(('.json', '.toml')):
        ev['config'] = config_summary(f['path'], text)
    if f['kind'] == 'workflow' or (f['kind'] == 'configuration' and re.search(r'^jobs:', text, re.M)):
        wf = workflow_facts(text)
        tb = titles_by_path or {}
        wf['run_titles'] = {r: tb[(f['repo'], r.lstrip('./'))] for r in wf['runs'] if (f['repo'], r.lstrip('./')) in tb}
        ev['workflow'] = wf
    if f['path'].endswith('.py'):
        ev['main_only'] = main_only(text)
    for k, v in bb_source_facts(text, f['kind']).items():  # describe-3 R4b/R7 literal source facts
        if not leaks(json.dumps(v)):
            ev[k] = v
    if f.get('vedic'):
        e = f['vedic'][0]
        ev['vedic'] = {'function': (e.get('translation_ref') or '').split(':')[-1].strip(), 'output': e.get('output'),
                       'inputs': list(e.get('inputs') or []), 'word': e.get('word', '')}
    deps = []
    for j in imported_by.get(i, []):
        h = files[j]
        lk = dict(zip(h.get('links') or [], h.get('link_kinds') or []))  # build.py edge kind of j -> i, if known
        deps.append({'title': h['title'], 'kind': h['kind'], 'role': h.get('role', ''), 'repo': h['repo'],
                     'edge': lk.get(i, ''),
                     'published': h.get('published', ''), 'is_map': h['kind'] == 'page' and
                     bool(MAP_EVIDENCE.search(h.get('text') or ''))})
    ev['dependents'] = deps
    ev['imports'] = [{'title': files[j]['title'], 'kind': files[j]['kind'], 'repo': files[j]['repo']}
                     for j in f.get('links') or [] if isinstance(j, int)]
    ev['repo_titles'] = {r: repo_title(r) for r in {f['repo']} | {x['repo'] for x in deps}}
    return ev


# ---------------------------------------------------------------- never-invent check
STOCK = set('''A An The It Its In On By Also Imported Loaded Feeds Checked Guards Defines Runs Published Served
Named Entry Python JavaScript TypeScript GitHub Actions PowerShell SQL UI README VEDIC Pages Its Is Of Name Says
Using Data From Covering That Checks Works With And Other Including Test Tests Map Page Web Configuration
Style Sheet Shell Batch Shader Component Module Tool'''.split())


def invented(output, evidence_text):
    """Capitalised words, acronyms, numbers with units and URLs in `output` that do not appear anywhere in the
    evidence text (case-insensitive) and are not stock phrase-bank or glossary words."""
    hay = evidence_text.lower()
    gloss = {v[1].lower() for v in GLOSSARY.values() if v[1]}
    bad = []
    for u in URL.findall(output):
        if u.rstrip('.,;)').lower() not in hay:
            bad.append(u)
    text = URL.sub(' ', output)
    for w in re.findall(r'`[^`]+`|\b[A-Z][\w\-]*[A-Za-z0-9]|\b\d+(?:\.\d+)?\s?(?:kV|MW|GW|MWh|km)\b', text):
        k = w.strip('`').lower()
        if w.strip('`') in STOCK or any(k in g.split() for g in gloss):
            continue
        if k not in hay and k.replace('-', ' ') not in hay and k.replace(' ', '') not in hay.replace(' ', ''):
            bad.append(w)
    return bad


# ---------------------------------------------------------------- evaluation over build_graph.json
SYN_RX = re.compile(r'^(?P<label>.*?) for (?P<subject>.*?)(?: that (?P<verb>builds and publishes|lists and searches|'
                    r'\w+)(?: (?P<obj>.*?))?|, covering (?P<cov>.*?))?(?: from (?P<src>.*?))?\.(?: Part of |$|…)', re.S)


def _split_list(s):
    if not s:
        return []
    out, buf, q = [], '', False
    for tok in re.split(r'(, | and |")', s):
        if tok == '"':
            q = not q
            buf += tok
        elif tok in (', ', ' and ') and not q:
            out.append(buf.strip())
            buf = ''
        else:
            buf += tok
    if buf.strip():
        out.append(buf.strip())
    return [o for o in out if o]


def parse_synopsis(s, title=''):
    """Recover build.py's synopsis parts (verb, objects, sources, published, repo title) from its text."""
    for subj in sorted({title, title.split(' — ')[0], title.split(' — ')[-1]} - {''}, key=len, reverse=True):
        k = s.find(' for %s' % subj)
        if 0 < k < 30:
            s = s[:k] + ' for X' + s[k + 5 + len(subj):]
            break
    m = SYN_RX.match(s)
    d = {'verb': '', 'objects': [], 'sources': [], 'published': '', 'repo_title': ''}
    if m:
        d['verb'] = m.group('verb') or ''
        if d['verb'] in ('fetches', 'loads', 'calculates', 'tests', 'runs', 'draws', 'maps') and not m.group('obj'):
            pass
        d['objects'] = _split_list(m.group('obj') or m.group('cov') or '')
        if s.rstrip().endswith('…') and not m.group('src') and d['objects']:
            d['objects'] = d['objects'][:-1]  # build.py trimmed this synopsis mid-list
        d['objects'] = [o for o in d['objects'] if o not in ('data', 'its inputs')]
        d['sources'] = _split_list(m.group('src') or '')
        d['has_map'] = m.group('label') == 'Map page'
    p = re.search(r'published at (https?://\S+?)(?:;|\.(?:\s|$)|\s)', s + ' ')
    if p:
        d['published'] = p.group(1)
    r = re.search(r'Part of (.+?)(?:;|\.(?:\s|$))', s)
    if r:
        d['repo_title'] = r.group(1)
    return d


VEDIC_RX = re.compile(r'Contains (\w+), which produces (.*?) from (.*?) \(VEDIC meaning (.*?), ', re.S)


def _readme_chain(src, repo, path, cache):
    d = posixpath.dirname(path)
    out = []
    while True:
        key = (repo, d)
        if key not in cache:
            cache[key] = []
            base = os.path.join(src, repo, d)
            try:
                for n in sorted(os.listdir(base)):
                    if re.match(r'^readme(\.(md|markdown|txt))?$', n, re.I):
                        with open(os.path.join(base, n), errors='replace') as fh:
                            cache[key] = readme_sentences(fh.read())
                        break
            except OSError:
                pass
        out.extend(cache[key])
        if not d:
            break
        d = posixpath.dirname(d)
    return out


def evidence_from_graph(g, i, src, cache, repo_titles):
    """Evidence for file i of build_graph.json, reading its source and READMEs from the clones."""
    F = g['files']
    f = F[i]
    syn = parse_synopsis(f['synopsis'], f['title'])
    try:
        with open(os.path.join(src, f['repo'], f['path']), errors='replace') as fh:
            text = fh.read(400000)
    except OSError:
        text = ''
    ev = dict(title=f['title'], kind=f['kind'], role=f['role'], repo=f['repo'], path=f['path'],
              name_words=f.get('name_words', []), defines=f.get('defines', []), verb=syn['verb'],
              objects=syn['objects'], sources=syn['sources'], has_map=syn.get('has_map', False),
              published=syn['published'], repo_title=repo_titles.get(f['repo'], f['repo']), repo_titles=repo_titles,
              entry=f.get('entry'))
    ev['comment'] = leading_comment(f['path'], text)
    cf = code_facts(text, f['kind'], f.get('defines', []), f['title'])
    if cf:
        ev['code'] = cf
    if specifics(text):
        ev['specifics'] = specifics(text)
    if f['kind'] == 'configuration' or f['path'].endswith(('.json', '.toml')):
        ev['config'] = config_summary(f['path'], text)
    if f['kind'] == 'workflow' or (f['kind'] == 'configuration' and re.search(r'^jobs:', text, re.M)):
        ev['workflow'] = workflow_facts(text)
        if '_bypath' not in cache:
            cache['_bypath'] = {(h['repo'], h['path']): h['title'] for h in F}
        ev['workflow']['run_titles'] = {r: cache['_bypath'][(f['repo'], r.lstrip('./'))]
                                        for r in ev['workflow']['runs'] if (f['repo'], r.lstrip('./')) in cache['_bypath']}
    if f['path'].endswith('.py'):
        ev['main_only'] = main_only(text)
    if f['achieves_provenance'] == 'code':
        m = VEDIC_RX.search(f['achieves'])
        if m:
            ev['vedic'] = {'function': m.group(1), 'output': m.group(2), 'inputs': _split_list(m.group(3)),
                           'word': m.group(4)}
    ev['readme'] = _readme_chain(src, f['repo'], f['path'], cache)
    deps = []
    for j in f.get('dependents', []):
        h = F[j]
        hs = parse_synopsis(h['synopsis'], h['title'])
        deps.append({'title': h['title'], 'kind': h['kind'], 'role': h['role'], 'repo': h['repo'],
                     'published': hs['published'], 'is_map': hs.get('has_map', False)})
    ev['dependents'] = deps
    ev['imports'] = [{'title': F[j]['title'], 'kind': F[j]['kind'], 'repo': F[j]['repo']} for j in f.get('imports', [])]
    ev['_text'] = text
    return ev


def evidence_text(ev):
    """Everything describe() may draw words from, as one string (for the never-invent check)."""
    parts = [ev.get('title', ''), polish_title(ev.get('title', '')), ev.get('kind', ''), ev.get('role', ''),
             ev.get('repo', ''), ev.get('repo_title', ''), ev.get('path', ''), ' '.join(ev.get('name_words') or []),
             ev.get('comment', ''), ev.get('config', ''), ' '.join(ev.get('readme') or []),
             ' '.join(ev.get('defines') or []), ev.get('verb', ''), ' '.join(ev.get('objects') or []),
             ' '.join(ev.get('sources') or []), ev.get('published', ''),
             (ev.get('main_only') or '') + (' main()' if ev.get('main_only') else ''),
             json.dumps(ev.get('workflow') or {}), json.dumps(ev.get('vedic') or {}),
             ' '.join(d.get('title', '') + ' ' + (d.get('published') or '') + ' ' + d.get('repo', '')
                      for d in ev.get('dependents') or []),
             ' '.join(d.get('title', '') for d in ev.get('imports') or []),
             ' '.join('%s %s' % kv for kv in (ev.get('repo_titles') or {}).items()),
             ' '.join((ev.get('code') or {}).get('terms') or []), ' '.join(ev.get('specifics') or []),
             ' '.join(ev.get('bb_units') or []), json.dumps(ev.get('bb_io') or {}),
             json.dumps(ev.get('context') or {}, ensure_ascii=False)]
    return '\n'.join(str(p) for p in parts)


# Problem detectors: the same mechanical rules applied before and after (see DESCRIBE-REVIEW.md).
def flags(title, synopsis, achieves, why, kind=''):
    out = set()
    syn_core = re.sub(r'\s*Part of .*$', '', synopsis)
    tw = {w.lower() for w in re.findall(r'[A-Za-z0-9]+', title)}
    stock = {'the', 'a', 'an', 'for', 'of', 'and', 'in', 'that', 'page', 'script', 'module', 'workflow', 'file',
             'tool', 'test', 'tests', 'python', 'javascript', 'typescript', 'configuration', 'style', 'sheet',
             'shell', 'command', 'line', 'web', 'github', 'actions', 'defines', 'runs', 'calculates', 'its', 'inputs',
             'draws', 'loads', 'fetches', 'data', 'lists', 'searches', 'covering'}
    # generic: synopsis and achieves together tell the reader fewer than three content words beyond the title,
    # the kind and stock words (identifiers in backticks do not count as content)
    ws = [w.lower() for w in re.findall(r'[A-Za-z0-9]+', re.sub(r'`[^`]*`', '', syn_core + ' ' + achieves))]
    if len({w for w in ws if w not in tw and w not in stock}) < 3:
        out.add('generic')
    # repetitive: the synopsis repeats the title, or achieves is "<kind> for <title>"
    if (len(title.split()) >= 2 or len(title) >= 8) and title.lower() in syn_core.lower() or \
            re.search(r'\bfor %s\b' % re.escape(title), achieves, re.I):
        out.add('repetitive')
    allt = ' '.join((synopsis, achieves, why))
    plain = re.sub(r'`[^`]*`|https?://\S+', '', allt)
    if re.search(r'(?<![\w`])(?:[a-z]+[A-Z]\w+|[a-z]+_\w+|\w+\.(?:mjs|cjs|py|js)\b)|\{[A-Z]+\}|%[sd]|\$\{|VEDIC meaning'
                 r'|esc\(', plain):
        out.add('jargon/identifiers')
    if re.search(r'\b(\w+) \1\b|Used by 1 file[^.]*including|that (?:tests|draws|calculates|loads|fetches)\.'
                 r'|its inputs|^[a-z]|\. [a-z]|\s\*\s|…\.|including [^.;]*…|: defines [^.]*,[^.]*,[^.]*,'
                 r'|says: "[^"]*[a-z]"\s*$|Test for Test', allt) or re.search(r'"[^"]*\b(?:and|for|an|the|of|to)"', allt):
        out.add('broken English')
    nourl = re.sub(r'`[^`]*`|https?://\S+', '', achieves + ' ' + why)
    if re.search(r'\b(candidate|not composed|not published|no production|retired|deprecated|superseded|unreviewed|'
                 r'quarantined|example only|copied|placeholder)\b|COPIED|run with:|usage:|Opus team|NL-\d{3}|'
                 r'Apache-2\.0|\b20\d{6,}\b|\b[0-9a-f]{10,}\b|generation \d', nourl, re.I):
        out.add('status/housekeeping')
    if re.search(r'127\.0\.0\.1|localhost|%s:|\$\{', synopsis) or \
            (re.search(r'published at', synopsis) and kind in ('Python CLI', 'Python module', 'test', 'shell script',
                                                                'workflow', 'configuration')):
        out.add('wrong place/URL')
    if re.search(r'Used by 1 file[^.]*including|feeds: [^;]*(?:\|…|…\.|\|)', why) or len(why.split()) > 45:
        out.add('misleading why')
    return out


def _main():
    ap = argparse.ArgumentParser(description='Evaluate describe.py over build_graph.json (before vs after).')
    ap.add_argument('--graph', default='/tmp/site5/explore-code/build_graph.json')
    ap.add_argument('--src', default='/home/claude/src')
    ap.add_argument('--sample', default='', help='JSON list of file ids for the before/after table')
    ap.add_argument('--out', default='', help='write per-file results (JSON) here')
    a = ap.parse_args()
    g = json.load(open(a.graph))
    F = g['files']
    repo_titles = {}
    for f in F:
        r = parse_synopsis(f['synopsis'])['repo_title']
        if r and f['repo'] not in repo_titles:
            repo_titles[f['repo']] = r
    cache, results = {}, []
    before, after = collections.Counter(), collections.Counter()
    any_b = any_a = inv_n = 0
    lb, la, dupb, dupa = [], [], 0, 0
    for i, f in enumerate(F):
        ev = evidence_from_graph(g, i, a.src, cache, repo_titles)
        d = describe(ev)
        fb = flags(f['title'], f['synopsis'], f['achieves'], f['why'], f['kind'])
        fa = flags(d['title'], d['synopsis'], d['achieves'], d['why'], f['kind'])
        before.update(fb)
        after.update(fa)
        any_b += bool(fb)
        any_a += bool(fa)
        bad = invented(' '.join((d['synopsis'], d['achieves'], d['why'])), evidence_text(ev))
        inv_n += bool(bad)
        lb.append(len(f['synopsis'].split()))
        la.append(len(d['synopsis'].split()))
        dupb += f['title'].lower() in (f['synopsis'] + f['achieves']).lower()
        dupa += d['title'].lower() in (d['synopsis'] + d['achieves']).lower()
        results.append({'id': i, 'before': {k: f[k] for k in ('title', 'synopsis', 'achieves', 'why')},
                        'after': {k: d[k] for k in ('title', 'synopsis', 'achieves', 'why')},
                        'prov': d['provenance'], 'flags_before': sorted(fb), 'flags_after': sorted(fa),
                        'invented': bad})
    n = len(F)
    print('files %d' % n)
    for k in sorted(set(before) | set(after)):
        print('%-22s before %5d (%4.1f%%)  after %5d (%4.1f%%)' % (k, before[k], 100 * before[k] / n, after[k],
                                                                   100 * after[k] / n))
    print('any flag              before %5d (%4.1f%%)  after %5d (%4.1f%%)' % (any_b, 100 * any_b / n, any_a,
                                                                              100 * any_a / n))
    print('synopsis words mean   before %.1f  after %.1f  (max after %d)' % (sum(lb) / n, sum(la) / n, max(la)))
    print('title repeated        before %d  after %d' % (dupb, dupa))
    print('invented (any)        after %d' % inv_n)
    pc = collections.Counter(r['prov']['achieves'] for r in results)
    print('achieves provenance after', dict(pc), 'before', dict(collections.Counter(f['achieves_provenance'] for f in F)))
    if a.out:
        json.dump(results, open(a.out, 'w'), ensure_ascii=False)


if __name__ == '__main__':
    _main()