GLOBALGRID2050 / EXPLORE CODE

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

Laws

A Python command-line tool in the explore folder of Cosmic that reads build graph, identity and sentences, using SHA-256.

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

Laws

A Python command-line tool in the explore folder of Cosmic that reads build graph, identity and sentences, using SHA-256.

rendercosmic / tools/explore/laws/laws.py · lines 1–700 of 960 · Entry point · pattern _minutes (shared by 2 files)

What it does
It loads build graph, identity and sentences. Defines 34 functions or classes, including load_json, ranks, pearson, spearman, gini. Uses libraries argparse, collections, itertools, json, math. Side effects: changes the web page (DOM); reads or writes files; starts processes.
Inputs & outputs
In: JSON file build_graph.json; JSON file identity.json; JSON file laws.json; JSON file sentences.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 1 file: Test Laws (cosmic).
What it achieves
It loads JSON (`load_json`) and is built from the ranks step (`ranks`) and the pearson step (`pearson`). The Explore Code estate measured as if it obeyed physical laws (GRAVITON-64, ). It accepts `--out`, `--demo` and `--no-lines`.
Why it matters
Checked by Test Laws.
Application
cosmic · tools/explore/laws · Python CLI
Uses
argparse, collections, itertools, json, math, os, re, sys
Used by
imported by Test Laws (import)
Produces
load_json, ranks, pearson, spearman, gini, r4, verdict, Estate, law_gravity, law_field, law_conservation, law_entropy
Defines here
load_json, ranks, pearson, spearman, gini, r4, verdict, Estate, __init__, key, label, law_gravity, _named, law_field, _lines_md, law_conservation, _stamp, law_entropy, _copy_components, find, law_inertia, law_kirchhoff, law_induction, law_key, _minutes, law_light
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/laws/laws.py:1-700 · blob 8bd2beb55a2caaf840f1c2f2bc0486eabfeebce7 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: dom, filesystem, process · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""laws.py - the Explore Code estate measured as if it obeyed physical laws (GRAVITON-64, 2026-12-05).

Each law is an ANALOGY with a precise, measurable definition on the Explore Code graph. It is measured on
the real estate and reported as HOLDS, PARTLY or DOES NOT HOLD against a threshold fixed in this file
before the run. Nothing here is physics: a 'force' is a drawing rule and a 'field' is a set of named
data items. The format follows Ventusltd/law: one sentence, what it means, the measure, the number, how
to show it is wrong, and the keys.

Inputs (read only; all paths can be overridden on the command line):
  graph     /tmp/site8/explore-code/build_graph.json   (explore-build-graph-v1)
  graph_old /tmp/site7/explore-code/build_graph.json   (an earlier cut, for conservation)
  identity  /tmp/vk/7/identity.json                     (explore-identity-v1: keys, functions, verdicts)
  manifest  /tmp/vk/clean/manifest.json                 (clean-manifest-v1)
  lines     /home/claude/src/stars/LINES.md             (numbered unique lines; optional, slow-ish)
  wafer     /home/claude/kuiper2/cosmos/wafer.tsv       (every commit, unix time + repo index; optional)
  repos     /home/claude/kuiper2/cosmos/repos.tsv

Outputs:
  /tmp/vk/laws/laws.json        every law with numbers, verdict, evidence keys, visual and translation rules
  /tmp/vk/laws/sentences.json   law sentences for a fixed sample of files (for the Big Bang writers)
  laws/demo/data.js             a small deterministic subgraph for the offline canvas demo

