GLOBALGRID2050 / EXPLORE CODE

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

Apply and 1 more file

A Python command-line tool in the clean folder of Cosmic that reads build graph, noise, families and units, using SHA-256.

633 lines of Python from cosmic, in 2 files. Topic: Kuiper, cosmos and drawing engines. Section 1093 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. Apply storage · cosmic / tools/explore/clean/apply.py lines 1–501
  2. CI automation · cosmic / tools/explore/clean/ci.py lines 1–132

Apply

A Python command-line tool in the clean folder of Cosmic that reads build graph, noise, families and units, using SHA-256.

storagecosmic / tools/explore/clean/apply.py · lines 1–501 of 501 · Entry point · pattern git_blobs (shared by 3 files)

What it does
It loads build graph, noise, families and units. Defines 21 functions or classes, including Key, parse_key, parse_category, sha256_file, load_proposals. Uses libraries __future__, argparse, collections, hashlib, json. Side effects: reads or writes files; starts processes.
Inputs & outputs
In: JSON file build_graph.json; JSON file noise.json; JSON file families.json; JSON file units.json; command-line arguments. Out: JSON file.
Downstream impact
Used directly by 2 files: CI (cosmic); Test Apply (cosmic). Reached from 1 other entry point, including Test CI (cosmic).
What it achieves
It parses key (`parse_key`), parses category (`parse_category`) and loads proposals (`load_proposals`). Merge clean-proposals-v1 files into one clean-manifest-v1 (see `clean/CONTRACT.md`). It accepts `--graph`, `--proposals` and `--input`.
Why it matters
Run by CI. Checked by Test Apply.
Application
cosmic · tools/explore/clean · Python CLI
Uses
__future__, argparse, collections, hashlib, json, os, re, subprocess
Used by
run by CI (script call), imported by Test Apply (import)
Produces
Key, parse_key, parse_category, sha256_file, load_proposals, git_blobs, version_of, stamp_of, size_ratio_of, guard_near_copies, file_key_like, merge
Defines here
Key, parse_key, parse_category, sha256_file, load_proposals, git_blobs, version_of, stamp_of, size_ratio_of, _demote, guard_near_copies, score, file_key_like, merge, reject, is_whole, rank, chain, file_key, summary, main
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/apply.py:1-501 · blob 5a174aecb081f57dc0a89ab16d800e12211b8e41 · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: output · effects: filesystem, process · domain stage: unknown · users: none · canonical: supporting_data
"""Merge clean-proposals-v1 files into one clean-manifest-v1 (see clean/CONTRACT.md).

    python3 apply.py [--graph build_graph.json] [--proposals DIR | --input FILE ...]
                     [--out /tmp/vk/clean/manifest.json] [--min-confidence 0.6] [--src /home/claude/src]
                     [--no-verify-blobs] [--approve]

Nothing is ever deleted or edited in any repository, and build.py is not touched. The output is a manifest:
which files stay in the main view, which are set aside (with reasons and evidence), counts and a plain-English
summary. Without --approve the manifest says "dry_run": true (a proposal for the owner to read).

Stdlib only. Deterministic: same inputs give byte-identical output.
"""
from __future__ import annotations

import argparse
import collections
import hashlib
import json
import os
import re
import subprocess
import sys

DEFAULT_GRAPH = "/tmp/site7/explore-code/build_graph.json"
DEFAULT_PROPOSALS = "/tmp/vk/clean/proposals"
DEFAULT_INPUTS = ("noise.json", "families.json", "units.json")
DEFAULT_OUT = "/tmp/vk/clean/manifest.json"
DEFAULT_SRC = "/home/claude/src"

SCHEMA_IN = "clean-proposals-v1"
SCHEMA_OUT = "clean-manifest-v1"
ORDER = ("noise-generated", "noise-vendored", "noise-minified", "noise-data-blob",
         "near-copy-of", "family-older-than", "unit-duplicate-of", "keep")
