GLOBALGRID2050 / EXPLORE CODE

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

Test Apply and 4 more files

A test in the clean folder of Cosmic that checks Apply and Noise. It merges tests (`MergeTests`) and guards tests (`GuardTests`).

685 lines of Python from cosmic, in 5 files. Topic: Kuiper, cosmos and drawing engines. Section 1095 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 Apply test · cosmic / tools/explore/clean/test_apply.py lines 1–221
  2. Test CI test · cosmic / tools/explore/clean/test_ci.py lines 1–39
  3. Test Families test · cosmic / tools/explore/clean/test_families.py lines 1–43
  4. Test Noise test · cosmic / tools/explore/clean/test_noise.py lines 1–170
  5. Test Units test · cosmic / tools/explore/clean/test_units.py lines 1–212

Test Apply

A test in the clean folder of Cosmic that checks Apply and Noise. It merges tests (`MergeTests`) and guards tests (`GuardTests`).

testcosmic / tools/explore/clean/test_apply.py · lines 1–221 of 221 · Entry point · pattern test_parse_key (shared by 2 files)

What it does
It tests its inputs. Defines 34 functions or classes, including graph, key, rec, run, aside. Uses libraries json, os, subprocess, sys, tempfile. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file p.json; JSON file x.json; JSON file families.json; JSON file f.json; JSON file g.json; JSON file noise.json; JSON file m.json. Out: JSON file.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for `clean/apply.py` (clean-manifest-v1).
Why it matters
Guards the behaviour of Apply, Noise and Families.
Application
cosmic · tools/explore/clean · test
Uses
Apply (import), Noise (script call), Families (script call), Units (script call), json, os, subprocess, sys, tempfile, unittest
Used by
none found
Produces
graph, key, rec, run, aside, KeyTests, MergeTests, GuardTests, CliTests
Defines here
graph, key, rec, run, aside, KeyTests, test_parse_key, test_parse_category, MergeTests, test_partition_and_counts, test_threshold_and_keep, test_human_wins, test_tie_breaks_by_category_order, test_partial_units_are_annotations, test_chain_repointed, test_cycle_keeps_smallest_key, test_copy_of_noise, test_rejections_and_bad_targets, test_wrong_schema_and_missing_input, test_blob_mismatch_is_warning, test_deterministic_order_independent, GuardTests, g2, k2, r2, m2, test_size_mismatch_kept, test_version_helpers, test_canonical_rechosen_by_reach_then_version, test_unversioned_canonical_not_beaten_by_version
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/clean/test_apply.py:1-221 · blob 99d922d339e9045d5a0cce543147ab0c75d2623e · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Tests for clean/apply.py (clean-manifest-v1). Run: python3 -m pytest clean/test_apply.py"""
import json
import os
import subprocess
import sys
import tempfile
import unittest

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

C = "a" * 40
B = "b" * 40


def graph(n=8):
    return {"cut": "cut-1", "repos": [{"repo": "r", "commit": C}, {"repo": "s", "commit": C}],
            "files": [{"id": i, "repo": "r" if i < 6 else "s", "path": "d/f%d.js" % i, "lines": 10} for i in range(n)]}


def key(i, a=1, b=10, repo=None):
    return "%s@%s d/f%d.js:%d-%d %s" % (repo or ("r" if i < 6 else "s"), C, i, a, b, B)


def rec(i, cat, conf=0.9, proposer="noise.py", target=None, **kw):
    r = {"file_id": i, "key": key(i), "category": cat + ((" " + target) if target else ""),
         "reason": "because", "evidence": ["fact"], "confidence": conf, "proposer": proposer}
    r.update(kw)
    return r


def run(recs, **kw):
    return apply.merge(graph(), [("p.json", {"schema": "clean-proposals-v1", "proposer": "t", "graph_cut": "cut-1"},
                                  recs)], **kw)


def aside(m):
    return {x["file_id"]: x for x in m["set_aside"]}


class KeyTests(unittest.TestCase):
    def test_parse_key(self):
        k = apply.parse_key("globalgrid2050@%s a b/c.js:3-9 %s" % (C, B))
        self.assertEqual(k, ("globalgrid2050", C, "a b/c.js", 3, 9, B))
        self.assertIsNone(apply.parse_key("r@%s x.js:9-3 %s" % (C, B)))
        self.assertIsNone(apply.parse_key("r x.js:1-3 %s" % B))
        self.assertEqual(apply.parse_key("r@%s x.js:1-3 -" % C)[5], "-")

    def test_parse_category(self):
        self.assertEqual(apply.parse_category("keep"), ("keep", None))
        self.assertEqual(apply.parse_category("near-copy-of " + key(1))[0], "near-copy-of")
        self.assertIsNone(apply.parse_category("near-copy-of")[0])
        self.assertIsNone(apply.parse_category("noise-generated " + key(1))[0])
        self.assertIsNone(apply.parse_category("delete-it")[0])


class MergeTests(unittest.TestCase):
    def test_partition_and_counts(self):
        m = run([rec(1, "noise-vendored"), rec(2, "near-copy-of", target=key(3), proposer="families.py")])
        c = m["counts"]
        self.assertEqual(c["main_view"] + c["set_aside"], c["files"])
        self.assertEqual(sorted(aside(m)), [1, 2])
        self.assertEqual(len(m["main_view"]), 6)
        self.assertEqual(c["by_category"], {"noise-vendored": 1, "near-copy-of": 1})
        self.assertEqual(sum(v["main_view"] + v["set_aside"] for v in c["by_repo"].values()), 8)
        self.assertTrue(m["dry_run"])
        self.assertIn("dry run", m["summary"])
        self.assertIn("Nothing was deleted", m["summary"])

    def test_threshold_and_keep(self):
        m = run([rec(1, "noise-minified", conf=0.5), rec(2, "noise-minified", conf=0.7), rec(2, "keep", conf=0.8),
                 rec(3, "noise-minified", conf=0.7), rec(3, "keep", conf=0.3)])
        self.assertEqual(sorted(aside(m)), [3])
        self.assertEqual(aside(m)[3]["also_proposed"][0]["category"], "keep")
        self.assertEqual(sorted(aside(run([rec(1, "noise-minified", conf=0.5)], min_confidence=0.4))), [1])

    def test_human_wins(self):
        m = run([rec(1, "noise-generated", conf=1.0), rec(1, "keep", conf=0.1, proposer="human:owner")])
        self.assertEqual(aside(m), {})

    def test_tie_breaks_by_category_order(self):
        m = run([rec(1, "unit-duplicate-of", target=key(2), proposer="units.py"), rec(1, "noise-generated")])
        self.assertEqual(aside(m)[1]["category"], "noise-generated")

    def test_partial_units_are_annotations(self):
        r = rec(1, "unit-duplicate-of", target=key(2, 3, 5), proposer="units.py")
        r["key"] = key(1, 3, 6)
        m = run([r])
        self.assertEqual(aside(m), {})
        self.assertEqual(m["annotations"][0]["file_id"], 1)
        self.assertEqual(m["annotations"][0]["target_file_ids"], [2])
        r2 = dict(r, covers_whole_file=True)
        self.assertEqual(sorted(aside(run([r2]))), [1])

    def test_chain_repointed(self):
        m = run([rec(1, "near-copy-of", target=key(2)), rec(2, "family-older-than", target=key(3))])
        a = aside(m)
        self.assertEqual(a[1]["target_file_id"], 3)
        self.assertEqual(a[1]["repointed_from"], key(2))
        self.assertNotIn(3, a)

    def test_cycle_keeps_smallest_key(self):
        m = run([rec(1, "near-copy-of", target=key(2)), rec(2, "near-copy-of", target=key(1))])
        self.assertEqual(sorted(aside(m)), [2])
        self.assertEqual(aside(m)[2]["target_file_id"], 1)
        self.assertTrue(any("cycle" in w for w in m["warnings"]))

    def test_copy_of_noise(self):
        m = run([rec(1, "noise-vendored"), rec(2, "near-copy-of", target=key(1))])
        self.assertEqual(aside(m)[2]["target_set_aside"], "noise-vendored")

    def test_rejections_and_bad_targets(self):
        bad = [rec(1, "nonsense"), dict(rec(2, "keep"), key="garbage"), {"key": key(3)},
               rec(4, "noise-generated", conf=1.5), dict(rec(5, "keep"), key=key(9, repo="zzz"))]
        m = run(bad + [rec(5, "near-copy-of", target="r@%s nope.js:1-2 %s" % (C, B))])
        self.assertEqual(m["counts"]["records_rejected"], 5)
        self.assertEqual(aside(m), {})
        self.assertTrue(any("does not resolve" in w for w in m["warnings"]))

    def test_wrong_schema_and_missing_input(self):
        m = apply.merge(graph(), [("x.json", {"schema": "other"}, [rec(1, "noise-generated")]),
                                  ("families.json", {"missing": True, "proposer": ""}, [])])
        self.assertEqual(m["counts"]["records_rejected"], 1)
        self.assertIn("Not yet available: families.json", m["summary"])

    def test_blob_mismatch_is_warning(self):
        m = run([rec(1, "noise-generated")], blob_lookup=lambda repo, specs: {s: "c" * 40 for s in specs})
        self.assertIn(1, aside(m))
        self.assertTrue(any("blob" in w for w in m["warnings"]))

    def test_deterministic_order_independent(self):
        recs = [rec(1, "noise-vendored"), rec(2, "near-copy-of", target=key(3)), rec(4, "keep"),
                rec(4, "noise-data-blob", conf=0.9)]
        a = json.dumps(run(recs), sort_keys=True)
        b = json.dumps(run(list(reversed(recs))), sort_keys=True)
        self.assertEqual(a, b)


class GuardTests(unittest.TestCase):
    def g2(self, specs):
        g = {"cut": "cut-1", "repos": [{"repo": "r", "commit": C}], "files": []}
        for i, (path, lines, reach) in enumerate(specs):
            g["files"].append({"id": i, "repo": "r", "path": path, "lines": lines, "reachable": reach})
        return g

    def k2(self, g, i):
        f = g["files"][i]
        return "r@%s %s:1-%d %s" % (C, f["path"], f["lines"], B)

    def r2(self, g, i, t, conf=0.95):
        return {"file_id": i, "key": self.k2(g, i), "category": "near-copy-of " + self.k2(g, t), "reason": "x",
                "evidence": ["e"], "confidence": conf, "proposer": "families.py"}

    def m2(self, g, recs):
        return apply.merge(g, [("f.json", {"schema": "clean-proposals-v1"}, recs)])

    def test_size_mismatch_kept(self):
        g = self.g2([("homepage_versions/a.html", 21, True), ("homepage_versions/b.html", 203, True),
                     ("x/c.js", 100, True), ("x/d.js", 80, True)])
        m = self.m2(g, [self.r2(g, 0, 1), self.r2(g, 3, 2)])
        self.assertEqual(sorted(aside(m)), [3])        # 80/100 = 0.8 passes, 21/203 does not
        m = apply.merge(g, [("f.json", {}, [self.r2(g, 0, 1), self.r2(g, 3, 2)])], size_ratio=0.85)
        self.assertEqual(aside(m), {})

    def test_version_helpers(self):
        self.assertEqual(apply.version_of("homepage_versions/v028/index.html"), 28)
        self.assertEqual(apply.version_of("iterations/i0083-x/a.js"), 83)
        self.assertEqual(apply.version_of("solar-bess-topology-v7/a.js"), 7)
        self.assertEqual(apply.version_of("src/view.js"), -1)
        self.assertEqual(apply.version_of("lib/vite.config.js"), -1)

    def test_canonical_rechosen_by_reach_then_version(self):
        g = self.g2([("h/v028/a.html", 100, True), ("h/v031/a.html", 100, True), ("h/v040/a.html", 100, False)])
        # proposer picked v028 by date; v031 is reachable and higher; v040 is higher but unreached
        m = self.m2(g, [self.r2(g, 1, 0), self.r2(g, 2, 0)])
        a = aside(m)
        self.assertEqual(sorted(a), [0, 2])
        self.assertEqual(a[0]["target_file_id"], 1)
        self.assertEqual(a[2]["target_file_id"], 1)
        self.assertTrue(any("re-chosen" in w for w in m["warnings"]))
        self.assertEqual(m["counts"]["main_view"] + m["counts"]["set_aside"], 3)

    def test_unversioned_canonical_not_beaten_by_version(self):
        g = self.g2([("m/202612020205-engine.js", 100, True), ("c/202611180026-sandbox-v9-8.js", 100, True)])
        self.assertEqual(aside(self.m2(g, [self.r2(g, 1, 0)]))[1]["target_file_id"], 0)

    def test_unreached_canonical_gives_way(self):
        g = self.g2([("a/x.js", 100, False), ("b/v2/x.js", 100, True)])
        a = aside(self.m2(g, [self.r2(g, 1, 0)]))
        self.assertEqual(a[0]["target_file_id"], 1)

    def test_no_versions_keeps_proposer_choice(self):
        g = self.g2([("a/x.js", 100, True), ("b/x.js", 100, True)])
        self.assertEqual(aside(self.m2(g, [self.r2(g, 1, 0)]))[1]["target_file_id"], 0)


class CliTests(unittest.TestCase):
    def test_cli_writes_manifest_and_jsonl(self):
        with tempfile.TemporaryDirectory() as d:
            g = os.path.join(d, "g.json")
            json.dump(graph(), open(g, "w"))
            p = os.path.join(d, "noise.json")
            with open(p, "w") as fh:
                fh.write(json.dumps({"schema": "clean-proposals-v1", "proposer": "noise.py"}) + "\n")
                fh.write(json.dumps(rec(1, "noise-generated")) + "\n")
            out = os.path.join(d, "m.json")
            subprocess.run([sys.executable, os.path.join(HERE, "apply.py"), "--graph", g, "--input", p, "--out", out,
                            "--no-verify-blobs"], check=True, capture_output=True)
            m = json.load(open(out))
            self.assertEqual(m["schema"], "clean-manifest-v1")
            self.assertEqual(m["counts"]["set_aside"], 1)
            self.assertEqual(len(m["graph_sha256"]), 64)
            first = open(out).read()
            subprocess.run([sys.executable, os.path.join(HERE, "apply.py"), "--graph", g, "--input", p, "--out", out,
                            "--no-verify-blobs"], check=True, capture_output=True)
            self.assertEqual(open(out).read(), first)


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

Test CI

A test in the clean folder of Cosmic that checks CI. It sets up (`setUp`) and is built from the ci test class (`CiTest`) and the man step (`man`).

testcosmic / tools/explore/clean/test_ci.py · lines 1–39 of 39 · Entry point

What it does
It tests its inputs. Defines CiTest, setUp, man, test_sane, test_required_step_failure_writes_no_manifest. Uses libraries json, os, sys, tempfile, unittest. Side effects: reads or writes files.
Inputs & outputs
In: JSON file g.json; JSON file m.json; JSON file missing.json. Out: JSON file.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for `clean/ci.py`'s fail-safe checks.
Why it matters
Guards the behaviour of CI.
Application
cosmic · tools/explore/clean · test
Uses
CI (import), json, os, sys, tempfile, unittest
Used by
none found
Produces
CiTest
Defines here
CiTest, setUp, man, test_sane, test_required_step_failure_writes_no_manifest
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/clean/test_ci.py:1-39 · blob aed7c9de78933696dd20a0bb272aba82569f5a54 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Tests for clean/ci.py's fail-safe checks. Run: python3 -m pytest clean/test_ci.py"""
import json
import os
import sys
import tempfile
import unittest

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