Deterministic: no randomness, no network, no clock (dates come from the inputs). Standard library only.
Run:  python3 laws.py [--graph P] [--identity P] ... [--out DIR] [--demo DIR] [--no-lines]
"""
import argparse
import collections
import itertools
import json
import math
import os
import re
import sys

HERE = os.path.dirname(os.path.abspath(__file__))
DEFAULTS = {
    'graph': '/tmp/site8/explore-code/build_graph.json',
    'graph_old': '/tmp/site7/explore-code/build_graph.json',
    'identity': '/tmp/vk/7/identity.json',
    'manifest': '/tmp/vk/clean/manifest.json',
    'lines': '/home/claude/src/stars/LINES.md',
    'wafer': '/home/claude/kuiper2/cosmos/wafer.tsv',
    'repos': '/home/claude/kuiper2/cosmos/repos.tsv',
}
RULES = 'estate-laws-v1'

# Edge kinds that are a USE of the target (it is loaded, run, imported, fetched). Not uses: a comment that
# mentions a URL, a navigation link between pages, and a URL named in text.
NOT_USE = {'comment-url', 'link', 'estate-url'}
# A path folder or file name carrying a 12 or 14 digit time stamp (YYYYMMDDhhmm[ss]).
TS = re.compile(r'(?<![0-9])(20[0-9]{2})(0[1-9]|1[0-2])([0-3][0-9])([0-2][0-9])([0-5][0-9])([0-5][0-9])?(?![0-9])')
NAMED_DATA = re.compile(r'^(JSON|GeoJSON|CSV|Parquet|TSV|NDJSON|SQLite|YAML|TOML|text) file [^\s]+$')

# Thresholds fixed before measuring. A law HOLDS if its test passes, PARTLY if the main test passes and a
# stated secondary test fails (or the reverse), DOES NOT HOLD otherwise.
THRESH = {
    'gravity_top5_share': 0.50,      # top 5% of used files receive >= 50% of all uses
    'field_closed_share': 0.50,      # >= 50% of named data files that are read are also written in the estate
    'entropy_rho': 0.0,              # copy share rises with time: Spearman rho > 0 over dated days
    'inertia_rho': 0.0,              # heavier files keep more of their lines across copies: rho > 0
    'kirchhoff_leak_share': 0.05,    # <= 5% of files that take something in give nothing out
    'induction_lift': 1.5,           # P(user changed | used changed) / P(user changed | used unchanged) >= 1.5
}


# ---------------------------------------------------------------------------------------------- helpers
def load_json(p):
    with open(p, encoding='utf-8') as fh:
        return json.load(fh)


def ranks(xs):
    """Average ranks (1-based) with ties sharing the mean rank."""
    order = sorted(range(len(xs)), key=lambda i: xs[i])
    r = [0.0] * len(xs)
    i = 0
    while i < len(order):
        j = i
        while j + 1 < len(order) and xs[order[j + 1]] == xs[order[i]]:
            j += 1
        for k in range(i, j + 1):
            r[order[k]] = (i + j) / 2.0 + 1
        i = j + 1
    return r


def pearson(a, b):
    n = len(a)
    if n < 3:
        return None
    ma, mb = sum(a) / n, sum(b) / n
    va = sum((x - ma) ** 2 for x in a)
    vb = sum((y - mb) ** 2 for y in b)
    if va == 0 or vb == 0:
        return None
    return sum((x - ma) * (y - mb) for x, y in zip(a, b)) / math.sqrt(va * vb)


def spearman(a, b):
    r = pearson(ranks(a), ranks(b))
    return None if r is None else round(r, 4)


def gini(xs):
    xs = sorted(xs)
    n, s = len(xs), sum(xs)
    if n == 0 or s == 0:
        return 0.0
    cum = sum((i + 1) * x for i, x in enumerate(xs))
    return round((2.0 * cum) / (n * s) - (n + 1.0) / n, 4)


def r4(x):
    return None if x is None else round(x, 4)


def verdict(ok, partly=False):
    return 'HOLDS' if ok else ('PARTLY' if partly else 'DOES NOT HOLD')


# ---------------------------------------------------------------------------------------------- loading
class Estate:
    """The inputs plus a few derived indexes shared by every law."""

    def __init__(self, paths, read_lines=True):
        self.paths = paths
        self.g = load_json(paths['graph'])
        self.files = self.g['files']
        self.n = len(self.files)
        idn = load_json(paths['identity'])
        self.idn = idn
        self.I = {int(k): v for k, v in idn['files'].items()}
        self.manifest = load_json(paths['manifest']) if os.path.exists(paths['manifest']) else None
        self.g_old = load_json(paths['graph_old']) if paths.get('graph_old') and os.path.exists(paths['graph_old']) else None
        self.read_lines = read_lines
        self.repo_commit = {r['repo']: r['commit'] for r in self.g['repos']}
        self.core = sorted(r['repo'] for r in self.g['repos'] if r.get('core'))
        # use edges: importer -> imported
        self.uses = [(a, b, k) for a, b, k, _res in self.g['edges'] if k not in NOT_USE and a != b]
        self.users = collections.defaultdict(set)   # b -> set of a
        self.used = collections.defaultdict(set)    # a -> set of b
        for a, b, _k in self.uses:
            self.users[b].add(a)
            self.used[a].add(b)
        self.mass = [len(self.users[i]) for i in range(self.n)]

    def key(self, i):
        """The file's permanent evidence key: repo@commit path:1-N blob."""
        rec = self.I.get(i)
        if rec and rec.get('keys', {}).get('key'):
            return rec['keys']['key']
        f = self.files[i]
        return '%s@%s %s:1-%d' % (f['repo'], self.repo_commit.get(f['repo'], '?'), f['path'], f['lines'])

    def label(self, i):
        f = self.files[i]
        return '%s/%s' % (f['repo'], f['path'])