TARGETED = {"near-copy-of", "family-older-than", "unit-duplicate-of"}
TITLE = {
    "noise-generated": "written by a tool",
    "noise-vendored": "third-party code copied in",
    "noise-minified": "minified or bundled",
    "noise-data-blob": "data dressed as code",
    "near-copy-of": "a near copy of a file that stays",
    "family-older-than": "an older version of a file that stays",
    "unit-duplicate-of": "entirely made of code repeated from elsewhere",
    "keep": "kept",
}
KEY_RX = re.compile(r"^(?P<repo>[^@\s]+)@(?P<commit>[0-9a-f]{7,40}) (?P<path>.+):(?P<a>\d+)-(?P<b>\d+) "
                    r"(?P<blob>[0-9a-f]{40}|-)$")


class Key(tuple):
    """(repo, commit, path, first, last, blob)"""


def parse_key(s: str):
    m = KEY_RX.match(s or "")
    if not m:
        return None
    a, b = int(m["a"]), int(m["b"])
    if a < 1 or b < a:
        return None
    return Key((m["repo"], m["commit"], m["path"], a, b, m["blob"]))


def parse_category(s: str):
    """'near-copy-of <key>' -> ('near-copy-of', '<key>'); 'keep' -> ('keep', None); bad -> (None, why)."""
    s = (s or "").strip()
    token, _, rest = s.partition(" ")
    if token not in ORDER:
        return None, "unknown category %r" % token
    if token in TARGETED:
        if not rest or parse_key(rest) is None:
            return None, "category %s needs a valid target key" % token
        return token, rest
    if rest:
        return None, "category %s takes no target" % token
    return token, None


def sha256_file(path: str) -> str:
    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 load_proposals(path: str):
    """Return (header dict, list of records). Accepts a JSON object or JSON Lines."""
    with open(path, encoding="utf-8") as fh:
        text = fh.read()
    try:
        d = json.loads(text)
        if isinstance(d, dict):
            return d, list(d.get("proposals") or [])
        if isinstance(d, list):
            return {}, d
    except json.JSONDecodeError:
        pass
    recs = [json.loads(line) for line in text.splitlines() if line.strip()]
    head = {}
    if recs and "proposals" not in recs[0] and "key" not in recs[0]:
        head = recs.pop(0)
    return head, recs


def git_blobs(src: str, repo: str, specs: list[str]) -> dict[str, str]:
    """{'<commit>:<path>': blob or ''} via one `git cat-file --batch-check` per repo."""
    clone = os.path.join(src, repo)
    if not specs or not os.path.isdir(os.path.join(clone, ".git")) and not os.path.isfile(os.path.join(clone, ".git")):
        return {}
    try:
        p = subprocess.run(["git", "-C", clone, "cat-file", "--batch-check=%(objectname) %(objecttype)"],
                           input="\n".join(specs) + "\n", capture_output=True, text=True, timeout=300)
    except (OSError, subprocess.SubprocessError):
        return {}
    lines = p.stdout.splitlines()
    out = {}
    for spec, line in zip(specs, lines):
        parts = line.split()
        out[spec] = parts[0] if len(parts) == 2 and parts[1] == "blob" else ""
    return out


VERSION_RX = re.compile(r"(?:^|[/_.\-])(?:v|i)(\d{1,5})(?=$|[/_.\-])", re.I)
STAMP_RX = re.compile(r"(?<!\d)(20\d{6}(?:\d{4})?)(?!\d)")


def version_of(path: str) -> int:
    """Highest numeric version named in the path (v028, i0083, -v7/); -1 if none."""
    nums = [int(m) for m in VERSION_RX.findall(path or "")]
    return max(nums) if nums else -1


def stamp_of(path: str) -> str:
    st = STAMP_RX.findall(path or "")
    return max(st) if st else ""


def size_ratio_of(a: dict, b: dict) -> float:
    la, lb = int(a.get("lines") or 0), int(b.get("lines") or 0)
    hi = max(la, lb)
    return 1.0 if hi == 0 else min(la, lb) / hi


def _demote(a: dict, why: str, extra: str) -> None:
    a["evidence"] = a["evidence"] + [extra, "demoted from %s by apply.py" % a["token"]]
    a["token"], a["target"], a["tfid"] = "keep", None, None
    a["reason"] = why