class CiTest(unittest.TestCase):
    def setUp(self):
        self.d = tempfile.mkdtemp()
        self.graph = os.path.join(self.d, 'g.json')
        json.dump({'files': [{'id': i} for i in range(10)]}, open(self.graph, 'w'))

    def man(self, kept, aside, reason='r'):
        p = os.path.join(self.d, 'm.json')
        json.dump({'schema': 'clean-manifest-v1', 'main_view': [{}] * kept,
                   'set_aside': [{'reason': reason}] * aside}, open(p, 'w'))
        return p

    def test_sane(self):
        self.assertIsNone(ci.sane(self.man(8, 2), self.graph, 0.25))
        self.assertIn('!=', ci.sane(self.man(8, 1), self.graph, 0.25))
        self.assertIn('limit', ci.sane(self.man(5, 5), self.graph, 0.25))
        self.assertIn('no reason', ci.sane(self.man(8, 2, ''), self.graph, 0.25))

    def test_required_step_failure_writes_no_manifest(self):
        out = os.path.join(self.d, 'out', 'manifest.json')
        rc = ci.main(['--graph', os.path.join(self.d, 'missing.json'), '--src', self.d,
                      '--work', os.path.join(self.d, 'w'), '--out', out])
        self.assertEqual(rc, 1)
        self.assertFalse(os.path.exists(out))


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

