GLOBALGRID2050 / EXPLORE CODE

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

Build (part 1)

A Python command-line tool in the explore folder of Cosmic that maps dictionary and build graph, using EPSG:27700 and EPSG:4326, and uses data from the GridAtlas, ventus-grid-engine and SatNav repositories.

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

Build

A Python command-line tool in the explore folder of Cosmic that maps dictionary and build graph, using EPSG:27700 and EPSG:4326, and uses data from the GridAtlas, ventus-grid-engine and SatNav repositories.

rendercosmic / tools/explore/build.py · lines 1–700 of 3776 · Entry point · pattern clean_comment (shared by 2 files)

What it does
It maps dictionary, build graph, words and solar. Defines 114 functions or classes, including words_of, git, ext, slug, load_leaks. Uses libraries argparse, collections, datetime, fnmatch, html. Side effects: changes the web page (DOM); reads or writes files; makes network requests; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: solar, 132kV, 33kV, 11kV, 11kV/400V, 400V. README: "`build.py` is the method"
Inputs & outputs
In: data source: gridatlas data; data source: ventus-grid-engine data; data source: satnav data; data source: solar-electrical-topology-analysis-engine-text-based data; JSON file dictionary.json; JSON file build_graph.json; Parquet file code.parquet; Parquet file words.parquet. Out: Parquet file; JSON file; interactive map; SVG drawing. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid), WGS84 / EPSG:4326, Web Mercator / EPSG:3857, ETRS89 / EPSG:4258. Voltage levels named: 132kV, 33kV, 11kV, 11kV/400V, 400V.
Downstream impact
Used directly by 3 files: Cadastre 27 (cosmic); Ship (cosmic); Test Build (cosmic). Reached from 1 other entry point, including Test Ship (cosmic).
What it achieves
It loads leaks (`load_leaks`), loads essays (`load_essays`) and cleans key (`clean_key`). The README says: `build.py` is the method. Its code works with 132 kV, 33 kV and 11 kV. It writes `words/index.html`.
Why it matters
Imported by Cadastre 27. Run by Ship. Checked by Test Build.
Application
cosmic · tools/explore · Python CLI
Uses
Describe (import), Agentdocs (import), GridAtlas — Index Page (estate URL), SatNav — Scope Page (estate URL), Solar Electrical Topology Analysis Engine Text Based — Index Page (estate URL), argparse, collections, datetime, fnmatch, html, json, os, posixpath
Used by
imported by Cadastre 27 (sys.path import), run by Ship (script call), imported by Test Build (import)
Produces
words_of, git, ext, slug, load_leaks, humanise, kind_of, name_words, stamp_note, title_parts, title_of, repo_title
Defines here
words_of, git, ext, slug, load_leaks, _tokens, humanise, kind_of, _spell, name_words, stamp_note, _phrased, _is_term, title_parts, title_of, repo_title, md_strip, trim, front_matter, _readme_paragraphs, flush, _readme_usable, readme_score, readme_pick
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/build.py:1-700 · blob a82b6f8252f926b3e24b5469dc1f3b7b2ead6a33 · GitHub at these lines
State
achieves: readme · context: readme_derived · stage: output · effects: dom, filesystem, network, process, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
r"""tools/explore/build.py - Explore Code: the GlobalGrid2050 code estate as readable, linked web pages.

Run by .github/workflows/explore-code.yml on GitHub's machine. Nothing it writes is committed: the
pages and tables are published straight to GitHub Pages, so the repository does not grow.

  1. Read every public Ventusltd repository at its HEAD commit (one clone each, under --src).
  2. Code files only; no vendored, minified, binary or over-1 MB files.
  3. Unique: each git blob once, and only the newest of each family of timestamped versions
     (paths equal once 20YYMMDD[hhmm] stamps are masked).
  4. Anything matching a non-public repository digest (Kuiper's check_proof.leaks) is left out.
  5. Sorted by topic, repository and path, cut into sections of --min to --max lines.
  6. Each section is one static page with its code as plain text, so Gemini and other agents can
     read it with no script. Every file block is keyed repo@commit path:from-to with its blob SHA
     and a link to GitHub at those lines.
  7. Each file gets a VEDIC statement (docs/VEDIC-LANGUAGE.md in vedic-): What it achieves, Why it
     matters, Application, Uses, Used by, Produces, Cannot conclude, Evidence, State. It is a static
     reading and says so.
  8. The journey is computed, not designed: breadcrumbs ("Part of: topic / repository / folder /
     essay"), previous/next, imports and imported-by, every definition linked to the dictionary,
     topic and repository pages linking down, every page linking back up.
  9. Parquet tables (code, files, sections, words) are the compact master copy. search.html runs
     DuckDB in the browser against code.parquet: full-text search with no search algorithm to tune.

Context, in strict priority (top of each page, above the code):
  Tier 1  Human essays (--essays, default the cosmic repository's essays/ folder; see essays/README.md):
          essays/<repo>/index.md (the repository page), essays/<repo>/<folder path>.md (that folder and
          below) and essays/<repo>/<file path>.essay.md (one file). Optional front matter "title:".
          Rendered as written, labelled "Written by people"; essay_status = human. Never generated.
  Tier 2  Plain-English titles from folder + file name (title_of: timestamps and extensions dropped,
          an abbreviation dictionary, OHL -> "Overhead Line (OHL)" on first use), and the nearest
          README (README*, .md/.txt/none, case-insensitive) walking up from the file's folder to the
          repository root: its summary (readme_pick: the first paragraph, in reading order, whose
          descriptor score reaches README_THRESHOLD, else the best-scoring one; badges/headings/lists/
          tables skipped, markdown stripped, <= 400 characters; process records, policies, session logs,
          change logs, instructions to agents, dated or hashed records rejected; see readme_score) is
          shown once per folder per page as "Environment and domain context"; essay_status =
          readme_derived. A root README whose chosen paragraph scores below README_THRESHOLD is not
          shown as context, and the repository descriptor then comes from its files' evidence
          (provenance code). Essays under essays/drafts/ or with status: draft are never loaded.
  Tier 3  Per file, the synopsis (describe.py; when no data source or verb-and-object evidence exists,
          describe.code_facts adds what the code computes: verb-led defined names, recognised formulas,
          drawing calls, form inputs and units), "What it achieves" (first of: a matching VEDIC dictionary meaning, the file's own
          leading comment, the names it defines) and "Why it matters" (built only from the files that
          import it). Otherwise essay_status = auto. Nothing is invented: absent evidence says so.

Licences come only from the text of a LICENSE/LICENCE/COPYING file at the repository root, matched on
SPDX-identifying phrases (license_of); anything else is "other (see LICENSE)", and no file is "none
found" plus a WARNING line in the build log. CITATION.cff presence is reported per repository.

Side effects (effects_of) are regular expressions over the file text, by kind: dom, network, storage,
filesystem, process. HTML/CSS count as dom; shell, PowerShell, batch and workflow files as process.
A file with none is "pure".

Stage rule (build_graph.json "stage", deterministic, evidence only):
  output     touches the DOM, draws, renders, or writes outputs (files, Parquet, figures);
  ingest     otherwise, reads from network, files, storage or a data source;
  transform  otherwise, pure (no side effects; its calls go only to its own code, estate files or
             libraries) and defines at least one function or class;
  unknown    everything else (e.g. process-only scripts, data-only config).

Role rule (one of ROLES, first match wins, in this order of precedence):
  1 test         path words test/tests/spec/smoke, test_*.py, *_test.*, *.test.*, *.spec.*
  2 automation   .github/ files, shell/PowerShell/batch, path words ci/workflow/deploy/release
  3 docs-config  TOML, non-workflow YAML, file names config/settings/manifest
  4 geodesy / electrical / energy-data   domain keyword score >= 2, from the words of defined names
                 (1 each), the file name (2 each) and any matched VEDIC meaning (2 each); highest
                 wins, ties in that order
  5 render / interaction   HTML/CSS, or DOM/drawing evidence: interaction when event-handling
                 matches outnumber drawing matches, otherwise render
  6 storage      storage effects or file writes
  7 ingest       network or file reads, or a defined name starting fetch/load/parse/read/decode
  8 transform    pure and defines something
  9 other
Pattern: the most specific defined-name family (name minus trailing version digits, >= 5 characters,
not a generic name) shared by 2..100 files; fewest files wins, then longest name; '' if none.
Edges ("what it uses" / "what uses it"; refs_of finds references, Resolver maps them to estate files, any
repository). Each edge is one of EDGE_KINDS, read over the whole file:
  import            JS/TS static import / export-from; Python import and from-import (sibling, then repository root)
  python-relative   from . import x, from .x import y (package-relative; names tried as submodules)
  sys-path          a Python import found only through a folder added by sys.path.insert/append, where the
                    expression can be followed (HERE, Path(__file__).resolve().parents[1] / "x", os.path.join(...))
  require / dynamic-import / url-import-meta   require('./x'), import('./x'), new URL('./x', import.meta.url)
  worker            new Worker / SharedWorker, importScripts, serviceWorker.register
  script-src        <script src>, el.src = "x.js"
  stylesheet        <link rel=stylesheet href>, CSS @import
  modulepreload     <link rel=modulepreload|preload|prefetch href>
  import-map        targets in <script type=importmap>
  iframe            <iframe src>, <frame src>
  link              <a href>, meta refresh, location.href = / window.open( (same-site pages only resolve)
  fetch             fetch('...') of an estate file (relative path or estate URL)
  estate-url        any other absolute URL into the estate: https://ventusltd.github.io/<repo>/<path>, a CNAME host
                    (https://globalgrid2050.com/<path> -> globalgrid2050), raw.githubusercontent.com/Ventusltd/<repo>/<ref>/
                    <path>, cdn.jsdelivr.net/gh/Ventusltd/<repo>@<ref>/<path>, github.com/Ventusltd/<repo>/blob|raw/<ref>/<path>
  script-call       python/node/bash x in shell scripts, Python subprocess, child_process, sys.executable; in a file that
                    starts processes, a string literal naming a repository script; package.json scripts (entry points)
  workflow-run      GitHub workflow lines: python x.py, node x.mjs, bash x.sh, ./x.sh, python -m pkg.mod, globs
                    (node tools/*/proof.mjs), "$VAR" set to a script path, local uses: ./action, and test runners by
                    their documented discovery rules (pytest: test_*.py, *_test.py, conftest.py; python -m unittest
                    [discover -s DIR -p PAT]; node --test: *.test.js, test-*.js, test/ folders; py_compile files)
Resolution, in order: the path as written (relative to the file; for pages also root-absolute, where /<repo>/ on a
github.io project site names that repository); a directory URL (folder/ -> folder/index.html, via "index"); for
document-relative kinds, the repository's Pages root (repo root, or docs/ when only docs/index.html exists; via
"pages-root"); an older timestamped version maps to the kept newest member of its family (via "family"); a path whose
blob was kept once elsewhere maps to that copy (via "duplicate"). Script paths are tried from the repository root,
then cd / working-directory folders, then the file's folder. Each edge records via; build_graph.json carries
per-file "edge_kinds" (parallel to "imports") and a top-level "edges" list (GRAPH-CONTRACT.md, "Edges").
Entry points: HTML pages, GitHub workflows, Python with `if __name__ == "__main__"`, shebang scripts, package.json
main/bin/exports targets and npm script targets, files a page loads (<script src>, stylesheet, modulepreload,
import map, worker), files a workflow runs, and files the Pages root index references. "Reachable" is a
breadth-first walk from entry points over every edge kind. Unreached means no resolvable reference was found; it is
a candidate signal for review, never a reason to delete. Known blind spots: paths built at run time (string
concatenation, template literals, manifests in JSON), loops over file lists in shell, and prose mentions.

Agent ingestion (owner brief 2026-12-05; agentdocs.py holds the tables, RULES_VERSION in build_graph.json
"rules_version"; GRAPH-CONTRACT.md "Agent ingestion fields"). Evidence only; `unknown` / empty when absent:
  domain_stage      first of: (1) path words against STAGE_WORDS, stages tried in the order experimental, agent_infra,
                    hv_procurement, field_execution, site_feasibility, sub33kv_design, upstream_foresight; (2) the same
                    over repository name words; (3) voltages in the code: all >= 132kV -> upstream_foresight, all <= 33kV
                    -> sub33kv_design; (4) topic: agents-ai -> agent_infra, grid-network / markets-data ->
                    upstream_foresight, solar-storage / cables -> sub33kv_design, maps-gis -> site_feasibility;
                    (5) unknown. domain_stage_evidence names the rule and word.
  commercial_user   STAGE_USERS of the stage (upstream_foresight: IPP_developer, ICP_grid_engineer; site_feasibility:
                    IPP_developer, landowner_planner; sub33kv_design: EPC_contractor, ICP_grid_engineer; hv_procurement:
                    procurement_buyer, EPC_contractor; field_execution: EPC_contractor, landowner_planner; agent_infra:
                    ai_agent; experimental / unknown: none) plus any user whose USER_WORDS occur in repository or path words.
  data_contracts    {"in", "out", "crs", "voltages"}: in = data sources named by URL (only when the file reads or fetches),
                    data files named in code but not on a write line, browser storage reads, DuckDB / SQLite, form
                    fields, file pickers, command-line arguments; out = data files named on a write line, named downloads,
                    storage writes, web page, interactive map, canvas / WebGL / SVG drawing, figures, GitHub Pages
                    deployment, commits pushed; crs = OSGB36 / EPSG:27700 (epsg:27700, osgb, osgb36, british national
                    grid, bng, easting + northing), WGS84 / EPSG:4326, Web Mercator / EPSG:3857, ETRS89, UTM, each only when
                    written in the code; voltages = kV and V levels written in code or path, highest first.
  canonical_status  production_core (reachable, in CORE_REPOS, entry point or has dependents) > duplicate_candidate
                    (same text ignoring whitespace, >= 5 lines; or same pattern + same >= 2 defined names + lines within
                    25%, as a kept member chosen by production_core, reachable, entry, dependents, newest stamp, lines,
                    id; duplicate_of names it) > unreached_review (not reachable) > supporting_data (reachable, repository
                    name word "data" or role energy-data / storage) > unknown. None of these is a reason to delete.
  four-part block   What it does (verb, elements, definitions, libraries, side effects), Why it exists in the grid
                    workflow (stage meaning from the brief, domain terms, a README sentence naming the file), Inputs &
                    outputs (data_contracts in words), Downstream impact (dependents and the entry points that reach the
                    file, with published addresses). Each part is omitted when it has no evidence. Shown on section pages
                    above the statement, and in the shards.
  signatures        function / class / method names with their parameter text from the code (Python, JavaScript family,
                    shell); JavaScript exports from `export` statements only.
  llms.txt          routing index (< 15k tokens, about characters / 4): Ventus Ltd's stated mission (brief facts only,
                    attributed), CORE_REPOS with "Start here" (repository page + one entry point: a homepage launch
                    button into the repository, Pages root first; else the Pages root page; else the published entry
                    point reaching most files; else any entry point reaching most files),
                    topic hubs (HTML + text shard), journeys, Agent Navigation Protocol, shard list, licences.
  shards            llms-<topic>.txt, llms-repo-<core repo>.txt, llms-journey-<a..d>.txt: per file title, synopsis,
                    achieves, four-part block, signatures, VEDIC, labels, data contracts, edges, GitHub commit#L URL.
                    Over 5 MB a shard splits into -01, -02 ... and the unsplit name becomes an index of the parts.
                    llms-full.txt (every file) is written when under 25 MB, otherwise llms-full-index.txt.
  journeys          the four journeys named in the brief; each step found by repository name, a GlobalGrid2050 homepage
                    launch link, a repository containing the label words, or a folder name (agentdocs docstring); steps
                    not found say "not found in the public estate"; links between steps are resolved edges only.

Usage: python tools/explore/build.py --src CLONES --out _site/explore-code --base https://.../explore-code/
"""
import argparse
import collections
import datetime
import fnmatch
import html
import json
import os
import posixpath
import re
import shutil
import subprocess
import sys
import urllib.parse

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import describe  # noqa: E402  natural descriptions (DESCRIBE-REVIEW.md)
import agentdocs  # noqa: E402  agent ingestion fields, shards and journeys (GRAPH-CONTRACT.md)