def guard_near_copies(accepted: list[dict], byid: dict, warnings: list, *, min_ratio: float = 0.7) -> None:
    """Two guards on near-copy-of records (coordinator, 2026-12-05):

    1. Size: if min(lines)/max(lines) between the file and its canonical is below min_ratio, the pair is
       containment, not a copy: the record becomes `keep` with reason "size mismatch".
    2. Version names: within one canonical's group, if any member names a numeric version (v028, i0083):
       an unreached canonical gives way to the best reachable member; otherwise, if the canonical itself names a
       version, the member with the same reach and the higher version (then newer stamp, more lines, lower id)
       becomes canonical. Versions are never compared with an unversioned name. Members are re-pointed and the
       old canonical becomes a near copy of the new one.
    """
    near = [a for a in accepted if a["token"] == "near-copy-of" and a["tfid"] is not None]
    for a in near:
        r = size_ratio_of(byid[a["fid"]], byid[a["tfid"]])
        if r < min_ratio:
            _demote(a, "size mismatch", "size ratio %.2f (%d vs %d lines) below %.2f" % (
                r, byid[a["fid"]].get("lines") or 0, byid[a["tfid"]].get("lines") or 0, min_ratio))
    groups = collections.defaultdict(list)
    for a in accepted:
        if a["token"] == "near-copy-of" and a["tfid"] is not None:
            groups[(a["proposer"], a["tfid"])].append(a)
    for (proposer, canon), recs in sorted(groups.items()):
        members = sorted({canon} | {a["fid"] for a in recs})
        if all(version_of(byid[i]["path"]) < 0 for i in members):
            continue

        def score(i):
            f = byid[i]
            return (version_of(f["path"]), stamp_of(f["path"]), int(f.get("lines") or 0), -i)
        cf = byid[canon]
        reach = [i for i in members if byid[i].get("reachable")]
        if reach and not cf.get("reachable"):
            best = max(reach, key=score)              # reachable first
        elif version_of(cf["path"]) >= 0:
            # versions are compared only between files that both name one
            pool = [i for i in members if version_of(byid[i]["path"]) >= 0
                    and bool(byid[i].get("reachable")) == bool(cf.get("reachable"))]
            best = max(pool, key=score)
        else:
            continue
        if best == canon:
            continue
        bf = byid[best]
        best_key = next(a["key"] for a in recs if a["fid"] == best)
        link = next(a for a in recs if a["fid"] == best)
        warnings.append("near-copy group of file %d (%s): canonical re-chosen as file %d by reachable, then version"
                        % (canon, proposer, best))
        for a in recs:
            if a is link:
                # the old canonical becomes the copy; measured similarity is symmetric
                ck = file_key_like(byid[canon], link)
                a.update(fid=canon, key=ck, k=parse_key(ck), target=best_key, tfid=best,
                         reason="Near copy of %s (%s), which stays: reachable first, then the higher version." %
                                (bf["path"], bf["repo"]),
                         evidence=a["evidence"] + ["re-pointed by apply.py version rule (was canonical)"])
            else:
                a.update(target=best_key, tfid=best,
                         evidence=a["evidence"] + ["re-pointed by apply.py version rule from file %d to file %d; "
                                                   "similarity was measured to file %d" % (canon, best, canon)])
                r = size_ratio_of(byid[a["fid"]], bf)
                if r < min_ratio:
                    _demote(a, "size mismatch", "size ratio %.2f to re-chosen canonical below %.2f" % (r, min_ratio))


def file_key_like(f: dict, sample: dict) -> str:
    """Whole-file key for f, using the commit style of a sibling record (blob unknown: '-')."""
    commit = sample["k"][1] if sample["k"][0] == f["repo"] else "0" * 40
    return "%s@%s %s:1-%d -" % (f["repo"], commit, f["path"], max(1, int(f.get("lines") or 1)))