# ---------------------------------------------------------------------------------------------- the laws
def law_gravity(E):
    """Gravity: use concentrates. Mass = number of distinct files that use a file."""
    m = E.mass
    total = sum(m)
    used_files = sorted((x for x in m if x > 0), reverse=True)
    n_used = len(used_files)
    top5 = max(1, int(math.ceil(0.05 * n_used)))
    top1 = max(1, int(math.ceil(0.01 * n_used)))
    share5 = sum(used_files[:top5]) / total if total else 0
    share1 = sum(used_files[:top1]) / total if total else 0
    heavy = sorted(range(E.n), key=lambda i: (-m[i], i))[:10]
    # attraction is local? share of uses that stay inside the user's repo, for the 50 heaviest bodies
    top50 = sorted(range(E.n), key=lambda i: (-m[i], i))[:50]
    intra = sum(1 for b in top50 for a in E.users[b] if E.files[a]['repo'] == E.files[b]['repo'])
    allu = sum(len(E.users[b]) for b in top50)
    cross_repo_heavy = [i for i in heavy if len({E.files[a]['repo'] for a in E.users[i]}) > 1]
    ok = share5 >= THRESH['gravity_top5_share']
    return {
        'id': 'G1', 'name': 'Gravity', 'analogy': 'Mass attracts: heavily used files pull their users towards them.',
        'law': 'Use concentrates: a few files carry most of the estate\'s uses.',
        'means': 'If you count, for every file, how many other files load, import, run or fetch it, a small '
                 'number of files account for most of those uses. They are the heavy bodies.',
        'measure': 'mass(f) = number of distinct files with a use edge to f (edge kinds except comment-url, link, '
                   'estate-url). Test: top 5%% of used files receive >= %d%% of all use edges.' % int(THRESH['gravity_top5_share'] * 100),
        'falsified_by': 'The top 5% of used files receiving less than half of all uses.',
        'numbers': {
            'use_edges': total, 'files_used_at_least_once': n_used, 'files': E.n,
            'top5pct_files': top5, 'top5pct_share': r4(share5), 'top1pct_files': top1, 'top1pct_share': r4(share1),
            'gini_mass_over_used_files': gini(used_files),
            'heaviest_mass': m[heavy[0]] if heavy else 0,
            'top50_uses_from_same_repo_share': r4(intra / allu) if allu else None,
            'heaviest10_used_from_several_repos': len(cross_repo_heavy),
        },
        'heaviest': [{'file': i, 'mass': m[i], 'repos_using': len({E.files[a]['repo'] for a in E.users[i]}),
                      'key': E.key(i)} for i in heavy],
        'verdict': verdict(ok),
        'note': ('Use is spread more evenly than the law says: the top 5%% of used files carry %.0f%% of uses (Gini %.2f), and '
                 'the heaviest file has %d users. What does hold is that attraction is local: %.0f%% of the uses of the 50 '
                 'heaviest files come from their own repository.' % (100 * share5, gini(used_files), m[heavy[0]] if heavy else 0,
                                                                    100 * (intra / allu if allu else 0))),
        'evidence': [E.key(i) for i in heavy[:3]],
    }


def _named(item):
    return bool(NAMED_DATA.match(item))


def law_field(E):
    """Electromagnetism: a named data file is a field between the files that write it and those that read it."""
    producers = collections.defaultdict(set)
    consumers = collections.defaultdict(set)
    for f in E.files:
        dc = f.get('data_contracts') or {}
        for x in dc.get('out', []):
            if _named(x):
                producers[x].add(f['id'])
        for x in dc.get('in', []):
            if _named(x):
                consumers[x].add(f['id'])
    read = set(consumers)
    closed = sorted(read & set(producers))
    open_items = sorted(read - set(producers))
    lines = sum(len(producers[x]) * len(consumers[x]) for x in closed)
    # are field lines also code edges? a producer and consumer joined by a use edge in either direction
    joined = 0
    pairs = 0
    for x in closed:
        for p in producers[x]:
            for c in consumers[x]:
                if p == c:
                    continue
                pairs += 1
                if c in E.used[p] or p in E.used[c]:
                    joined += 1
    share = len(closed) / len(read) if read else 0
    strongest = sorted(closed, key=lambda x: (-(len(producers[x]) * len(consumers[x])), x))[:8]
    ok = share >= THRESH['field_closed_share']
    return {
        'id': 'F1', 'name': 'Electromagnetism (fields)',
        'analogy': 'A field joins a source to every body that feels it, without touching.',
        'law': 'Every named data file that is read is written somewhere in the estate.',
        'means': 'Files talk through data files as much as through imports. If the estate were closed, every '
                 'named data file a module reads would be produced by another module, and a field line would '
                 'join them even where no import does.',
        'measure': 'From data_contracts: a named data item ("JSON file x.json", "GeoJSON file ...", ...). '
                   'closed share = items read that some file also writes / all items read. Test >= %d%%.' % int(THRESH['field_closed_share'] * 100),
        'falsified_by': 'Fewer than half of the named data files that are read having a writer in the estate.',
        'numbers': {
            'named_items_read': len(read), 'named_items_written': len(producers), 'closed_items': len(closed),
            'closed_share': r4(share), 'open_items_read_only': len(open_items), 'field_lines': lines,
            'producer_consumer_pairs': pairs, 'pairs_also_joined_by_a_code_edge': joined,
            'pairs_joined_share': r4(joined / pairs) if pairs else None,
        },
        'strongest_fields': [{'item': x, 'writers': len(producers[x]), 'readers': len(consumers[x]),
                              'writer_key': E.key(min(producers[x]))} for x in strongest],
        'open_examples': open_items[:8],
        'verdict': verdict(ok),
        'note': ('Only %.0f%% of named data files that are read have a recorded writer, and only %.1f%% of writer-reader '
                 'pairs are also joined by a code edge, so data files are a second wiring the import graph does not show. '
                 'The open share is an upper bound on what comes from outside: a writer that builds its file name at run '
                 'time may not be recorded by the extractor (not checked here).' % (100 * share, 100 * (joined / pairs if pairs else 0))),
        'evidence': [E.key(min(producers[x])) for x in strongest[:3]],
        '_producers': producers, '_consumers': consumers,
    }