E = html.escape
EXT = re.compile(r'\.(py|js|mjs|cjs|ts|tsx|jsx|html|htm|css|sh|ps1|bat|yml|yaml|sql|rs|go|c|cc|cpp|h|hpp|'
                 r'java|kt|swift|rb|php|r|jl|lua|toml|glsl|wgsl|vue|svelte)$', re.I)
SKIP = re.compile(r'(^|/)(node_modules|vendor|third_party|dist|build|\.git)/|\.min\.(js|css)$', re.I)
STAMP = re.compile(r'(?<!\d)(20\d{6}(?:T?\d{4,6}Z?)?)(?!\d)')
LANG = {'py': 'Python', 'js': 'JavaScript', 'mjs': 'JavaScript', 'cjs': 'JavaScript', 'ts': 'TypeScript',
        'tsx': 'TypeScript', 'jsx': 'JavaScript', 'html': 'HTML', 'htm': 'HTML', 'css': 'CSS', 'sh': 'Shell',
        'ps1': 'PowerShell', 'bat': 'Batch', 'yml': 'YAML', 'yaml': 'YAML', 'sql': 'SQL', 'toml': 'TOML'}
LINE_CAP = 400  # characters shown per line on a page; the Parquet table and GitHub keep every line whole
JSX = ('js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx', 'html', 'htm', 'vue', 'svelte')
SITE = 'GlobalGrid2050 Explore Code'
AUTHOR = 'Ventus Ltd — GlobalGrid2050'
# Topics are assigned from whole words of the repository name and path (camelCase, snake_case and
# kebab-case split), first match wins, so "star" never matches "start". A word matches a keyword when it
# equals it, or, for keywords of 5+ letters, starts with it ("cables", "substations"). Order matters.
TOPICS = [
    ('cables', 'Cables and conductors', 'Sizing, derating, geometry and prices of AC and DC cables.',
     'cable conductor derating copper aluminium aluminum trench drill 132kv 33kv 11kv ampacity'),
    ('solar-storage', 'Solar and storage design', 'Solar PV layout, strings, battery storage and site design.',
     'solar pv bess battery inverter repower repowering floating panel panels irradiance yield array'),
    ('grid-network', 'Grid network and substations', 'Substations, network topology, single-line diagrams and connections.',
     'substation sld topology network dno tso interconnector interconnectors transformer feeder faraday ukpn ssen voltage busbar switchgear'),
    ('maps-gis', 'Maps, GIS and field navigation', 'Maps, geodesy, LiDAR, terrain and SatNav field journeys.',
     'atlas gridatlas satnav gis geo geodesy geojson lidar terrain map maps maplibre survey gps route routing walk soil tiles osm'),
    ('markets-data', 'Electricity markets and data pipelines', 'Generation, prices, project pipelines and news data.',
     'market markets price prices tracking generation elexon bmrs pipeline pipelinenews repd news datacentre datacentres federation registry companies dashboard energy'),
    ('kuiper-cosmos', 'Kuiper, cosmos and drawing engines', 'The code universe, wafers, stars and drawing engines.',
     'kuiper cosmic cosmos wafer galaxy galaxies star stars universe belt particle graphics drawing elements periodic stones trillion quantum'),
    ('agents-ai', 'AI agents and coordination', 'Agent start points, neural links, spiders, Vedic and Gemini bridges.',
     'agent agents neural spider spiders vedic gemini claude chatgpt codex llm prompt session sessions crawler teleprinter tokens'),
    ('automation', 'Automation and CI', 'GitHub workflows, checks, tests and build tooling.',
     'github workflow workflows test tests ci check checks proof tools scripts automation build'),
    ('web-apps', 'Websites and apps', 'Homepages, interfaces and the remaining applications.', ''),
]
# One palette for the site and the visualiser (GRAPH-CONTRACT.md "Palette": homepage + Pipeline News).
ROLES = [
    ('geodesy', 'Geodesy and coordinates', '#00ffff'),
    ('electrical', 'Electrical engineering', '#ffae00'),
    ('energy-data', 'Energy data and markets', '#ffff00'),
    ('ingest', 'Ingest (fetch, load, parse)', '#66ccff'),
    ('transform', 'Transform (pure maths and conversion)', '#00ff88'),
    ('render', 'Render (DOM, canvas, maps, HTML)', '#ff6666'),
    ('interaction', 'Interaction (events, input, navigation)', '#ffd24a'),
    ('storage', 'Storage (browser, DuckDB, files written)', '#86e1d1'),
    ('test', 'Tests and checks', '#aef7d1'),
    ('automation', 'Automation and CI', '#8d95a3'),
    ('docs-config', 'Configuration and manifests', '#a6adbb'),
    ('other', 'Other', '#4c5a65'),
]
ROLE_TITLE = {k: t for k, t, c in ROLES}
# Owner-curated (editable): the repositories shown first on the index as core production engines.
CORE_REPOS = ['gridatlas', 'ventus-grid-engine', 'globalgrid2050', 'satnav',
              'solar-electrical-topology-analysis-engine-text-based', 'pipelinenews']
