GLOBALGRID2050 / EXPLORE CODE

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

Clarity and 1 more file

A Python command-line tool in the translator folder of Cosmic that draws build graph. It joins words (`join_words`), counts line (`count_line`) and filters nav (`filter_nav`).

700 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1164 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. Test Theme test · cosmic / tools/explore/theme/test_theme.py lines 1–207
  2. Clarity render · cosmic / tools/explore/translator/clarity.py lines 1–493

Test Theme

A test in the explore folder of Cosmic that checks Inject and Play, using EPSG:4326. It makes site (`make_site`) and sets up (`setUp`).

testcosmic / tools/explore/theme/test_theme.py · lines 1–207 of 207 · Entry point · pattern test_no_external_hosts (shared by 2 files)

What it does
It tests cables. Defines 22 functions or classes, including TextOnly, __init__, handle_starttag, handle_endtag, handle_data. Uses libraries __future__, json, re, shutil, subprocess. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Why it exists in the grid workflow
Domain terms in the code: cables.
Inputs & outputs
In: JSON file play-index.json; JSON file places.json. Out: JSON file build_graph.json; JSON file pilot-places.json. Coordinate systems named: WGS84 / EPSG:4326.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for the Explore Code play layer: python -m pytest `tools/explore/theme/test_theme.py` (or run directly).
Why it matters
Guards the behaviour of Inject and Play.
Application
cosmic · tools/explore/theme · test
Uses
Inject (import), Play (script call), __future__, json, re, shutil, subprocess, sys, tempfile, unittest
Used by
none found
Produces
TextOnly, text_of, make_site, InjectTests, RealSiteTest
Defines here
TextOnly, __init__, handle_starttag, handle_endtag, handle_data, text_of, make_site, InjectTests, setUp, tearDown, snapshot, test_idempotent, test_text_ids_and_body_unchanged, test_one_link_one_deferred_script_in_head, test_no_external_hosts, test_digest_copies_graph, test_rerun_replaces_old_version_tags, test_pilot_hook_copies_when_present, test_storage_wrapped_and_sound_off, test_play_js_parses, RealSiteTest, test_real_build
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/theme/test_theme.py:1-207 · blob 44ceb5beabc1424c086da27655feeaf0a1359045 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: unknown
"""Tests for the Explore Code play layer: python -m pytest tools/explore/theme/test_theme.py (or run directly).

Checks: injection is idempotent, page text/ids are unchanged, no external hosts, tags land in <head> with the
right relative paths, the digest copies build_graph.json values only, and the Pilot page hook is a plain copy."""
from __future__ import annotations

import json
import re
import shutil
import subprocess
import sys
import tempfile
import unittest
from html.parser import HTMLParser
from pathlib import Path

HERE = Path(__file__).resolve().parent
sys.path.insert(0, str(HERE))
import inject  # noqa: E402

GRAPH = {
    "schema": "explore-build-graph-v1", "cut": "2026-12-05T15:19:52+00:00",
    "roles": [{"id": "render", "title": "Rendering", "colour": "#ff6666"}, {"id": "geodesy", "title": "Geodesy", "colour": "#00ffff"}],
    "topics": [{"id": "cables", "title": "Cables and conductors", "sections": 2}],
    "sections": [{"section": 1, "url": "s/0001.html", "topic": "cables", "title": "One"},
                 {"section": 2, "url": "s/0002.html", "topic": "cables", "title": "Two"}],
    "files": [
        {"id": 0, "repo": "r1", "section": 1, "block": 1, "title": "A", "pattern": "huntMe", "role": "render", "lang": "JavaScript",
         "published": "https://example.org/tool/", "data_contracts": {"crs": ["WGS84 / EPSG:4326"]}},
        {"id": 1, "repo": "r1", "section": 1, "block": 2, "title": "B", "pattern": "huntMe", "role": "geodesy", "lang": "Python",
         "published": "", "data_contracts": {"crs": []}},
        {"id": 2, "repo": "r2", "section": 2, "block": 1, "title": "C", "pattern": "huntMe", "role": "render", "lang": "Python",
         "published": "", "data_contracts": {"crs": []}},
    ],
}
PAGE = ('<!doctype html><html lang="en"><head><meta charset="utf-8"><title>{t}</title><link rel="stylesheet" href="{r}explore.css">'
        '<script type="application/ld+json">{{"a":1}}</script></head><body><header><h1 id="top">{t}</h1>'
        '<p class="k">Cut 2026-12-05T15:19:52+00:00. Notes.</p></header><nav><a href="{r}index.html">All topics</a></nav>'
        '<main><section id="f1" class="file r-render"><h2>A</h2><p>Text &amp; more</p></section></main></body></html>')


class TextOnly(HTMLParser):
    """Visible text, ids and anchors of a page (script/style bodies left out)."""
    def __init__(self):
        super().__init__(convert_charrefs=True)
        self.text, self.ids, self.skip = [], [], 0

    def handle_starttag(self, tag, attrs):
        if tag in ('script', 'style'):
            self.skip += 1
        for k, v in attrs:
            if k in ('id', 'name'):
                self.ids.append(v)

    def handle_endtag(self, tag):
        if tag in ('script', 'style') and self.skip:
            self.skip -= 1

    def handle_data(self, d):
        if not self.skip:
            self.text.append(d)