def _lines_md(path):
    """Read stars/LINES.md: numbers must be unique, rising and within the stated range."""
    head = None
    nums = 0
    prev = 0
    rising = True
    dup = 0
    mx = 0
    seen_prev = set()
    with open(path, encoding='utf-8', errors='replace') as fh:
        for ln in fh:
            if head is None and ln.strip() and not ln.startswith('#'):
                head = ln.strip()[:200]
            tab = ln.find('\t')
            if tab <= 0 or not ln[:tab].isdigit():
                continue
            k = int(ln[:tab])
            nums += 1
            if k <= prev:
                rising = False
                if k == prev:
                    dup += 1
            prev = k
            mx = max(mx, k)
    del seen_prev
    m = re.search(r'([0-9,]+) unique lines, numbered 1 to ([0-9,]+)', head or '')
    stated = (int(m.group(1).replace(',', '')), int(m.group(2).replace(',', ''))) if m else (None, None)
    return {'rows': nums, 'rising': rising, 'repeats': dup, 'max_number': mx,
            'stated_unique_lines': stated[0], 'stated_max_number': stated[1]}


def law_conservation(E):
    """Conservation: keys (file id, commit, blob, line range, line numbers) never change; words may."""
    c = E.idn.get('checks', {})
    out = {
        'files': E.n,
        'identity_blob_found_at_clone_head': c.get('files_blob_found_at_clone_head'),
        'identity_commit_equals_graph_commit': sum(1 for i, v in E.I.items()
                                                   if v['keys']['commit'] == E.repo_commit.get(v['repo'])),
        'identity_id_path_matches_graph': sum(1 for i, v in E.I.items()
                                              if i < E.n and (v['repo'], v['path']) == (E.files[i]['repo'], E.files[i]['path'])),
    }
    two_cuts = None
    if E.g_old:
        A = {(f['repo'], f['path']): f for f in E.g_old['files']}
        B = {(f['repo'], f['path']): f for f in E.files}
        com = set(A) & set(B)
        ea = set(map(tuple, E.g_old['edges']))
        eb = set(map(tuple, E.g['edges']))
        ca = {r['repo']: r['commit'] for r in E.g_old['repos']}
        two_cuts = {
            'cut_before': E.g_old['cut'], 'cut_after': E.g['cut'],
            'files_before': len(A), 'files_after': len(B), 'files_in_both': len(com),
            'id_kept': sum(A[k]['id'] == B[k]['id'] for k in com),
            'lines_kept': sum(A[k]['lines'] == B[k]['lines'] for k in com),
            'section_kept': sum(A[k]['section'] == B[k]['section'] for k in com),
            'repo_commit_kept': sum(ca.get(r) == E.repo_commit[r] for r in E.repo_commit),
            'repos': len(E.repo_commit),
            'edges_kept': len(ea & eb), 'edges_before': len(ea), 'edges_after': len(eb),
            'title_kept': sum(A[k]['title'] == B[k]['title'] for k in com),
            'synopsis_kept': sum(A[k]['synopsis'] == B[k]['synopsis'] for k in com),
        }
    mod = c.get('modular', {})
    lines = None
    if E.read_lines and E.paths.get('lines') and os.path.exists(E.paths['lines']):
        lines = _lines_md(E.paths['lines'])
    keys_ok = (out['identity_blob_found_at_clone_head'] == E.n and out['identity_commit_equals_graph_commit'] == E.n
               and out['identity_id_path_matches_graph'] == E.n)
    cuts_ok = bool(two_cuts) and all(two_cuts[k] == two_cuts['files_in_both'] for k in ('id_kept', 'lines_kept', 'section_kept')) \
        and two_cuts['edges_kept'] == two_cuts['edges_after'] and two_cuts['repo_commit_kept'] == two_cuts['repos']
    lines_ok = lines is None or (lines['rising'] and lines['repeats'] == 0 and lines['rows'] == lines['stated_unique_lines']
                                 and lines['max_number'] <= (lines['stated_max_number'] or 0))
    one_to_one = mod.get('number_to_several_family_shas', 0) == 0 and mod.get('family_sha_to_several_numbers', 0) == 0
    ok = keys_ok and cuts_ok and lines_ok and one_to_one
    partly = keys_ok and cuts_ok and lines_ok and not one_to_one
    return {
        'id': 'C1', 'name': 'Conservation',
        'analogy': 'Charge and momentum are conserved; the shape of things is not.',
        'law': 'A key, once issued, never changes and is never reused; descriptions may change freely.',
        'means': 'File ids, commits, blob hashes, line ranges and the numbered line keys of the modular star '
                 'are the conserved quantities. Titles and synopses are the free energy: they can be rewritten '
                 'between builds without breaking anything that cites a key.',
        'measure': 'Between two cuts of the graph: ids, line counts, sections, repo commits and edges identical; '
                   'identity keys reproduce at the clone head; LINES.md numbers unique and rising and the count '
                   'matches its header; modular number <-> function-family hash one to one.',
        'falsified_by': 'One file whose id, line count or commit differs between two cuts with the same commits; '
                        'one line number used twice; one number pointing at two different function families.',
        'numbers': {'identity': out, 'two_cuts': two_cuts, 'lines_md': lines,
                    'modular_number_to_several_family_shas': mod.get('number_to_several_family_shas'),
                    'modular_family_sha_to_several_numbers': mod.get('family_sha_to_several_numbers'),
                    'modular_places_unmatched': mod.get('places_at_pinned_commit_unmatched'),
                    'modular_places_matched': mod.get('places_at_pinned_commit_matched')},
        'verdict': verdict(ok, partly),
        'note': ('Keys are conserved across the two cuts and in LINES.md. The exception is the modular function '
                 'index as read by identity.py: %s numbers map to more than one function-family hash and %s hash to '
                 'more than one number, so at function level the one-to-one rule is broken in a few places.'
                 % (mod.get('number_to_several_family_shas'), mod.get('family_sha_to_several_numbers'))) if not one_to_one else '',
        'evidence': [E.key(0), 'graph cut %s sha256 %s' % (E.idn['graph']['cut'], E.idn['graph']['sha256'])],
    }