ROLE_COLOUR = {k: c for k, t, c in ROLES}
# Generator version (rapid-ship swarm 2026-12-05): bump on every output change; recorded in build_graph.json and
# each page's <meta name="generator">. History: tools/explore/CHANGELOG.md.
GENERATOR_VERSION = '2.1.0'
# Owner-pending one-paragraph descriptors for the core engines: the first paragraph of LEDGER-41's "What this is"
# drafts (/tmp/vk/11/<repo>/ABOUT.md), written by an AI assistant from evidence. They are DRAFTS awaiting owner
# approval: shown with that label, recorded as descriptor_provenance "core_hook_draft" in build_graph.json, and
# always overridden by a human essay (essays/<repo>/index.md). The owner approves by moving a text into an essay or
# by changing CORE_HOOKS_STATUS to 'owner_approved'.
CORE_HOOKS_STATUS = 'draft_awaiting_owner_approval'
CORE_HOOKS_SOURCE = 'LEDGER-41 "What this is" drafts (AI-assisted, from evidence), 2026-12-05'
CORE_HOOKS = {
    'gridatlas':
        'GridAtlas is an open-source browser map of UK renewable energy projects and the electricity grid around them, published at https://ventusltd.github.io/gridatlas/. It compiles the official DESNZ Renewable Energy Planning Database (REPD) into a searchable registry with project addresses and postcodes, and draws transmission circuits and substations beside it.',
    'ventus-grid-engine':
        "Ventus Grid Engine is the calculation library for GlobalGrid2050's grid tools, taken out of GridAtlas and Pipeline News, which had each grown their own copies. It holds the distance, area and nearest-substation mathematics and the deep-link contract between the two applications, once each and checked by proofs. Its home page is published at https://ventusltd.github.io/ventus-grid-engine/.  … [line shortened here: 402 characters; full line on GitHub]
    'globalgrid2050':
        "GlobalGrid2050 is the repository that publishes globalgrid2050.com, Ventus Ltd's open website for electricity infrastructure, through GitHub Pages. It holds the site's public pages and historical tools, which process their data in the browser: maps of UK renewable projects from the Renewable Energy Planning Database, engineering estimators and design sandboxes.",
    'satnav':
        "SatNav is GlobalGrid2050's open-source project for reaching UK electricity infrastructure on and off road: substations, projects and powerlines. It is a development preview, published at https://ventusltd.github.io/satnav/scope/, and the part available for testing is a GPS field compass for mobile devices.",
    'solar-electrical-topology-analysis-engine-text-based':
        'The Solar Electrical Topology Analysis Engine is an open-source, text-based engine that models the DC electrical network of a solar PV plant from its physical geometry and electrical parameters. Its browser workbenches are published at https://ventusltd.github.io/solar-electrical-topology-analysis-engine-text-based/.',
    'pipelinenews':
        "PipelineNews is GlobalGrid2050's UK renewables pipeline application. It presents solar, battery storage and wind projects from the official DESNZ Renewable Energy Planning Database (REPD) as a filterable register, with daily project news and sector intelligence beside it, and lets readers export the register as CSV.",
}
# Repository pages (phone first, agent reading review 2026-12-05): above this many main-view files the folder lists
# give names only (the synopsis is on each section page); more sections than SECTION_FOLD go behind a fold.
REPO_SYNOPSIS_MAX = 300
SECTION_FOLD = 12
# Opens a folded <details> when the address names it (#d-<folder>), so breadcrumb links still land on the folder.
FOLD_OPEN_JS = ('<script>(function(){function o(){var h=location.hash.slice(1),d=h&&document.getElementById(h);'
                'if(d&&d.tagName==="DETAILS"){d.open=true;d.scrollIntoView();}}addEventListener("hashchange",o);o();})();</script>')