Test Families

A test in the clean folder of Cosmic that checks Families. It sets up class (`setUpClass`) and is built from the families tests class (`FamiliesTests`).

testcosmic / tools/explore/clean/test_families.py · lines 1–43 of 43 · Entry point · pattern test_deterministic (shared by 11 files)

What it does
It tests its inputs. Defines FamiliesTests, setUpClass, test_contract_shape, test_targets_stay, test_deterministic. Uses libraries json, os, sys, tempfile, unittest.
Inputs & outputs
In: JSON file identity-files.json; JSON file build_graph.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for `clean/families.py` (contract shape, targets stay, determinism).
Why it matters
Guards the behaviour of Families.
Application
cosmic · tools/explore/clean · test
Uses
Families (import), json, os, sys, tempfile, unittest
Used by
none found
Produces
FamiliesTests
Defines here
FamiliesTests, setUpClass, test_contract_shape, test_targets_stay, test_deterministic
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/clean/test_families.py:1-43 · blob 6eace776c1afea04d3c382f3f45e638fc22504d6 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: transform · effects: none found · domain stage: unknown · users: none · canonical: unknown
"""Tests for clean/families.py (contract shape, targets stay, determinism)."""
import json
import os
import sys
import tempfile
import unittest

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

IDENT = "/tmp/vk/7/identity-files.json"
GRAPH = "/tmp/site7/explore-code/build_graph.json"