def text_of(html: str):
    p = TextOnly()
    p.feed(html)
    return ''.join(p.text), p.ids


def make_site(root: Path) -> Path:
    site = root / 'explore-code'
    for rel in ('index.html', 's/0001.html', 's/0002.html', 'topics/cables.html', 'visual/index.html'):
        f = site / rel
        f.parent.mkdir(parents=True, exist_ok=True)
        f.write_text(PAGE.format(t=rel, r='../' * rel.count('/')), encoding='utf-8')
    (site / 'build_graph.json').write_text(json.dumps(GRAPH), encoding='utf-8')
    return site


class InjectTests(unittest.TestCase):
    def setUp(self):
        self.tmp = Path(tempfile.mkdtemp())
        self.site = make_site(self.tmp)
        self.orig = {p: p.read_text(encoding='utf-8') for p in self.site.rglob('*.html')}

    def tearDown(self):
        shutil.rmtree(self.tmp, ignore_errors=True)

    def snapshot(self):
        return {p: p.read_bytes() for p in sorted(self.site.rglob('*')) if p.is_file()}

    def test_idempotent(self):
        first = inject.run(self.site, quiet=True)
        self.assertEqual(first['changed'], 5)
        snap = self.snapshot()
        second = inject.run(self.site, quiet=True)
        self.assertEqual(second['changed'], 0)
        self.assertEqual(snap, self.snapshot())

    def test_text_ids_and_body_unchanged(self):
        inject.run(self.site, quiet=True)
        for p, old in self.orig.items():
            new = p.read_text(encoding='utf-8')
            self.assertEqual(text_of(old), text_of(new), p)
            self.assertEqual(old[old.index('</head>'):], new[new.index('</head>'):], p)  # body byte-identical
            self.assertEqual(inject.TAG_RE.sub('', new), old, p)                      # only tagged additions

    def test_one_link_one_deferred_script_in_head(self):
        inject.run(self.site, quiet=True, ide=False)
        for p in self.orig:
            h = p.read_text(encoding='utf-8')
            head = h[:h.index('</head>')]
            self.assertEqual(len(re.findall(r'<link[^>]*data-ec-theme="play"', head)), 1, p)
            self.assertEqual(len(re.findall(r'<script defer src="[^"]*theme/play\.js\?v=\w+" data-ec-theme="play"></script>', head)), 1, p)
            self.assertNotIn('data-ec-theme', h[h.index('</head>'):])
        s1 = (self.site / 's/0001.html').read_text(encoding='utf-8')
        self.assertIn('href="../theme/play.css?v=', s1)
        self.assertIn('href="theme/play.css?v=', (self.site / 'index.html').read_text(encoding='utf-8'))
        self.assertTrue((self.site / 'theme/play.js').is_file() and (self.site / 'theme/play.css').is_file())

    def test_no_external_hosts(self):
        inject.run(self.site, quiet=True)
        for name in ('play.css', 'play.js'):
            src = (HERE / name).read_text(encoding='utf-8')
            self.assertIsNone(re.search(r'(https?:)?//[a-z0-9.-]+\.[a-z]{2,}', src.split('*/', 1)[-1] if name.endswith('.css') else
                                        re.sub(r'^\s*(/\*|\*|//).*$', '', src, flags=re.M)), name)
            self.assertNotRegex(src, r'@import|cdn\.|googleapis|jsdelivr|unpkg')
        for p in self.orig:
            tags = ''.join(m.group(0) for m in inject.TAG_RE.finditer(p.read_text(encoding='utf-8')))
            self.assertNotRegex(tags, r'(https?:)?//')

    def test_digest_copies_graph(self):
        inject.run(self.site, quiet=True)
        d = json.loads((self.site / 'theme/play-index.json').read_text(encoding='utf-8'))
        self.assertEqual(d['cut'], GRAPH['cut'])
        self.assertEqual(d['patterns'], ['huntMe'])
        self.assertEqual(d['hunts'], [0])                         # 3 files over 2 sections
        self.assertEqual(d['urls'], ['https://example.org/tool/'])
        self.assertEqual([f[4] for f in d['files']], [1, 0, 0])   # crs flag only where the graph names one
        self.assertEqual(d['topics'][0][3], [2, 1])               # role counts per topic
        self.assertEqual([s[1] for s in d['sections']], ['s/0001.html', 's/0002.html'])

    def test_rerun_replaces_old_version_tags(self):
        p = self.site / 'index.html'
        p.write_text(self.orig[p].replace('</head>', '<link rel="stylesheet" href="theme/play.css?v=old" data-ec-theme="play"></head>'))
        inject.run(self.site, quiet=True)
        self.assertEqual(p.read_text(encoding='utf-8').count('data-ec-theme="play"'), 2)  # one link + one script

    def test_pilot_hook_copies_when_present(self):
        fake = self.tmp / 'theme'
        fake.mkdir()
        for n in ('play.css', 'play.js'):
            shutil.copy(HERE / n, fake / n)
        (fake / 'pilot.html').write_text('<!doctype html><html><head><title>P</title></head><body data-pl-nohud>Pilot</body></html>')
        (fake / 'pilot.js').write_text('//p')
        (fake / 'pilot-places.json').write_text('{}')
        old = inject.HERE
        inject.HERE = fake
        try:
            inject.run(self.site, quiet=True)
            snap = self.snapshot()
            self.assertEqual(inject.run(self.site, quiet=True)['changed'], 0)
            self.assertEqual(snap, self.snapshot())
        finally:
            inject.HERE = old
        page = (self.site / 'pilot/index.html').read_text()
        self.assertIn('href="../theme/play.css?v=', page)
        self.assertEqual(text_of(page)[0], 'PPilot')
        self.assertEqual((self.site / 'pilot/places.json').read_text(), '{}')
        self.assertFalse((self.site / 'pilot/pilot.css').exists())

    def test_storage_wrapped_and_sound_off(self):
        js = (HERE / 'play.js').read_text(encoding='utf-8')
        self.assertEqual(len(re.findall(r'localStorage\.', js)), len(re.findall(r'try \{[^\n]*localStorage\.', js)))
        self.assertIn("sound: get('sound', false)", js)
        self.assertNotRegex(js.lower(), r'\b(god|divine|holy|heaven|sacred|prayer|blessed|maya)\b')

    @unittest.skipUnless(shutil.which('node'), 'node not installed')
    def test_play_js_parses(self):
        r = subprocess.run(['node', '--check', str(HERE / 'play.js')], capture_output=True, text=True)
        self.assertEqual(r.returncode, 0, r.stderr)