# Self-hosted DuckDB-WASM for search.html (contract agreed with SWARM-SHIP / KEEL-84): the workflow or ship.py places
# these files under <out>/vendor/duckdb/ after build.py; search.html probes VERSION and falls back to jsDelivr, then
# to the Topics and Words pages. duckdb-browser.mjs is the esbuild bundle of dist/duckdb-browser.mjs + apache-arrow.
DUCKDB_VERSION = '1.29.0'
DUCKDB_PATH = 'vendor/duckdb/'
DUCKDB_FILES = ('duckdb-browser.mjs', 'duckdb-eh.wasm', 'duckdb-browser-eh.worker.js', 'duckdb-mvp.wasm',
                'duckdb-browser-mvp.worker.js', 'VERSION')
# The parquet extension DuckDB loads on first read_parquet (core v1.1.1 inside duckdb-wasm 1.29.0), self-hosted from
# https://extensions.duckdb.org/v1.1.1/<variant>/parquet.duckdb_extension.wasm; absent -> DuckDB fetches it from there.
DUCKDB_EXT = ('ext/v1.1.1/wasm_eh/parquet.duckdb_extension.wasm', 'ext/v1.1.1/wasm_mvp/parquet.duckdb_extension.wasm')
# Honest framing of the commercial labels (owner review 2026-12-05): shown on section pages and in llms.txt.
RULES_URL = ('https://github.com/Ventusltd/cosmic/blob/main/tools/explore/GRAPH-CONTRACT.md'
             '#agent-ingestion-fields-owner-brief-2026-12-05-semantic-and-commercial-understanding')