def _stamp(path):
    m = TS.search(path)
    if not m:
        return None
    return '%s-%s-%s' % (m.group(1), m.group(2), m.group(3))


def law_entropy(E):
    """Entropy: copies accumulate over time unless distilled."""
    by_day = collections.defaultdict(lambda: [0, 0, 0, 0])  # files, near-copy files, functions, copied functions
    for f in E.files:
        d = _stamp(f['path'])
        if not d:
            continue
        rec = E.I.get(f['id'])
        if not rec:
            continue
        row = by_day[d]
        row[0] += 1
        if rec['verdict']['verdict'] in ('near-copy-of',):
            row[1] += 1
        for fn in rec.get('functions', []):
            row[2] += 1
            if fn.get('verdict') in ('copy', 'copy-estate'):
                row[3] += 1
    days = sorted(d for d, r in by_day.items() if r[0] >= 10)
    idx = list(range(len(days)))
    file_share = [by_day[d][1] / by_day[d][0] for d in days]
    fdays = [d for d in days if by_day[d][2] >= 20]
    fn_share = [by_day[d][3] / by_day[d][2] for d in fdays]
    rho_files = spearman(idx, file_share) if len(days) >= 3 else None
    rho_fn = spearman(list(range(len(fdays))), fn_share) if len(fdays) >= 3 else None
    cnt = E.idn['counts']
    fv = cnt['function_verdicts']
    copies_fn = fv.get('copy', 0) + fv.get('copy-estate', 0)
    man = E.manifest or {}
    set_aside = len(man.get('set_aside', []))
    main_view = len(man.get('main_view', []))
    ok_now = copies_fn / cnt['functions'] > 0.5
    rising = rho_fn is not None and rho_fn > THRESH['entropy_rho']
    rising_files = rho_files is not None and rho_files > THRESH['entropy_rho']
    half = len(fdays) // 2
    first = sum(by_day[d][3] for d in fdays[:half]) / max(1, sum(by_day[d][2] for d in fdays[:half]))
    second = sum(by_day[d][3] for d in fdays[half:]) / max(1, sum(by_day[d][2] for d in fdays[half:]))
    pooled_rising = second >= first
    ok = ok_now and rising and rising_files and pooled_rising
    partly = ok_now and (rising or rising_files or pooled_rising) and not ok
    return {
        'id': 'S1', 'name': 'Entropy',
        'analogy': 'Disorder grows in a closed system unless work is done to remove it.',
        'law': 'Copies accumulate over time unless someone distils them.',
        'means': 'Code is copied into dated release and session folders. Each copy is cheap; together they make '
                 'the estate harder to read. The clean pipeline is the work done against it.',
        'measure': 'Level: share of functions whose identity verdict is copy or copy-estate. Trend: for files in '
                   'folders dated YYYYMMDDhhmm, per day (>= 10 files), the near-copy share of files and (>= 20 '
                   'functions) the copied share of functions; Spearman rho against day order, and the pooled copied share '
                   'of the later half of days against the earlier half. Test: level > 50%, both rho > 0 and later >= earlier.',
        'falsified_by': 'The copied share falling (rho <= 0) as dated folders accumulate, with no distillation applied.',
        'numbers': {
            'functions': cnt['functions'], 'copied_functions': copies_fn,
            'copied_function_share': r4(copies_fn / cnt['functions']),
            'file_verdicts': cnt['verdicts'],
            'dated_days_used': len(days), 'first_day': days[0] if days else None, 'last_day': days[-1] if days else None,
            'rho_near_copy_file_share_vs_day': rho_files,
            'function_days_used': len(fdays), 'rho_copied_function_share_vs_day': rho_fn,
            'copied_function_share_first_half_days': r4(first),
            'copied_function_share_second_half_days': r4(second),
            'distilled_main_view': main_view, 'distilled_set_aside': set_aside,
            'set_aside_share': r4(set_aside / E.n) if E.n else None,
        },
        'series': [{'day': d, 'files': by_day[d][0], 'near_copy_files': by_day[d][1],
                    'functions': by_day[d][2], 'copied_functions': by_day[d][3]} for d in days],
        'verdict': verdict(ok, partly),
        'note': '' if ok else ('The level is high (%.0f%% of functions are copies) and both day-rank correlations are '
                               'positive but weak (%s, %s over %d days), while the pooled copied share fell from %.0f%% '
                               'to %.0f%% between the earlier and later halves. Accumulation is shown; growth is not.'
                               % (100.0 * copies_fn / cnt['functions'], rho_files, rho_fn, len(days), 100 * first, 100 * second)),
        'evidence': ['identity.json counts.function_verdicts', 'clean manifest graph_sha256 %s' % man.get('graph_sha256')],
    }