@unittest.skipUnless(os.path.exists(IDENT) and os.path.exists(GRAPH), "inputs missing")
class FamiliesTests(unittest.TestCase):
    @classmethod
    def setUpClass(cls):
        cls.res = families.build(IDENT, GRAPH, "/home/claude/src")

    def test_contract_shape(self):
        self.assertEqual(self.res["schema"], "clean-proposals-v1")
        for r in self.res["proposals"]:
            for k in ("file_id", "key", "category", "reason", "evidence", "confidence", "proposer"):
                self.assertIn(k, r)
            self.assertTrue(r["category"].startswith("near-copy-of "))
            self.assertGreaterEqual(r["similarity"], families.MIN_SIM)
            self.assertTrue(0 < r["confidence"] <= 1)
            self.assertTrue(r["evidence"])

    def test_targets_stay(self):
        set_aside = {r["file_id"] for r in self.res["proposals"]}
        for r in self.res["proposals"]:
            self.assertNotIn(r["target_file_id"], set_aside)
            self.assertNotEqual(r["target_file_id"], r["file_id"])

    def test_deterministic(self):
        self.assertEqual(json.dumps(self.res, sort_keys=True),
                         json.dumps(families.build(IDENT, GRAPH, "/home/claude/src"), sort_keys=True))


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

Test Noise

A test in the clean folder of Cosmic that checks Noise. It is built from the verdict step (`verdict`), the minified step (`minified`) and the classify class (`Classify`).

testcosmic / tools/explore/clean/test_noise.py · lines 1–170 of 170 · Entry point · pattern verdict (shared by 6 files)

What it does
It tests its inputs. Defines 22 functions or classes, including verdict, minified, Classify, test_authored_code_has_no_signal, test_min_in_name. Uses libraries json, os, random, subprocess, sys. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file g.json. Out: JSON file. Coordinate systems named: OSGB36 / EPSG:27700 (British National Grid).
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for `noise.py`: synthetic files with known answers, plus one end-to-end run on a throwaway git repo.
Why it matters
Guards the behaviour of Noise.
Application
cosmic · tools/explore/clean · test
Uses
Noise (import), json, os, random, subprocess, sys, tempfile, unittest
Used by
none found
Produces
verdict, minified, Classify, EndToEnd
Defines here
verdict, minified, Classify, test_authored_code_has_no_signal, test_min_in_name, test_mangled_long_lines_are_minified, test_dense_but_readable_code_stays, test_node_modules_is_vendored, test_named_library_with_its_header_is_vendored, test_mentioning_a_library_is_not_vendoring, test_vendor_folder_without_header_is_borderline_keep, test_generated_banner, test_written_by_script_is_generated_but_written_by_author_is_not, test_banner_phrase_deep_in_a_comment_is_prose, test_banner_inside_a_string_is_not_a_banner, test_copy_banner_stays_for_the_copy_checks, test_lock_file, test_literal_data_file_is_a_data_blob, test_base64_blob, test_every_finding_has_evidence_and_a_valid_category, EndToEnd, test_run_reads_blobs_at_the_commit_and_writes_contract_keys
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/clean/test_noise.py:1-170 · blob 661f4122c19c48549b9b138fff528c33753b19ba · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: unknown
"""Tests for noise.py: synthetic files with known answers, plus one end-to-end run on a throwaway git repo.

    python3 -m unittest tools/explore/clean/test_noise.py
"""
import json
import os
import random
import subprocess
import sys
import tempfile
import unittest

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


def verdict(path, text, lang="JavaScript"):
    data = text.encode() if isinstance(text, str) else text
    hits = noise.classify({"path": path, "lang": lang}, data, noise.measure(data))
    return hits[0] if hits else None