LABELS_NOTE = ('domain_stage, commercial_user and canonical_status are rule-based first approximations from code and path '
               'evidence (rules %s), not observed facts')


def words_of(s):
    s = re.sub(r'([a-z0-9])([A-Z])', r'\1 \2', s)
    return [w for w in re.split(r'[^a-z0-9]+', s.lower()) if w]


TOPIC_RX = [(k, t, d, set(kw.split())) for k, t, d, kw in TOPICS]

JS_DEF = [(re.compile(r'^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)'), 'function'),
          (re.compile(r'^\s*(?:export\s+)?(?:default\s+)?class\s+([A-Za-z_$][\w$]*)'), 'class'),
          (re.compile(r'^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=\s*(?:async\s*)?'
                      r'(?:function\b|\([^)]*\)\s*=>|[A-Za-z_$][\w$]*\s*=>)'), 'function')]
PY_DEF = [(re.compile(r'^\s*(?:async\s+)?def\s+([A-Za-z_]\w*)'), 'function'),
          (re.compile(r'^\s*class\s+([A-Za-z_]\w*)'), 'class')]
SH_DEF = [(re.compile(r'^\s*(?:function\s+)?([A-Za-z_][\w-]*)\s*\(\)\s*\{'), 'function')]
YML_DEF = [(re.compile(r'^name:\s*["\']?([^"\'#\n]{2,80})'), 'workflow')]
JS_EXPORT = re.compile(r'^\s*export\s+(?:default\s+)?(?:async\s+)?(?:function\s*\*?|class|const|let|var)\s+([A-Za-z_$][\w$]*)')


def git(d, *a, binary=False):
    r = subprocess.run(['git', '-C', d] + list(a), capture_output=True)
    return r.stdout if binary else r.stdout.decode('utf-8', 'replace').strip()


def ext(path):
    return path.rsplit('.', 1)[-1].lower() if '.' in path.rsplit('/', 1)[-1] else ''


def slug(s):
    return re.sub(r'[^a-z0-9]+', '-', s.lower()).strip('-') or 'x'


def load_leaks(kuiper_tools):
    if kuiper_tools and os.path.isfile(os.path.join(kuiper_tools, 'check_proof.py')):
        sys.path.insert(0, kuiper_tools)
        from check_proof import leaks
        return leaks
    print('WARNING: Kuiper check_proof not found; non-public digest check skipped', file=sys.stderr)
    return lambda text: 0


# ---------------------------------------------------------------- titles (Tier 2)
# Abbreviations: (shown form, expansion or None). Expanded on first use in a title: "Overhead Line (OHL)".
TERMS = {
    'ohl': ('OHL', 'Overhead Line'), 'sld': ('SLD', 'Single-Line Diagram'),
    'bess': ('BESS', 'Battery Energy Storage System'), 'pv': ('PV', 'Photovoltaic'),
    'dno': ('DNO', 'Distribution Network Operator'), 'tso': ('TSO', 'Transmission System Operator'),
    'repd': ('REPD', 'Renewable Energy Planning Database'), 'ugc': ('UGC', 'Underground Cable'),
}
for _w in ('gis ukpn ssen hv lv mv ac dc api csv json ui ci ux html css js url uk gb gpu ai llm svg pdf kml osm '
           'bmrs id cli http https sql xml dem dtm dsm crs wgs84 osgb utm rgb mcp ip mac cvaa dpu iso iec bs '
           'npm pr qa cd os neso cfd ppa ev cad bom').split():
    TERMS[_w] = (_w.upper(), None)
for _w in ('LiDAR SatNav GridAtlas Kuiper GeoJSON WebGL DuckDB GitHub MapLibre Elexon JavaScript TypeScript '
           'GlobalGrid2050 OpenStreetMap PipelineNews Parquet WebGPU Leaflet ChatGPT Gemini Claude Codex Vedic').split():
    TERMS[_w.lower()] = (_w, None)
TERMS['vedic'] = ('VEDIC', None)
UNITS = {'v': 'V', 'kv': 'kV', 'va': 'VA', 'kva': 'kVA', 'mva': 'MVA', 'w': 'W', 'kw': 'kW', 'mw': 'MW', 'gw': 'GW',
         'wh': 'Wh', 'kwh': 'kWh', 'mwh': 'MWh', 'gwh': 'GWh', 'km': 'km', 'mm': 'mm', 'mm2': 'mm²', 'hz': 'Hz'}
UNIT_RX = re.compile(r'^(\d+(?:\.\d+)?)(%s)$' % '|'.join(sorted(UNITS, key=len, reverse=True)), re.I)
SMALL = {'of', 'and', 'to', 'for', 'in', 'on', 'the', 'a', 'an', 'by', 'with', 'or', 'at', 'from', 'vs'}
GENERIC_DIRS = {'src', 'lib', 'libs', 'js', 'css', 'scripts', 'script', 'tools', 'tool', 'app', 'apps', 'public',
                'static', 'assets', 'asset', 'docs', 'doc', '.github', 'github', 'workflows', 'components', 'component',
                'utils', 'util', 'modules', 'module', 'pages', 'page', 'core', 'common', 'shared', 'www', 'web',
                'site', 'code', 'source', 'sources', 'bin', 'includes', 'inc', 'helpers', 'styles', 'style',
                'frontend', 'backend', 'server', 'client', 'files', 'misc', 'main'}


def _tokens(s):
    """Plain-English word tokens of a path component: (shown, expansion or None)."""
    s = STAMP.sub(' ', s)
    out = []
    for raw in re.split(r'[_\-\s./()\[\]+,]+', s):
        if not raw or (raw.isdigit() and len(raw) >= 6) or re.match(r'^[0-9a-f]{12,}$', raw, re.I):
            continue  # timestamps, long numbers and commit hashes say nothing about purpose
        lo = raw.lower()
        if lo in TERMS:
            out.append(TERMS[lo])
            continue
        m = UNIT_RX.match(raw)
        if m:
            out.append((m.group(1) + UNITS[m.group(2).lower()], None))
            continue
        sub = re.sub(r'([a-z])([A-Z])', r'\1 \2', raw)
        sub = re.sub(r'([A-Z]+)([A-Z][a-z])', r'\1 \2', sub)
        for t in sub.split():
            tl = t.lower()
            if tl in TERMS:
                out.append(TERMS[tl])
            elif UNIT_RX.match(t):
                m = UNIT_RX.match(t)
                out.append((m.group(1) + UNITS[m.group(2).lower()], None))
            elif t.isupper() and len(t) <= 5:
                out.append((t, None))
            else:
                out.append((t[:1].upper() + t[1:].lower() if (t.islower() or t.isupper()) else t[:1].upper() + t[1:], None))
    return out