def merge(graph: dict, inputs: list[tuple[str, dict, list]], *, min_confidence: float = 0.6,
          blob_lookup=None, approve: bool = False, graph_sha256: str = "", size_ratio: float = 0.7) -> dict:
    """Pure merge. inputs = [(path, header, records)]. blob_lookup(repo, [specs]) -> {spec: blob}."""
    files = sorted(graph["files"], key=lambda f: f["id"])
    byid = {f["id"]: f for f in files}
    bypath = {(f["repo"], f["path"]): f for f in files}
    commits = {r["repo"]: r.get("commit", "") for r in graph.get("repos") or []}
    warnings, rejected, in_meta = [], [], []
    accepted = []   # dicts: fid, key, kobj, token, target, tfid, rec, source

    def reject(source, rec, why):
        rejected.append({"source": source, "record": {k: rec.get(k) for k in ("file_id", "key", "category", "proposer")}
                         if isinstance(rec, dict) else rec, "why": why})

    for path, head, recs in inputs:
        meta = {"path": path, "proposer": head.get("proposer", ""), "records": len(recs)}
        if head.get("sha256"):
            meta["sha256"] = head["sha256"]
        if head.get("missing"):
            meta["missing"] = True
        in_meta.append(meta)
        if head and head.get("schema") not in (None, SCHEMA_IN):
            for r in recs:
                reject(path, r, "file schema %r is not %s" % (head.get("schema"), SCHEMA_IN))
            continue
        if head.get("graph_cut") and graph.get("cut") and head["graph_cut"] != graph["cut"]:
            warnings.append("%s was made for graph cut %s, not %s" % (path, head["graph_cut"], graph["cut"]))
        for r in recs:
            if not isinstance(r, dict):
                reject(path, r, "record is not an object")
                continue
            missing = [k for k in ("file_id", "key", "category", "reason", "evidence", "confidence", "proposer")
                       if k not in r]
            if missing:
                reject(path, r, "missing fields: " + ", ".join(missing))
                continue
            k = parse_key(r["key"])
            if k is None:
                reject(path, r, "malformed key")
                continue
            token, target = parse_category(r["category"])
            if token is None:
                reject(path, r, target)
                continue
            try:
                conf = float(r["confidence"])
            except (TypeError, ValueError):
                reject(path, r, "confidence is not a number")
                continue
            if not 0.0 <= conf <= 1.0:
                reject(path, r, "confidence outside 0..1")
                continue
            f = bypath.get((k[0], k[2]))
            if f is None:
                reject(path, r, "key does not resolve to a file in build_graph")
                continue
            if r["file_id"] != f["id"]:
                warnings.append("file_id %s in %s does not match key (file %d); key used" % (r["file_id"], path, f["id"]))
            if commits.get(k[0]) and not commits[k[0]].startswith(k[1]):
                warnings.append("key commit %s for %s differs from build_graph commit %s" % (k[1], k[0], commits[k[0]]))
            tfid = None
            if target:
                tk = parse_key(target)
                tf = bypath.get((tk[0], tk[2]))
                tfid = tf["id"] if tf else None
            accepted.append({"fid": f["id"], "key": r["key"], "k": k, "token": token, "target": target, "tfid": tfid,
                             "conf": conf, "proposer": str(r["proposer"]), "reason": str(r["reason"]),
                             "evidence": [str(e) for e in (r["evidence"] if isinstance(r["evidence"], list)
                                                           else [r["evidence"]])],
                             "whole_flag": r.get("covers_whole_file"), "source": path})

    # blob verification (one batch per repo); a mismatch is a warning, never a rejection
    if blob_lookup:
        need = collections.defaultdict(set)
        for a in accepted:
            if a["k"][5] != "-":
                need[a["k"][0]].add("%s:%s" % (a["k"][1], a["k"][2]))
        found = {}
        for repo in sorted(need):
            for spec, blob in (blob_lookup(repo, sorted(need[repo])) or {}).items():
                found[(repo, spec)] = blob
        bad = collections.Counter()
        for a in accepted:
            spec = (a["k"][0], "%s:%s" % (a["k"][1], a["k"][2]))
            if spec in found and found[spec] and a["k"][5] != "-" and found[spec] != a["k"][5]:
                bad[a["k"][0]] += 1
        for repo, n in sorted(bad.items()):
            warnings.append("%d key(s) in %s carry a blob id that differs from the clone" % (n, repo))

    guard_near_copies(accepted, byid, warnings, min_ratio=size_ratio)

    def is_whole(a):
        lines = int(byid[a["fid"]].get("lines") or 0)
        return (a["k"][3] <= 1 and a["k"][4] >= lines) or a["whole_flag"] is True

    def rank(a):
        human = a["proposer"].startswith("human:")
        return (0 if human else 1, -a["conf"], ORDER.index(a["token"]), a["proposer"], a["key"], a["target"] or "")

    per_file = collections.defaultdict(list)
    partial = collections.defaultdict(list)
    for a in accepted:
        if a["token"] == "unit-duplicate-of" and not is_whole(a):
            partial[a["fid"]].append(a)
        else:
            per_file[a["fid"]].append(a)

    aside = {}   # fid -> winning record
    for fid in sorted(per_file):
        recs = sorted(per_file[fid], key=rank)
        win = recs[0]
        win["others"] = recs[1:]
        if win["token"] == "keep":
            continue
        if win["conf"] < min_confidence and not win["proposer"].startswith("human:"):
            continue
        if win["token"] in TARGETED:
            if win["tfid"] is None:
                warnings.append("file %d: target of %s does not resolve; file stays" % (fid, win["token"]))
                continue
            if win["tfid"] == fid:
                warnings.append("file %d: proposed as a copy of itself; file stays" % fid)
                continue
        aside[fid] = win

    # targets must stay: follow chains, break cycles by smallest key
    def chain(fid):
        seen, cur = [], fid
        while cur in aside and aside[cur]["token"] in TARGETED:
            if cur in seen:
                return seen, cur
            seen.append(cur)
            cur = aside[cur]["tfid"]
        return seen, None

    for fid in sorted(aside):
        if fid not in aside:
            continue
        seen, loop = chain(fid)
        if loop is not None:
            cyc = seen[seen.index(loop):]
            keeper = min(cyc, key=lambda i: aside[i]["key"])
            warnings.append("cycle of copies %s: file %d stays" % (sorted(cyc), keeper))
            del aside[keeper]
    for fid in sorted(aside):
        a = aside[fid]
        if a["token"] not in TARGETED:
            continue
        cur, hops = a["tfid"], 0
        while cur in aside and aside[cur]["token"] in TARGETED:
            cur = aside[cur]["tfid"]
            hops += 1
        a["final"] = cur
        a["hops"] = hops
        a["target_set_aside"] = aside[cur]["token"] if cur in aside else None

    def file_key(f):
        return "%s@%s %s:1-%d -" % (f["repo"], commits.get(f["repo"], "0" * 40), f["path"], max(1, int(f.get("lines") or 1)))

    main_view, set_aside = [], []
    by_cat, by_prop = collections.Counter(), collections.Counter()
    by_repo = collections.defaultdict(lambda: {"main_view": 0, "set_aside": 0})
    for f in files:
        fid = f["id"]
        if fid not in aside:
            main_view.append({"file_id": fid, "key": file_key(f)})
            by_repo[f["repo"]]["main_view"] += 1
            continue
        a = aside[fid]
        item = {"file_id": fid, "key": a["key"], "category": a["token"], "target": None, "target_file_id": None,
                "reason": a["reason"], "evidence": a["evidence"], "confidence": a["conf"], "proposer": a["proposer"],
                "also_proposed": [{"category": o["token"], "proposer": o["proposer"], "confidence": o["conf"]}
                                  for o in a.get("others", [])]}
        if a["token"] in TARGETED:
            final = a.get("final", a["tfid"])
            if final == a["tfid"]:
                item["target"] = a["target"]
            else:
                item["target"] = file_key(byid[final])
                item["repointed_from"] = a["target"]
            item["target_file_id"] = final
            if a.get("target_set_aside"):
                item["target_set_aside"] = a["target_set_aside"]
        set_aside.append(item)
        by_cat[a["token"]] += 1
        by_prop[a["proposer"]] += 1
        by_repo[f["repo"]]["set_aside"] += 1

    annotations = []
    for fid in sorted(partial):
        recs = sorted(partial[fid], key=lambda a: (a["k"][3], a["k"][4], a["key"], a["target"]))
        annotations.append({"file_id": fid, "category": "unit-duplicate-of", "units": len(recs),
                            "target_file_ids": sorted({a["tfid"] for a in recs if a["tfid"] is not None}),
                            "ranges": ["%d-%d" % (a["k"][3], a["k"][4]) for a in recs]})

    counts = {"files": len(files), "main_view": len(main_view), "set_aside": len(set_aside),
              "by_category": {c: by_cat[c] for c in ORDER if by_cat[c]},
              "by_proposer": dict(sorted(by_prop.items())),
              "by_repo": {r: by_repo[r] for r in sorted(by_repo)},
              "records_accepted": len(accepted), "records_rejected": len(rejected),
              "files_with_partial_unit_copies": len(annotations)}
    return {
        "schema": SCHEMA_OUT,
        "dry_run": not approve,
        "graph_cut": graph.get("cut", ""),
        "graph_sha256": graph_sha256,
        "inputs": in_meta,
        "min_confidence": min_confidence,
        "size_ratio": size_ratio,
        "counts": counts,
        "summary": summary(counts, in_meta, approve),
        "main_view": main_view,
        "set_aside": set_aside,
        "annotations": annotations,
        "rejected": rejected,
        "warnings": sorted(set(warnings)),
    }