AUTHORED = "\n".join(
    ["// Distance between two points on the earth, in kilometres.",
     "export function distanceKm(a, b) {",
     "  const rad = (d) => d * Math.PI / 180;",
     "  const dLat = rad(b.lat - a.lat), dLon = rad(b.lon - a.lon);",
     "  const h = Math.sin(dLat / 2) ** 2 + Math.cos(rad(a.lat)) * Math.cos(rad(b.lat)) * Math.sin(dLon / 2) ** 2;",
     "  return 2 * 6371.0088 * Math.asin(Math.sqrt(h));",
     "}"] * 20)


def minified(n_chars=60_000, seed=1):
    rnd = random.Random(seed)
    parts = []
    while sum(map(len, parts)) < n_chars:
        a, b, c = (rnd.choice("abcdefghijklmnopqrstuvwxyz") for _ in range(3))
        parts.append(f"function {a}({b},{c}){{return {b}+{c}*{a}.{b}}}var {a}{b}={c}?{b}:{a};")
    return "".join(parts)


class Classify(unittest.TestCase):
    def test_authored_code_has_no_signal(self):
        self.assertIsNone(verdict("src/geo.js", AUTHORED))

    def test_min_in_name(self):
        v = verdict("lib/app.min.js", "var a=1;\n" * 400)
        self.assertEqual(v[0], "noise-minified")
        self.assertGreaterEqual(v[1], 0.9)

    def test_mangled_long_lines_are_minified(self):
        v = verdict("web/bundle.js", minified())
        self.assertEqual(v[0], "noise-minified")
        self.assertTrue(any("short identifier share" in e for e in v[3]))

    def test_dense_but_readable_code_stays(self):
        dense = ";".join(f"function drawChart{i}(rows,meta){{return rows.map(row=>row.value*meta.scale)}}"
                         for i in range(12))
        v = verdict("web/dense.js", (dense + "\n") * 6)
        self.assertEqual(v[0], "keep")
        self.assertLess(v[1], 0.6)

    def test_node_modules_is_vendored(self):
        v = verdict("web/node_modules/left-pad/index.js", AUTHORED)
        self.assertEqual(v[0], "noise-vendored")

    def test_named_library_with_its_header_is_vendored(self):
        v = verdict("assets/leaflet.js", "/* @preserve\n * Leaflet 1.9.4, a JS library for interactive maps. "
                    "https://leafletjs.com\n * (c) 2010-2023 Vladimir Agafonkin */\n" + AUTHORED)
        self.assertEqual(v[0], "noise-vendored")
        self.assertGreaterEqual(v[1], 0.9)

    def test_mentioning_a_library_is_not_vendoring(self):
        text = "// loads maplibre-gl from the CDN\nconst url = 'https://unpkg.com/maplibre-gl';\n" + AUTHORED
        self.assertIsNone(verdict("web/map.js", text))

    def test_vendor_folder_without_header_is_borderline_keep(self):
        v = verdict("web/vendor/geo.js", AUTHORED)
        self.assertEqual(v[0], "keep")
        self.assertLess(v[1], 0.6)

    def test_generated_banner(self):
        v = verdict("atlas/part.js", "/**\n * TELEPRINT CONTROLS -- GENERATED. DO NOT EDIT THIS FILE.\n */\n" + AUTHORED)
        self.assertEqual(v[0], "noise-generated")
        self.assertGreaterEqual(v[1], 0.95)

    def test_written_by_script_is_generated_but_written_by_author_is_not(self):
        v = verdict("run.sh", "#!/bin/sh\n# Written by automation/new_version.py from the template.\necho hi\n",
                    lang="Shell")
        self.assertEqual(v[0], "noise-generated")
        self.assertIsNone(verdict("t.js", "// Written by OPUS-5 tester in the form of tools/x.cjs\n" + AUTHORED))
        self.assertIsNone(verdict("t.js", "/**\n * built by hand: an owner is never inferred\n */\n" + AUTHORED))

    def test_banner_phrase_deep_in_a_comment_is_prose(self):
        text = "/**\n * Build.\n *\n * Notes.\n *\n * every stale map has the same cause: an artefact generated by a\n" \
               " * script nobody reran.\n */\n" + AUTHORED
        self.assertIsNone(verdict("build.mjs", text))

    def test_banner_inside_a_string_is_not_a_banner(self):
        text = "out.write('// Generated by build.py. Do not edit.')\n" + AUTHORED
        self.assertIsNone(verdict("build.py", text, lang="Python"))

    def test_copy_banner_stays_for_the_copy_checks(self):
        text = "// COPIED UNCHANGED from web/world/bng.mjs at 3adcee9.\n" \
               "// Do not edit here: change the source and re-copy.\n" + AUTHORED
        v = verdict("mod/bng.mjs", text)
        self.assertEqual(v[0], "keep")

    def test_lock_file(self):
        self.assertEqual(verdict("pnpm-lock.yaml", "lockfileVersion: 9\n", lang="YAML")[0], "noise-generated")

    def test_literal_data_file_is_a_data_blob(self):
        rows = ",\n".join(f"[{i}.{i % 97}, {i * 3}.25, \"{i:06d}\"]" for i in range(6000))
        v = verdict("data/points.js", "export default [\n" + rows + "\n];\n")
        self.assertEqual(v[0], "noise-data-blob")

    def test_base64_blob(self):
        b64 = "".join(random.Random(2).choice("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")
                      for _ in range(40_000))
        v = verdict("img/logo.js", f"export const LOGO = 'data:image/png;base64,{b64}';\n")
        self.assertEqual(v[0], "noise-data-blob")

    def test_every_finding_has_evidence_and_a_valid_category(self):
        cats = {"noise-generated", "noise-vendored", "noise-minified", "noise-data-blob", "keep"}
        for path, text in [("a.min.js", "x"), ("b.js", minified()), ("node_modules/c.js", AUTHORED)]:
            for cat, conf, reason, ev in noise.classify({"path": path, "lang": "JavaScript"}, text.encode(),
                                                        noise.measure(text.encode())):
                self.assertIn(cat, cats)
                self.assertTrue(ev and reason)
                self.assertTrue(0 <= conf <= 1)