def humanise(*parts):
    """Join token lists into a title: small words lower-case, abbreviations expanded on first use."""
    toks = []
    for p in parts:
        for t in _tokens(p):
            if not toks or toks[-1][0].lower() != t[0].lower():
                toks.append(t)
    used, words = set(), []
    for i, (shown, long_) in enumerate(toks):
        if long_ and shown not in used:
            used.add(shown)
            words.append('%s (%s)' % (long_, shown))
        elif i and shown.lower() in SMALL:
            words.append(shown.lower())
        else:
            words.append(shown)
    return ' '.join(words)


# Estate misspellings seen in paths; the raw path is never changed, only the title.
SPELLING = {'requirments': 'requirements', 'distibution': 'distribution', 'hompage': 'homepage',
            'storeage': 'storage', 'sorage': 'storage'}
# Multi-word phrases, matched on lower-case word runs after spelling: shown form.
PHRASES = [(('employers', 'requirements'), "Employers' Requirements"), (('large', 'scale'), 'Large-Scale'),
           (('single', 'line', 'diagram'), 'Single-Line Diagram'), (('off', 'grid'), 'Off-Grid'),
           (('on', 'road'), 'On-Road'), (('off', 'road'), 'Off-Road')]
GENERIC_STEMS = {'index', 'main', 'app', 'package', 'default', 'home', 'init', 'mod', 'utils', 'util', 'helpers',
                 'helper', 'script', 'scripts', 'style', 'styles', 'common', 'lib', 'core', 'module', 'readme', 'run',
                 'cli', 'setup', 'config', 'settings', 'constants', 'types', 'globals', 'shared', 'base', 'data'}


def kind_of(path, lines=None):
    """Kind of file from its name and extension (name evidence)."""
    e = ext(path)
    name = path.rsplit('/', 1)[-1].lower()
    if re.search(r'(^test_|_test\.|\.test\.|\.spec\.)', name):
        return 'test'
    if path.startswith('.github/workflows/') and e in ('yml', 'yaml'):
        return 'workflow'
    if e in ('html', 'htm'):
        return 'page'
    if e == 'css':
        return 'style sheet'
    if e == 'py':
        text = '\n'.join(lines or [])
        return 'Python CLI' if re.search(r"""if\s+__name__\s*==\s*['"]__main__['"]""", text) else 'Python module'
    if e in ('mjs', 'ts', 'tsx'):
        return 'TypeScript module' if e in ('ts', 'tsx') else 'JavaScript module'
    if e in ('js', 'cjs', 'jsx'):
        text = '\n'.join((lines or [])[:400])
        return 'JavaScript module' if re.search(r'^\s*(import\s|export\s)|module\.exports|require\(', text, re.M) \
            else 'script'
    return {'sh': 'shell script', 'ps1': 'PowerShell script', 'bat': 'batch script', 'yml': 'configuration',
            'yaml': 'configuration', 'toml': 'configuration', 'sql': 'SQL query', 'vue': 'component',
            'svelte': 'component', 'glsl': 'shader', 'wgsl': 'shader'}.get(e, (LANG.get(e) or e.upper() or 'text') + ' file')


def _spell(s):
    return re.sub(r'[A-Za-z]+', lambda m: SPELLING.get(m.group(0).lower(), m.group(0)), s)


def name_words(path):
    """Words of the folder and file names, timestamps and extension dropped, spelling corrected."""
    p = STAMP.sub(' ', path)
    p = p.rsplit('.', 1)[0] if '.' in p.rsplit('/', 1)[-1].lstrip('.') else p
    return [SPELLING.get(w, w) for w in words_of(p) if not w.isdigit()]


def stamp_note(path):
    m = STAMP.findall(path.rsplit('/', 1)[-1]) or STAMP.findall(path)
    if not m:
        return ''
    s = re.sub(r'\D', '', m[-1])
    out = 'version %s-%s-%s' % (s[:4], s[4:6], s[6:8])
    return out + (' %s:%s' % (s[8:10], s[10:12]) if len(s) >= 12 else '')


def _phrased(title):
    for words, shown in PHRASES:
        rx = r'\b' + r'[\s-]+'.join(w.capitalize() for w in words) + r'\b'
        title = re.sub(rx, shown, title, flags=re.I)
    # "Employers' Requirements Large-Scale Solar" -> comma after a possessive phrase that is followed by more words
    return re.sub(r"(Employers' Requirements) (?=\w)", r'\1, ', title)


def _is_term(s):
    toks = _tokens(s)
    return bool(toks) and all(UNIT_RX.match(t[0]) or t[0] in {v[0] for v in TERMS.values()} for t in toks)


def title_parts(repo, path, lines=None):
    """(title, subject, qualifier, kind) from folder + file name."""
    path_t = _spell(path)
    name = path_t.rsplit('/', 1)[-1]
    stem = name.rsplit('.', 1)[0] if '.' in name.lstrip('.') else name
    if stem == '__init__':
        stem = 'package'
    kind = kind_of(path, lines)
    folders = [d for d in path_t.split('/')[:-1] if d.lower() not in GENERIC_DIRS and humanise(d)]
    stem_h = humanise(stem)
    generic = not stem_h or stem_h.lower() in GENERIC_STEMS or STAMP.sub('', stem).strip('-_ ').lower() in GENERIC_STEMS
    if generic:
        leaf = folders[-1] if folders else ''
        parent = folders[-2] if len(folders) >= 2 else (repo if leaf else repo)
        kword = {'page': 'Page', 'style sheet': 'Style Sheet', 'workflow': 'Workflow'}.get(kind, '')
        qual = ' '.join(x for x in (humanise(leaf or stem), kword) if x).strip()
        subject = _phrased(humanise(_spell(parent)))
        if qual.lower() == subject.lower():
            qual = kword or humanise(stem)
        title = '%s — %s' % (subject, qual)
    else:
        context = folders[-1] if folders else repo
        subject = _phrased(humanise(context, stem) if _is_term(context) and context.lower() not in stem.lower() else stem_h)
        subject = _phrased(subject)
        qual = 'Workflow' if kind == 'workflow' else ''
        title = subject + (' Workflow' if qual and not subject.lower().endswith('workflow') else '')
    if len(title) > 110:
        title = title[:107].rsplit(' ', 1)[0] + '…'
    return title, subject, qual, kind


def title_of(repo, path, lines=None):
    """Folder + file name -> plain-English title, e.g. 132kV/ohl_coordinates.py -> 132kV Overhead Line (OHL) Coordinates."""
    return title_parts(repo, path, lines)[0]


