"""Recompute root Set/Get evidence and protections without services or upstream execution.""" from __future__ import annotations import argparse import hashlib import json import sqlite3 import subprocess import sys import tarfile import zipfile from collections import Counter from pathlib import Path BASE = "818706412967ca371e39fe80f8951520b19e5779" def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--repo", type=Path, required=True) parser.add_argument("--db", type=Path, required=True) parser.add_argument("--documents", type=Path, required=True) args = parser.parse_args() repo = args.repo.resolve() sys.path.insert(0, str(repo / "calliope-backend")) from calliope.comfyui.serialization_reference import VHS_COMBINE_COMMIT from calliope.comfyui.structure_reference import ( SETGET_PROFILES, project_reference_setget, ) from scripts import audit_reference_conversion as audit from scripts.audit_library_documents import audit as audit_docs from scripts.verify_frontend_sources import verify out = repo / "docs/hel-892/setget-evidence" def write(name, value): (out / name).write_text(json.dumps(value, ensure_ascii=False, indent=2) + "\n") old = json.loads((repo / "docs/hel-892/vhs-evidence/library.json").read_bytes()) profiles = tuple(old["profiles"]) assert len(profiles) == 18 assert profiles == tuple( p for p in audit.REFERENCE_PROFILES if p not in SETGET_PROFILES ) before = audit.audit_library(repo, profiles) now = audit.audit_library(repo, baseline_profiles=profiles) write("library.json", now) for a, b, c in zip(old["cases"], before["cases"], now["cases"]): assert a["source_path"] == b["source_path"] == c["source_path"] assert a["attempts"] == b["attempts"] == c["attempts"][:18] assert a.get("comparisons") == b.get("comparisons") == c.get("comparisons") assert a["candidate_hashes"] == c["candidate_hashes"] assert old["gap_groups"] == before["gap_groups"] six = audit.audit(repo, "case04-batch-reference") assert six == json.loads( (repo / "docs/hel-892/media-evidence/protected-six-cases.json").read_bytes() ) write( "previous-protection.json", { "baseline_profiles": profiles, "old_attempts_identical": True, "old_gaps_identical": True, "six_companion_differences_identical": True, "old_candidate_hashes_identical": True, }, ) def groups(report): return { tuple( g[k] for k in ("type", "provider", "version", "profile", "code", "rule_gap") ): Counter( (o["source_path"], o["node_pointer"], o["node_id"]) for o in g["occurrences"] ) for g in report["gap_groups"] } def stats(report): gs = groups(report) return { "groups": len(gs), "raw_occurrences": sum(sum(c.values()) for c in gs.values()), "unique_occurrences_per_group": sum(len(c) for c in gs.values()), "unique_nodes": len({o for c in gs.values() for o in c}), "unique_paths": len({o[0] for c in gs.values() for o in c}), } def diffrows(a, b): return [ { "key": list(k), "occurrences": [ { "source_path": o[0], "node_pointer": o[1], "node_id": o[2], "count": n, } for o, n in sorted((v - b.get(k, Counter())).items(), key=str) ], } for k, v in sorted(a.items(), key=str) if v - b.get(k, Counter()) ] def unavailable(report): return sorted( r["source_path"] for r in report["cases"] if all(a["status"] == "not_applicable" for a in r["attempts"]) ) assert unavailable(before) == unavailable(now) ga, gb = groups(before), groups(now) added, removed = diffrows(gb, ga), diffrows(ga, gb) write( "coverage-delta.json", { "baseline_profiles": profiles, "baseline": stats(before), "current": stats(now), "key_fields": [ "type", "provider", "version", "profile", "code", "rule_gap", ], "occurrence_key": ["source_path", "node_pointer", "node_id"], "added_groups": added, "removed_groups": removed, "added_occurrences": sum( o["count"] for g in added for o in g["occurrences"] ), "removed_occurrences": sum( o["count"] for g in removed for o in g["occurrences"] ), "new_complete_paths": now["coverage_delta"]["new_complete_paths"], "complete_paths": now["coverage_delta"]["current_complete_paths"], "closed_paths": [ r["source_path"] for r in now["cases"] if r["status"] == "blocked" ], "unavailable_frontend_paths_unchanged": unavailable(now), "attempt_counts": dict( Counter(a["status"] for r in now["cases"] for a in r["attempts"]) ), "conflicts": sum(r["status"] == "candidate_conflict" for r in now["cases"]), }, ) # Read every manifest path, including non-.json suffixes and unused subgraphs. inventory = [] for row in now["cases"]: source = json.loads((repo / row["source_path"]).read_bytes()) for n in audit.node_inventory(source, include_aux=True): if n["type"] not in ("SetNode", "GetNode"): continue node = source for k in n["pointer"].split("/")[1:]: node = node[int(k)] if isinstance(node, list) else node[k] inventory.append( { "source_path": row["source_path"], "source_sha256": row["source_sha256"], "node_pointer": n["pointer"], "node_id": n["node_id"], "type": n["type"], "mode": node.get("mode", 0), "scope": "root" if n["pointer"].startswith("/nodes/") else "definition", "properties": node.get("properties"), "widgets_values": node.get("widgets_values"), "frontend": row["frontend_version"], } ) write("inventory.json", inventory) old_gaps = [g for g in old["gap_groups"] if g["type"] in ("SetNode", "GetNode")] occurrences = Counter( (o["source_path"], o["node_pointer"], o["node_id"]) for g in old_gaps for o in g["occurrences"] ) write( "inventory-summary.json", { "target_scope": "145 UI after case06 exclusion; includes unused definitions", "nodes": len(inventory), "paths": len({n["source_path"] for n in inventory}), "types": dict(Counter(n["type"] for n in inventory)), "scopes": dict(Counter(n["scope"] for n in inventory)), "declarations": dict( Counter( json.dumps( { k: (n["properties"] or {}).get(k) for k in ("cnr_id", "aux_id", "ver") }, sort_keys=True, ) for n in inventory ) ), "modes": dict(Counter(str(n["mode"]) for n in inventory)), "old_gap_groups": len(old_gaps), "old_gap_raw": sum(occurrences.values()), "old_gap_unique_nodes": len(occurrences), "old_gap_paths": len({o[0] for o in occurrences}), "old_gap_occurrences": [ {"source_path": k[0], "node_pointer": k[1], "node_id": k[2], "count": v} for k, v in sorted(occurrences.items()) ], }, ) # Diagnostic raw trace for the TWO previously scoped Scail Combine nodes. # NEVER remove other nodes/definitions or feed a clipped graph to conversion. chains = [] for row in now["cases"]: if "Scail-2" not in row["source_path"]: continue source = json.loads((repo / row["source_path"]).read_bytes()) nodes = {n["id"]: (i, n) for i, n in enumerate(source["nodes"])} links = {e[0]: (i, e) for i, e in enumerate(source["links"])} for ni, n in enumerate(source["nodes"]): if ( n["type"] != "VHS_VideoCombine" or (n.get("properties") or {}).get("ver") != VHS_COMBINE_COMMIT ): continue slot, s = next( (i, s) for i, s in enumerate(n["inputs"]) if s["name"] == "frame_rate" ) hops = [] lid = s["link"] seen = set() while True: li, e = links[lid] ai, a = nodes[e[1]] _bi, b = nodes[e[3]] assert b["inputs"][e[4]]["link"] == lid assert (a["outputs"][e[2]].get("links") or []).count(lid) == 1 assert a["outputs"][e[2]]["type"] == e[5] == b["inputs"][e[4]]["type"] assert a["id"] not in seen seen.add(a["id"]) hop = { "original_link": e, "link_pointer": f"/links/{li}", "node_pointer": f"/nodes/{ai}", "node_id": a["id"], "type": a["type"], "output_slot": e[2], "output_pointer": f"/nodes/{ai}/outputs/{e[2]}", "mode": a.get("mode", 0), "properties": a.get("properties"), } hops.append(hop) if a["type"] == "GetNode": name = a["widgets_values"][0] matched = [ (i, t) for i, t in enumerate(source["nodes"]) if t["type"] == "SetNode" and t["widgets_values"][0] == name ] assert len(matched) == 1 si, setter = matched[0] assert setter["inputs"][0]["type"] == a["outputs"][e[2]]["type"] hop.update( name=name, name_pointer=f"/nodes/{ai}/widgets_values/0", raw_root_unique_set=setter["id"], ) hops.append( { "node_id": setter["id"], "type": "SetNode", "node_pointer": f"/nodes/{si}", "current_name": setter["widgets_values"][0], "name_pointer": f"/nodes/{si}/widgets_values/0", "previousName": (setter.get("properties") or {}).get( "previousName" ), "mode": setter.get("mode", 0), "properties": setter.get("properties"), "input_slot": 0, "input_pointer": f"/nodes/{si}/inputs/0", } ) lid = setter["inputs"][0]["link"] elif a["type"] in ("SetNode", "Reroute"): lid = a["inputs"][0]["link"] else: break result = project_reference_setget(source) assert result.graph is None chains.append( { "source_path": row["source_path"], "source_sha256": row["source_sha256"], "combine_id": n["id"], "saved_frame_rate": n["widgets_values"]["frame_rate"], "saved_value_pointer": f"/nodes/{ni}/widgets_values/frame_rate", "target_pointer": f"/nodes/{ni}/inputs/{slot}", "hops": hops, "endpoint": [str(a["id"]), e[2]], "endpoint_type": a["outputs"][e[2]]["type"], "final_scalar": "unknown; upstream VHS_VideoInfoLoaded has no selected node contract; no media probe", "authority": "literal_root_topology_only_not_trusted_binding_or_partial_prompt", "whole_graph_rejections": result.issues, "comparison_status": row["comparison_status"], } ) assert len(chains) == 2 write("scail-frame-rate.json", chains) dirs = [ "serialization-evidence", "structure-reference", "controlnet-reference", "promoted-reference", "case04-reference", "media-reference", "separation-reference", "crop-split-reference", "vhs-reference", "setget-reference", ] entries = [] counts = [] for name in dirs: directory = repo / "docs/hel-892" / name verify(directory) rows = json.loads((directory / "sources.json").read_bytes())["sources"] for entry in rows: lines = (directory / entry["local_file"]).read_text().splitlines() locations = entry.get("rule_locations", {}) for lo, hi in ( locations.values() if isinstance(locations, dict) else locations ): assert 1 <= lo <= hi <= len(lines) counts.append( { "manifest": name, "entries": len(rows), "unique_ids": len({r["id"] for r in rows}), } ) entries.extend(rows) write( "cached-sources-check.json", { "manifests": counts, "entries": len(entries), "unique_ids_summed_per_manifest": sum(c["unique_ids"] for c in counts), "global_distinct_id_strings": len({r["id"] for r in entries}), "unique_url_and_hash": len({(r["raw_url"], r["sha256"]) for r in entries}), "note": "ID counts are strings; URL+SHA256 is separately deduplicated; repeated frontend originals retained", }, ) originals = json.loads( (repo / "docs/hel-892/media-evidence/original-bytes.json").read_bytes() )["files"] for row in originals: raw = (repo / row["path"]).read_bytes() assert raw == subprocess.check_output( ["git", "show", f"{BASE}:{row['path']}"], cwd=repo ) assert len(originals) == 163 write( "original-bytes.json", {"base": BASE, "count": 163, "all_unchanged": True, "files": originals}, ) production = json.loads( (repo / "docs/hel-892/vhs-evidence/production-protection.json").read_bytes() )["files"] for row in production: raw = (repo / row["path"]).read_bytes() assert raw == subprocess.check_output( ["git", "show", f"{BASE}:{row['path']}"], cwd=repo ) assert hashlib.sha256(raw).hexdigest() == row["sha256"] write("production-protection.json", {"base": BASE, "files": production}) db = sqlite3.connect(args.db) db.row_factory = sqlite3.Row rows = db.execute( "SELECT * FROM workflows WHERE source_repo_path IS NOT NULL" ).fetchall() assert len(rows) == 155 assert not any( r["is_enabled"] or r["doc_completed_at"] or r["exec_verified_at"] for r in rows ) issues = Counter(i["code"] for r in rows for i in json.loads(r["import_issues"])) companion_values = sum( p.get("value_origin") == "supplied_api_companion" for r in rows for p in json.loads(r["doc_json"])["params"] ) assert ( companion_values == 294 and issues["companion_unverified"] == 6 and issues["environment_unchecked"] == 16 ) write( "isolation.json", { "states": dict(Counter(r["import_state"] for r in rows)), "count": 155, "enabled_or_completed_or_executed": 0, "issue_counts": dict(issues), "companion_named_values": companion_values, "reference_candidates_written_to_db": False, "user_whole_row_protection": "executed affected tests", }, ) db.close() report = audit_docs(repo, args.documents.resolve()) summary = {k: v for k, v in report.items() if k != "files"} assert ( summary["named_values_preserved"] == 1217 and summary["unnamed_widget_nodes"] == 3660 ) assert summary["full_documents_completed"] == 0 and summary["real_executions"] == 0 write("document-audit-summary.json", summary) packages = [] with ( zipfile.ZipFile(next((repo / "calliope-backend/dist").glob("*.whl"))) as wh, tarfile.open(next((repo / "calliope-backend/dist").glob("*.tar.gz"))) as sd, ): for name in [ "structure_reference.py", "serialization_reference.py", "ui2api.py", "protocol_references.json", "source_reviews.json", "delivery_scope.py", "delivery_scope.json", ]: p = f"calliope-backend/src/calliope/comfyui/{name}" raw = (repo / p).read_bytes() assert wh.read(f"calliope/comfyui/{name}") == raw member = next( n for n in sd.getnames() if n.endswith(f"/src/calliope/comfyui/{name}") ) assert sd.extractfile(member).read() == raw packages.append( { "path": p, "sha256": hashlib.sha256(raw).hexdigest(), "wheel_matches": True, "sdist_matches": True, } ) write("package-check.json", packages) print( json.dumps( { "ui": now["ui_total"], "attempts": Counter( a["status"] for r in now["cases"] for a in r["attempts"] ), "complete": len(now["coverage_delta"]["current_complete_paths"]), "new_complete": now["coverage_delta"]["new_complete_paths"], "inventory_nodes": len(inventory), "inventory_paths": len({n["source_path"] for n in inventory}), "gap_stats": stats(now), }, ensure_ascii=False, ) ) if __name__ == "__main__": main()