GLOBALGRID2050 / EXPLORE CODE

Part of: Explore Code / Maps, GIS and field navigation / compass / upstream/tools/satnav/orientation

Map and 2 more files

A Python command-line tool in the periodic folder of Cosmic that reads build graph, identity, periodic and table, using SHA-256. It loads identity (`load_identity`) and adds numbered (`add_numbered`).

700 lines of Python and JavaScript from compass, cosmic, in 3 files. Topic: Maps, GIS and field navigation. Section 467 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. Heading transform · compass / upstream/tools/satnav/orientation/heading.mjs lines 1–57
  2. Heading Test test · compass / upstream/tools/satnav/orientation/heading.test.mjs lines 1–46
  3. Map storage · cosmic / tools/explore/periodic/map.py lines 1–597

Heading

A JavaScript module in the orientation folder of Compass that formats degrees (`formatDegrees`) and calculates planar distances and angles.

transformcompass / upstream/tools/satnav/orientation/heading.mjs · lines 1–57 of 57 · pattern deviceHeading (shared by 2 files)

What it does
It calculates its inputs. Defines normalise, formatDegrees, deviceHeading, compactTargetBearing.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 4 files: Heading Test (compass); Orient17a V9211 Heading (gridatlas); Orient17a V9212 Heading (gridatlas); Compass (compass). Reached from 2 other entry points, including Verify Workflow (compass); Compass Test (compass).
What it achieves
It formats degrees (`formatDegrees`) and is built from the device heading helper (`deviceHeading`) and the compact target bearing helper (`compactTargetBearing`). Defines `normalise`, `formatDegrees`, `deviceHeading` and 1 more.
Why it matters
Imported by Orient17a V9211 Heading, Orient17a V9212 Heading and Compass, from GridAtlas. Checked by Heading Test.
Application
compass · upstream/tools/satnav/orientation · JavaScript module
Uses
../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs, ../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs
Used by
imported by Heading Test (import), imported by Orient17a V9211 Heading (import), imported by Orient17a V9212 Heading (import), imported by Compass (import)
Produces
formatDegrees, deviceHeading, compactTargetBearing
Defines here
normalise, formatDegrees, deviceHeading, compactTargetBearing
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
compass@e200c888acbcc7af59d7cc38b29806e90b0a50db upstream/tools/satnav/orientation/heading.mjs:1-57 · blob 4a72e94ee1fa07dc69650adafa25b6e3f9eddf2e · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
import { distanceKm, initialBearingDeg } from '../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs';
import { MAX_ACCURACY_M } from '../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/nav/compass.mjs';

const radians = Math.PI / 180;
const normalise = degrees => (degrees % 360 + 360) % 360;

export function formatDegrees(degrees) {
  return String(Math.round(normalise(degrees)) % 360).padStart(3, '0') + '°';
}

// Project the screen's top edge onto the horizontal plane using the W3C
// intrinsic Z-X'-Y'' rotation. A vertical top edge has no horizontal heading.
export function deviceHeading(event, screenAngle = 0) {
  if (!Number.isFinite(screenAngle)) return null;
  const beta = (Number.isFinite(event.beta) ? event.beta : 0) * radians;
  const gamma = (Number.isFinite(event.gamma) ? event.gamma : 0) * radians;
  const angle = screenAngle * radians;
  const east = Math.cos(gamma) * Math.sin(angle);
  const north = Math.sin(beta) * Math.sin(gamma) * Math.sin(angle) + Math.cos(beta) * Math.cos(angle);
  if (Math.hypot(east, north) < 0.15) return null;
  const screenOffset = Math.atan2(east, north) / radians;

  if (typeof event.webkitCompassHeading === 'number') {
    const heading = event.webkitCompassHeading;
    const accuracy = event.webkitCompassAccuracy;
    if (!Number.isFinite(heading) || heading < 0 || heading > 360) return null;
    if (accuracy != null && (!Number.isFinite(accuracy) || accuracy < 0)) return null;
    // WebKit reports the magnetic bearing of the device's top in portrait.
    // The portrait edge points backwards if the phone is held upside down.
    const portraitOffset = Math.cos(beta) < 0 ? 180 : 0;
    return { degrees: normalise(heading + screenOffset - portraitOffset), reference: 'magnetic' };
  }
  if (!(event.absolute === true || event.type === 'deviceorientationabsolute')) return null;
  if (!Number.isFinite(event.alpha) || event.alpha < 0 || event.alpha > 360) return null;
  return { degrees: normalise(screenOffset - event.alpha), reference: 'sensor' };
}

// The V1 source contains the two manually selected endpoints, a measured
// marker and an accuracy circle generated by the same canonical maths. Read
// only those published roles; never open another location watch.
export function compactTargetBearing(features) {
  if (!Array.isArray(features)) return '';
  const roles = new Map(features.map(feature => [feature.properties?.role, feature.geometry]));
  const to = roles.get('destination-point')?.coordinates;
  const measured = roles.get('measured-gps')?.coordinates;
  const from = measured ?? roles.get('start-point')?.coordinates;
  if (!from || !to) return '';
  const distanceM = 1000 * distanceKm(...from, ...to);
  const edge = roles.get('gps-accuracy')?.coordinates?.[0]?.[0];
  const accuracyM = measured && edge ? 1000 * distanceKm(...measured, ...edge) : 0;
  if (measured && accuracyM > MAX_ACCURACY_M + 0.001) return 'Bearing awaiting an accurate GPS fix';
  if (measured && distanceM <= accuracyM + 0.001) return 'TO within GPS accuracy';
  if (distanceM < 0.001) return 'FROM and TO coincide';
  const deltaLon = normalise(to[0] - from[0]);
  if (Math.abs(deltaLon - 180) < 1e-9 && Math.abs(to[1] + from[1]) < 1e-9) return 'Bearing undetermined';
  return (measured ? 'GPS to TO ' : 'FROM to TO ') + formatDegrees(initialBearingDeg(...from, ...to)) + ' true';
}

