In this section
- Genome storage · cosmic / tools/explore/identity/genome.py lines 456–824
- Test Genome test · cosmic / tools/explore/identity/test_genome.py lines 1–155
Genome
A Python command-line tool in the identity folder of Cosmic that reads jobs, rules, units and electron, using SHA-256. It loads JSON (`load_json`), runs extract (`run_extract`) and builds lite (`build_lite`).
storagecosmic / tools/explore/identity/genome.py · lines 456–824 of 824 (continued from section 1101) · Entry point · pattern preference (shared by 2 files)
- What it does
- It loads jobs, rules, units and electron. Defines 24 functions or classes, including sha256_file, load_json, run_extract, modular_numbers, vedic_clusters. Uses libraries argparse, collections, glob, hashlib, importlib.util. Side effects: reads or writes files; starts processes; uses storage (browser storage, DuckDB or Parquet).
- Why it exists in the grid workflow
- README: "`genome.py` gives every file in `build_graph.json`, and every function inside it, the identity keys the estate already uses."
- Inputs & outputs
- In: JSON file jobs.json; JSON file rules.json; Parquet file units.parquet; Parquet file candidates.parquet; JSON file electron.json; JSON file entangled.json; JSON file functions.json; JSON file surfaces.json. Out: JSON file.
- Downstream impact
- Used directly by 3 files: Families (cosmic); Extras (cosmic); Test Genome (cosmic). Reached from 7 other entry points, including CI (cosmic); Ship (cosmic); Test Apply (cosmic).
- What it achieves
- The estate's own permanent identities and genome for every Explore Code file. It accepts `--graph`, `--src` and `--fingerprints`.
- Why it matters
- Imported by Families. Run by Extras. Checked by Test Genome.
- Application
- cosmic · tools/explore/identity · Python CLI
- Uses
- argparse, collections, glob, hashlib, importlib.util, json, math, os
- Used by
- imported by Families (sys.path import), run by Extras (script call), imported by Test Genome (import)
- Produces
- sha256_file, load_json, run_extract, modular_numbers, vedic_clusters, estate_blobs, norm_lines, preference, logical_group_key, build, default_path, work_dir
- Defines here
- default_path, work_dir, full_prerequisites, file_keys, build_lite, key_of, by_path_cache, files_in_cluster, cluster_shared_outside, write, 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/identity/genome.py:456-824 · blob 82d260d119c6ebcca00de149b81cdc029f2b7484 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem, process, storage · domain stage: unknown · users: none · canonical: supporting_data
if in_graph:
fv = "copy"
elif estate and x["family"] is not None and fams[x["family"]]["files"] > 1:
fv = "copy-estate"
elif twins:
fv = "name-twin"
else:
fv = "unique"
if fv in ("copy", "copy-estate") and span >= SUBSTANTIAL_LINES:
shared_keys.add(x["fkey"])
atom = [a["n"] for a in atoms_by_name.get(x["name"], ()) if f["repo"] in a.get("homes", [])]
ent = ent_by_def.get((f"{f['repo']}/{f['path']}", x["name"]))
funcs.append({
"name": x["name"], "kind": x["kind"], "first": x["first"], "last": x["last"], "family_key": x["fkey"],
"signature": sigs[i].get(x["name"]),
"family": x["family"], "family_basis": x["family_basis"], "family_sha": x["family_sha"],
"element_sha": x["element_sha"], "standalone": x["standalone"],
"elements_key": f"family:{x['family']}" if x["family"] in el_funcs else None,
"line_keys": ([f"line:{fams[x['family']]['lines'][0]}", f"line:{fams[x['family']]['lines'][-1]}"]
if x["family"] is not None and fams[x["family"]].get("lines") else None),
"copies_in_graph": sorted(in_graph)[:20], "copies_in_graph_count": len(in_graph),
"name_twin_repos": twins, "state_atoms": atom,
"entangled": {"n": ent["n"], "called_from": ent["called_from"]} if ent else None,
"verdict": fv,
})
# attach genome-spider hash + Vedic unit per function (by first line)
gs_by_line = collections.defaultdict(list)
for g in gsf or []:
gs_by_line[g["line"]].append(g)
vunits = units_by_file.get((f["repo"], f["path"]), [])
v_by_line = {(u["line_from"], u["name"]): u for u in vunits}
for fn in funcs:
g = [g for g in gs_by_line.get(fn["first"], []) if g["name"] == fn["name"]]
fn["spider_hash"] = g[0]["hash"] if g else None
u = v_by_line.get((fn["first"], fn["name"]))
fn["vedic_unit"] = u["unit_id"] if u else None
fn["vedic_cluster"] = unit_cluster.get(u["unit_id"]) if u else None
# functions known to Vedic / build_graph signatures but not split by the Modular Star (e.g. other langs)
seen_names = {fn["name"] for fn in funcs}
extra_sigs = [s for nm, s in sorted(sigs[i].items()) if nm not in seen_names]
vclusters = sorted({unit_cluster[u["unit_id"]] for u in vunits if u["unit_id"] in unit_cluster})
v_shared = sorted(c for c in vclusters if cluster_size[c] > 1 and cluster_shared_outside(c, i, own_cluster,
unit_cluster, units_by_file, fid, cluster_root, by_path_cache(files)))
vedic = {"units": len(vunits), "clusters": vclusters, "shared_clusters": v_shared,
"dropped_units": sum(1 for u in vunits if u["unit_id"] in dropped),
"candidates": [{"cluster_id": c, "word": cand[c]["suggested_word"], "score": cand[c]["score"]}
for c in vclusters if c in cand]}
surf = None
if f.get("published"):
surf = next((s for s in surfaces if f["published"].startswith(s)), None)
elements = {"family_keys": sorted(el_fams, key=lambda k: int(k.split(":")[1])), "blocks": sorted(el_blocks),
"surface": f"surface:{surf}" if surf else None}
modular = {"tablet": r["blob"], "lang": r.get("ms_lang"), "issue": r.get("ms_issue"),
"elements": len(funcs), "families": sorted(set(fam_list)),
"exact": sum(1 for fn in funcs if fn["family_basis"] == "exact"),
"matched": sum(1 for fn in funcs if fn["family_basis"] == "matched"),
"unnumbered": sum(1 for fn in funcs if fn["family_basis"] == "unnumbered")}
# ---- the single uniqueness verdict (Kuiper: every verdict carries keys)
canon = canon_of[i]
if canon != i:
verdict, of = "copy-of", fid[canon]
evidence = [f"sha256:{r['sha256']}", f"blob:{r['blob']}", f"file:{canon}"]
reason = "byte-identical to the preferred copy"
sim = 1.0
elif i in near_target:
root, jac = near_root(i)
tgt, j1 = near_target[i]
verdict, of = "near-copy-of", fid[tgt]
evidence = [f"sha256:{r['sha256']}", f"sha256:{recs[tgt]['sha256']}", f"line-jaccard:{j1}", f"file:{tgt}"]
reason = f"{round(j1 * 100)}% of normalised lines shared with the preferred file"
sim = j1
elif shared_keys or v_shared:
verdict, of = "family-shared", None
evidence = sorted(shared_keys)[:12] + [f"vedic:{c}" for c in v_shared[:6]]
reason = (f"{len(shared_keys)} substantial function famil{'y' if len(shared_keys) == 1 else 'ies'} "
f"and {len(v_shared)} Vedic cluster(s) also live in other files")
sim = None
else:
verdict, of = "unique", None
fam_keys = [fn["elements_key"] or (f"family:{fn['family']}" if fn["family"] is not None else
"familysha:" + fn["family_sha"][:16]) for fn in funcs]
evidence = [f"sha256:{r['sha256']}", f"blob:{r['blob']}"] + sorted(set(fam_keys))[:10]
reason = "no other file holds these bytes, these lines, or these function families"
sim = None
verdicts[verdict] += 1
copies = sorted(o for o in by_sha[r["sha256"]] if o != i) if canon == i else []
graph_paths = {(fid[o]["repo"], fid[o]["path"]) for o in by_sha[r["sha256"]]}
outside = sorted(pl for pl in blobs.get(r["blob"], ()) if pl not in graph_paths)
if outside:
evidence = evidence + [f"estate-copies:{len(outside)}"]
twin = None
if of is not None:
twin = {"kind": verdict.replace("-of", ""), "file": of["id"], "key": key_of(of)}
elif shared_keys:
cnt = collections.Counter(o for fn in funcs for o in fam_files[fn["family_key"]] if o != i and cluster_root[o] != own_cluster)
if cnt:
o, c = sorted(cnt.items(), key=lambda t: (-t[1], t[0]))[0]
twin = {"kind": "family", "file": o, "key": key_of(fid[o]), "shared_functions": c}
out_files[str(i)] = {
"id": i, "repo": f["repo"], "path": f["path"], "keys": keys,
"genome": genome, "modular": modular, "elements": elements, "vedic": vedic,
"quantum": {**shells(f), "twin": twin},
"verdict": {"verdict": verdict, "of": key_of(of) if of else None, "of_file": of["id"] if of else None,
"similarity": sim, "evidence": evidence, "reason": reason,
"verbatim_copies": copies,
"estate_verbatim_copies": len(outside),
"estate_verbatim_examples": [f"{rp}@{heads.get(rp, '-')} {pp}" for rp, pp in outside[:5]]},
"functions": funcs, "signatures_not_split": extra_sigs,
}
# ---- checks: genome-spider hash reproduction against its committed genome.json
gs_cmp = gs_hit = 0
by_path = {(f["repo"], f["path"]): f["id"] for f in files}
for grp in gs_genome["markers"].get("duplication", []):
for c in grp.get("copies", []):
o = by_path.get((c["repo"].split("/")[-1], c["path"]))
if o is None or grp.get("kind") != "function":
continue
gs_cmp += 1
gs_hit += any(g["name"] == grp["name"] and g["hash"] == c["hash"] for g in recs[o].get("gs_functions") or [])
result = {
"schema": SCHEMA,
"graph": {"path": args.graph, "schema": graph["schema"], "cut": graph["cut"], "sha256": sha256_file(args.graph)},
"sources": {
"modular_lib_sha256": sha256_file(os.path.join(args.src, "stars/modular-star/lib.mjs")),
"modular_functions_py_sha256": sha256_file(os.path.join(args.src, "stars/modular-star/functions.py")),
"modular_code_index_sha256": sha256_file(os.path.join(args.src, "stars/code/index.json")),
"genome_spider_markers_sha256": sha256_file(os.path.join(args.src, "spiders/species/genome-spider/lib/markers.mjs")),
"genome_spider_genome_generated_at": gs_genome.get("generated_at"),
"sqt_electron_sha256": sha256_file(os.path.join(sqt, "electron.json")),
"elements_functions_sha256": sha256_file(os.path.join(el, "catalogue", "functions.json")),
"elements_register": os.path.basename(reg_path),
"vedic_units_sha256": sha256_file(os.path.join(args.fingerprints, "out", "units.parquet")),
"vedic_rules_sha256": sha256_file(os.path.join(args.fingerprints, "rules.json")),
},
"rules": {"substantial_lines": SUBSTANTIAL_LINES, "near_jaccard": NEAR_JACCARD,
"common_line_files": COMMON_LINE_FILES,
"preference": "reachable, production_core, not under a release/archive/timestamp folder, shorter path, repo, path, id"},
"checks": {"modular": ms_check, "vedic": vd_check,
"genome_spider": {"recorded_copies_in_graph": gs_cmp, "hash_reproduced": gs_hit},
"files": len(files), "files_covered": len(out_files),
"clone_head_differs_from_graph_commit": head_mismatch,
"files_blob_found_at_clone_head": sum(1 for f in files if blobs.get(recs[f["id"]]["blob"]))},
"counts": {"verdicts": dict(sorted(verdicts.items())),
"functions": sum(len(v["functions"]) for v in out_files.values()),
"function_verdicts": dict(sorted(collections.Counter(fn["verdict"] for v in out_files.values()
for fn in v["functions"]).items())),
"family_basis": dict(sorted(collections.Counter(fn["family_basis"] for v in out_files.values()
for fn in v["functions"]).items()))},
"files": out_files,
}
return result
# ----------------------------------------------------------------------------------------- lite (CI) mode
def default_path(env, *cands):
"""$env if set, else the first candidate that exists, else the first candidate (CI layout first)."""
if os.environ.get(env):
return os.environ[env]
return next((c for c in cands if os.path.exists(c)), cands[0])
def work_dir(sub):
"""Where intermediate outputs go: $EXPLORE_WORK/<sub>, else _work/<sub> under the current folder (never /tmp)."""
base = os.environ.get("EXPLORE_WORK") or "_work"
return os.path.join(base, sub)
def full_prerequisites(src, fingerprints):
"""Names of what the full build needs and this machine lacks ([] = full build possible)."""
miss = []
if not shutil.which("node"):
miss.append("node")
if not any(os.path.isdir(f"{p}/acorn") and os.path.isdir(f"{p}/acorn-walk")
for p in ("/opt/node-tools/node_modules", "/opt/npm-tools/node_modules")):
miss.append("acorn")
for rel in ("stars/modular-star/lib.mjs", "spiders/species/genome-spider/lib/markers.mjs",
"star-quantum-twin/data/electron.json", "elements/catalogue/functions.json"):
if not os.path.exists(os.path.join(src, rel)):
miss.append("clone:" + rel.split("/")[0])
for rel in ("candidates.py", "rules.json", "out/units.parquet", "out/candidates.parquet"):
if not os.path.exists(os.path.join(fingerprints, rel)):
miss.append("fingerprints:" + rel)
try:
import pyarrow # noqa: F401
except ImportError:
miss.append("pyarrow")
return miss
def file_keys(path):
"""(sha256, git blob id) of a file's bytes, or (None, None) if the clone lacks it."""
try:
with open(path, "rb") as fh:
data = fh.read()
except OSError:
return None, None
return hashlib.sha256(data).hexdigest(), hashlib.sha1(b"blob %d\0" % len(data) + data).hexdigest()
def build_lite(graph, src, missing=()):
"""Keys-only identity from build_graph + clones (photon rule: ids and keys, never code text): file sha256 and git
blob, exact copy groups and line-Jaccard near copies, with the same preference order and thresholds as build()."""
files = graph["files"]
fid = {f["id"]: f for f in files}
commit = {r["repo"]: r["commit"] for r in graph["repos"]}
keys = {}
for f in files:
sha, blob = file_keys(os.path.join(src, f["repo"], f["path"]))
keys[f["id"]] = (sha, blob)
def key_of(f):
return f"{f['repo']}@{commit.get(f['repo'], '-')} {f['path']}:1-{max(1, f['lines'])} {keys[f['id']][1] or '-'}"
by_sha = collections.defaultdict(list)
for f in files:
if keys[f["id"]][0]:
by_sha[keys[f["id"]][0]].append(f["id"])
canon_of = {f["id"]: f["id"] for f in files}
for ids in by_sha.values():
best = min(ids, key=lambda i: preference(fid[i]))
for i in ids:
canon_of[i] = best
reps = sorted({canon_of[f["id"]] for f in files if keys[f["id"]][0]})
lines = {i: norm_lines(os.path.join(src, fid[i]["repo"], fid[i]["path"])) for i in reps}
inv = collections.defaultdict(list)
for i in reps:
for h in lines[i]:
inv[h].append(i)
shared = collections.Counter()
for ids in inv.values():
if 1 < len(ids) <= COMMON_LINE_FILES:
for a in range(len(ids)):
for b in range(a + 1, len(ids)):
shared[(ids[a], ids[b])] += 1
near = collections.defaultdict(list)
for (a, b), c in shared.items():
la, lb = lines[a], lines[b]
if not la or not lb or c < NEAR_JACCARD * min(len(la), len(lb)) * 0.5:
continue
jac = len(la & lb) / len(la | lb)
if jac >= NEAR_JACCARD:
near[a].append((round(jac, 4), b))
near[b].append((round(jac, 4), a))
out_files, verdicts = {}, collections.Counter()
for f in files:
i = f["id"]
sha, blob = keys[i]
better = [(j, o) for j, o in near.get(i, []) if preference(fid[o]) < preference(fid[i])]
if sha is None:
verdict, of, sim, ev, reason = "unknown", None, None, [], "the clone does not hold this file"
elif canon_of[i] != i:
of = fid[canon_of[i]]
verdict, sim, ev, reason = "copy-of", 1.0, [f"sha256:{sha}", f"blob:{blob}", f"file:{of['id']}"], \
"byte-identical to the preferred copy"
elif better:
j, o = sorted(better, key=lambda t: (-t[0], preference(fid[t[1]])))[0]
of = fid[o]
verdict, sim = "near-copy-of", j
ev = [f"sha256:{sha}", f"sha256:{keys[o][0]}", f"line-jaccard:{j}", f"file:{o}"]
reason = f"{round(j * 100)}% of normalised lines shared with the preferred file"
else:
verdict, of, sim, ev, reason = "unique", None, None, [f"sha256:{sha}", f"blob:{blob}"], \
"no other file holds these bytes or these lines"
verdicts[verdict] += 1
out_files[str(i)] = {"id": i, "repo": f["repo"], "path": f["path"],
"keys": {"sha256": sha, "git_blob": blob, "commit": commit.get(f["repo"]), "key": key_of(f)},
"verdict": {"verdict": verdict, "of": key_of(of) if of else None,
"of_file": of["id"] if of else None, "similarity": sim, "evidence": ev,
"reason": reason}}
return {"schema": SCHEMA, "mode": "lite", "_mode": "lite", "graph_cut": graph.get("cut"),
"lite_reason": "missing: " + ", ".join(missing) if missing else "requested",
"counts": {"files": len(files), "verdicts": dict(sorted(verdicts.items()))},
"checks": {"files_without_clone": verdicts.get("unknown", 0)}, "files": out_files}
_BP = {}
def by_path_cache(files):
if not _BP:
_BP.update({(f["repo"], f["path"]): f["id"] for f in files})
return _BP
def files_in_cluster(root, cluster_root):
return [i for i, r in cluster_root.items() if r == root]
_VC = {}
def cluster_shared_outside(cid, i, own_cluster, unit_cluster, units_by_file, fid, cluster_root, bp):
"""True if Vedic cluster cid has a member unit in a graph file outside this file's copy cluster,
or in a unit file not in the graph at all."""
if not _VC:
for (repo, path), us in units_by_file.items():
for u in us:
c = unit_cluster.get(u["unit_id"])
if c:
_VC.setdefault(c, set()).add(bp.get((repo, path), ("ext", repo, path)))
for o in _VC.get(cid, ()):
if isinstance(o, tuple):
return True
if o != i and cluster_root[o] != own_cluster:
return True
return False
def write(result, out_dir):
full = os.path.join(out_dir, "identity.json")
with open(full, "w", encoding="utf-8") as fh:
json.dump(result, fh, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
slim = dict(result)
slim["files"] = {k: {kk: vv for kk, vv in v.items() if kk != "functions"} for k, v in result["files"].items()}
with open(os.path.join(out_dir, "identity-files.json"), "w", encoding="utf-8") as fh:
json.dump(slim, fh, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
return full
def main(argv=None):
ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
ap.add_argument("--graph", default=default_path("EXPLORE_GRAPH", "_site/explore-code/build_graph.json",
"/tmp/site8/explore-code/build_graph.json",
"/tmp/site7/explore-code/build_graph.json"))
ap.add_argument("--src", default=default_path("EXPLORE_SRC", "clones", "/home/claude/src"))
ap.add_argument("--fingerprints", default="")
ap.add_argument("--out", default="")
ap.add_argument("--reuse-extract", action="store_true", help="reuse OUT/extract.jsonl if present")
ap.add_argument("--lite", action="store_true", help="keys-only identity (no node, no Vedic, no estate data files)")
args = ap.parse_args(argv)
args.fingerprints = args.fingerprints or default_path("EXPLORE_FINGERPRINTS",
os.path.join(args.src, "vedic-", "fingerprints"),
"/home/claude/vedic-/fingerprints")
args.out = args.out or work_dir("7")
if not os.path.exists(args.graph):
print(f"genome.py: no build graph at {args.graph}; skipped", file=sys.stderr)
return 0
os.makedirs(args.out, exist_ok=True)
missing = [] if args.lite else full_prerequisites(args.src, args.fingerprints)
result = None
if not args.lite and not missing:
try:
result = build(args)
except (SystemExit, Exception) as e: # one broken estate input must not stop the site build
missing = [f"full build failed: {e}"[:200]]
if result is None:
print("genome.py: lite mode (%s)" % (", ".join(missing) or "requested"), file=sys.stderr)
result = build_lite(load_json(args.graph), args.src, missing)
prev = os.path.join(args.out, "identity.json")
if os.path.exists(prev) and not os.environ.get("GENOME_LITE_OVERWRITE"):
try:
with open(prev, encoding="utf-8") as fh:
head = fh.read(4096)
except OSError:
head = ""
if head and '"_mode":"lite"' not in head:
print(f"genome.py: {prev} is a full identity; lite output not written over it", file=sys.stderr)
return 0
path = write(result, args.out)
print(json.dumps({"wrote": path, "mode": result.get("mode", "full"), "counts": result["counts"]}, indent=1))
return 0
if __name__ == "__main__":
sys.exit(main())Test Genome
A test in the identity folder of Cosmic that checks Genome, using SHA-256.
testcosmic / tools/explore/identity/test_genome.py · lines 1–155 of 155 · Entry point · pattern setUpClass (shared by 19 files)
- What it does
- It tests its inputs. Defines 15 functions or classes, including sha, IdentityTests, setUpClass, test_every_file_covered, test_verdict_counts_add_up. Uses libraries hashlib, json, os, shutil, sys. Side effects: reads or writes files.
- Inputs & outputs
- In: JSON file build_graph.json; JSON file identity.json; JSON file identity-files.json. Out: JSON file build_graph.json.
- Downstream impact
- It is itself an entry point (test); no other file was found loading it.
- What it achieves
- It sets up class (`setUpClass`) and is built from the sha step (`sha`) and the identity tests class (`IdentityTests`). Tests for `identity/genome.py`.
- Why it matters
- Guards the behaviour of Genome.
- Application
- cosmic · tools/explore/identity · test
- Uses
- Genome (import), hashlib, json, os, shutil, sys, tempfile, unittest
- Used by
- none found
- Produces
- sha, IdentityTests, UnitTests, test_no_tmp_inputs_lite
- Defines here
- sha, IdentityTests, setUpClass, test_every_file_covered, test_verdict_counts_add_up, test_evidence_keys_present, test_near_copy_targets_are_not_circular, test_keys_match_bytes_on_disk, test_function_view, test_reproduction_checks, test_determinism, UnitTests, test_logical_group_key_strips_timestamp, test_preference_prefers_reachable_then_non_release, test_no_tmp_inputs_lite
- 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/identity/test_genome.py:1-155 · blob 099d08ecf32a85e4c9f2054602fe4adafef64dd2 · GitHub at these lines
- State
- achieves: comment · context: readme_derived · stage: output · effects: filesystem · domain stage: unknown · users: none · canonical: unknown
"""Tests for identity/genome.py. Run: python3 -m unittest test_genome (from this folder).
Uses the real inputs (build_graph.json, /home/claude/src, Vedic fingerprints) and the committed run in
/tmp/vk/7; skips if they are absent. The determinism test rebuilds into a temp dir (reusing the extractor
output, which is itself a pure function of the file bytes) and compares bytes.
"""
import hashlib
import json
import os
import shutil
import sys
import tempfile
import unittest
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
import genome # noqa: E402
GRAPH = "/tmp/site7/explore-code/build_graph.json"
OUT = "/tmp/vk/7"
IDENTITY = os.path.join(OUT, "identity.json")
VERDICTS = {"unique", "copy-of", "near-copy-of", "family-shared"}
EVIDENCE_PREFIXES = ("sha256:", "blob:", "file:", "line-jaccard:", "family:", "familysha:", "vedic:", "estate-copies:")
def sha(path):
with open(path, "rb") as fh:
return hashlib.sha256(fh.read()).hexdigest()
@unittest.skipUnless(os.path.exists(GRAPH) and os.path.exists(IDENTITY), "inputs or identity.json missing")
class IdentityTests(unittest.TestCase):
@classmethod
def setUpClass(cls):
with open(GRAPH) as fh:
cls.graph = json.load(fh)
with open(IDENTITY) as fh:
cls.ident = json.load(fh)
def test_every_file_covered(self):
ids = {str(f["id"]) for f in self.graph["files"]}
self.assertEqual(ids, set(self.ident["files"]))
self.assertEqual(self.ident["checks"]["files_covered"], len(ids))
def test_verdict_counts_add_up(self):
counts = self.ident["counts"]["verdicts"]
self.assertTrue(set(counts) <= VERDICTS)
self.assertEqual(sum(counts.values()), len(self.graph["files"]))
seen = {}
for v in self.ident["files"].values():
seen[v["verdict"]["verdict"]] = seen.get(v["verdict"]["verdict"], 0) + 1
self.assertEqual(seen, counts)
def test_evidence_keys_present(self):
for k, v in self.ident["files"].items():
vd = v["verdict"]
self.assertIn(vd["verdict"], VERDICTS, k)
self.assertTrue(vd["evidence"], f"file {k} has no evidence")
for e in vd["evidence"]:
self.assertTrue(e.startswith(EVIDENCE_PREFIXES), f"file {k}: unkeyed evidence {e!r}")
if vd["verdict"] in ("copy-of", "near-copy-of"):
self.assertIsNotNone(vd["of"], k)
self.assertIn(f"file:{vd['of_file']}", vd["evidence"])
self.assertNotEqual(vd["of_file"], v["id"])
else:
self.assertIsNone(vd["of"], k)
self.assertRegex(v["keys"]["sha256"], r"^[0-9a-f]{64}$")
self.assertRegex(v["keys"]["git_blob"], r"^[0-9a-f]{40}$")
def test_near_copy_targets_are_not_circular(self):
files = self.ident["files"]
for k, v in files.items():
seen, cur = set(), v
while cur["verdict"]["verdict"] in ("copy-of", "near-copy-of"):
self.assertNotIn(cur["id"], seen, f"cycle from {k}")
seen.add(cur["id"])
cur = files[str(cur["verdict"]["of_file"])]
def test_keys_match_bytes_on_disk(self):
for f in self.graph["files"][:: max(1, len(self.graph["files"]) // 50)]:
v = self.ident["files"][str(f["id"])]
path = os.path.join("/home/claude/src", f["repo"], f["path"])
self.assertEqual(sha(path), v["keys"]["sha256"])
def test_function_view(self):
n = 0
for v in self.ident["files"].values():
for fn in v["functions"]:
n += 1
self.assertIn(fn["family_basis"], ("exact", "matched", "unnumbered"))
self.assertEqual(fn["family"] is None, fn["family_basis"] == "unnumbered")
self.assertRegex(fn["family_sha"], r"^[0-9a-f]{64}$")
self.assertIn(fn["verdict"], ("copy", "copy-estate", "name-twin", "unique"))
self.assertEqual(n, self.ident["counts"]["functions"])
def test_reproduction_checks(self):
c = self.ident["checks"]
self.assertEqual(c["vedic"]["candidate_clusters_reproduced"], c["vedic"]["candidate_clusters_published"])
self.assertEqual(c["genome_spider"]["hash_reproduced"], c["genome_spider"]["recorded_copies_in_graph"])
self.assertLessEqual(c["modular"]["family_sha_to_several_numbers"], 5)
@unittest.skipUnless(os.path.exists(os.path.join(OUT, "extract.jsonl")), "extract.jsonl missing")
def test_determinism(self):
with tempfile.TemporaryDirectory(dir="/tmp") as tmp:
shutil.copyfile(os.path.join(OUT, "extract.jsonl"), os.path.join(tmp, "extract.jsonl"))
genome.main(["--graph", GRAPH, "--src", "/home/claude/src", "--fingerprints",
"/home/claude/vedic-/fingerprints", "--out", tmp, "--reuse-extract"])
self.assertEqual(sha(os.path.join(tmp, "identity.json")), sha(IDENTITY))
class UnitTests(unittest.TestCase):
def test_logical_group_key_strips_timestamp(self):
self.assertEqual(genome.logical_group_key("a/b/202609011950-geodesy.js"), "a/b::geodesy.js")
self.assertEqual(genome.logical_group_key("geodesy.js"), "::geodesy.js")
def test_preference_prefers_reachable_then_non_release(self):
base = {"reachable": False, "canonical_status": "unknown", "repo": "r", "id": 1}
a = dict(base, path="releases/202601010000/x.js", reachable=True, id=1)
b = dict(base, path="x.js", id=2)
c = dict(base, path="src/x.js", id=3)
d = dict(base, path="releases/1/x.js", id=4)
self.assertLess(genome.preference(a), genome.preference(b))
self.assertLess(genome.preference(c), genome.preference(d))
if __name__ == "__main__":
unittest.main()
def test_no_tmp_inputs_lite(tmp_path, monkeypatch):
"""CI layout only (_site/explore-code/build_graph.json + ./clones), no /tmp inputs, no node: lite identity."""
import json as _json
import genome as _g
(tmp_path / "clones" / "r").mkdir(parents=True)
body = "\n".join("line number %d of the shared code" % k for k in range(40)) + "\n"
(tmp_path / "clones" / "r" / "a.js").write_text(body)
(tmp_path / "clones" / "r" / "b.js").write_text(body)
(tmp_path / "clones" / "r" / "c.js").write_text(body + "one more distinct line here\n")
files = [{"id": k, "repo": "r", "path": p, "lines": 40, "reachable": k == 0, "canonical_status": "x"}
for k, p in enumerate(("a.js", "b.js", "c.js", "missing.js"))]
(tmp_path / "_site" / "explore-code").mkdir(parents=True)
(tmp_path / "_site" / "explore-code" / "build_graph.json").write_text(_json.dumps(
{"cut": "t", "repos": [{"repo": "r", "commit": "c0"}], "files": files}))
monkeypatch.chdir(tmp_path)
for k in ("EXPLORE_GRAPH", "EXPLORE_SRC", "EXPLORE_WORK", "EXPLORE_FINGERPRINTS"):
monkeypatch.delenv(k, raising=False)
monkeypatch.setattr(_g.shutil, "which", lambda n: None) # behave as if node were missing
assert _g.main([]) == 0
out = _json.loads((tmp_path / "_work" / "7" / "identity-files.json").read_text())
assert out["mode"] == "lite" and "node" in out["lite_reason"]
v = {int(k): f["verdict"]["verdict"] for k, f in out["files"].items()}
assert v == {0: "unique", 1: "copy-of", 2: "near-copy-of", 3: "unknown"}
blob = _json.dumps(out)
assert "shared code" not in blob and "/tmp" not in blob # photon rule: keys only, no code text
assert out["files"]["1"]["keys"]["key"].startswith("r@c0 b.js:1-40 ")