class EndToEnd(unittest.TestCase):
    def test_run_reads_blobs_at_the_commit_and_writes_contract_keys(self):
        with tempfile.TemporaryDirectory() as tmp:
            src = os.path.join(tmp, "src")
            repo = os.path.join(src, "demo")
            os.makedirs(os.path.join(repo, "web"))
            files = {"web/geo.js": AUTHORED, "web/app.min.js": "var a=1;\n" * 300,
                     "web/part.js": "// Generated by tools/build.mjs. Do not edit.\n" + AUTHORED}
            for p, t in files.items():
                with open(os.path.join(repo, p), "w") as fh:
                    fh.write(t)
            env = dict(os.environ, GIT_AUTHOR_NAME="t", GIT_AUTHOR_EMAIL="t@example.invalid",
                       GIT_COMMITTER_NAME="t", GIT_COMMITTER_EMAIL="t@example.invalid")
            for cmd in (["init", "-q"], ["add", "."], ["commit", "-q", "-m", "x"]):
                subprocess.run(["git", "-C", repo, *cmd], check=True, env=env, capture_output=True)
            commit = subprocess.check_output(["git", "-C", repo, "rev-parse", "HEAD"], text=True).strip()
            # the working tree changes after the commit: evidence must come from the committed blob
            with open(os.path.join(repo, "web/geo.js"), "w") as fh:
                fh.write("// Generated by x.py. Do not edit.\n")
            graph = {"cut": "2026-12-05T00:00:00+00:00", "repos": [{"repo": "demo", "commit": commit}],
                     "files": [{"id": i, "repo": "demo", "path": p, "lang": "JavaScript",
                                "lines": t.count("\n") + 1} for i, (p, t) in enumerate(sorted(files.items()))]}
            gpath = os.path.join(tmp, "g.json")
            with open(gpath, "w") as fh:
                json.dump(graph, fh)
            doc = noise.run(gpath, src)
            self.assertEqual(doc["schema"], "clean-proposals-v1")
            by_path = {r["key"].split(" ")[1].rsplit(":", 1)[0]: r for r in doc["proposals"]}
            self.assertNotIn("web/geo.js", by_path)
            self.assertEqual(by_path["web/app.min.js"]["category"], "noise-minified")
            self.assertEqual(by_path["web/part.js"]["category"], "noise-generated")
            blob = subprocess.check_output(["git", "-C", repo, "rev-parse", f"{commit}:web/part.js"], text=True).strip()
            self.assertEqual(by_path["web/part.js"]["key"], f"demo@{commit} web/part.js:1-{files['web/part.js'].count(chr(10)) + 1} {blob}")
            self.assertEqual(json.dumps(doc), json.dumps(noise.run(gpath, src)))  # deterministic


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

Test Units

A test in the clean folder of Cosmic that checks Units. It runs tests (`RunTests`) and sets up (`setUp`).

testcosmic / tools/explore/clean/test_units.py · lines 1–212 of 212 · Entry point · pattern KeyTests (shared by 2 files)