Heading Test

A test in the orientation folder of Compass that checks Heading.

testcompass / upstream/tools/satnav/orientation/heading.test.mjs · lines 1–46 of 46 · Entry point · pattern radius (shared by 3 files)

What it does
It tests its inputs. Defines point, radius. Uses libraries node:assert/strict, node:test.
Why it exists in the grid workflow
Domain stage field_execution (path word 'satnav'): on-road and off-road field navigation to the farm gate (access gates, terrain slope, ground-bearing limits, electrical hazards), as Ventus Ltd describes its SatNav work.
Downstream impact
Used directly by 1 file: Verify Workflow (compass).
What it achieves
Defines `point` and `radius`.
Why it matters
Run by Verify Workflow.
Application
compass · upstream/tools/satnav/orientation · test
Uses
Heading (import), node:assert/strict, node:test, ../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs
Used by
run by Verify Workflow (workflow run)
Produces
point, radius
Defines here
point, radius
Cannot conclude
Whether this code runs, is used by a live app today, or is correct. This is a static reading.
Evidence
compass@e200c888acbcc7af59d7cc38b29806e90b0a50db upstream/tools/satnav/orientation/heading.test.mjs:1-46 · blob c936a96ada63b1f774bd19336adb2fa375fb9d67 · GitHub at these lines
State
achieves: name · context: readme_derived · stage: transform · effects: none found · domain stage: field_execution · users: EPC_contractor, landowner_planner · canonical: unknown
import assert from 'node:assert/strict';
import test from 'node:test';
import { geodesicCircle } from '../vendor/9698781539e549deaa6ecaa4a2b34610c1f9fd29/vendor/grid-distance-maths/src/geodesy.mjs';
import { compactTargetBearing, deviceHeading, formatDegrees } from './heading.mjs';

const point = (role, coordinates) => ({ properties: { role }, geometry: { type: 'Point', coordinates } });
const start = [-1, 51];
const destination = [-1, 51.005];
const end = point('destination-point', destination);

test('calibrated WebKit compass reports magnetic bearings in both orientations', () => {
  const event = { webkitCompassHeading: 350, webkitCompassAccuracy: 9 };
  assert.deepEqual(deviceHeading(event), { degrees: 350, reference: 'magnetic' });
  assert.deepEqual(deviceHeading(event, 90), { degrees: 80, reference: 'magnetic' });
  assert.equal(deviceHeading({ ...event, webkitCompassAccuracy: -1 }), null);
  assert.equal(deviceHeading({ ...event, webkitCompassHeading: -1 }), null);
});

test('absolute orientation uses the screen top and ignores relative or vertical readings', () => {
  const event = { absolute: true, alpha: 90, beta: 0, gamma: 0 };
  assert.equal(deviceHeading(event).degrees, 270);
  assert.equal(deviceHeading(event, 90).degrees, 0);
  assert.equal(deviceHeading({ ...event, absolute: false }), null);
  assert.equal(deviceHeading({ ...event, alpha: null }), null);
  assert.equal(deviceHeading({ ...event, beta: 90 }), null);
  assert.equal(formatDegrees(359.9), '000°');
});

test('planned and current target bearings identify their origin', () => {
  assert.equal(compactTargetBearing([]), '');
  assert.equal(compactTargetBearing([end, point('start-point', start)]), 'FROM to TO 000° true');
  assert.equal(compactTargetBearing([end, point('measured-gps', start)]), 'GPS to TO 000° true');
  assert.equal(compactTargetBearing([end, point('measured-gps', destination)]), 'TO within GPS accuracy');
  assert.equal(compactTargetBearing([end, point('start-point', destination)]), 'FROM and TO coincide');
  assert.equal(compactTargetBearing([point('start-point', [0, 1]), point('destination-point', [180, -1])]), 'Bearing undetermined');
});

test('the existing measured accuracy ring controls bearing availability', () => {
  const measured = point('measured-gps', start);
  function radius(metres) {
    return { properties: { role: 'gps-accuracy' }, geometry: { type: 'Polygon', coordinates: [geodesicCircle(...start, metres / 1000, 64)] } };
  }
  assert.equal(compactTargetBearing([end, measured, radius(30)]), 'GPS to TO 000° true');
  assert.equal(compactTargetBearing([end, measured, radius(31)]), 'Bearing awaiting an accurate GPS fix');
  assert.equal(compactTargetBearing([point('destination-point', [-1, 51.00002]), measured, radius(10)]), 'TO within GPS accuracy');
});

Map

A Python command-line tool in the periodic folder of Cosmic that reads build graph, identity, periodic and table, using SHA-256. It loads identity (`load_identity`) and adds numbered (`add_numbered`).

storagecosmic / tools/explore/periodic/map.py · lines 1–597 of 651 · Entry point · pattern evidence_key (shared by 2 files)