def repo_title(repo):
    return humanise(repo) or repo


# ---------------------------------------------------------------- READMEs, licences, essays
README_RX = re.compile(r'(^|/)readme(\.(md|markdown|txt))?$', re.I)
LICENSE_RX = re.compile(r'^(licen[cs]e|copying)([.\-][\w.\-]*)?$', re.I)


def md_strip(t):
    t = re.sub(r'\[!\[[^\]]*\]\([^)]*\)\]\([^)]*\)', ' ', t)
    t = re.sub(r'!\[[^\]]*\]\([^)]*\)', ' ', t)
    t = re.sub(r'\[([^\]]*)\]\([^)]*\)', r'\1', t)
    t = re.sub(r'\[([^\]]*)\]\[[^\]]*\]', r'\1', t)
    t = re.sub(r'<[^>]+>', ' ', t)
    t = re.sub(r'`([^`]*)`', r'\1', t)
    t = re.sub(r'(\*\*|__)(.+?)\1', r'\2', t)
    t = re.sub(r'(?<![\w*])\*(?!\s)(.+?)(?<!\s)\*(?![\w*])', r'\1', t)
    t = re.sub(r'(?<![\w])_(?!\s)(.+?)(?<!\s)_(?![\w])', r'\1', t)
    return re.sub(r'\s+', ' ', html.unescape(t)).strip()


def trim(t, n=400):
    if len(t) <= n:
        return t
    cut = t[:n]
    m = re.match(r'(.{80,}[.!?])\s', cut + ' ')
    return m.group(1) if m else cut[:n - 1].rsplit(' ', 1)[0] + '…'


def front_matter(text):
    meta = {}
    text = text.lstrip('')
    m = re.match(r'---\s*\n(.*?)\n---\s*\n', text, re.S)
    if m:
        for line in m.group(1).split('\n'):
            if ':' in line:
                k, v = line.split(':', 1)
                meta[k.strip().lower()] = v.strip().strip('"\'')
        text = text[m.end():]
    return meta, text


# README descriptor selection (owner review 2026-12-05): a root README often opens with a process record, a policy
# or a status table instead of saying what the software is. Candidate paragraphs are scored; process records,
# policies, session logs, change logs, instructions to agents, dated or hashed records are rejected outright.
README_REJECT = re.compile(  # the whole paragraph is a record of process, not a description
    r'\bthis (?:record|document|file|note|section|readme|log|report|block|ledger|page) (?:documents|records|describes how|'
    r'explains how|exists|is (?:generated|maintained|written|deliberately|placed|kept))|\baudit record\b|'
    r'\b(?:during|from) (?:an?|the|this) [\w\- ]{0,30}session\b|\b(?:ai|assistant|chat|claude|codex|gpt) sessions?\b|'
    r'\bprogress policy\b|\bpolicy\s*:|\bchange ?log\b|\brelease notes\b|\bis claimed\b|\bthe assistant\b|'
    r'^dated\b|\bdated\s*:|^(?:status|baseline|backlog|future objective|objective|roadmap|plan|todo|next steps?)\s*:|'
    r'\b(?:this|the) (?:block|status|manifest) is generated\b|\bgenerated from\b', re.I)
README_DROP = re.compile(  # one sentence is an instruction, a date or a hash: dropped, the rest of the paragraph kept
    r'\bfuture (?:ai|agents?|sessions?)\b|\b(?:agents?|ai|assistants?|captains?) (?:should|must|shall)\b|\byou must\b|'
    r'\bmust not\b|\bread (?:it|this) (?:first|before)\b|\bif you are reading\b|\bbefore (?:you|proposing|editing|'
    r'modifying|introducing)\b|\bdo not (?:edit|treat|modify|change|patch)\b|\b(?:date|commit|hash|run)\s*:|'
    r'\b20\d\d-\d\d-\d\d\b|(?<!\d)20\d{6}(?:T\d{4,6}Z?)?(?!\d)|\b[0-9a-f]{40,64}\b|\bsha-?256\b', re.I)
README_BAD_HEAD = re.compile(r'\b(?:audit|polic(?:y|ies)|status|progress|change ?log|history|session|agents?|ai|instructions?|'
                             r'ci|cd|releases?|discipline|governance|disclaimer|licen[cs]e|deploy\w*|contribut\w*|install\w*|'
                             r'usage|setup|how to|fast start|state|doctrine|rules?|laws?|workflows?|hygiene|notes?|todo|'
                             r'entanglement|size)\b', re.I)
README_GOOD_HEAD = re.compile(r'\b(?:overview|about|what (?:it|this) (?:is|does)|introduction|summary|purpose|architecture|'
                              r'description|primary modules|the products?|what is)\b', re.I)
README_SUBJECT = re.compile(r'^(?:(?:this|the|our) (?:[\w\-]+ ){0,3}(?:repository|repo|project|engine|platform|application|app|'
                            r'tool|site|library|package|instrument|simulator|atlas|system|layer|software|estate|code|map)\b|'
                            r'an? (?:[\w\-,]+ ){0,8}(?:engine|tool|platform|library|application|app|repository|map|'
                            r'simulator|instrument|layer|system|site|database|registry|page|drawing|visuali[sz]ation|bench|'
                            r'catalogue|toolkit|tooling|model|calculator|producer|prototype|viewer|explorer)\b)', re.I)
README_VERB = re.compile(r'\b(?:is|are|provides?|maps|models|computes|calculates|holds|keeps|compiles|publishes|shows|tracks|'
                         r'draws|builds|turns|reads|delivers|uses|utili[sz]es|runs|measures|answers|owns|separates|watches|'
                         r'emits|offers|lets|helps|contains|serves|generates|visuali[sz]es|simulates|joins|converts|'
                         r'analy[sz]es|searches|looks at|assists|lists|stores|renders|plans|routes|connects|exposes|'
                         r'checks|verifies|produces|describes|explains|turned into|for (?:scoping|modelling|modeling|'
                         r'compiling|mapping|drawing|designing|visuali[sz]ing))\b', re.I)
README_DOMAIN = re.compile(r'\b(?:grid|cables?|substations?|solar|pv|voltages?|\d*kv|network|maps?|atlas|energy|power|'
                           r'electric\w*|generation|storage|battery|bess|transmission|distribution|routes?|routing|navigation|'
                           r'geodesy|geospatial|geometry|gis|lidar|terrain|projects?|pipelines?|data|parquet|duckdb|browser|'
                           r'registry|interconnectors?|wind|offshore|topology|strings?|inverters?|engine|calculators?|'
                           r'estimat\w+|layout|drawings?|survey|coordinates|postcodes?|repd|news|markets?|prices?|'
                           r'infrastructure|electrification|net zero|powerlines?|trench\w*|conductors?|weather|tiles?)\b', re.I)