def _copy_components(E):
    """Files joined by identity near-copy-of verdicts (union find)."""
    par = list(range(E.n))

    def find(x):
        while par[x] != x:
            par[x] = par[par[x]]
            x = par[x]
        return x
    for i, v in sorted(E.I.items()):
        vd = v['verdict']
        if vd['verdict'] == 'near-copy-of' and vd.get('of_file') is not None and i < E.n:
            a, b = find(i), find(vd['of_file'])
            if a != b:
                par[max(a, b)] = min(a, b)
    return [find(x) for x in range(E.n)]


def law_inertia(E, comp):
    """Inertia: heavy files resist change. Among near copies, similarity to the kept file vs mass."""
    sim, mass = [], []
    for i, v in sorted(E.I.items()):
        vd = v['verdict']
        if vd['verdict'] == 'near-copy-of' and vd.get('similarity') is not None and vd.get('of_file') is not None:
            sim.append(vd['similarity'])
            mass.append(E.mass[vd['of_file']])
    rho = spearman(mass, sim)
    heavy = [s for s, m in zip(sim, mass) if m >= 5]
    light = [s for s, m in zip(sim, mass) if m == 0]
    # secondary: repo level. Commits in the last 30 days of the wafer per repo vs repo mass (uses from outside).
    repo_rho = None
    repo_n = 0
    wafer = E.paths.get('wafer')
    repos = E.paths.get('repos')
    if wafer and repos and os.path.exists(wafer) and os.path.exists(repos):
        names = {}
        with open(repos, encoding='utf-8') as fh:
            for ln in fh:
                if ln.startswith('#') or not ln.strip():
                    continue
                p = ln.rstrip('\n').split('\t')
                names[int(p[0])] = p[1]
        commits = []
        with open(wafer, encoding='utf-8') as fh:
            for ln in fh:
                if ln.startswith('#') or not ln.strip():
                    continue
                p = ln.split('\t')
                commits.append((int(p[0]), int(p[2])))
        last = max(t for t, _ in commits)
        recent = collections.Counter(names.get(r) for t, r in commits if t > last - 30 * 86400)
        total = collections.Counter(names.get(r) for t, r in commits)
        rmass = collections.Counter()
        for a, b, _k in E.uses:
            ra, rb = E.files[a]['repo'], E.files[b]['repo']
            if ra != rb:
                rmass[rb] += 1
        rs = sorted(r for r in E.repo_commit if total.get(r))
        repo_n = len(rs)
        repo_rho = spearman([rmass[r] for r in rs], [recent[r] / total[r] for r in rs]) if repo_n >= 3 else None
    ok_file = rho is not None and rho > THRESH['inertia_rho']
    ok_repo = repo_rho is not None and repo_rho < 0
    return {
        'id': 'I1', 'name': 'Inertia',
        'analogy': 'A heavy body needs more force to move.',
        'law': 'The more a file is used, the less its copies drift from it.',
        'means': 'If heavy code resists change, then when it is copied into a new folder the copy should keep '
                 'more of its lines than a copy of a little-used file does.',
        'measure': 'For every identity verdict near-copy-of: similarity (share of normalised lines shared with the kept '
                   'file) against the kept file\'s mass. Test: Spearman rho > 0. Secondary, repository level: share '
                   'of a repository\'s commits that fall in the wafer\'s last 30 days against the uses it receives '
                   'from other repositories; inertia predicts rho < 0.',
        'falsified_by': 'Copies of heavy files drifting as much as or more than copies of light ones (rho <= 0).',
        'numbers': {
            'near_copies': len(sim), 'rho_similarity_vs_kept_file_mass': rho,
            'mean_similarity_kept_mass_ge5': r4(sum(heavy) / len(heavy)) if heavy else None, 'n_mass_ge5': len(heavy),
            'mean_similarity_kept_mass_0': r4(sum(light) / len(light)) if light else None, 'n_mass_0': len(light),
            'repos_compared': repo_n, 'rho_recent_commit_share_vs_cross_repo_uses': repo_rho,
        },
        'verdict': verdict(ok_file and ok_repo, ok_file != ok_repo),
        'note': ('Copies of heavy files drift as much as copies of unused ones (mean similarity %s vs %s; rho %s), and at '
                 'repository level the most used repositories are not quieter (rho %s). On this estate heavy code is '
                 'copied and changed like everything else.' % (r4(sum(heavy) / len(heavy)) if heavy else None,
                                                                  r4(sum(light) / len(light)) if light else None, rho, repo_rho)),
        'evidence': ['identity.json files[*].verdict.similarity', 'kuiper2 cosmos/wafer.tsv (unix, repo_index, sha12)'],
    }