What it does
It tests its inputs. Defines 20 functions or classes, including mh, unit, graph, KeyTests, test_key_round_trip_with_spaces_in_path. Uses libraries json, os, sys, tempfile, unittest. Side effects: reads or writes files; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file g.json; Parquet file u.parquet; JSON file units.json; JSON file shares.json; JSON file rules.json.
Downstream impact
It is itself an entry point (test); no other file was found loading it.
What it achieves
Tests for `tools/explore/clean/units.py` (unittest, no network).
Why it matters
Guards the behaviour of Units.
Application
cosmic · tools/explore/clean · test
Uses
Units (import), json, os, sys, tempfile, unittest, pathlib, pyarrow, pyarrow.parquet
Used by
none found
Produces
mh, unit, graph, KeyTests, RunTests, MainTests
Defines here
mh, unit, graph, KeyTests, test_key_round_trip_with_spaces_in_path, test_jaccard, RunTests, setUp, run_it, by_name, test_exact_struct_near_and_targets, test_whole_file_unit, test_nested_same_file_small_anonymous_ungraphed, test_shares, test_near_copy_files_are_left_to_families, test_byte_identical_with_clones, test_canonical_prefers_core_and_status, test_deterministic_and_top, MainTests, test_main_writes_contract_files
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/clean/test_units.py:1-212 · blob 9b9ea8f3ea3e4bb31352d54d3e17b615839decfa · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""Tests for tools/explore/clean/units.py (unittest, no network).
Run: python -m unittest tools/explore/clean/test_units.py"""
import json
import os
import sys
import tempfile
import unittest
from pathlib import Path

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

C1, C2, C3 = "a" * 40, "b" * 40, "c" * 40
RULES = dict(U.DEFAULT_RULES, min_tokens=5)


def mh(seed, change=0):
    """64-value MinHash; `change` values differ from the seed signature."""
    base = [(seed * 1000 + i) for i in range(64)]
    return [v + 7 if i < change else v for i, v in enumerate(base)]


def unit(uid, repo, path, a, b, name, exact, struct, sig, kind="function", tokens=40, commit=None, blob="f" * 40):
    return {"unit_id": uid, "repo": repo, "commit": commit or {"r1": C1, "r2": C2, "r3": C3}[repo], "path": path,
            "blob": blob, "kind": kind, "name": name, "line_from": a, "line_to": b, "n_tokens": tokens,
            "exact_hash": exact, "struct_hash": struct, "minhash": sig}


def graph(files, core=("r1",)):
    return {"schema": "explore-build-graph-v1", "cut": "2026-12-05T13:33:26+00:00",
            "repos": [{"repo": r, "commit": c, "core": r in core} for r, c in (("r1", C1), ("r2", C2), ("r3", C3))],
            "files": [dict({"canonical_status": "unknown", "reachable": False, "entry": False}, **f) for f in files]}


class KeyTests(unittest.TestCase):
    def test_key_round_trip_with_spaces_in_path(self):
        k = U.make_key("r1", C1, "dir with space/a b.js", 3, 9, "e" * 40)
        self.assertEqual(k, f"r1@{C1} dir with space/a b.js:3-9 {'e' * 40}")
        p = U.parse_key(k)
        self.assertEqual((p["repo"], p["commit"], p["path"], p["first"], p["last"], p["blob"]),
                         ("r1", C1, "dir with space/a b.js", 3, 9, "e" * 40))

    def test_jaccard(self):
        self.assertEqual(U.est_jaccard(mh(1), mh(1)), 1.0)
        self.assertAlmostEqual(U.est_jaccard(mh(1), mh(1, change=16)), 0.75)


class RunTests(unittest.TestCase):
    def setUp(self):
        self.files = [
            {"id": 0, "repo": "r1", "path": "core/geo.js", "lines": 100, "canonical_status": "production_core",
             "reachable": True},
            {"id": 1, "repo": "r2", "path": "copy/app.js", "lines": 50},
            {"id": 2, "repo": "r3", "path": "other/tool.js", "lines": 20},
            {"id": 3, "repo": "r2", "path": "single.js", "lines": 10},
        ]
        self.units = [
            # exact copy across three files; canonical must be file 0 (production_core, core repo)
            unit("u1", "r2", "copy/app.js", 1, 10, "dist", "E1", "S1", mh(1)),
            unit("u0", "r1", "core/geo.js", 20, 29, "dist", "E1", "S1", mh(1)),
            unit("u2", "r3", "other/tool.js", 1, 20, "dist", "E1", "S1", mh(1)),
            # struct-only copy (renamed)
            unit("u3", "r1", "core/geo.js", 40, 49, "bear", "E2", "S2", mh(2)),
            unit("u4", "r2", "copy/app.js", 20, 29, "heading", "E3", "S2", mh(2)),
            # nested unit inside u1's file range duplicates something too: must be dropped (outer kept)
            unit("u5", "r1", "core/geo.js", 60, 64, "inner", "E4", "S4", mh(4)),
            unit("u6", "r2", "copy/app.js", 3, 7, "inner", "E4", "S4", mh(4)),
            # near variant (Jaccard 0.875)
            unit("u7", "r1", "core/geo.js", 70, 79, "area", "E5", "S5", mh(5)),
            unit("u8", "r2", "copy/app.js", 31, 40, "area2", "E6", "S6", mh(5, change=8)),
            # same-file duplicate only: never proposed
            unit("u9", "r2", "single.js", 1, 4, "twice", "E7", "S7", mh(7)),
            unit("u10", "r2", "single.js", 5, 8, "twice", "E7", "S7", mh(7)),
            # too small and anonymous: ignored
            unit("u11", "r2", "copy/app.js", 41, 43, "tiny", "E8", "S8", mh(8), tokens=3),
            unit("u12", "r1", "core/geo.js", 90, 93, "tiny", "E8", "S8", mh(8), tokens=3),
            unit("u13", "r2", "copy/app.js", 44, 48, "<anonymous>", "E9", "S9", mh(9)),
            unit("u14", "r1", "core/geo.js", 94, 98, "<anonymous>", "E9", "S9", mh(9)),
            # not in the graph
            unit("u15", "r3", "missing.js", 1, 9, "dist", "E1", "S1", mh(1)),
        ]
        self.g = graph(self.files)

    def run_it(self, src=None, **kw):
        return U.run(self.g, self.units, RULES, src, **kw)

    def by_name(self, records):
        return {(r["file_id"], r["unit_name"]): r for r in records}

    def test_exact_struct_near_and_targets(self):
        records, shares, counts, top = self.run_it()
        r = self.by_name(records)
        target = U.make_key("r1", C1, "core/geo.js", 20, 29, "f" * 40)
        self.assertEqual(r[(1, "dist")]["category"], "unit-duplicate-of " + target)
        self.assertEqual(r[(1, "dist")]["confidence"], 0.9)          # no clone given: exact, not byte-identical
        self.assertEqual(r[(1, "dist")]["target_file_id"], 0)
        self.assertEqual(r[(1, "heading")]["confidence"], 0.55)
        self.assertEqual(r[(1, "heading")]["relation"], "struct")
        self.assertEqual(r[(1, "area2")]["relation"], "near")
        self.assertLess(r[(1, "area2")]["confidence"], 0.6)
        self.assertNotIn((0, "dist"), r)                              # the canonical is never proposed
        for rec in records:
            self.assertNotEqual(rec["file_id"], rec["target_file_id"])
            self.assertEqual(rec["proposer"], "units.py")
            for f in ("file_id", "key", "category", "reason", "evidence", "confidence", "proposer"):
                self.assertIn(f, rec)
            U.parse_key(rec["key"])
            U.parse_key(rec["category"].split(" ", 1)[1])

    def test_whole_file_unit(self):
        records, *_ = self.run_it()
        r = self.by_name(records)
        self.assertTrue(r[(2, "dist")]["covers_whole_file"])
        self.assertIn("whole file", r[(2, "dist")]["reason"])
        self.assertFalse(r[(1, "dist")]["covers_whole_file"])

    def test_nested_same_file_small_anonymous_ungraphed(self):
        records, shares, counts, top = self.run_it()
        names = {(r["file_id"], r["unit_name"]) for r in records}
        self.assertNotIn((1, "inner"), names)                         # inside dist 1-10 in file 1
        self.assertNotIn((3, "twice"), names)                         # duplicate only within one file
        self.assertFalse(any(n in ("tiny", "<anonymous>") for _, n in names))
        self.assertEqual(counts["units_dropped"], {"below_min_tokens": 2, "anonymous": 2, "not_in_build_graph": 1})
        self.assertGreaterEqual(counts["nested_dropped"], 1)

    def test_shares(self):
        records, shares, counts, top = self.run_it()
        s = {x["file_id"]: x for x in shares}
        self.assertEqual(len(shares), 4)
        # file 1: dist 1-10, heading 20-29, area2 31-40 -> 30 of 50 lines; exact (>=0.9) only dist -> 10
        self.assertEqual(s[1]["duplicated_lines"], 30)
        self.assertEqual(s[1]["share"], 0.6)
        self.assertEqual(s[1]["duplicated_lines_exact"], 10)
        self.assertEqual(s[0]["share"], 0.0)
        self.assertEqual(s[2]["share"], 1.0)
        self.assertEqual(s[3]["share"], 0.0)

    def test_near_copy_files_are_left_to_families(self):
        records, shares, counts, top = self.run_it(near_copy_files=0.1)
        self.assertFalse(any(r["file_id"] == 1 for r in records))
        self.assertGreater(counts["skipped_whole_file_near_copy"], 0)

    def test_byte_identical_with_clones(self):
        with tempfile.TemporaryDirectory() as d:
            for repo, path, lines in (("r1", "core/geo.js", 100), ("r2", "copy/app.js", 50),
                                      ("r3", "other/tool.js", 20), ("r2", "single.js", 10)):
                p = Path(d, repo, path)
                p.parent.mkdir(parents=True, exist_ok=True)
                body = [f"x{i}" for i in range(lines)]
                if path == "core/geo.js":
                    body[19:29] = [f"line {i}" for i in range(10)]
                if path == "copy/app.js":
                    body[0:10] = [f"line {i}" for i in range(10)]
                if path == "other/tool.js":
                    body[0:20] = [f"  line {i}" for i in range(20)]
                p.write_text("\n".join(body))
            records, *_ = self.run_it(src=d)
            r = self.by_name(records)
            self.assertEqual(r[(1, "dist")]["confidence"], 1.0)
            self.assertEqual(r[(1, "dist")]["relation"], "byte-identical")
            self.assertEqual(r[(2, "dist")]["confidence"], 0.9)        # indentation differs

    def test_canonical_prefers_core_and_status(self):
        self.files[0]["canonical_status"] = "duplicate_candidate"
        self.files[1]["canonical_status"] = "production_core"
        self.g = graph(self.files, core=("r2",))
        records, *_ = self.run_it()
        r = self.by_name(records)
        self.assertEqual(r[(0, "dist")]["target_file_id"], 1)

    def test_deterministic_and_top(self):
        a = self.run_it()
        b = U.run(self.g, list(reversed(self.units)), RULES, None)
        self.assertEqual(json.dumps(a, sort_keys=True), json.dumps(b, sort_keys=True))
        self.assertEqual(a[3][0]["name"], "dist")
        self.assertEqual(a[3][0]["files"], 3)


class MainTests(unittest.TestCase):
    def test_main_writes_contract_files(self):
        try:
            import pyarrow as pa
            import pyarrow.parquet as pq
        except ImportError:
            self.skipTest("pyarrow not installed")
        t = RunTests()
        t.setUp()
        with tempfile.TemporaryDirectory() as d:
            gp, up = Path(d, "g.json"), Path(d, "u.parquet")
            gp.write_text(json.dumps(t.g))
            pq.write_table(pa.Table.from_pylist(t.units), up)
            out, sh = Path(d, "o", "units.json"), Path(d, "o", "shares.json")
            rules = Path(d, "rules.json")
            rules.write_text(json.dumps({"cluster": {"min_tokens": 5}}))
            import contextlib
            import io
            with contextlib.redirect_stdout(io.StringIO()):
                U.main(["--graph", str(gp), "--units", str(up), "--rules", str(rules), "--out", str(out),
                        "--shares", str(sh)])
            p = json.loads(out.read_text())
            self.assertEqual(p["schema"], "clean-proposals-v1")
            self.assertEqual(p["proposer"], "units.py")
            self.assertEqual(p["graph_cut"], t.g["cut"])
            self.assertTrue(p["proposals"])
            s = json.loads(sh.read_text())
            self.assertEqual(s["schema"], "clean-unit-shares-v1")
            self.assertEqual(len(s["files"]), 4)


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