What it does
It loads build graph, identity, periodic and table. Defines 15 functions or classes, including zs, sha256, git_head, load, top. Uses libraries argparse, collections, hashlib, json, os. Side effects: reads or writes files; starts processes.
Why it exists in the grid workflow
Domain stage site_feasibility (topic 'maps-gis'): substation-to-site feasibility (terrain, LiDAR and connection evidence before design), a journey named in Ventus Ltd's brief.
Inputs & outputs
In: JSON file build_graph.json; JSON file identity.json; JSON file periodic.json; JSON file table.json; JSON file elements.json; JSON file functions.json; JSON file blocks.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 2 files: Test Map (cosmic); Extras (cosmic). Reached from 3 other entry points, including Ship (cosmic); Test Extras (cosmic); Test Ship (cosmic).
What it achieves
Periodic table of the code estate: the MAPPER.
Why it matters
Run by Extras. Checked by Test Map.
Application
cosmic · tools/explore/periodic · Python CLI
Uses
argparse, collections, hashlib, json, os, re, subprocess, sys
Used by
imported by Test Map (import), run by Extras (script call)
Produces
zs, sha256, git_head, load, top, quantile_assign, propose_symbol, fam_sort, evidence_key, load_identity, build, assign_analogues
Defines here
zs, sha256, git_head, load, top, quantile_assign, propose_symbol, fam_sort, evidence_key, load_identity, build, add_numbered, assign_analogues, give
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/periodic/map.py:1-597 · blob 4a3a781cdcd640d8c283d7c1fd5057bc903d228c · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: site_feasibility · users: IPP_developer, landowner_planner · canonical: supporting_data
#!/usr/bin/env python3
"""Periodic table of the code estate: the MAPPER.

Answers "if the whole code base were elements on a periodic table, what would
they be?" using only the estate's existing tables and keys:

  * star-maker/elements/table.json      the 47 elements (number, symbol, state)
  * elements/catalogue/elements.json    the Elements catalogue blocks (block:<Sym>)
  * elements/catalogue/functions.json   catalogue family -> block
  * /tmp/vk/7/identity.json             per graph file: blocks, Modular Star
                                        families (family:<n>), Vedic clusters
  * /tmp/site8/explore-code/build_graph.json  roles, stages, kinds, edges

Existing numbers and symbols are copied, never changed. Code that fits no
existing element becomes a CANDIDATE element (proposed symbol, number null).
Each element also carries a playful "analogue" (a real chemical element H..Og)
chosen by documented rules; it never replaces the estate number or symbol.

Output: /tmp/vk/periodic/periodic.json (schema explore-periodic-v1).
Deterministic: same inputs -> byte-identical output (no clocks, sorted keys).
Stdlib only.
"""
import argparse
import collections
import hashlib
import json
import os
import re
import subprocess
import sys

SCHEMA = "explore-periodic-v1"
HOME = "/home/claude/src"
DEFAULTS = {
    "graph": "/tmp/site8/explore-code/build_graph.json",
    "identity": "/tmp/vk/7/identity.json",
    "starmaker": os.path.join(HOME, "star-maker"),
    "elements": os.path.join(HOME, "elements"),
    "stars": os.path.join(HOME, "stars"),
    "out": "/tmp/vk/periodic/periodic.json",
}

# ---------------------------------------------------------------- axes
# Groups (columns) are the Explore Code graph roles, in the graph's own order.
# Periods (rows) are abstraction levels.
PERIODS = [
    (1, "constant", "Constants and vocabularies"),
    (2, "data-contract", "Data layers, contracts, configuration, styles"),
    (3, "function", "Function-level clusters (shared Vedic fingerprints)"),
    (4, "module", "Modules: one file's functions, libraries, scripts, tests"),
    (5, "engine", "Engines (settled shared maths)"),
    (6, "cartridge-tool", "Cartridges, tools, command lines, workflows"),
    (7, "app-page", "Apps and pages"),
]
PERIOD_BY_KIND = {  # Elements catalogue kind -> period
    "constant": 1, "layer": 2, "deeplink": 2, "auto": 4, "pack": 4, "engine": 5,
    "cartridge": 6, "tool": 6, "app": 7,
}
PERIOD_BY_GRAPH_KIND = {  # build_graph file kind -> period (candidates by name)
    "configuration": 2, "SQL query": 2, "style sheet": 2,
    "JavaScript module": 4, "Python module": 4, "script": 4, "test": 4,
    "Python CLI": 6, "workflow": 6, "shell script": 6, "PowerShell script": 6,
    "page": 7,
}
GROUP_BY_CATEGORY = {  # Elements catalogue category -> graph role (column)
    "constants": "docs-config", "geodesy": "geodesy", "network": "electrical",
    "connections": "electrical", "solar": "electrical", "layers": "storage",
    "cartridges": "render", "interface": "interaction", "arrival": "interaction",
    "news": "energy-data", "proofs": "test",
}
GROUP_BY_STAR_FAMILY = {"physics": "transform", "vocabulary": "docs-config"}

NAME_STOP = set("""tools tool github workflows workflow scripts script test tests testcode
index src modules module mod archive archives versions version fixes iterations iteration
build check run app apps main lib libs utils util common shared assets static public dist
releases release prototype new old copy final backup tmp temp docs doc data page pages
config readme init js css html py mjs cjs ts json yml yaml md cli core min bundle vendor
site homepage studio ui web www nl the and of for""".split())
TIMESTAMP_RE = re.compile(r"(^|/)(\d{8,14}[^/]*|releases?|archives?|versions|history|backup)(/|$)")
VERSION_RE = re.compile(r"^(v\d+|r\d+|\d+.*)$")
MIN_CLUSTER = 3