def summary(c: dict, inputs: list[dict], approve: bool) -> str:
    used = [m["proposer"] or os.path.basename(m["path"]) for m in inputs if not m.get("missing")]
    missing = [os.path.basename(m["path"]) for m in inputs if m.get("missing")]
    s = ["Of %d files in the estate, %d stay in the main view and %d are set aside from it."
         % (c["files"], c["main_view"], c["set_aside"])]
    if c["by_category"]:
        s.append("Set aside: " + "; ".join("%d %s" % (n, TITLE[k]) for k, n in c["by_category"].items()) + ".")
    if c["files_with_partial_unit_copies"]:
        s.append("%d more files share some functions with other files but have their own code too, so they stay "
                 "(listed as annotations)." % c["files_with_partial_unit_copies"])
    s.append("Proposals came from %s." % (", ".join(used) if used else "no proposer"))
    if missing:
        s.append("Not yet available: %s." % ", ".join(missing))
    if c["records_rejected"]:
        s.append("%d proposal records were rejected as malformed (see 'rejected')." % c["records_rejected"])
    s.append("Nothing was deleted or edited in any repository; set-aside files keep their section pages.")
    s.append("This manifest is approved for the build." if approve else
             "This is a dry run for the owner to review; the site build is unchanged.")
    return " ".join(s)


