In this section
- Families storage · cosmic / tools/explore/clean/families.py lines 1–118
- Noise storage · cosmic / tools/explore/clean/noise.py lines 1–405
Families
A Python command-line tool in the clean folder of Cosmic that reads identity and build graph, using SHA-256.
storagecosmic / tools/explore/clean/families.py · lines 1–118 of 118 · Entry point
- What it does
- It loads identity and build graph. Defines canon_order, _neg, build, find, main. Uses libraries argparse, collections, json, os, re. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file identity-files.json; JSON file build_graph.json; JSON file families.json; command-line arguments. Out: JSON file.
- Downstream impact
- Used directly by 3 files: CI (cosmic); Test Apply (cosmic); Test Families (cosmic). Reached from 1 other entry point, including Test CI (cosmic).
- What it achieves
- It is built from the canon order helper (`canon_order`), the build step (`build`) and the find step (`find`). Near-copy proposals (clean-proposals-v1) built from `identity/genome.py` verdicts. It accepts `--identity`, `--graph` and `--src`.
- Why it matters
- Run by CI. Checked by 2 tests, including Test Apply.
- Application
- cosmic · tools/explore/clean · Python CLI
- Uses
- Genome (sys.path import), argparse, collections, json, os, re, sys
- Used by
- run by CI (script call), run by Test Apply (script call), imported by Test Families (import)
- Produces
- canon_order, build, main
- Defines here
- canon_order, _neg, build, find, 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/families.py:1-118 · blob 7a347dceea6f8f6aa7456de15640d9e2a1139628 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: supporting_data
#!/usr/bin/env python3
"""clean/families.py: near-copy proposals (clean-proposals-v1) built from identity/genome.py verdicts.
Minimal, conservative version (GENOTYPE-17, 2026-12-05). It covers only exact and near-exact groups:
- Edges: identity.json near-copy-of verdicts with line Jaccard >= MIN_SIM (0.9). copy-of edges are also
used, but build.py already keeps one file per blob, so there are 0 of them today.
- Groups are the connected components of those edges.
- Canonical file (the one that stays), by the coordinator's rule: reachable, then newest (the largest
20YYMMDD stamp in the path, using build.py's STAMP), then core repo (build.py CORE_REPOS), then the longest
(most lines), then the smallest key.
- Every other member gets `near-copy-of <canonical key>`. Its similarity is its own line Jaccard to the
canonical, recomputed here. A member whose Jaccard to the canonical is below MIN_SIM gets no proposal,
so it stays. The members get no keep record either (uncertain = leave alone).
- confidence = similarity, capped at 0.99. 1.0 is reserved for byte-identical files.
Never deletes anything. Output: /tmp/vk/clean/families.json and /tmp/vk/clean/proposals/families.json.
Not done yet: renamed/v2/final/backup name families below 0.9 similarity (see identity/README.md handoff).
"""
import argparse
import collections
import json
import os
import re
import sys
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, os.path.join(HERE, "..", "identity"))
from genome import norm_lines # noqa: E402
MIN_SIM = 0.9
STAMP = re.compile(r"(?<!\d)(20\d{6}(?:T?\d{4,6}Z?)?)(?!\d)") # build.py STAMP
CORE_REPOS = {"gridatlas", "ventus-grid-engine", "globalgrid2050", "satnav",
"solar-electrical-topology-analysis-engine-text-based", "pipelinenews"}
def canon_order(f, key):
stamp = max(STAMP.findall(f["path"]) or [""])
return (0 if f["reachable"] else 1, _neg(stamp), 0 if f["repo"] in CORE_REPOS else 1, -f["lines"], key)
def _neg(s):
return tuple(-ord(c) for c in s) + (1,) # larger stamp sorts first; "" sorts last
def build(identity_path, graph_path, src):
with open(identity_path) as fh:
ident = json.load(fh)
with open(graph_path) as fh:
graph = json.load(fh)
fid = {f["id"]: f for f in graph["files"]}
files = ident["files"]
parent = {}
def find(x):
while parent.get(x, x) != x:
x = parent[x]
return x
for k, v in files.items():
vd = v["verdict"]
if vd["verdict"] in ("copy-of", "near-copy-of") and (vd["similarity"] or 0) >= MIN_SIM:
a, b = find(v["id"]), find(vd["of_file"])
if a != b:
parent[max(a, b)] = min(a, b)
groups = collections.defaultdict(list)
for i in {x for x in parent} | set(parent.values()):
groups[find(i)].append(i)
proposals, checked = [], []
for members in groups.values():
members = sorted(set(members))
key = {i: files[str(i)]["keys"]["key"] for i in members}
canon = min(members, key=lambda i: canon_order(fid[i], key[i]))
cl = norm_lines(os.path.join(src, fid[canon]["repo"], fid[canon]["path"]))
for i in members:
if i == canon:
continue
ml = norm_lines(os.path.join(src, fid[i]["repo"], fid[i]["path"]))
sim = round(len(ml & cl) / len(ml | cl), 4) if (ml | cl) else 0.0
if files[str(i)]["keys"]["sha256"] == files[str(canon)]["keys"]["sha256"]:
sim = 1.0
if sim < MIN_SIM:
continue
proposals.append({
"file_id": i, "key": key[i], "category": f"near-copy-of {key[canon]}",
"reason": f"{round(sim * 100)}% of its lines are the same as {fid[canon]['path']} "
f"({fid[canon]['repo']}), which stays.",
"evidence": [f"line-jaccard {sim} to {key[canon]}",
f"sha256 {files[str(i)]['keys']['sha256']}",
f"target sha256 {files[str(canon)]['keys']['sha256']}",
f"group of {len(members)} (identity.json near-copy edges >= {MIN_SIM})",
"canonical rule: reachable, newest stamp, core repo, most lines"],
"confidence": 1.0 if sim == 1.0 else min(0.99, sim),
"proposer": "families.py", "similarity": sim, "target_file_id": canon,
})
checked.append((len(members), canon))
proposals.sort(key=lambda r: r["file_id"])
return {"schema": "clean-proposals-v1", "proposer": "families.py", "graph_cut": graph["cut"],
"rules": {"min_similarity": MIN_SIM, "source": identity_path},
"counts": {"groups": len(groups), "proposals": len(proposals)},
"proposals": proposals}
def main(argv=None):
ap = argparse.ArgumentParser()
ap.add_argument("--identity", default="/tmp/vk/7/identity-files.json")
ap.add_argument("--graph", default="/tmp/site7/explore-code/build_graph.json")
ap.add_argument("--src", default="/home/claude/src")
ap.add_argument("--out", default="/tmp/vk/clean")
a = ap.parse_args(argv)
res = build(a.identity, a.graph, a.src)
os.makedirs(os.path.join(a.out, "proposals"), exist_ok=True)
for p in (os.path.join(a.out, "families.json"), os.path.join(a.out, "proposals", "families.json")):
with open(p, "w") as fh:
json.dump(res, fh, indent=1, sort_keys=True)
print(json.dumps(res["counts"]))
if __name__ == "__main__":
main()Noise
A Python command-line tool in the clean folder of Cosmic that maps NPM shrinkwrap and build graph.
storagecosmic / tools/explore/clean/noise.py · lines 1–405 of 405 · Entry point · pattern classify (shared by 27 files)
- What it does
- It maps NPM shrinkwrap and build graph. Defines 10 functions or classes, including git, tree_blobs, cat_blobs, measure, header_text. Uses libraries __future__, argparse, json, os, re. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Inputs & outputs
- In: JSON file npm-shrinkwrap.json; JSON file build_graph.json; JSON file noise.json; DuckDB queries; command-line arguments.
- Downstream impact
- Used directly by 3 files: CI (cosmic); Test Apply (cosmic); Test Noise (cosmic). Reached from 1 other entry point, including Test CI (cosmic).
- What it achieves
- It is built from the git step (`git`), the tree blobs helper (`tree_blobs`) and the cat blobs helper (`cat_blobs`). Propose files in Explore Code's unique set that are not authored code. It accepts `--graph`, `--src` and `--out`.
- Why it matters
- Run by CI. Checked by 2 tests, including Test Apply.
- Application
- cosmic · tools/explore/clean · Python CLI
- Uses
- __future__, argparse, json, os, re, subprocess, sys, collections
- Used by
- run by CI (script call), run by Test Apply (script call), imported by Test Noise (import)
- Produces
- git, tree_blobs, cat_blobs, measure, header_text, path_segments, classify, run, main
- Defines here
- git, tree_blobs, cat_blobs, measure, header_text, path_segments, classify, is_banner, run, 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/noise.py:1-405 · blob bad8c5d5765e3568241237a8e7dbd64569f14c71 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: supporting_data
"""tools/explore/clean/noise.py - propose files in Explore Code's unique set that are not authored code.
python3 tools/explore/clean/noise.py [--graph /tmp/site7/explore-code/build_graph.json]
[--src /home/claude/src] [--out /tmp/vk/clean/proposals/noise.json]
[--copy /tmp/vk/clean/noise.json]
Writes clean-proposals-v1 records (see CONTRACT.md beside this file). Nothing is deleted or edited anywhere;
every record is a proposal with measurable evidence. Four categories:
noise-minified path contains ".min.", or the file is made of very long lines with little whitespace
noise-vendored third-party code: node_modules/ or vendor/-style folders, or a known library's own header
noise-generated a tool's banner ("generated by", "do not edit", "@generated") in a top-of-file comment,
lock files, bundler output
noise-data-blob data dressed as code: large files that are mostly literals, or mostly embedded base64
Borderline cases are written as `keep` with confidence below 0.6, with the evidence that made them borderline,
so a reader can see why they stayed. Files with no signal at all get no record (they stay in the main view).
The file bytes are read from git at the commit build_graph records (`git cat-file --batch`), so the evidence is
about exactly the blob Explore Code published. Deterministic: same graph and same clones give identical output.
Stdlib only.
"""
from __future__ import annotations
import argparse
import json
import os
import re
import subprocess
import sys
from collections import Counter
RULES = "noise-rules-v1"
PROPOSER = "noise.py"
# --- thresholds (printed into the output so the run states its rules) ---------------------------------------
MIN_LONG_LINE = 1000 # a line this long is "very long"
MINIFIED_AVG = 300 # average characters per non-empty line for a minified file
MINIFIED_WS = 0.12 # whitespace share below which long-line files read as minified
DATA_MIN_BYTES = 50_000 # a data blob must be at least this big
DATA_LITERAL = 0.70 # share of bytes that are literal characters (digits, quotes, punctuation of data)
DATA_KEYWORDS_PER_KB = 1.0 # code keywords per KB below which a large literal-heavy file reads as data
B64_MIN_RUN = 200 # base64 run length that counts as embedded binary
B64_SHARE = 0.5 # share of bytes in base64 runs for a data blob
B64_MIN_BYTES = 20_000
HEADER_LINES = 15 # header text window
GEN_TOP_LINES = 6 # generator banners must sit in the first lines
MINIFIED_AVG_STRICT = 500 # average line length for a minified verdict
MINIFIED_SHORT_IDENT = 0.35 # share of identifiers of one or two characters (mangled names)
VENDOR_SEGMENTS = ("node_modules", "vendor", "vendors", "third_party", "third-party", "thirdparty",
"bower_components", "external", "extern")
LIBS = {
# library name -> (filename pattern, header pattern)
"Leaflet": (r"^leaflet([.-].*)?\.(js|css)$", r"Leaflet \d|leafletjs\.com|\(c\) \d{4}.*Vladimir Agafonkin"),
"D3": (r"^d3([.-].*)?\.js$", r"d3js\.org|https://d3js\.org|Copyright \d{4}.*Mike Bostock"),
"three.js": (r"^three([.-].*)?\.(js|mjs)$", r"three\.js|threejs\.org|Copyright \d{4} Three\.js Authors"),
"jQuery": (r"^jquery([.-].*)?\.js$", r"jQuery v\d|jquery\.(com|org)/license"),
"Chart.js": (r"^chart([.-].*)?\.js$", r"Chart\.js v\d|chartjs\.org"),
"proj4": (r"^proj4([.-].*)?\.js$", r"proj4js"),
"Turf": (r"^turf([.-].*)?\.js$", r"turfjs\.org|@turf/"),
"PapaParse": (r"^papaparse([.-].*)?\.js$", r"Papa Parse|papaparse\.com"),
"pako": (r"^pako([.-].*)?\.js$", r"pako \d|nodeca/pako"),
"MapLibre": (r"^maplibre-gl([.-].*)?\.(js|css)$", r"maplibre-gl|MapLibre GL JS"),
"Mapbox GL": (r"^mapbox-gl([.-].*)?\.(js|css)$", r"mapbox-gl-js|Mapbox GL JS"),
"OpenLayers": (r"^ol([.-].*)?\.(js|css)$", r"openlayers\.org"),
"Cesium": (r"^cesium([.-].*)?\.js$", r"CesiumJS|cesium\.com/license"),
"Lodash": (r"^lodash([.-].*)?\.js$", r"lodash\.com|Lodash <https"),
"Plotly": (r"^plotly([.-].*)?\.js$", r"plotly\.js v\d|plot\.ly"),
"ECharts": (r"^echarts([.-].*)?\.js$", r"Apache ECharts|echarts\.apache\.org"),
"React": (r"^react(-dom)?([.-].*)?\.js$", r"@license React"),
"Vue": (r"^vue([.-].*)?\.js$", r"Vue\.js v\d"),
"Bootstrap": (r"^bootstrap([.-].*)?\.(js|css)$", r"Bootstrap v\d|getbootstrap\.com"),
"Font Awesome": (r"^(all|fontawesome)([.-].*)?\.(css|js)$", r"Font Awesome (Free|Pro) \d"),
"Apache Arrow": (r"^arrow([.-].*)?\.js$", r"apache/arrow|Apache Arrow"),
"DuckDB-Wasm": (r"^duckdb([.-].*)?\.(js|mjs)$", r"duckdb-wasm"),
"hls.js": (r"^hls([.-].*)?\.js$", r"hls\.js"),
"Normalize.css": (r"^normalize([.-].*)?\.css$", r"normalize\.css v\d"),
"Highlight.js": (r"^highlight([.-].*)?\.js$", r"Highlight\.js v\d"),
"Marked": (r"^marked([.-].*)?\.(js|mjs)$", r"marked v\d|markedjs"),
"Shapefile": (r"^shp([.-].*)?\.js$", r"calvinmetcalf/shapefile-js"),
"GeoTIFF": (r"^geotiff([.-].*)?\.js$", r"geotiff\.js"),
"pdf.js": (r"^pdf(\.worker)?([.-].*)?\.(js|mjs)$", r"Mozilla Foundation.*pdf\.js|pdfjs"),
}
LIB_FILE = {k: re.compile(v[0], re.I) for k, v in LIBS.items()}
LIB_HEAD = {k: re.compile(v[1]) for k, v in LIBS.items()}
LICENSE_HEAD = re.compile(r"@license|@preserve|\bSPDX-License-Identifier:\s*([\w.+-]+)|\(c\)\s*\d{4}|Copyright\s+(\(c\)\s*)?\d{4}", re.I)
OWN_NAMES = re.compile(r"ventus|globalgrid", re.I)
LOCK_NAMES = {"package-lock.json", "yarn.lock", "pnpm-lock.yaml", "poetry.lock", "Pipfile.lock", "Cargo.lock",
"composer.lock", "Gemfile.lock", "npm-shrinkwrap.json", "uv.lock"}
COMMENT_START = re.compile(r"^\s*(#|//|/\*|\*|<!--|--|;|rem\b)", re.I)
GEN_BANNER = re.compile(
r"(@generated\b|\bauto-?generated\b|\bautomatically generated\b|\bgenerated (automatically )?by\b|"
r"\bcode generated\b|\bdo not edit\b|\bdon't edit\b|\bdo not modify\b|\bmachine[- ]generated\b|"
r"\bthis file (is|was) generated\b)", re.I)
GEN_STRONG = re.compile(r"(@generated\b|\bdo not edit\b|\bcode generated\b.*\bdo not edit\b)", re.I)
BUNDLER = re.compile(r"__webpack_require__|__webpack_modules__|\bparcelRequire\b|System\.register\(|"
r"//# sourceMappingURL=|/\*! For license information please see")
B64_RUN = re.compile(rb"[A-Za-z0-9+/]{%d,}={0,2}" % B64_MIN_RUN)
DATA_URI = re.compile(rb"data:[\w/+.-]+;base64,")
KEYWORDS = re.compile(rb"\b(function|def|class|return|if|for|while|const|let|var|import|async|await|elif|else|"
rb"switch|case|try|except|catch|lambda|yield|=>)\b|=>")
IDENT = re.compile(rb"[A-Za-z_$][A-Za-z0-9_$]*")
COMMENT_MARK = re.compile(rb"(^|\s)(//|/\*|<!--|#\s)")
COPY_BANNER = re.compile(r"\b(copied|carried over|carried|taken) (unchanged|byte for byte|verbatim)\b|\bre-?copy\b|"
r"\bcarry it again\b|\bbyte-identical to the source\b", re.I)
SCRIPT_REF = re.compile(r"\b(by|from|with)\s+(the\s+)?`?[\w./-]+\.(py|mjs|cjs|js|sh|ts|rb|go|ps1)\b", re.I)
GEN_LEAD = re.compile(r"^\s*(//+|#+|/\*+!?|\*|<!--|--)\s*(this file (is|was) )?(auto-?|automatically |machine[- ])?"
r"(generated|assembled|built|written|compiled) (by|from|with)\b|^\s*(//+|#+|/\*+|\*|<!--)\s*@generated\b", re.I)
LITERAL_CHARS = set(b"0123456789.,-+eE[]{}:\"' \t\r\n")
def git(repo_dir, *args, data=None):
return subprocess.run(["git", "-C", repo_dir, *args], input=data, capture_output=True, check=True).stdout
def tree_blobs(repo_dir, commit):
out = git(repo_dir, "ls-tree", "-r", "-z", commit)
blobs = {}
for rec in out.split(b"\0"):
if not rec:
continue
meta, path = rec.split(b"\t", 1)
parts = meta.split()
if parts[1] == b"blob":
blobs[path.decode("utf-8", "surrogateescape")] = parts[2].decode()
return blobs
def cat_blobs(repo_dir, shas):
"""Read many blobs in one git process; returns sha -> bytes."""
if not shas:
return {}
p = subprocess.Popen(["git", "-C", repo_dir, "cat-file", "--batch"], stdin=subprocess.PIPE,
stdout=subprocess.PIPE)
out = {}
try:
for sha in shas:
p.stdin.write(sha.encode() + b"\n")
p.stdin.flush()
header = p.stdout.readline().split()
if len(header) < 3 or header[1] == b"missing":
continue
size = int(header[2])
out[sha] = p.stdout.read(size)
p.stdout.read(1)
finally:
p.stdin.close()
p.wait()
p.stdout.close()
return out
def measure(data: bytes) -> dict:
"""Plain, checkable numbers about one file's bytes."""
text_lines = data.split(b"\n")
nonempty = [l for l in text_lines if l.strip()]
n = len(data) or 1
ws = sum(data.count(c) for c in (b" ", b"\t", b"\n", b"\r"))
lens = [len(l) for l in nonempty] or [0]
b64 = sum(len(m.group(0)) for m in B64_RUN.finditer(data))
lit = sum(1 for b in data if b in LITERAL_CHARS) if n <= 4_000_000 else int(n * 0.5)
alpha_words = len(re.findall(rb"[A-Za-z_]{3,}", data))
idents = IDENT.findall(data[:2_000_000])
short = sum(1 for i in idents if len(i) <= 2)
body_lines = text_lines[:20000]
indented = sum(1 for l in body_lines if l[:1] in (b" ", b"\t"))
return {
"bytes": len(data),
"lines": len(text_lines),
"nonempty_lines": len(nonempty),
"max_line": max(lens),
"avg_line": round(sum(lens) / max(1, len(nonempty)), 1),
"long_lines": sum(1 for x in lens if x >= MIN_LONG_LINE),
"long_line_bytes": sum(x for x in lens if x >= MIN_LONG_LINE),
"ws_share": round(ws / n, 3),
"b64_bytes": b64,
"data_uris": len(DATA_URI.findall(data)),
"literal_share": round(lit / n, 3),
"keywords_per_kb": round(len(KEYWORDS.findall(data)) / (n / 1024), 2),
"words_per_kb": round(alpha_words / (n / 1024), 1),
"short_ident_share": round(short / max(1, len(idents)), 3),
"comment_marks": len(COMMENT_MARK.findall(data[:2_000_000])),
"indented_share": round(indented / max(1, len(body_lines)), 3),
}
def header_text(data: bytes, nlines=HEADER_LINES):
lines = data[:20_000].decode("utf-8", "replace").split("\n")[:nlines]
return lines
def path_segments(path):
return [s.lower() for s in path.split("/")[:-1]]
def classify(f, data, m):
"""Return a list of (category, confidence, reason, evidence). Highest confidence first."""
path = f["path"]
base = os.path.basename(path)
out = []
head = header_text(data)
big_head = data[:4000].decode("utf-8", "replace")
# ---- generated -----------------------------------------------------------------------------------------
if base in LOCK_NAMES:
out.append(("noise-generated", 1.0, f"Lock file written by a package manager ({base}).",
[f"file name {base}"]))
top = head[:GEN_TOP_LINES]
copy_line = next(((i, l) for i, l in enumerate(top) if COMMENT_START.match(l) and COPY_BANNER.search(l)), None)
def is_banner(line):
if COMMENT_START.match(line) and GEN_STRONG.search(line):
return True
mt = GEN_LEAD.match(line)
if not mt:
return False
verb = (mt.group(5) or "").lower()
# "generated by ..." is a banner; "written/built/assembled/compiled by" must name a script, so that
# "written by <an author>" or "built by hand" is not mistaken for tool output
return verb == "generated" or "@generated" in line or bool(SCRIPT_REF.search(line))
gen_line = next(((i, l) for i, l in enumerate(top) if is_banner(l)), None)
if copy_line:
# A copy that names its source is a copy, not tool output: families.py owns copies. Stay, with the fact.
i, l = copy_line
out.append(("keep", 0.3, "Header says it is a copy of another file; left for the copy checks to judge.",
[f"line {i + 1} comment: {l.strip()[:160]}"]))
elif gen_line:
i, l = gen_line
strong = bool(GEN_STRONG.search(l)) or bool(re.search(r"@generated", l))
out.append(("noise-generated", 0.95 if strong else 0.85,
"A comment at the top of the file says a tool wrote it.",
[f"line {i + 1} comment: {l.strip()[:160]}"]))
bm = BUNDLER.search(data[:200_000].decode("utf-8", "replace")) if f["lang"] in ("JavaScript", "HTML") else None
if bm and m["avg_line"] > 500 and m["short_ident_share"] >= 0.35:
out.append(("noise-generated", 0.85, "Bundler output: a bundler's runtime marker in a minified file.",
[f"marker {bm.group(0)!r}", f"avg line length {m['avg_line']}",
f"short identifier share {m['short_ident_share']}"]))
# ---- vendored ------------------------------------------------------------------------------------------
segs = path_segments(path)
vseg = next((s for s in segs if s in VENDOR_SEGMENTS), None)
libs_by_name = [k for k, rx in LIB_FILE.items() if rx.match(base)]
libs_by_head = [k for k, rx in LIB_HEAD.items() if rx.search(big_head[:1500])]
lic = LICENSE_HEAD.search(big_head[:1500])
own = bool(OWN_NAMES.search(big_head[:1500]))
both = [k for k in libs_by_name if k in libs_by_head]
if vseg == "node_modules" or "bower_components" in segs:
out.append(("noise-vendored", 0.97, f"Third-party package folder ({vseg or 'bower_components'}/).",
[f"path segment {vseg or 'bower_components'}/"]))
elif both and not own:
lib = both[0]
ev = [f"file name {base} matches {lib}",
f"first 1,500 bytes name {lib}: {LIB_HEAD[lib].search(big_head[:1500]).group(0)!r}"]
if lic:
ev.append(f"licence header {lic.group(0)!r}")
out.append(("noise-vendored", 0.95, f"A copy of the {lib} library.", ev))
elif vseg and (lic or libs_by_head) and not own:
ev = [f"path segment {vseg}/"]
if lic:
ev.append(f"licence header {lic.group(0)!r}")
if libs_by_head:
ev.append(f"first 1,500 bytes name {libs_by_head[0]}")
out.append(("noise-vendored", 0.9, f"Third-party code kept in a {vseg}/ folder.", ev))
elif vseg and not own:
out.append(("keep", 0.4, f"Sits in a {vseg}/ folder but carries no licence or library header.",
[f"path segment {vseg}/", "no licence or library header in first 1,500 bytes"]))
elif libs_by_name and lic and not own:
out.append(("noise-vendored", 0.7, f"Named like the {libs_by_name[0]} library and has a licence header.",
[f"file name {base} matches {libs_by_name[0]}", f"licence header {lic.group(0)!r}"]))
# ---- minified ------------------------------------------------------------------------------------------
is_web = f["lang"] in ("JavaScript", "CSS", "HTML")
if ".min." in base.lower():
out.append(("noise-minified", 0.95, "Minified file (\".min.\" in its name).",
[f"file name {base}", f"avg line length {m['avg_line']}", f"max line {m['max_line']}"]))
elif is_web and m["bytes"] >= 2000 and m["literal_share"] < DATA_LITERAL:
long_share = m["long_line_bytes"] / max(1, m["bytes"])
mangled = m["short_ident_share"] >= MINIFIED_SHORT_IDENT
if m["avg_line"] >= MINIFIED_AVG_STRICT and mangled and m["comment_marks"] <= 2:
out.append(("noise-minified", 0.9,
f"Minified: {m['nonempty_lines']:,} lines averaging {m['avg_line']:,.0f} characters, "
f"mostly one- and two-letter names.",
[f"avg line length {m['avg_line']}", f"short identifier share {m['short_ident_share']}",
f"comment marks {m['comment_marks']}", f"whitespace share {m['ws_share']}"]))
elif long_share > 0.8 and mangled and m["comment_marks"] <= 2:
out.append(("noise-minified", 0.75,
f"Mostly minified: {long_share:.0%} of bytes in lines of {MIN_LONG_LINE}+ characters with "
f"short names.",
[f"bytes in long lines {m['long_line_bytes']} of {m['bytes']}",
f"short identifier share {m['short_ident_share']}"]))
elif m["avg_line"] >= MINIFIED_AVG or long_share > 0.5:
out.append(("keep", 0.45, "Written densely (long lines), but names are readable: authored, not minified.",
[f"avg line length {m['avg_line']}", f"bytes in long lines {m['long_line_bytes']} of {m['bytes']}",
f"short identifier share {m['short_ident_share']}", f"comment marks {m['comment_marks']}"]))
# ---- data blob -----------------------------------------------------------------------------------------
if m["bytes"] >= B64_MIN_BYTES and m["b64_bytes"] / m["bytes"] >= B64_SHARE:
out.append(("noise-data-blob", 0.9,
f"Mostly embedded binary: {m['b64_bytes'] / m['bytes']:.0%} of the file is base64.",
[f"base64 bytes {m['b64_bytes']} of {m['bytes']}", f"data URIs {m['data_uris']}"]))
elif m["bytes"] >= DATA_MIN_BYTES and m["literal_share"] >= DATA_LITERAL \
and m["keywords_per_kb"] < DATA_KEYWORDS_PER_KB:
out.append(("noise-data-blob", 0.85,
f"Data written as code: {m['bytes']:,} bytes, {m['literal_share']:.0%} literal characters, "
f"{m['keywords_per_kb']} code keywords per KB.",
[f"bytes {m['bytes']}", f"literal share {m['literal_share']}",
f"keywords per KB {m['keywords_per_kb']}"]))
elif m["bytes"] >= DATA_MIN_BYTES and m["literal_share"] >= 0.6 and m["keywords_per_kb"] < 3:
out.append(("keep", 0.45, "Large and literal-heavy, but has enough code to stay.",
[f"bytes {m['bytes']}", f"literal share {m['literal_share']}",
f"keywords per KB {m['keywords_per_kb']}"]))
elif m["bytes"] >= B64_MIN_BYTES and m["b64_bytes"] / m["bytes"] >= 0.25:
out.append(("keep", 0.45, "Carries embedded base64, but most of the file is code.",
[f"base64 bytes {m['b64_bytes']} of {m['bytes']}"]))
elif m["max_line"] >= 50_000 and m["max_line"] / max(1, m["bytes"]) >= 0.3:
out.append(("keep", 0.45, "One very long line (embedded data) inside an otherwise authored file.",
[f"max line {m['max_line']} of {m['bytes']} bytes", f"keywords per KB {m['keywords_per_kb']}"]))
order = {"noise-generated": 0, "noise-vendored": 1, "noise-minified": 2, "noise-data-blob": 3, "keep": 9}
out.sort(key=lambda r: (-r[1], order[r[0]]))
# a positive noise finding wins over a borderline keep from another check
noise = [r for r in out if r[0] != "keep"]
return noise + [r for r in out if r[0] == "keep"] if noise else out
def run(graph_path, src):
with open(graph_path, encoding="utf-8") as fh:
g = json.load(fh)
commits = {r["repo"]: r["commit"] for r in g["repos"]}
by_repo = {}
for f in g["files"]:
by_repo.setdefault(f["repo"], []).append(f)
proposals, stats, missing = [], Counter(), []
for repo in sorted(by_repo):
rdir = os.path.join(src, repo)
commit = commits.get(repo)
files = by_repo[repo]
try:
blobs = tree_blobs(rdir, commit)
except Exception:
blobs = {}
missing.append(repo)
content = cat_blobs(rdir, sorted({blobs[f["path"]] for f in files if f["path"] in blobs}))
for f in files:
blob = blobs.get(f["path"], "-")
data = content.get(blob)
if data is None:
stats["unreadable"] += 1
continue
m = measure(data)
hits = classify(f, data, m)
if not hits:
stats["no-signal"] += 1
continue
cat, conf, reason, ev = hits[0]
key = f"{repo}@{commit} {f['path']}:1-{max(1, f['lines'])} {blob}"
rec = {"file_id": f["id"], "key": key, "category": cat, "reason": reason, "evidence": ev,
"confidence": conf, "proposer": PROPOSER,
"metrics": m, "rules": RULES}
if len(hits) > 1:
rec["also"] = [{"category": c, "confidence": k, "reason": r} for c, k, r, _ in hits[1:]]
proposals.append(rec)
stats[cat if (cat == "keep" or conf >= 0.6) else cat + " (below 0.6)"] += 1
proposals.sort(key=lambda r: r["file_id"])
doc = {
"schema": "clean-proposals-v1",
"proposer": PROPOSER,
"graph_cut": g.get("cut"),
"rules": {"version": RULES, "MIN_LONG_LINE": MIN_LONG_LINE, "MINIFIED_AVG": MINIFIED_AVG,
"MINIFIED_WS": MINIFIED_WS, "DATA_MIN_BYTES": DATA_MIN_BYTES, "DATA_LITERAL": DATA_LITERAL,
"DATA_KEYWORDS_PER_KB": DATA_KEYWORDS_PER_KB, "B64_MIN_RUN": B64_MIN_RUN,
"B64_SHARE": B64_SHARE, "HEADER_LINES": HEADER_LINES,
"GEN_TOP_LINES": GEN_TOP_LINES, "MINIFIED_AVG_STRICT": MINIFIED_AVG_STRICT,
"MINIFIED_SHORT_IDENT": MINIFIED_SHORT_IDENT},
"counts": dict(sorted(stats.items())),
"files_examined": len(g["files"]),
"missing_clones": missing,
"proposals": proposals,
}
return doc
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
ap.add_argument("--graph", default="/tmp/site7/explore-code/build_graph.json")
ap.add_argument("--src", default="/home/claude/src")
ap.add_argument("--out", default="/tmp/vk/clean/proposals/noise.json")
ap.add_argument("--copy", default="/tmp/vk/clean/noise.json", help="second copy of the output ('' for none)")
a = ap.parse_args(argv)
doc = run(a.graph, a.src)
if doc["files_examined"] and not doc["proposals"] and not doc["counts"].get("no-signal"):
print("refused: nothing was examined", file=sys.stderr)
return 1
raw = json.dumps(doc, indent=1, ensure_ascii=False, sort_keys=False) + "\n"
for p in filter(None, [a.out, a.copy]):
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p, "w", encoding="utf-8") as fh:
fh.write(raw)
print(json.dumps(doc["counts"]), f"files={doc['files_examined']}", f"-> {a.out}")
return 0
if __name__ == "__main__":
sys.exit(main())