# ------------------------------------------------- real periodic table
REAL = ("H Hydrogen,He Helium,Li Lithium,Be Beryllium,B Boron,C Carbon,N Nitrogen,O Oxygen,"
        "F Fluorine,Ne Neon,Na Sodium,Mg Magnesium,Al Aluminium,Si Silicon,P Phosphorus,S Sulfur,"
        "Cl Chlorine,Ar Argon,K Potassium,Ca Calcium,Sc Scandium,Ti Titanium,V Vanadium,Cr Chromium,"
        "Mn Manganese,Fe Iron,Co Cobalt,Ni Nickel,Cu Copper,Zn Zinc,Ga Gallium,Ge Germanium,"
        "As Arsenic,Se Selenium,Br Bromine,Kr Krypton,Rb Rubidium,Sr Strontium,Y Yttrium,"
        "Zr Zirconium,Nb Niobium,Mo Molybdenum,Tc Technetium,Ru Ruthenium,Rh Rhodium,Pd Palladium,"
        "Ag Silver,Cd Cadmium,In Indium,Sn Tin,Sb Antimony,Te Tellurium,I Iodine,Xe Xenon,"
        "Cs Caesium,Ba Barium,La Lanthanum,Ce Cerium,Pr Praseodymium,Nd Neodymium,Pm Promethium,"
        "Sm Samarium,Eu Europium,Gd Gadolinium,Tb Terbium,Dy Dysprosium,Ho Holmium,Er Erbium,"
        "Tm Thulium,Yb Ytterbium,Lu Lutetium,Hf Hafnium,Ta Tantalum,W Tungsten,Re Rhenium,"
        "Os Osmium,Ir Iridium,Pt Platinum,Au Gold,Hg Mercury,Tl Thallium,Pb Lead,Bi Bismuth,"
        "Po Polonium,At Astatine,Rn Radon,Fr Francium,Ra Radium,Ac Actinium,Th Thorium,"
        "Pa Protactinium,U Uranium,Np Neptunium,Pu Plutonium,Am Americium,Cm Curium,"
        "Bk Berkelium,Cf Californium,Es Einsteinium,Fm Fermium,Md Mendelevium,No Nobelium,"
        "Lr Lawrencium,Rf Rutherfordium,Db Dubnium,Sg Seaborgium,Bh Bohrium,Hs Hassium,"
        "Mt Meitnerium,Ds Darmstadtium,Rg Roentgenium,Cn Copernicium,Nh Nihonium,Fl Flerovium,"
        "Mc Moscovium,Lv Livermorium,Ts Tennessine,Og Oganesson")
REAL_TABLE = [dict(Z=i + 1, symbol=s.split()[0], name=s.split()[1])
              for i, s in enumerate(REAL.split(","))]
assert len(REAL_TABLE) == 118
SYM2Z = {r["symbol"]: r["Z"] for r in REAL_TABLE}


def zs(syms):
    return [SYM2Z[s] for s in syms.split()]


# Rule pools, in priority order. Each pool is a list of real Z values; the
# code elements a rule selects are sorted by its size metric ascending and
# spread over the pool by quantile (lighter real element = smaller code).
ANALOGUE_RULES = [
    ("halogen", zs("F Cl Br I At Ts"),
     "UNSETTLED elements (competing values in the code) -> halogens (group 17): one step short of a "
     "stable shell; ranked by number of competing values"),
    ("hydrogen", zs("H"),
     "the element holding the most tiny helpers (function occurrences of at most 5 lines) -> hydrogen: "
     "the smallest, most common building block"),
    ("carbon-group", zs("C Si Ge Sn Pb Fl"),
     "the 6 highest-valence hubs (most distinct elements bonded through graph edges; residue clusters excluded) -> group 14, "
     "carbon first: the most bonded backbone code"),
    ("noble", zs("He Ne Ar Kr Xe Rn Og"),
     "valence 0 and nothing reachable from an entry point -> noble gases: inert, isolated code; "
     "ranked by file count"),
    ("heavy-unstable", [z for z in range(89, 117) if z not in (114,)],
     "at least half of the files under timestamp/release/archive/version folders and above-median "
     "lines per file -> actinides and superheavies (Ac..Lv): large, short-lived versions; ranked by lines"),
    ("alkali", zs("Li Na K Rb Cs Fr"),
     "dominant role ingest -> alkali metals (group 1): reactive, hand data on"),
    ("alkaline-earth", zs("Be Mg Ca Sr Ba Ra"),
     "dominant role storage or docs-config -> alkaline earth metals (group 2): hold and keep"),
    ("transition-geodesy", zs("Sc Ti V Y Zr Nb Hf Ta"),
     "dominant role geodesy -> transition metals groups 3-5"),
    ("transition-electrical", zs("Cr Mn Fe Co Mo Tc Ru Rh W Re Os Ir"),
     "dominant role electrical -> transition metals groups 6-9 (the structural workhorses)"),
    ("transition-energy", zs("Ni Cu Zn Pd Ag Cd Pt Au Hg"),
     "dominant role energy-data -> transition metals groups 10-12 (the trade metals)"),
    ("lanthanide-test", zs("La Ce Pr Nd Pm Sm Eu Gd"),
     "dominant role test -> lanthanides La..Gd: many near-identical members"),
    ("lanthanide-automation", zs("Tb Dy Ho Er Tm Yb Lu"),
     "dominant role automation -> lanthanides Tb..Lu"),
    ("boron-group", zs("B Al Ga In Tl"),
     "dominant role render or other -> group 13 (B..Tl)"),
    ("pnictogen", zs("N P As Sb Bi"),
     "dominant role transform -> group 15 (N..Bi): conversion chemistry"),
    ("chalcogen", zs("O S Se Te Po"),
     "dominant role interaction -> group 16 (O..Po): binds to almost everything"),
]
ROLE_RULE = {
    "ingest": "alkali", "storage": "alkaline-earth", "docs-config": "alkaline-earth",
    "geodesy": "transition-geodesy", "electrical": "transition-electrical",
    "energy-data": "transition-energy", "test": "lanthanide-test",
    "automation": "lanthanide-automation", "render": "boron-group", "other": "boron-group",
    "transform": "pnictogen", "interaction": "chalcogen",
}