class RealSiteTest(unittest.TestCase):
    """Optional: the latest local build, copied, injected twice."""
    SRC = Path('/tmp/site8/explore-code')

    @unittest.skipUnless(SRC.is_dir(), 'no local build')
    def test_real_build(self):
        tmp = Path(tempfile.mkdtemp())
        try:
            site = tmp / 'explore-code'
            shutil.copytree(self.SRC, site, ignore=shutil.ignore_patterns('*.parquet', 'theme', 'pilot'))
            pages = sorted(p for p in site.rglob('*.html'))
            sample = pages[::97]
            before = {p: p.read_text(encoding='utf-8') for p in sample}
            st = inject.run(site, quiet=True, ide=False)
            self.assertEqual(st['pages'], len(pages))
            self.assertEqual(inject.run(site, quiet=True, ide=False)['changed'], 0)
            for p, old in before.items():
                self.assertEqual(text_of(old), text_of(p.read_text(encoding='utf-8')), p)
        finally:
            shutil.rmtree(tmp, ignore_errors=True)


if __name__ == '__main__':
    unittest.main()

Clarity

A Python command-line tool in the translator folder of Cosmic that draws build graph. It joins words (`join_words`), counts line (`count_line`) and filters nav (`filter_nav`).

rendercosmic / tools/explore/translator/clarity.py · lines 1–493 of 577 · Entry point · pattern neutral (shared by 2 files)