def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--graph", default=DEFAULT_GRAPH)
    ap.add_argument("--proposals", default=DEFAULT_PROPOSALS, help="folder holding noise/families/units .json")
    ap.add_argument("--input", action="append", help="explicit proposal file (repeatable; overrides --proposals)")
    ap.add_argument("--out", default=DEFAULT_OUT)
    ap.add_argument("--min-confidence", type=float, default=0.6)
    ap.add_argument("--src", default=DEFAULT_SRC, help="clones, for blob checks")
    ap.add_argument("--no-verify-blobs", action="store_true")
    ap.add_argument("--size-ratio", type=float, default=0.7, help="near copies below this line ratio are kept")
    ap.add_argument("--approve", action="store_true", help='write "dry_run": false')
    a = ap.parse_args(argv)

    with open(a.graph, encoding="utf-8") as fh:
        graph = json.load(fh)
    paths = a.input or [os.path.join(a.proposals, n) for n in DEFAULT_INPUTS]
    inputs = []
    for p in paths:
        if not os.path.exists(p):
            inputs.append((p, {"missing": True, "proposer": ""}, []))
            continue
        head, recs = load_proposals(p)
        head = dict(head)
        head.pop("proposals", None)
        head["sha256"] = sha256_file(p)
        inputs.append((p, head, recs))
    lookup = None if a.no_verify_blobs else (lambda repo, specs: git_blobs(a.src, repo, specs))
    man = merge(graph, inputs, min_confidence=a.min_confidence, blob_lookup=lookup, approve=a.approve, size_ratio=a.size_ratio,
                graph_sha256=sha256_file(a.graph))
    os.makedirs(os.path.dirname(os.path.abspath(a.out)), exist_ok=True)
    tmp = a.out + ".tmp"
    with open(tmp, "w", encoding="utf-8", newline="\n") as fh:
        json.dump(man, fh, sort_keys=True, indent=1, ensure_ascii=False)
        fh.write("\n")
    os.replace(tmp, a.out)
    print(man["summary"])
    print("wrote %s (%d warnings)" % (a.out, len(man["warnings"])))
    return 0


