"""Recompute H3 core first-group reference 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 = "8e832b8e0e14db85932f4d830be2d2929b9e62a1" 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.h3_core_reference import CORE_PROFILE 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/h3-core-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/h3-evidence/library.json").read_bytes()) profiles = tuple(old["profiles"]) assert len(profiles) == 26 assert profiles == tuple(p for p in audit.REFERENCE_PROFILES if p != CORE_PROFILE) 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"][:26] assert a.get("comparisons") == b.get("comparisons") == c.get("comparisons") if a["candidate_hashes"]: 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"]) ) removed_unavailable = sorted(set(unavailable(before)) - set(unavailable(now))) added_unavailable = sorted(set(unavailable(now)) - set(unavailable(before))) 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_before": unavailable(before), "unavailable_frontend_after": unavailable(now), "removed_unavailable_frontend_paths": removed_unavailable, "added_unavailable_frontend_paths": added_unavailable, "unavailable_frontend_change_reason": "new explicit missing-identity 1.53.10/core0.33.0 assumption; applicability is not source provenance or conversion success", "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"]), }, ) from calliope.comfyui.ui2api import convert_reference targets = sorted( (repo / "example_ComfyUI_workflows/4-视频生成/uncensored").glob("*.json") ) assert len(targets) == 3 actual_rows = [] for target in targets: source = json.loads(target.read_bytes()) actual = convert_reference(source, CORE_PROFILE) assert actual.prompt is None and actual.issues row = next( r for r in now["cases"] if r["source_path"] == target.relative_to(repo).as_posix() ) assert row["comparison_status"] == "comparison_unavailable" attempt = next(a for a in row["attempts"] if a["profile"] == CORE_PROFILE) assert attempt["status"] == "rejected" and "candidate_prompt" not in attempt actual_rows.append( { "source_path": row["source_path"], "source_sha256": row["source_sha256"], "profile": CORE_PROFILE, "prompt": None, "comparison_status": row["comparison_status"], "execution_verified": False, "original_bytes_modified": False, "attempt": attempt, } ) write("actual-three-graphs.json", actual_rows) main = next( r for r in actual_rows if r["source_path"].endswith("minimax-h3文生视频无审核版.json") ) evidence = main["attempt"]["supported_node_evidence"] assert len(evidence) == 7 and sum(e["layout_accepted"] for e in evidence) == 5 assert sum(len(e["saved_fields"]) for e in evidence) == 11 main_source = json.loads((repo / main["source_path"]).read_bytes()) def pointer(doc, text): for key in text.strip("/").split("/"): doc = doc[int(key)] if isinstance(doc, list) else doc[key] return doc for r in actual_rows: doc = json.loads((repo / r["source_path"]).read_bytes()) for e in r["attempt"]["supported_node_evidence"]: for f in e["saved_fields"]: value = pointer(doc, f["source_value_pointer"]) assert type(value).__name__ == f["json_type"] and value == f["value"] for edge in e["physical_input_evidence"]: original = pointer(doc, edge["link_pointer"]) assert edge["endpoint"] == [str(original[1]), original[2]] write( "main-node-evidence.json", { "source_path": main["source_path"], "source_sha256": main["source_sha256"], "source_entities": len(main_source["nodes"]), "source_edges": len(main_source["links"]), "profile": CORE_PROFILE, "prompt": None, "complete_candidates_added": 0, "comparison_status": "comparison_unavailable", "saved_fields_only": 11, "layout_accepted_instances": 5, "layout_rejected_instances": 2, "supported_node_evidence": evidence, "remaining_classes": sorted( { n["type"] for n in main_source["nodes"] if n["type"] not in {e["type"] for e in evidence} } ), "remaining_instance_count": len(main_source["nodes"]) - len(evidence), "issues": main["attempt"]["issues"], "no_partial_prompt": True, "execution_verified": False, }, ) inventory = evidence attempts = [ { "source_path": r["source_path"], "source_sha256": r["source_sha256"], "declared_frontend": r["frontend_version"], "attempt": r["attempts"][-1], } for r in now["cases"] ] assert all(r["attempt"]["profile"] == CORE_PROFILE for r in attempts) write( "profile-disposition.json", { "profile": CORE_PROFILE, "counts": dict(Counter(r["attempt"]["status"] for r in attempts)), "cases": attempts, "proven_source_identity": False, "complete_candidates_added": 0, }, ) dirs = [ "serialization-evidence", "structure-reference", "controlnet-reference", "promoted-reference", "case04-reference", "media-reference", "separation-reference", "crop-split-reference", "vhs-reference", "setget-reference", "videoinfo-reference", "scail-load-reference", "grid-reference", "h3-reference", "h3-core-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/setget-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 Counter(r["import_state"] for r in rows) == { "pending_check": 16, "needs_conversion": 139, } 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", }, ) from calliope.comfyui.companions import load_companions from calliope.comfyui.library import import_library # A separate in-memory copy proves the complete user row is preserved; # the fresh catalogue under audit is never mutated by this protection check. protected = sqlite3.connect(":memory:") db.backup(protected) protected.row_factory = sqlite3.Row wid = rows[0]["id"] protected.execute( "UPDATE workflows SET description='用户整行保护测试' WHERE id=?", (wid,) ) protected.commit() snapshot = dict( protected.execute("SELECT * FROM workflows WHERE id=?", (wid,)).fetchone() ) rerun = import_library( protected, repo / "example_ComfyUI_workflows", source_commit=BASE, companions=load_companions(repo / "docs/hel-892/supplied-api/manifest.json"), ) assert rerun["counts"] == {"conflict": 1, "skipped": 154, "user_excluded": 1} assert ( dict(protected.execute("SELECT * FROM workflows WHERE id=?", (wid,)).fetchone()) == snapshot ) write( "user-row-protection.json", { "isolated_in_memory_copy": True, "counts": rerun["counts"], "all_columns_identical": True, "column_count": len(snapshot), "fresh_catalogue_mutated": False, }, ) protected.close() 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 [ "h3_core_reference.py", "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": 1, "gap_stats": stats(now), }, ensure_ascii=False, ) ) if __name__ == "__main__": main()