def law_kirchhoff(E):
    """Kirchhoff current law: what flows into a file flows out of it."""
    takes = gives = leaks = sources = isolated = 0
    leak_files = []
    for f in E.files:
        i = f['id']
        dc = f.get('data_contracts') or {}
        fin = bool(dc.get('in')) or bool(E.used[i])
        fout = bool(dc.get('out')) or bool(E.users[i])
        if fin:
            takes += 1
            if fout:
                gives += 1
            else:
                leaks += 1
                leak_files.append(i)
        elif fout:
            sources += 1
        else:
            isolated += 1
    share = leaks / takes if takes else 0
    test_re = re.compile(r'(^|/)(tests?|spec|__tests__)/|(^|/)test_[^/]*$|[._-](test|spec)\.[a-z]+$|(^|/)verify[^/]*$', re.I)
    tests = [i for i in leak_files if test_re.search(E.files[i]['path'])]
    share_ex = (leaks - len(tests)) / (takes - len(tests)) if takes - len(tests) else 0
    by_stage = collections.Counter(E.files[i]['stage'] for i in leak_files)
    by_status = collections.Counter(E.files[i]['canonical_status'] for i in leak_files)
    ok = share <= THRESH['kirchhoff_leak_share']
    return {
        'id': 'K9', 'name': 'Kirchhoff (what flows in flows out)',
        'analogy': 'At a junction the current in equals the current out (Ventusltd/law L9).',
        'law': 'Every file that takes something in gives something out.',
        'means': 'A file that reads data or imports code should hand a result on: to another file, to a page, a '
                 'drawing, a data file or a commit. A file that only takes in is a leak: its work goes nowhere the '
                 'graph can see.',
        'measure': 'in = named inputs in data_contracts.in or at least one use edge out of the file; out = '
                   'data_contracts.out or at least one file using it. leak = in and not out. Test: leaks <= %d%% of '
                   'files that take something in.' % int(THRESH['kirchhoff_leak_share'] * 100),
        'falsified_by': 'More than 5% of files that take something in giving nothing out.',
        'numbers': {'files_taking_in': takes, 'balanced': gives, 'leaks': leaks, 'leak_share': r4(share),
                    'leaks_that_are_tests_or_checks': len(tests), 'leak_share_with_tests_as_ground': r4(share_ex),
                    'sources_out_only': sources, 'isolated_no_in_no_out': isolated,
                    'leaks_by_stage': dict(sorted(by_stage.items())), 'leaks_by_status': dict(sorted(by_status.items()))},
        'leak_examples': [{'file': i, 'key': E.key(i), 'in': (E.files[i]['data_contracts'] or {}).get('in', [])[:3]}
                          for i in leak_files[:6]],
        'verdict': verdict(ok),
        'note': ('%d of the %d leaks are tests or checks, whose result is a pass or fail rather than data; treating '
                 'them as the earth return (like a circuit\'s ground) still leaves %.0f%% of files leaking, above the '
                 '%d%% threshold.' % (len(tests), leaks, 100 * share_ex, int(THRESH['kirchhoff_leak_share'] * 100))),
        'evidence': [E.key(i) for i in leak_files[:3]],
        '_leaks': set(leak_files),
    }