# ------------------------------------------------------------- helpers
def sha256(path):
    h = hashlib.sha256()
    with open(path, "rb") as fh:
        for chunk in iter(lambda: fh.read(1 << 20), b""):
            h.update(chunk)
    return h.hexdigest()


def git_head(repo):
    try:
        return subprocess.check_output(["git", "-C", repo, "rev-parse", "HEAD"],
                                       text=True, stderr=subprocess.DEVNULL).strip()
    except Exception:
        return None


def load(path):
    with open(path) as fh:
        return json.load(fh)


def top(counter, order=None):
    """Most common key; ties broken by `order` index then key text."""
    if not counter:
        return None
    rank = {k: i for i, k in enumerate(order or [])}
    return sorted(counter.items(), key=lambda kv: (-kv[1], rank.get(kv[0], 1e9), str(kv[0])))[0][0]


def quantile_assign(items, pool):
    """items: list of (metric, key) -> {key: Z}; spread ascending over pool."""
    items = sorted(items)
    n = len(items)
    return {key: pool[min(len(pool) - 1, (i * len(pool)) // n)] for i, (_, key) in enumerate(items)}


def propose_symbol(word, taken):
    w = re.sub(r"[^A-Za-z]", "", word).capitalize() or "X"
    low = w[1:].lower()
    tries = ([w[0] + c for c in low] + [w[0] + a + b for i, a in enumerate(low) for b in low[i + 1:]]
             + [w[0] + c for c in "abcdefghijklmnopqrstuvwxyz"])
    for t in tries:
        if t not in taken:
            taken.add(t)
            return t
    for i in range(2, 1000):
        t = w[:2] + str(i)
        if t not in taken:
            taken.add(t)
            return t


def fam_sort(k):
    """family:<n> numerically first, then identity's unnumbered familysha:<hex> keys."""
    pre, _, rest = k.partition(":")
    return (0, int(rest), "") if pre == "family" and rest.isdigit() else (1, 0, k)


def evidence_key(idf):
    k = idf["keys"]["key"]  # repo@commit path:1-N blob
    return k.rsplit(" ", 1)[0] if k.count(" ") >= 2 else k


# ------------------------------------------------------------- mapping
def load_identity(path, graph):
    """identity.json (full) or identity-files.json (published slim view: no per-function list) or nothing.
    Missing pieces become empty, so map.py runs from a clean build output alone (CI: identity extra optional).
    Patched by QUANTA-19 (SHIPPER-PERIODIC) after the MAPPER finished."""
    ident = load(path) if path and os.path.exists(path) else {"files": {}, "schema": None}
    commit = {r["repo"]: r["commit"] for r in graph["repos"]}
    files = ident.setdefault("files", {})
    for f in graph["files"]:
        v = files.setdefault(str(f["id"]), {})
        if "functions" not in v:
            v["functions"] = [{"family_key": "family:%d" % n} for n in (v.get("modular") or {}).get("families") or []]
        v.setdefault("elements", {}).setdefault("blocks", [])
        v.setdefault("vedic", {}).setdefault("candidates", [])
        v.setdefault("keys", {}).setdefault("key", "%s@%s %s:1-%d" % (f["repo"], commit.get(f["repo"], "?"), f["path"],
                                                                      f.get("lines") or 0))
    return ident


def build(args):
    graph = load(args.graph)
    ident = load_identity(args.identity, graph)
    sm_path = os.path.join(args.starmaker, "elements", "table.json")
    cat_path = os.path.join(args.elements, "catalogue", "elements.json")
    fn_path = os.path.join(args.elements, "catalogue", "functions.json")
    star = load(sm_path)["elements"]
    cat = load(cat_path)
    catfn = load(fn_path)
    sm_head, el_head = git_head(args.starmaker), git_head(args.elements)

    roles = [r["id"] for r in graph["roles"]]
    gfiles = {f["id"]: f for f in graph["files"]}
    ifiles = {int(k): v for k, v in ident["files"].items()}
    star_by_sym = {s["symbol"]: s for s in star}

    reg_path = os.path.join(args.stars, "blocks", "blocks.json")
    reg = load(reg_path)["blocks"] if os.path.exists(reg_path) else []
    st_head = git_head(args.stars)

    # family -> block: catalogue elements.json function_keys, then catalogue
    # functions.json block field (includes pack blocks), then live register 'inside'
    fam_block = {}
    for e in cat:
        for k in e["function_keys"]:
            fam_block[k] = e["key"]
    for x in catfn:
        if x.get("block") and x["key"] not in fam_block:
            fam_block[x["key"]] = x["block"]
    for b in reg:
        for x in b.get("inside", []):
            fam_block.setdefault("family:%d" % x["family"], "block:" + b["symbol"])

    # ---- numbered elements (never re-numbered)
    elements = {}
    num_owner = {}

    def add_numbered(key, number, sym, **kw):
        if key in elements:
            if elements[key]["number"] != number:
                raise SystemExit("number conflict for %s: %s vs %s" % (key, elements[key]["number"], number))
            return False
        if num_owner.get(number, key) != key:
            raise SystemExit("number %s used by %s and %s" % (number, num_owner[number], key))
        num_owner[number] = key
        elements[key] = dict(key=key, status="numbered", number=number, symbol=sym, proposed_symbol=None, **kw)
        return True

    for e in cat:
        s = star_by_sym.get(e["symbol"])
        if s is not None and s["number"] != e["number"]:
            raise SystemExit("number conflict %s" % e["symbol"])
        state = (s or {}).get("state") or e.get("state")
        add_numbered(
            e["key"], e["number"], e["symbol"],
            name=(s or {}).get("name") or e["title"], title=e["title"],
            source="star-maker" if s else "elements-catalogue",
            number_basis="star-maker table.json + elements catalogue" if s else "elements catalogue",
            star_family=(s or {}).get("family"), kind=e["kind"], category=e["category"],
            state=state,
            competing_values=[dict(value=c["value"], files=c["files"])
                              for c in (s or {}).get("candidates", [])] if state == "UNSETTLED" else [],
            catalogue_evidence=(["%s@%s %s" % (f["repo"].split("/")[-1], f["commit"], f["path"])
                                 for f in e.get("files", [])][:4]
                                + (["star-maker@%s %s" % (sm_head, s["evidence"])] if s and s.get("evidence") else [])
                                + (["star-maker@%s elements/table.json (%s)" % (sm_head, s["key"])] if s else [])
                                + ["elements@%s catalogue/elements.json (%s)" % (el_head, e["key"])]),
            evidence_keys=[e["key"]] + (["star-maker:" + s["key"]] if s else []),
        )
    for s in star:  # every star-maker element must be in the catalogue
        if "block:" + s["symbol"] not in elements:
            raise SystemExit("star-maker element missing from catalogue: " + s["symbol"])
    for b in reg:  # live register in the stars repo (superset of the catalogue)
        add_numbered(
            "block:" + b["symbol"], b["number"], b["symbol"], name=b["title"], title=b["title"],
            source="stars-register", number_basis="stars blocks/blocks.json",
            star_family=None, kind=b["kind"], category=b["category"], state=b.get("state"),
            competing_values=[],
            catalogue_evidence=["%s@%s %s" % (f["repo"].split("/")[-1], f["commit"], f["path"])
                                for f in b.get("files", [])][:4]
                               + ["stars@%s blocks/blocks.json (block:%s)" % (st_head, b["symbol"])],
            evidence_keys=["block:" + b["symbol"]],
        )
    pack_names = collections.defaultdict(list)
    for x in catfn:
        if x.get("block"):
            pack_names[x["block"]].append(x["name"])
    for key in sorted(pack_names, key=lambda k: (len(k), k)):
        m = re.fullmatch(r"block:x(\d+)", key)
        if key in elements or not m:
            continue
        names = sorted(set(pack_names[key]))
        add_numbered(
            key, int(m.group(1)), key[6:], name=key[6:],
            title="Pack block %s (%s)" % (key[6:], ", ".join(names[:3]) + (" ..." if len(names) > 3 else "")),
            source="elements-pack", number_basis="symbol x<n> of a pack block named in elements catalogue/functions.json "
                                                   "(not in the current register; same numbering space, no clash)",
            star_family=None, kind="pack", category="other", state=None, competing_values=[],
            catalogue_evidence=["elements@%s catalogue/functions.json" % el_head], evidence_keys=[key],
        )
    block_num = {k: e["number"] for k, e in elements.items()}
    reg_files = collections.defaultdict(set)
    for b in reg:
        for f in b.get("files", []):
            reg_files[(f["repo"].split("/")[-1], f["path"])].add("block:" + b["symbol"])

    # ---- files with a block (identity blocks, live register files, catalogue family)
    file_el, file_via, file_also = {}, {}, {}
    for fid in sorted(gfiles):
        idf = ifiles[fid]
        fks = [x["family_key"] for x in idf["functions"] if x.get("family_key")]
        blocks, via = list(idf["elements"]["blocks"]), "block"
        if not blocks:
            blocks, via = sorted(reg_files.get((gfiles[fid]["repo"], gfiles[fid]["path"]), ())), "register"
        if not blocks:
            blocks, via = sorted({fam_block[k] for k in fks if k in fam_block}), "family"
        blocks = [b for b in blocks if b in elements]
        if not blocks:
            continue
        cnt = collections.Counter(fam_block.get(k) for k in fks)
        primary = sorted(blocks, key=lambda b: (-cnt.get(b, 0), block_num[b], b))[0]
        file_el[fid], file_via[fid] = primary, via
        file_also[fid] = sorted(b for b in blocks if b != primary)

    # ---- candidates: unmapped files clustered by Vedic word, then by name
    unm = [fid for fid in sorted(gfiles) if fid not in file_el]
    vword = {}
    for fid in unm:
        c = [x for x in ifiles[fid]["vedic"]["candidates"] if x.get("word")]
        if c:
            vword[fid] = sorted(c, key=lambda x: (-x["score"], x["word"]))[0]
    vcount = collections.Counter(v["word"] for v in vword.values())
    df = collections.Counter()
    words = {}
    for fid in unm:
        ws = [w for w in gfiles[fid]["name_words"] if w not in NAME_STOP and not VERSION_RE.match(w) and len(w) > 2]
        words[fid] = ws
        df.update(set(ws))
    cand_of, cand_basis = {}, {}
    for fid in unm:
        v = vword.get(fid)
        if v and vcount[v["word"]] >= MIN_CLUSTER:
            cand_of[fid] = ("vedic", v["word"].upper())
            cand_basis[fid] = "vedic:%s" % v["cluster_id"]
            continue
        ws = words[fid]
        if ws:
            pos = {w: i for i, w in enumerate(ws)}
            best = sorted(set(ws), key=lambda w: (-df[w], -pos[w], w))[0]
            if df[best] >= MIN_CLUSTER:
                cand_of[fid] = ("name", best.upper())
                cand_basis[fid] = "name:%s" % best
                continue
        role = gfiles[fid]["role"]
        cand_of[fid] = ("residue", (role.upper() + "-RESIDUE"))
        cand_basis[fid] = "role:%s" % role
    # name clusters can shrink below MIN once vedic took members: fold into residue
    csize = collections.Counter(cand_of.values())
    for fid in unm:
        if csize[cand_of[fid]] < MIN_CLUSTER and cand_of[fid][0] != "residue":
            role = gfiles[fid]["role"]
            cand_of[fid] = ("residue", role.upper() + "-RESIDUE")
            cand_basis[fid] = "role:%s" % role
    taken = set(e["symbol"] for e in elements.values()) | set(SYM2Z)
    for (basis, word) in sorted(set(cand_of.values()), key=lambda t: (t[1], t[0])):
        key = "candidate:" + word
        if key in elements:  # vedic and name produced the same word: keep apart
            key = "candidate:%s-%s" % (word, basis.upper())
        elements[key] = dict(
            key=key, status="candidate", number=None, symbol=None,
            proposed_symbol="*" + propose_symbol(word, taken), name=word,
            title="%s (candidate, clustered by %s)" % (word.title(), basis),
            source="candidate", cluster_basis=basis, star_family=None, kind=None, category=None,
            state=None, competing_values=[], catalogue_evidence=[], evidence_keys=[],
        )
        for fid in unm:
            if cand_of[fid] == (basis, word) and fid not in file_el:
                file_el[fid], file_via[fid], file_also[fid] = key, "candidate", []
    for fid in unm:
        elements[file_el[fid]]["evidence_keys"].append(cand_basis[fid])

    # ---- families -> element
    fam_files = collections.defaultdict(collections.Counter)
    tiny = collections.Counter()
    unnumbered = 0
    for fid in sorted(gfiles):
        for x in ifiles[fid]["functions"]:
            if not x.get("family_key"):
                unnumbered += 1
                continue
            fam_files[x["family_key"]][file_el[fid]] += 1
            if x.get("first") is not None and x.get("last") is not None and x["last"] - x["first"] + 1 <= 5:
                tiny[file_el[fid]] += 1
    family_map = {}
    for fk in sorted(fam_files, key=fam_sort):
        if fk in fam_block:
            family_map[fk] = dict(element=fam_block[fk], via="catalogue")
        else:
            c = fam_files[fk]
            best = sorted(c, key=lambda k: (-c[k], elements[k]["number"] is None,
                                            elements[k]["number"] or 0, k))[0]
            family_map[fk] = dict(element=best, via="files")
    for fk in sorted(fam_block):  # catalogue families never seen in the graph still map
        family_map.setdefault(fk, dict(element=fam_block[fk], via="catalogue"))

    # ---- per element metrics
    members = collections.defaultdict(list)
    for fid, k in file_el.items():
        members[k].append(fid)
    fams_of = collections.defaultdict(list)
    for fk, v in family_map.items():
        fams_of[v["element"]].append(fk)
    bonds = collections.defaultdict(collections.Counter)
    for e in graph["edges"]:
        a, b = file_el.get(e[0]), file_el.get(e[1])
        if a and b and a != b:
            bonds[a][b] += 1
            bonds[b][a] += 1
    for k, el in elements.items():
        fids = sorted(members.get(k, []))
        fl = [gfiles[i] for i in fids]
        el["files"] = fids
        el["file_count"] = len(fids)
        el["families"] = sorted(fams_of.get(k, []), key=fam_sort)
        el["family_count"] = len(el["families"])
        el["lines"] = sum(f["lines"] for f in fl)
        el["roles"] = dict(sorted(collections.Counter(f["role"] for f in fl).items()))
        el["stages"] = dict(sorted(collections.Counter(f["stage"] for f in fl).items()))
        el["graph_kinds"] = dict(sorted(collections.Counter(f["kind"] for f in fl).items()))
        el["valence"] = len(bonds[k])
        el["bonds"] = [dict(key=b, edges=n) for b, n in
                       sorted(bonds[k].items(), key=lambda kv: (-kv[1], kv[0]))[:12]]
        el["reachable_share"] = round(sum(1 for f in fl if f.get("reachable")) / len(fl), 4) if fl else 0.0
        el["timestamp_share"] = round(sum(1 for f in fl if TIMESTAMP_RE.search(f["path"])) / len(fl), 4) if fl else 0.0
        el["dependents"] = sum(len(f.get("dependents") or []) for f in fl)
        el["tiny_helpers"] = tiny.get(k, 0)
        repos = collections.Counter(f["repo"] for f in fl)
        el["repos"] = sorted(repos)
        # group (column)
        dom_role = top(collections.Counter(f["role"] for f in fl), roles)
        if el["status"] == "numbered" and GROUP_BY_CATEGORY.get(el["category"]):
            el["group"], el["group_rule"] = GROUP_BY_CATEGORY[el["category"]], "category"
        elif dom_role:
            el["group"], el["group_rule"] = dom_role, "dominant-role"
        elif el["star_family"] in GROUP_BY_STAR_FAMILY:
            el["group"], el["group_rule"] = GROUP_BY_STAR_FAMILY[el["star_family"]], "star-family"
        else:
            el["group"], el["group_rule"] = "other", "none"
        el["dominant_role"] = dom_role
        # period (row)
        if el["status"] == "numbered":
            el["period"] = PERIOD_BY_KIND.get(el["kind"], 4)
        elif el.get("cluster_basis") == "vedic":
            el["period"] = 3
        else:
            el["period"] = PERIOD_BY_GRAPH_KIND.get(top(collections.Counter(f["kind"] for f in fl)), 4)
        # evidence: repo@commit path:lines for the members most depended on
        ev_f = sorted(fids, key=lambda i: (-len(gfiles[i].get("dependents") or []), gfiles[i]["repo"], gfiles[i]["path"]))
        el["evidence"] = [evidence_key(ifiles[i]) for i in ev_f[:8]] or el.pop("catalogue_evidence")
        el.pop("catalogue_evidence", None)
        ek = list(dict.fromkeys(el["evidence_keys"]))
        el["evidence_keys"] = (ek[:6] + el["families"][:6])
        el["importance"] = el["dependents"] + el["file_count"] + 10 * el["valence"]

    assign_analogues(elements, roles)

    # ---- order: numbered by number, then candidates by key
    ordered = sorted(elements.values(), key=lambda e: (e["number"] is None, e["number"] or 0, e["key"]))
    files_out = {str(fid): dict(element=file_el[fid], via=file_via[fid], also=file_also[fid])
                 for fid in sorted(file_el)}
    counts = dict(
        files=len(gfiles), files_mapped=len(file_el),
        files_by_via=dict(sorted(collections.Counter(file_via.values()).items())),
        elements=len(ordered), numbered=sum(1 for e in ordered if e["status"] == "numbered"),
        numbered_with_files=sum(1 for e in ordered if e["status"] == "numbered" and e["file_count"]),
        candidates=sum(1 for e in ordered if e["status"] == "candidate"),
        candidates_by_basis=dict(sorted(collections.Counter(e["cluster_basis"] for e in ordered if e["status"] == "candidate").items())),
        star_maker=sum(1 for e in ordered if e["source"] == "star-maker"),
        unsettled=sum(1 for e in ordered if e["state"] == "UNSETTLED"),
        families=len(family_map),
        families_modular_star=sum(1 for k in family_map if k.startswith("family:")),
        families_unnumbered_familysha=sum(1 for k in family_map if k.startswith("familysha:")),
        families_by_via=dict(sorted(collections.Counter(v["via"] for v in family_map.values()).items())),
        function_occurrences_without_family=unnumbered,
    )
    return dict(
        schema=SCHEMA,
        cut=graph.get("cut"),
        sources=dict(
            build_graph=dict(path=args.graph, sha256=sha256(args.graph), cut=graph.get("cut")),
            identity=dict(path=args.identity, sha256=sha256(args.identity) if args.identity and os.path.exists(args.identity) else None,
                          schema=ident.get("schema")),
            star_maker=dict(repo="star-maker", commit=sm_head, path="elements/table.json", sha256=sha256(sm_path)),
            elements_catalogue=dict(repo="elements", commit=el_head, path="catalogue/elements.json", sha256=sha256(cat_path)),
            stars_register=dict(repo="stars", commit=st_head, path="blocks/blocks.json",
                                sha256=sha256(reg_path) if os.path.exists(reg_path) else None),
            elements_functions=dict(repo="elements", commit=el_head, path="catalogue/functions.json", sha256=sha256(fn_path)),
        ),
        rules=RULES,
        axes=dict(groups=graph["roles"],
                  periods=[dict(n=n, id=i, title=t) for n, i, t in PERIODS]),
        analogue_rules=[dict(id=r, pool=[REAL_TABLE[z - 1]["symbol"] for z in pool], text=t)
                        for r, pool, t in ANALOGUE_RULES],
        real_elements=REAL_TABLE,
        counts=counts,
        elements=ordered,
        files=files_out,
        families=family_map,
    )


def assign_analogues(elements, roles):
    els = sorted(elements.values(), key=lambda e: e["key"])
    done = {}
    basis = {}
    pools = {r: (pool, t) for r, pool, t in ANALOGUE_RULES}

    def give(rule, chosen, metric_name, metric):
        pool = pools[rule][0]
        for k, z in quantile_assign([(metric(elements[k]), k) for k in chosen], pool).items():
            done[k] = (rule, z)
            basis[k] = {metric_name: metric(elements[k])}

    # 1 halogen
    give("halogen", [e["key"] for e in els if e["state"] == "UNSETTLED"],
         "competing_values", lambda e: len(e["competing_values"]))
    # 2 hydrogen
    rest = [e for e in els if e["key"] not in done and e["tiny_helpers"] > 0]
    if rest:
        h = sorted(rest, key=lambda e: (-e["tiny_helpers"], e["key"]))[0]
        give("hydrogen", [h["key"]], "tiny_helpers", lambda e: e["tiny_helpers"])
    # 3 carbon group: top 6 valence, carbon = highest
    rest = [e for e in els if e["key"] not in done and e["valence"] > 0
            and e.get("cluster_basis") != "residue"]
    hubs = sorted(rest, key=lambda e: (-e["valence"], e["key"]))[:6]
    for i, e in enumerate(hubs):
        done[e["key"]] = ("carbon-group", pools["carbon-group"][0][i])
        basis[e["key"]] = {"valence": e["valence"], "valence_rank": i + 1}
    # 4 noble
    give("noble", [e["key"] for e in els if e["key"] not in done and e["valence"] == 0
                   and e["reachable_share"] == 0],
         "file_count", lambda e: e["file_count"])
    # 5 heavy unstable
    lpf = sorted(e["lines"] / e["file_count"] for e in els if e["file_count"])
    median = lpf[len(lpf) // 2] if lpf else 0
    give("heavy-unstable", [e["key"] for e in els if e["key"] not in done and e["file_count"]
                            and e["timestamp_share"] >= 0.5 and e["lines"] / e["file_count"] > median],
         "lines", lambda e: e["lines"])
    # 6 by group column
    by_rule = collections.defaultdict(list)
    for e in els:
        if e["key"] not in done:
            by_rule[ROLE_RULE.get(e["group"], "boron-group")].append(e["key"])
    for rule in sorted(by_rule):
        give(rule, by_rule[rule], "lines", lambda e: e["lines"])