if __name__ == "__main__":
    sys.exit(main())

CI

A Python command-line tool in the clean folder of Cosmic that reads noise, families, units and identity.

automationcosmic / tools/explore/clean/ci.py · lines 1–132 of 132 · Entry point

What it does
It loads noise, families, units and identity. Defines warn, run, sane, main. Uses libraries argparse, json, os, subprocess, sys. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
Inputs & outputs
In: JSON file noise.json; JSON file families.json; JSON file units.json; JSON file identity-files.json; Parquet file units.parquet; JSON file rules.json; JSON file unit-shares.json; command-line arguments.
Downstream impact
Used directly by 1 file: Test CI (cosmic).
What it achieves
It is built from the warn step (`warn`), the run step (`run`) and the sane step (`sane`). Produce the clean manifest on the build machine, from the build's own outputs (no /tmp inputs). It accepts `--graph`, `--src` and `--work`.
Why it matters
Checked by Test CI.
Application
cosmic · tools/explore/clean · Python CLI
Uses
Noise (script call), Families (script call), Units (script call), Apply (script call), argparse, json, os, subprocess, sys, time
Used by
imported by Test CI (import)
Produces
warn, run, sane, main
Defines here
warn, run, sane, main
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/ci.py:1-132 · blob b5df66db6b906f8357950a8a9d24bb0b6a9b19ce · GitHub at these lines
State
achieves: comment · context: readme_derived · stage: ingest · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: unknown
#!/usr/bin/env python3
"""clean/ci.py: produce the clean manifest on the build machine, from the build's own outputs (no /tmp inputs).

    python tools/explore/clean/ci.py --graph _site/explore-code/build_graph.json --src clones \
        --work _work/clean --out _work/clean/manifest.json

Steps (each a subprocess with its own timeout; outputs stay under --work):
  noise      clean/noise.py                                  REQUIRED
  identity   identity/genome.py --lite (keys only)            REQUIRED for families
  families   clean/families.py                               REQUIRED
  units      vedic-/fingerprints/extract.py + clean/units.py  optional: skipped with a warning when the fingerprint
             units cannot be made here (no vedic- clone, extract fails or times out)
  apply      clean/apply.py --approve                        REQUIRED

Fail-safe: if a required step fails, or the manifest fails its sanity check (every file accounted for, at most
--max-share of files set aside), no manifest is written and the script exits 1, so the site is published without
the cleaned view. Nothing is deleted anywhere: the manifest only says which files leave the main view, and why.
"""
import argparse
import json
import os
import subprocess
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
EXPLORE = os.path.dirname(HERE)


def warn(msg):
    print('[clean] WARNING: %s' % msg, file=sys.stderr)
    if os.environ.get('GITHUB_ACTIONS'):
        print('::warning::clean: %s' % msg)


def run(name, argv, timeout):
    t = time.time()
    print('[clean] %s: %s' % (name, ' '.join(argv[1:])), flush=True)
    try:
        p = subprocess.run(argv, capture_output=True, text=True, timeout=timeout)
    except subprocess.TimeoutExpired:
        warn('%s timed out after %d s' % (name, timeout))
        return False
    if p.returncode != 0:
        tail = (p.stderr or p.stdout or '').strip().splitlines()[-4:]
        warn('%s exited %d: %s' % (name, p.returncode, ' | '.join(tail)))
        return False
    print('[clean] %s: ok (%.1f s) %s' % (name, time.time() - t, (p.stdout or '').strip().splitlines()[-1:]), flush=True)
    return True