def law_induction(E, comp):
    """Faraday induction: a change in a used file induces a change in the files that use it."""
    fam = {}
    for i, v in E.I.items():
        fam[i] = frozenset(fn['family_sha'] for fn in v.get('functions', []) if fn.get('family_sha'))
    byc = collections.defaultdict(list)
    for a, b, _k in E.uses:
        byc[(comp[a], comp[b])].append((a, b))
    t = collections.Counter()
    examples = {}
    for key in sorted(byc):
        lst = sorted(set(byc[key]))
        for (a, b), (a2, b2) in itertools.combinations(lst, 2):
            if a == a2 or b == b2:
                continue
            if not fam.get(a) or not fam.get(b) or not fam.get(a2) or not fam.get(b2):
                continue
            k = (fam[b] != fam[b2], fam[a] != fam[a2])
            t[k] += 1
            examples.setdefault(k, (a, b, a2, b2))
    cc, cu, uc, uu = t[(True, True)], t[(True, False)], t[(False, True)], t[(False, False)]
    p1 = cc / (cc + cu) if cc + cu else None
    p0 = uc / (uc + uu) if uc + uu else None
    lift = (p1 / p0) if p1 is not None and p0 else None
    ok = lift is not None and lift >= THRESH['induction_lift']
    ex = examples.get((True, True))
    return {
        'id': 'FA', 'name': 'Faraday induction',
        'analogy': 'A changing current in one coil induces a current in the coil beside it.',
        'law': 'When a used file changes, the files that use it change with it.',
        'means': 'The estate keeps many dated copies of the same small systems. Where a system was copied twice and '
                 'the used file differs between the two copies, the file that uses it should differ too, more '
                 'often than when the used file is the same.',
        'measure': 'Copy families = files joined by identity near-copy-of. A replicated pair = use edges A->B and '
                   'A2->B2 with A, A2 in one family and B, B2 in another (A != A2, B != B2, all with functions). '
                   '"Changed" = the set of function-family hashes differs. lift = P(A changed | B changed) / '
                   'P(A changed | B unchanged). Test: lift >= %.1f.' % THRESH['induction_lift'],
        'falsified_by': 'Users changing no more often when the used file changed than when it did not (lift <= 1).',
        'numbers': {'replicated_pairs': cc + cu + uc + uu, 'used_changed_user_changed': cc,
                    'used_changed_user_same': cu, 'used_same_user_changed': uc, 'used_same_user_same': uu,
                    'p_user_changed_given_used_changed': r4(p1), 'p_user_changed_given_used_same': r4(p0),
                    'lift': r4(lift)},
        'note': ('Pairs share files, so they are not independent trials, and only %d pairs have a changed used file; the '
                 'lift is descriptive, not a significance test. %d of %d users changed with the file they use; %d of %d '
                 'changed although it did not, so change also arrives from elsewhere.' % (cc + cu, cc, cc + cu, uc, uc + uu)),
        'example': ({'user': E.key(ex[0]), 'used': E.key(ex[1]), 'user_copy': E.key(ex[2]), 'used_copy': E.key(ex[3])}
                    if ex else None),
        'verdict': verdict(ok),
        'evidence': [E.key(x) for x in ex] if ex else [],
    }


def law_key(E):
    """Kuiper's first law: no claim without a key."""
    keyed = sum(1 for i in range(E.n) if E.I.get(i, {}).get('keys', {}).get('sha256') and E.I[i]['keys'].get('git_blob'))
    man = E.manifest or {}
    mv = man.get('main_view', [])
    sa = man.get('set_aside', [])
    mv_keyed = sum(1 for r in mv if r.get('key'))
    sa_evid = sum(1 for r in sa if r.get('evidence'))
    prov = collections.Counter(f.get('achieves_provenance', '') for f in E.files)
    name_only = prov.get('name', 0)
    claims_ok = keyed == E.n and mv_keyed == len(mv) and sa_evid == len(sa)
    return {
        'id': 'K1', 'name': 'Kuiper\'s first law (no claim without a key)',
        'analogy': 'A measurement without a reference frame is not a measurement.',
        'law': 'Every statement carries a key anyone can recompute; a statement without one is a candidate.',
        'means': 'Positions, verdicts and set-aside decisions all cite a commit, a blob or a hash. Plain-English '
                 'descriptions are claims too: one built only from a file\'s name has no key behind it and should '
                 'say it is a candidate.',
        'measure': 'files with sha256 + git blob in identity; clean main-view rows with a key; set-aside rows with '
                   'evidence; synopsis provenance (achieves_provenance) counted, "name" = candidate.',
        'falsified_by': 'One placed body, verdict or set-aside row with no key or evidence.',
        'numbers': {'files': E.n, 'files_keyed': keyed, 'main_view_rows': len(mv), 'main_view_keyed': mv_keyed,
                    'set_aside_rows': len(sa), 'set_aside_with_evidence': sa_evid,
                    'achieves_provenance': dict(sorted(prov.items())), 'descriptions_from_name_only': name_only,
                    'descriptions_from_name_only_share': r4(name_only / E.n)},
        'verdict': verdict(claims_ok and name_only == 0, claims_ok and name_only > 0),
        'note': ('Every structural claim is keyed. %d descriptions (%.0f%%) rest on the file name alone and are '
                 'candidates under this law until they say so.' % (name_only, 100.0 * name_only / E.n)) if name_only else '',
        'evidence': [E.key(0), 'clean manifest %s' % man.get('graph_sha256')],
    }


_CUT = re.compile(r'^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}([+-]\d{2}:\d{2}|Z)$')


def _minutes(a, b):
    import datetime
    fa = datetime.datetime.fromisoformat(a.replace('Z', '+00:00'))
    fb = datetime.datetime.fromisoformat(b.replace('Z', '+00:00'))
    return round((fb - fa).total_seconds() / 60.0, 1)


def law_light(E):
    """Light: everything you see is the past. Every layer carries its cut with an offset."""
    layers = [('graph', E.g.get('cut'))]
    layers.append(('identity (graph it read)', E.idn.get('graph', {}).get('cut')))
    if E.manifest:
        layers.append(('clean manifest (graph it read)', E.manifest.get('graph_cut')))
    if E.g_old:
        layers.append(('graph, earlier cut', E.g_old.get('cut')))
    stamped = [(n, c) for n, c in layers if c and _CUT.match(c)]
    newest = max(c for _n, c in stamped) if stamped else None
    ages = {n: _minutes(c, newest) for n, c in stamped} if newest else {}
    ok = len(stamped) == len(layers)
    stale = {n: a for n, a in ages.items() if a > 0}
    return {
        'id': 'L11', 'name': 'Light (everything you see is the past)',