What it does
It draws build graph. Defines 26 functions or classes, including neutral, esc, slugify, section_href, folder_of. Uses libraries __future__, argparse, collections, html, json. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Inputs & outputs
In: JSON file build_graph.json; JSON file clarity.json; command-line arguments. Out: SVG drawing.
Downstream impact
Used directly by 3 files: Extras (cosmic); Test No Tmp (cosmic); Test Translator (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
Clarity view: read the whole estate as fields of pictograms and see what is real. It accepts `--graph` and `--out`.
Why it matters
Run by Extras. Checked by 2 tests, including Test No Tmp.
Application
cosmic · tools/explore/translator · Python CLI
Uses
Glyphs (import), __future__, argparse, collections, html, json, os, re, sys
Used by
run by Extras (script call), run by Test No Tmp (script call), imported by Test Translator (import)
Produces
neutral, esc, slugify, section_href, folder_of, reach_from_entries, classify, synopsis_clause, plural, join_words, repo_paragraph, page
Defines here
neutral, esc, slugify, section_href, folder_of, reach_from_entries, classify, synopsis_clause, plural, join_words, _lower, repo_paragraph, page, topbar, glyph_link, count_line, proportion_bar, filter_nav, legend_html, demo, fields_html, mini_strip, repo_picture, build
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/translator/clarity.py:1-493 · blob 9ed90260d14fe25ead11c1594bccf8fca7d63755 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Clarity view: read the whole estate as fields of pictograms and see what is real.

    python3 clarity.py [--graph build_graph.json] [--out DIR]

Writes static pages (readable without JavaScript; clarity.js only adds in-page filtering):

    index.html       every file as a pictogram, grouped by repository then top folder, legend in words
    core.html        unique and in use (the real core)
    copies.html      copies of other code
    via-copies.html  reachable only through copies
    unreached.html   not reached from any entry point
    repo-<slug>.html one-screen picture per repository plus a paragraph built from evidence
    clarity.css, clarity.js, clarity.json (per-file category, for other tools)

Every pictogram links to its section page as ../s/NNNN.html#fB, so the folder is meant to sit beside s/
in the explore-code site (e.g. explore-code/clarity/).

The four categories are disjoint and cover every file:

    copy       duplicate_of is set (whatever its reach)
    unreached  not a copy and reachable is false
    via        not a copy, reachable, but no longer reachable once copies are removed from the graph
               (every path from an entry point to it passes through a copy, or only copies are its entries)
    core       everything else: not a copy and reachable without passing through any copy
"""
from __future__ import annotations

import argparse
import collections
import html
import json
import os
import re
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import glyphs  # noqa: E402

# No host paths: extras.py sets EXPLORE_GRAPH / EXTRA_OUT (CI has only build_graph.json); otherwise the current folder.
DEFAULT_GRAPH = os.environ.get("EXPLORE_GRAPH") or "build_graph.json"
DEFAULT_OUT = os.environ.get("EXTRA_OUT") or "clarity"

CATS = ("core", "copy", "via", "unreached")
CAT_TITLE = {
    "core": "Unique and in use",
    "copy": "Copies of other code",
    "via": "Reachable only through copies",
    "unreached": "Not reached",
}
CAT_PAGE = {"core": "core.html", "copy": "copies.html", "via": "via-copies.html", "unreached": "unreached.html"}
CAT_EXPLAIN = {
    "core": "Files that are not copies and that something which runs (a page, workflow, tool or loaded script) "
            "reaches without going through a copy. This is the real core of the estate.",
    "copy": "Files whose text (or defined names and size) match another file that is kept as the original. "
            "Shown as two stacked shapes.",
    "via": "Files that are not copies themselves, but are only reached because a copy loads them. "
           "Remove the copies and nothing reaches these.",
    "unreached": "Files that no entry point reaches by any recorded import, script tag, data load or workflow "
                 "step. A signal to review, never a deletion order.",
}

def neutral(s: str) -> str:
    """Kept for callers; names are shown exactly as they are (owner decision 2026-12-05)."""
    return s


def esc(s) -> str:
    return html.escape(neutral(str(s)), quote=True)


def slugify(s: str) -> str:
    return re.sub(r"[^a-z0-9]+", "-", neutral(s).lower()).strip("-") or "repo"


def section_href(f: dict) -> str:
    return "../s/%04d.html#f%d" % (int(f["section"]), int(f["block"]))


def folder_of(f: dict) -> str:
    h = f.get("folder_hierarchy") or [f["repo"]]
    return h[1] if len(h) > 1 else ""


# ---------------------------------------------------------------- classification

def reach_from_entries(files: list[dict], skip: set[int]) -> set[int]:
    seen = {f["id"] for f in files if f.get("entry") and f["id"] not in skip}
    stack = sorted(seen)
    byid = {f["id"]: f for f in files}
    while stack:
        i = stack.pop()
        for j in byid[i].get("imports") or []:
            if j not in seen and j not in skip and j in byid:
                seen.add(j)
                stack.append(j)
    return seen


def classify(files: list[dict]) -> dict[int, str]:
    copies = {f["id"] for f in files if f.get("duplicate_of") is not None}
    clean = reach_from_entries(files, copies)
    out = {}
    for f in files:
        i = f["id"]
        if i in copies:
            out[i] = "copy"
        elif not f.get("reachable"):
            out[i] = "unreached"
        elif i not in clean:
            out[i] = "via"
        else:
            out[i] = "core"
    return out


# ---------------------------------------------------------------- evidence paragraph

_CLAUSE = re.compile(r"\b(that|which|covering|using|for)\b\s+([^.]+)")
_URL = re.compile(r"https?://\S+")


def synopsis_clause(s: str) -> str:
    """The informative part of a synopsis ('A JavaScript module in X that draws Y.' -> 'draws Y'), or ''."""
    first = _URL.sub("", (s or "").split(". ")[0]).strip().rstrip(".")
    m = _CLAUSE.search(first)
    if not m:
        return ""
    word, rest = m.group(1), m.group(2).strip()
    if word in ("that", "which"):
        return rest
    return word + " " + rest


KIND_PLURAL = {
    "page": "web pages", "JavaScript module": "JavaScript modules", "Python CLI": "Python command-line tools",
    "Python module": "Python modules", "workflow": "workflows", "test": "tests", "script": "browser scripts",
    "style sheet": "style sheets", "configuration": "configuration files", "shell script": "shell scripts",
    "PowerShell script": "PowerShell scripts", "SQL query": "SQL queries",
}


KIND_ONE = {"page": "web page", "Python CLI": "Python command-line tool", "script": "browser script",
            "configuration": "configuration file"}


def plural(n: int, one: str, many: str | None = None) -> str:
    return "%d %s" % (n, one if n == 1 else (many or one + "s"))


def join_words(items: list[str]) -> str:
    if not items:
        return ""
    if len(items) == 1:
        return items[0]
    return ", ".join(items[:-1]) + " and " + items[-1]


def _lower(s: str) -> str:
    return " ".join(w if w.isupper() else w.lower() for w in s.split())


def repo_paragraph(repo: str, files: list[dict], cat: dict[int, str], role_title: dict[str, str]) -> str:
    """Plain English, built only from evidence fields of the unique reachable files."""
    counts = collections.Counter(cat[f["id"]] for f in files)
    core = [f for f in files if cat[f["id"]] == "core"]
    s = ["%s holds %s." % (repo, plural(len(files), "file")),
         "%d %s unique and in use, %d %s copies of other code, %d %s reached only through copies and %d %s not reached."
         % (counts["core"], "is" if counts["core"] == 1 else "are",
            counts["copy"], "is" if counts["copy"] == 1 else "are",
            counts["via"], "is" if counts["via"] == 1 else "are",
            counts["unreached"], "is" if counts["unreached"] == 1 else "are")]
    if not core:
        s.append("No file here is both unique and reached, so there is no real core to describe.")
        return " ".join(s)
    kinds = collections.Counter(f.get("kind") or "file" for f in core)
    kk = sorted(kinds.items(), key=lambda kv: (-kv[1], kv[0]))[:4]
    s.append("The real core is %s." % join_words(
        ["%d %s" % (n, KIND_PLURAL.get(k, k + "s") if n != 1 else KIND_ONE.get(k, k)) for k, n in kk]))
    roles = collections.Counter(f.get("role") or "other" for f in core)
    rr = sorted(roles.items(), key=lambda kv: (-kv[1], kv[0]))[:3]
    s.append("By role it is mostly %s." % join_words(
        ["%s (%d)" % (_lower(role_title.get(r, r).split(" (")[0]), n) for r, n in rr]))
    ranked = sorted(core, key=lambda f: (-len(f.get("dependents") or []), -int(f.get("lines") or 0), f["path"]))
    said, seen = [], set()
    for f in ranked:
        c = synopsis_clause(f.get("synopsis", ""))
        if not c or c.lower() in seen:
            continue
        seen.add(c.lower())
        said.append("%s %s" % (f.get("title") or os.path.basename(f["path"]), c))
        if len(said) == 4:
            break
    if said:
        s.append("Its most-used unique files, in their synopses' words: " + "; ".join(said) + ".")
    else:
        s.append("The synopses of its unique files name no subject beyond their file type.")
    return " ".join(s)


# ---------------------------------------------------------------- HTML pieces

def page(title: str, body: str, *, script: bool = False, desc: str = "") -> str:
    js = '<script src="clarity.js" defer></script>' if script else ""
    return ("<!DOCTYPE html>\n<html lang=\"en-GB\"><head><meta charset=\"utf-8\">"
            "<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">"
            "<title>%s</title><meta name=\"description\" content=\"%s\">"
            "<link rel=\"stylesheet\" href=\"clarity.css\">%s</head>\n<body data-show=\"all\">\n%s\n</body></html>\n"
            % (esc(title), esc(desc or title), js, body))


def topbar(here: str) -> str:
    items = [("index.html", "Clarity: whole estate"), ("../index.html", "Explore code home")]
    return ('<header class="top"><nav aria-label="Site">%s</nav></header>'
            % "".join('<a class="chip%s" href="%s">%s</a>' % (" here" if h == here else "", h, esc(t))
                      for h, t in items))


def glyph_link(f: dict, g: glyphs.Glyph, c: str, role_title: dict[str, str]) -> str:
    tip = "%s: %s (%s)" % (f.get("title") or "", f["path"], CAT_TITLE[c].lower())
    return ('<a class="g c-%s" href="%s" title="%s"><svg viewBox="0 0 40 40" aria-hidden="true">'
            '<use href="#%s"/></svg></a>' % (c, section_href(f), esc(tip), glyphs.key(g)))


def count_line(counter, total=None) -> str:
    parts = ["%d %s" % (counter[c], CAT_TITLE[c].lower()) for c in CATS if counter[c]]
    return esc(("%s: " % plural(total, "file") if total is not None else "") + ", ".join(parts))


def proportion_bar(counter) -> str:
    total = sum(counter[c] for c in CATS) or 1
    segs = "".join('<span class="seg s-%s" style="width:%.3f%%"></span>' % (c, 100.0 * counter[c] / total)
                   for c in CATS if counter[c])
    return '<div class="bar" role="img" aria-label="%s">%s</div>' % (count_line(counter, total), segs)


def filter_nav(counter, *, live: bool, here: str = "all") -> str:
    items = [("all", "index.html", "Everything", sum(counter[c] for c in CATS))]
    items += [(c, CAT_PAGE[c], CAT_TITLE[c], counter[c]) for c in CATS]
    out = []
    for key, href, label, n in items:
        attrs = ' data-filter="%s" aria-pressed="%s"' % (key, "true" if key == here else "false") if live else ""
        cur = ' aria-current="page"' if (not live and key == here) else ""
        out.append('<a class="chip f-%s%s" href="%s"%s%s><span class="sw s-%s"></span>%s <b>%d</b></a>'
                   % (key, " here" if key == here else "", href, attrs, cur, key, esc(label), n))
    return '<nav class="filters" aria-label="Split the estate">%s</nav>' % "".join(out)


def legend_html(role_list: list[dict], colours: dict[str, str], *, open_: bool) -> str:
    def demo(**kw):
        base = dict(role="transform", colour=colours.get("transform", "#00ff88"), stage="transform",
                    shape="diamond", size="L", scale=1.0, solid=True, stacked=False, ring=False, rays=0, links=0)
        base.update(kw)
        return glyphs.svg(glyphs.Glyph(**base), 40)
    rows = []
    sw = "".join('<span class="lg-item">%s<span>%s</span></span>'
                 % (demo(role=r["id"], colour=r["colour"]), esc(r["title"])) for r in role_list)
    rows.append(("Colour", glyphs.LEGEND[0][1], sw))
    shapes = "".join('<span class="lg-item">%s<span>%s</span></span>' % (demo(stage=s, shape=glyphs.STAGE_SHAPE[s]), s)
                     for s in glyphs.STAGES)
    rows.append(("Shape", glyphs.LEGEND[1][1], shapes))
    sizes = "".join('<span class="lg-item">%s<span>%s</span></span>' % (demo(size=n, scale=sc), lab)
                    for (_, n, sc), lab in zip(glyphs.SIZE_STEPS, ["under 50 lines", "under 200", "under 800", "800+"]))
    rows.append(("Size", glyphs.LEGEND[2][1], sizes))
    rows.append(("Solid or outline", glyphs.LEGEND[3][1],
                 '<span class="lg-item">%s<span>reachable</span></span><span class="lg-item">%s<span>not reached</span></span>'
                 % (demo(), demo(solid=False))))
    rows.append(("Single or stacked", glyphs.LEGEND[4][1],
                 '<span class="lg-item">%s<span>unique</span></span><span class="lg-item">%s<span>copy</span></span>'
                 % (demo(), demo(stacked=True))))
    rows.append(("White ring", glyphs.LEGEND[5][1],
                 '<span class="lg-item">%s<span>entry point</span></span>' % demo(ring=True)))
    rows.append(("Rays", glyphs.LEGEND[6][1], "".join(
        '<span class="lg-item">%s<span>%s</span></span>' % (demo(rays=n, links=n), "%d link%s" % (n, "" if n == 1 else "s") if n < 8 else "8 or more")
        for n in (0, 1, 3, 8))))
    rows.append(("Dotted blue frame", "reachable only through copies (otherwise drawn like the core).", ""))
    body = "".join('<div class="lg-row"><h3>%s</h3><p>%s</p><div class="lg-demo">%s</div></div>' % (esc(h), esc(t), d)
                   for h, t, d in rows)
    return ('<details class="legend panel" id="legend"%s><summary>How to read a pictogram</summary>%s</details>'
            % (" open" if open_ else "", body))


def fields_html(files: list[dict], enc: dict, cat: dict, role_title: dict, *, with_repo: bool,
                repo_order: list[str], repo_slug: dict[str, str], hlevel: int = 2) -> str:
    by_repo = collections.defaultdict(lambda: collections.defaultdict(list))
    for f in files:
        by_repo[f["repo"]][folder_of(f)].append(f)
    out = []
    for repo in repo_order:
        if repo not in by_repo:
            continue
        folders = by_repo[repo]
        rfiles = [f for fl in folders.values() for f in fl]
        rc = collections.Counter(cat[f["id"]] for f in rfiles)
        inner = []
        if with_repo:
            inner.append('<h%d class="repo-h"><a class="rlink" href="repo-%s.html">%s</a></h%d>'
                         % (hlevel, repo_slug[repo], esc(repo), hlevel))
            inner.append('<p class="muted small">%s</p>%s' % (count_line(rc, len(rfiles)), proportion_bar(rc)))
        for folder in sorted(folders, key=lambda k: (k != "", k.lower(), k)):
            fl = sorted(folders[folder], key=lambda f: (f["path"], f["id"]))
            fc = collections.Counter(cat[f["id"]] for f in fl)
            cats = " ".join("has-%s" % c for c in CATS if fc[c])
            links = "".join(glyph_link(f, enc[f["id"]], cat[f["id"]], role_title) for f in fl)
            inner.append('<section class="folder %s"><h%d class="folder-h">%s <span class="muted small">%s</span></h%d>'
                         '<div class="field">%s</div></section>'
                         % (cats, hlevel + 1, esc((folder or "top level") + ("/" if folder else "")),
                            count_line(fc, len(fl)), hlevel + 1, links))
        cats = " ".join("has-%s" % c for c in CATS if rc[c])
        out.append('<section class="repo %s" id="r-%s">%s</section>' % (cats, repo_slug[repo], "".join(inner)))
    return "".join(out)


def mini_strip(files: list[dict], enc: dict, cat: dict, n: int) -> str:
    """Up to n pictograms, slots shared between groups in proportion (largest remainder, at least 1 if present);
    within a group the most-linked files come first. Decorative: the counts beside it carry the meaning."""
    by = {c: sorted([f for f in files if cat[f["id"]] == c],
                    key=lambda f: (-glyphs.link_count(f), f["repo"], f["path"], f["id"])) for c in CATS}
    total = sum(len(v) for v in by.values())
    if not total:
        return ""
    if total <= n:
        slots = {c: len(by[c]) for c in CATS}
    else:
        present = [c for c in CATS if by[c]]
        slots = {c: 1 for c in present}
        left = n - len(present)
        quota = {c: left * len(by[c]) / total for c in present}
        for c in present:
            slots[c] += int(quota[c])
        rest = n - sum(slots.values())
        for c in sorted(present, key=lambda c: (-(quota[c] - int(quota[c])), CATS.index(c)))[:rest]:
            slots[c] += 1
    pick = [f for c in CATS for f in by[c][:slots.get(c, 0)]]
    uses = "".join('<use href="#%s" x="%d" y="0" width="20" height="20"/>' % (glyphs.key(enc[f["id"]]), 20 * i)
                   for i, f in enumerate(pick))
    return '<svg class="strip" viewBox="0 0 %d 20" aria-hidden="true">%s</svg>' % (20 * n, uses)


def repo_picture(files: list[dict], enc: dict, cat: dict, repo: str) -> str:
    """One-screen SVG: four bands (one per category), each a packed grid of mini pictograms."""
    W, HMAX, LAB, GAP = 360.0, 540.0, 20.0, 8.0
    bands = {c: sorted([f for f in files if cat[f["id"]] == c], key=lambda f: (folder_of(f), f["path"], f["id"]))
             for c in CATS}
    cell = 4.0
    for k in range(80, 7, -1):          # 40.0 .. 4.0 in 0.5 steps
        c = k / 2.0
        cols = max(1, int(W // c))
        h = sum(LAB + -(-len(b) // cols) * c + GAP for b in bands.values())
        if h <= HMAX:
            cell = c
            break
    cols = max(1, int(W // cell))
    y, parts = 0.0, []
    for c in CATS:
        b = bands[c]
        parts.append('<text x="0" y="%.1f" class="pl">%s: %d</text>' % (y + 14, esc(CAT_TITLE[c]), len(b)))
        y += LAB
        for n, f in enumerate(b):
            parts.append('<use href="#%s" x="%.1f" y="%.1f" width="%.1f" height="%.1f"/>'
                         % (glyphs.key(enc[f["id"]]), (n % cols) * cell, y + (n // cols) * cell, cell, cell))
        y += -(-len(b) // cols) * cell + GAP
    counts = ", ".join("%d %s" % (len(bands[c]), CAT_TITLE[c].lower()) for c in CATS)
    return ('<svg class="picture" viewBox="0 0 %d %d" role="img" aria-label="%s"><title>%s</title>%s</svg>'
            % (int(W), int(y + 1), esc("%s: %s" % (repo, counts)), esc(repo + " at a glance"), "".join(parts)))


# ---------------------------------------------------------------- build

def build(graph: dict) -> dict[str, str]:
    """Return {filename: content}. Pure function of the graph (deterministic)."""
    files = sorted(graph["files"], key=lambda f: f["id"])
    role_list = graph.get("roles") or []
    colours = glyphs.palette(role_list)
    role_title = {r["id"]: r["title"] for r in role_list}
    cat = classify(files)
    enc = {f["id"]: glyphs.encode(f, colours) for f in files}
    total = collections.Counter(cat.values())
    repo_files = collections.defaultdict(list)
    for f in files:
        repo_files[f["repo"]].append(f)
    repo_order = sorted(repo_files, key=lambda r: (-len(repo_files[r]), r.lower(), r))
    repo_slug, used = {}, set()
    for r in sorted(repo_files):
        s = slugify(r)
        while s in used:
            s += "-x"
        used.add(s)
        repo_slug[r] = s
    out = {}

    intro = ('<h1>Clarity: the estate as pictures</h1>'
             '<p class="lead">Each of the %s is one pictogram. Here the estate is split into four groups and listed by '
             'repository; open a group or a repository to see every pictogram, and tap a pictogram to open its '
             'section page.</p>' % plural(len(files), "file") + proportion_bar(total)
             + '<p class="small muted">%s. Built from build_graph.json (%s).</p>'
             % (count_line(total, len(files)), esc(graph.get("cut", ""))))
    cards = '<div class="cards">%s</div>' % "".join(
        '<a class="card panel" href="%s"><span class="card-h"><span class="sw s-%s"></span>%s <b>%d</b></span>'
        '%s<span class="small muted">%s</span></a>'
        % (CAT_PAGE[c], c, esc(CAT_TITLE[c]), total[c],
           mini_strip([f for f in files if cat[f["id"]] == c], enc, cat, 16), esc(CAT_EXPLAIN[c]))
        for c in CATS)
    rows = "".join(
        '<li><a class="row" href="repo-%s.html"><span class="row-h">%s <span class="muted small">%s</span></span>'
        '<span class="nums small">%s</span>%s</a></li>'
        % (repo_slug[r], esc(r), plural(len(repo_files[r]), "file"),
           "".join('<span><span class="sw s-%s"></span>%d</span>'
                   % (c, sum(1 for f in repo_files[r] if cat[f["id"]] == c)) for c in CATS),
           mini_strip(repo_files[r], enc, cat, 16))
        for r in repo_order)
    used = sorted({k for k in re.findall(r'href="#(g-[^"]+)"', cards + rows)})
    keyed = {glyphs.key(g): g for g in enc.values()}
    sprite = glyphs.sprite(keyed[k] for k in used)
    body = (topbar("index.html") + '<main>' + intro + cards
            + legend_html(role_list, colours, open_=False)
            + '<h2>Repositories</h2><p class="small muted">Counts per row, in order: %s. The strip shows up to 16 '
              'pictograms in the same proportions, most-linked files first.</p><ul class="repos">%s</ul>'
              % (esc(", ".join(CAT_TITLE[c].lower() for c in CATS)), rows)
            + '</main>' + sprite)
    out["index.html"] = page("Clarity: the estate as pictures", body,
                             desc="Every file of the estate as a pictogram, split into unique code in use, copies, "
                                  "code reached only through copies, and code nothing reaches.")

    for c in CATS:
        sel = [f for f in files if cat[f["id"]] == c]
        sp = glyphs.sprite(enc[f["id"]] for f in sel)
        body = (topbar("") + '<main><h1>%s <span class="muted">(%d)</span></h1><p class="lead">%s</p>'
                % (esc(CAT_TITLE[c]), len(sel), esc(CAT_EXPLAIN[c]))
                + filter_nav(total, live=False, here=c) + legend_html(role_list, colours, open_=False)
                + ('<div id="fields">%s</div>' % fields_html(sel, enc, cat, role_title, with_repo=True,
                                                             repo_order=repo_order, repo_slug=repo_slug)
                   if sel else '<p>No files in this group.</p>')
                + '</main>' + sp)
        out[CAT_PAGE[c]] = page("Clarity: " + CAT_TITLE[c], body)

    for r in repo_order:
        rf = repo_files[r]
        rc = collections.Counter(cat[f["id"]] for f in rf)
        sp = glyphs.sprite(enc[f["id"]] for f in rf)
        para = repo_paragraph(r, rf, cat, role_title)
        body = (topbar("") + '<main><h1 class="repo-title">%s</h1>' % esc(r)
                + '<div class="hero"><figure class="pic panel">%s<figcaption class="small muted">Each band is one group; '
                  'pictograms are sorted by folder then path. Details below.</figcaption></figure>'
                  % repo_picture(rf, enc, cat, r)
                + '<div class="about"><h2>What the real unique code does</h2><p>%s</p>%s'
                  '<p class="small muted">Built only from the synopses, kinds and roles of this repository\'s '
                  'unique reachable files.</p></div></div>' % (esc(para), proportion_bar(rc))
                + filter_nav(rc, live=True) + legend_html(role_list, colours, open_=False)
                + '<div id="fields">%s</div>' % fields_html(rf, enc, cat, role_title, with_repo=False,
                                                            repo_order=[r], repo_slug=repo_slug)
                + '</main>' + sp)
        out["repo-%s.html" % repo_slug[r]] = page("Clarity: " + r, body, script=True, desc=para[:300])

    out["clarity.css"] = CSS
    out["clarity.js"] = JS
    out["clarity.json"] = json.dumps({
        "schema": "clarity-v1", "cut": graph.get("cut", ""),
        "categories": list(CATS), "titles": CAT_TITLE,
        "counts": {c: total[c] for c in CATS},
        "repos": {r: {c: sum(1 for f in repo_files[r] if cat[f["id"]] == c) for c in CATS} for r in sorted(repo_files)},
        "file_category": [cat[f["id"]] for f in files],
        "glyph_key": [glyphs.key(enc[f["id"]]) for f in files],
    }, sort_keys=True, separators=(",", ":"))
    return out


CSS = """:root{--bg:#000;--panel:#0b0e14;--line:#2f343d;--text:#fff;--muted:#a6adbb;--link:#66ccff;--accent:#00ffff;--hl:#0066ff}
*{box-sizing:border-box}
html{-webkit-text-size-adjust:100%}
body{margin:0;background:var(--bg);color:var(--text);font:16px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;overflow-wrap:anywhere}
a{color:var(--link)}
main{max-width:1280px;margin:0 auto;padding:0 12px 48px}
h1{font-size:1.5rem;line-height:1.25;margin:12px 0 8px}
h2{font-size:1.2rem;margin:20px 0 6px}
h3{font-size:1rem;margin:14px 0 4px}
.lead{color:var(--text);margin:0 0 10px}
.muted{color:var(--muted)}.small{font-size:.875rem}
.panel{background:var(--panel);border:1px solid var(--line);border-radius:8px;padding:10px 12px;margin:12px 0}
.top{border-bottom:1px solid var(--line);background:var(--panel)}
.top nav{max-width:1280px;margin:0 auto;padding:4px 8px;display:flex;flex-wrap:wrap;gap:4px}
.chip{display:inline-flex;min-width:44px;justify-content:center;align-items:center;gap:6px;min-height:44px;padding:6px 12px;border:1px solid var(--line);border-radius:22px;background:var(--panel);text-decoration:none;color:var(--link);line-height:1.2}
.chip b{color:var(--text);font-weight:600}
.chip.here,.chip[aria-pressed=true]{border-color:var(--accent);color:var(--text)}
.chip:focus-visible,.g:focus-visible,.rlink:focus-visible{outline:2px solid var(--accent);outline-offset:1px}
.filters{display:flex;flex-wrap:wrap;gap:6px;margin:12px 0;background:var(--bg);padding:6px 0;border-bottom:1px solid var(--line)}
.filters .chip{font-size:.9rem}
.sw{display:inline-block;width:14px;height:14px;border-radius:3px;flex:none}
.s-all{background:linear-gradient(90deg,var(--accent) 50%,var(--muted) 50%)}
.s-core,.seg.s-core{background:var(--accent)}
.s-copy,.seg.s-copy{background:repeating-linear-gradient(45deg,var(--muted) 0 3px,#4c5a65 3px 6px)}
.s-via,.seg.s-via{background:var(--hl)}
.s-unreached,.seg.s-unreached{background:transparent;box-shadow:inset 0 0 0 1px var(--muted)}
.bar{display:flex;height:14px;border-radius:7px;overflow:hidden;border:1px solid var(--line);margin:6px 0}