README_THRESHOLD = 5  # a root README paragraph scoring below this is not shown as context nor used as the descriptor


def _readme_paragraphs(text):
    """(heading, raw paragraph) pairs of a README: badges, lists, tables, code and HTML-only lines skipped."""
    _, text = front_matter(re.sub(r'<!--.*?-->', '', text, flags=re.S))
    paras, cur, fence, head = [], [], False, ['']

    def flush():
        if cur:
            paras.append((head[0], ' '.join(cur)))
        cur.clear()
    for line in text.split('\n'):
        s = line.strip()
        if s.startswith(('```', '~~~')):
            flush()
            fence = not fence
            continue
        if fence:
            continue
        if not s or s.startswith('#'):
            flush()
            if s.startswith('#'):
                head[0] = md_strip(s.lstrip('#').strip())
            continue
        if re.match(r'^(=+|-{2,})$', s):
            if cur and s.startswith('=') or (cur and len(cur) == 1 and s.startswith('-')):
                head[0] = md_strip(cur[0])  # setext heading
            cur.clear()
            continue
        if s.startswith(('|', '- ', '* ', '+ ', '[!', '![')) or re.match(r'^\d+[.)]\s', s) or line.startswith(('    ', '\t')):
            flush()
            continue
        if s.startswith('<') and not re.sub(r'<[^>]+>', '', s).strip():
            continue
        cur.append(s.lstrip('>').strip())
    flush()
    return paras


def _readme_usable(p):
    """Plain text of a paragraph that passes the original filters (length, links, banners), with README_DROP
    sentences removed, else ''."""
    plain = md_strip(p)
    sents = re.split(r'(?<=[.!?])\s+(?=[A-Z0-9"“(])', plain)
    if any(README_DROP.search(x) for x in sents):
        plain = ' '.join(x for x in sents if not README_DROP.search(x))
    links = len(re.findall(r'\]\(', p))
    nonlink = md_strip(re.sub(r'\[[^\]]*\]\([^)]*\)', ' ', p))
    if len(plain) < 25 or not re.search(r'[A-Za-z]{3,}(\W+[A-Za-z0-9]{1,}){2,}', plain):
        return ''
    if links >= 3 and len(nonlink.split()) < 8:
        return ''
    if re.match(r'^(status|version|license|licence|copyright|built with|last updated)\b', plain, re.I):
        return ''
    # Housekeeping banners for agents and generators are not a description of the code.
    if re.search(r'^(ai\b|agents?\b|for (ai|agents|llms?)\b|read (this )?first|this (block|file|section) is '
                 r'(generated|maintained|written)|generated (by|from)|do not edit|auto-?generated|note to|warning\b|'
                 r'before (you|proposing|editing)|dated\b|date:|comparison hash|sha-?256|hash:|commit:)|\bread first\b|\bai read\b|'
                 r'\b[0-9a-f]{40,64}\b', plain, re.I):
        return ''
    return plain


def readme_score(plain, heading='', names=(), opening=False, lead=False):
    """Score of one README paragraph as a description of what the software or estate is or does; None = rejected.
    +2 in the opening section (before any heading other than the title), +1 more for the first usable paragraph; +3 a subject (the repository's name or title words in its first words, 'This repository/engine/...', 'An ...
    engine/tool/...'); +2 a present-tense descriptive verb (+1 more within the first 12 words); +1 per distinct domain
    noun (max 4); +2 under an Overview/About/Architecture-like heading, -3 under a housekeeping heading (status,
    policy, agents, CI, licence, ...); -2 per imperative sentence; -1 per past-tense or future auxiliary (max -3);
    -1 per negation (max -3); -3 when it ends with ':' (introduces a list); a paragraph starting lower-case is a
    fragment (rejected); -2 when it opens with a word leaning on an earlier paragraph (That, They, It, Also ...);
    +1 a verbless tagline of at most 20 words with a domain noun in the opening section; -1 when shorter than 40
    characters. Rejected: process records, policies, session logs, change logs, instructions
    records and generated blocks (README_REJECT), or a heading naming an audit record / AI fast start. Sentences that
    instruct agents or carry dates or hashes (README_DROP) are removed before scoring (_readme_usable)."""
    if not plain or README_REJECT.search(plain) or README_REJECT.search(heading) or \
            re.search(r'\b(?:audit record|fast start for ai|programme state|disclaimer)\b', heading, re.I):
        return None
    lo = plain.lower()
    first = ' '.join(re.findall(r'[\w\-]+', lo)[:8])
    squash = re.sub(r'[^a-z0-9]', '', first)
    score = (2 if opening else 0) + (1 if lead else 0)
    if re.match(r'^[a-z]', plain):
        return None  # a fragment continuing an earlier line
    subj = any(n and (n in squash or n in first) for n in names) or README_SUBJECT.search(lo)
    score += 3 if subj else 0
    if README_VERB.search(plain):
        score += 2 + (1 if README_VERB.search(' '.join(plain.split()[:12])) else 0)
    score += min(4, len({m.group(0).lower().rstrip('s') for m in README_DOMAIN.finditer(plain)}))
    if heading and README_GOOD_HEAD.search(heading):
        score += 2
    elif heading and README_BAD_HEAD.search(heading):
        score -= 3
    sents = re.split(r'(?<=[.!?])\s+', plain)
    score -= 2 * sum(1 for x in sents if re.match(r'^(?:read|run|use|do|don\'t|never|always|update|inspect|verify|keep|'
                                                   r'install|clone|click|start|note|please|retain|preserve|record|open|drag|tap|move|choose|enter|see|go|'
                                                   r'visit|press|select|scroll|type|follow)\b', x, re.I))
    score -= min(3, len(re.findall(r'\b(?:was|were|had|did|will)\b', lo)))
    score -= min(3, len(re.findall(r"\b(?:not|never|no|nothing|isn't|doesn't)\b", lo)))
    if plain.rstrip().endswith(':'):
        score -= 3  # introduces a list the summary cannot show
    if re.match(r'^(?:that|they|it|its|those|these|there|here|then|also|so|but|and)\b', lo):
        score -= 2  # leans on a previous paragraph
    if opening and not README_VERB.search(plain) and len(plain.split()) <= 20 and README_DOMAIN.search(plain):
        score += 1
    if len(plain) < 40:
        score -= 1
    return score


def readme_pick(text, repo=''):
    """(summary, score) of a README: the first usable paragraph, in reading order, that scores README_THRESHOLD or more
    (README_REJECT paragraphs never count); when none does, the best-scoring one (earliest wins ties), which callers
    treat as weak. The next usable paragraph of the same section is appended when the pick is shorter than 80