def sane(manifest_path, graph_path, max_share):
    """Why the manifest must not be used, or None when it is fine."""
    try:
        man = json.load(open(manifest_path, encoding='utf-8'))
        n = len(json.load(open(graph_path, encoding='utf-8'))['files'])
    except (OSError, ValueError, KeyError) as e:
        return 'unreadable (%s)' % e
    if man.get('schema') != 'clean-manifest-v1':
        return 'schema is %r' % man.get('schema')
    kept, aside = len(man.get('main_view') or []), len(man.get('set_aside') or [])
    if kept + aside != n:
        return 'main view %d + set aside %d != %d files' % (kept, aside, n)
    if aside > max_share * n:
        return '%d of %d files set aside, above the %.0f%% limit' % (aside, n, max_share * 100)
    if any(not r.get('reason') for r in man['set_aside']):
        return 'a set-aside file has no reason'
    return None


def main(argv=None):
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument('--graph', required=True)
    ap.add_argument('--src', required=True, help='folder with one clone per public repository')
    ap.add_argument('--work', required=True, help='scratch folder for proposals (not published)')
    ap.add_argument('--out', required=True, help='manifest path, written only when every required step passed')
    ap.add_argument('--fingerprints', default='', help='vedic-/fingerprints (default <src>/vedic-/fingerprints)')
    ap.add_argument('--max-share', type=float, default=0.25)
    ap.add_argument('--timeout', type=int, default=900)
    a = ap.parse_args(argv)
    py = sys.executable
    work, props = os.path.abspath(a.work), os.path.join(os.path.abspath(a.work), 'proposals')
    os.makedirs(props, exist_ok=True)
    if os.path.exists(a.out):
        os.remove(a.out)
    for stale in ('noise.json', 'families.json', 'units.json'):
        if os.path.exists(os.path.join(props, stale)):
            os.remove(os.path.join(props, stale))
    ok = run('noise', [py, os.path.join(HERE, 'noise.py'), '--graph', a.graph, '--src', a.src,
                       '--out', os.path.join(props, 'noise.json'), '--copy', ''], a.timeout)
    ok = ok and run('identity', [py, os.path.join(EXPLORE, 'identity', 'genome.py'), '--lite', '--graph', a.graph,
                                 '--src', a.src, '--out', os.path.join(work, 'identity')], a.timeout)
    ok = ok and run('families', [py, os.path.join(HERE, 'families.py'), '--graph', a.graph, '--src', a.src,
                                 '--identity', os.path.join(work, 'identity', 'identity-files.json'),
                                 '--out', work], a.timeout)
    if not ok:
        warn('a required cleaning step failed; the site is published without the cleaned view')
        return 1
    fp = a.fingerprints or os.path.join(a.src, 'vedic-', 'fingerprints')
    if os.path.isfile(os.path.join(fp, 'extract.py')):
        units = os.path.join(work, 'fingerprints', 'units.parquet')
        if run('fingerprints', [py, os.path.join(fp, 'extract.py'), '--src', a.src,
                                '--out', os.path.dirname(units)], a.timeout) and os.path.isfile(units):
            rules = os.path.join(fp, 'rules.json')
            if not run('units', [py, os.path.join(HERE, 'units.py'), '--graph', a.graph, '--units', units,
                                 '--src', a.src, '--out', os.path.join(props, 'units.json'),
                                 '--shares', os.path.join(work, 'unit-shares.json')]
                       + (['--rules', rules] if os.path.isfile(rules) else []), a.timeout):
                warn('units skipped; the manifest uses noise and families only')
        else:
            warn('fingerprint units not made; units skipped')
    else:
        warn('no %s/extract.py; units skipped' % fp)
    tmp = a.out + '.tmp'
    if not run('apply', [py, os.path.join(HERE, 'apply.py'), '--graph', a.graph, '--proposals', props,
                         '--src', a.src, '--out', tmp, '--approve'], a.timeout):
        warn('apply.py failed; the site is published without the cleaned view')
        return 1
    why = sane(tmp, a.graph, a.max_share)
    if why:
        warn('manifest refused: %s; the site is published without the cleaned view' % why)
        return 1
    os.replace(tmp, a.out)
    man = json.load(open(a.out, encoding='utf-8'))
    print('[clean] manifest: %d files, %d in the main view, %d set aside %s' % (
        man['counts']['files'], man['counts']['main_view'], man['counts']['set_aside'],
        json.dumps(man['counts'].get('by_category', {}))), flush=True)
    return 0


if __name__ == '__main__':
    sys.exit(main())