"""The source-bound editorial block cannot grant conversion or execution eligibility.""" from __future__ import annotations import copy import hashlib import json from collections import Counter from pathlib import Path import pytest from calliope.comfyui import source_reviews from calliope.comfyui.companions import load_companions from calliope.comfyui.fixed_document import SOURCE_PATH from calliope.comfyui.library import build_document, import_library, rollback_batch from calliope.db import get_db, migrate_db REPO = Path(__file__).resolve().parents[2] RAW = (REPO / SOURCE_PATH).read_bytes() SOURCE = json.loads(RAW) REVIEW = source_reviews.review_for(SOURCE_PATH, hashlib.sha1(RAW).hexdigest()) BLOCK = REVIEW["fixed_version_document"] def pointer(value, path): for token in path.strip("/").split("/"): value = value[int(token)] if isinstance(value, list) else value[token] return value def document(source=SOURCE, review=REVIEW, path=SOURCE_PATH): return build_document(path, source, None, None, [], review) def test_original_binding_and_independent_accounts(): doc = document() fixed = doc["fixed_version"] assert fixed["matched"] and fixed["counts"] == { "saved_fields": 18, "final_scalars": 16, "linked_saved_fields": 1, "frontend_only": 1, "physical_edges": 3, } assert Counter(f["role"] for f in fixed["fields"]) == {"scalar": 16, "linked": 1, "frontend": 1} assert len({(f["node_id"], f["field"]) for f in fixed["fields"]}) == 18 assert doc["params"] == [] assert "fixed_version_document" not in doc["source_review"] assert doc["source_review"]["reviewed_named_fields"] == REVIEW["reviewed_named_fields"] assert doc["status"] == {"imported": True, "doc_done": False, "exec_verified": False} assert doc["dependencies"]["check_state"] == "unchecked" assert all(step in doc["steps"] for step in fixed["steps"]) # No shared mutable state leaks into later builds. fixed["fields"][0]["value"] = "consumer edit" assert ( document()["fixed_version"]["fields"][0]["value"] == SOURCE["nodes"][0]["widgets_values"][0] ) @pytest.mark.parametrize("index", range(18)) def test_every_value_pointer_and_fixed_evidence(index): field = BLOCK["fields"][index] for key in ("pointer", "named_pointer"): value = pointer(SOURCE, field[key]) assert type(value).__name__ == field["json_type"] assert type(value) is type(field["value"]) and value == field["value"] assert field["label"] and field["effect"] and field["limits"] and field["evidence"] for number in field["evidence"]: evidence = BLOCK["sources"][number] raw = (REPO / "docs/hel-892/h3-reference" / evidence["local_file"]).read_bytes() assert hashlib.sha256(raw).hexdigest() == evidence["sha256"] assert len(evidence["commit"]) == 40 a, b = evidence["lines"] assert 1 <= a <= b <= len(raw.decode().splitlines()) assert evidence["commit"] in evidence["url"] @pytest.mark.parametrize("index", range(18)) @pytest.mark.parametrize("form", ["pointer", "named_pointer"]) def test_each_saved_value_change_refuses_old_definition(index, form): source = copy.deepcopy(SOURCE) path = BLOCK["fields"][index][form] parent, _, token = path.rpartition("/") target = pointer(source, parent) if isinstance(target, list): target[int(token)] = None else: target[token] = None fixed = document(source)["fixed_version"] assert not fixed["matched"] and "fields" not in fixed @pytest.mark.parametrize( "change", [ "frontend", "provider", "plugin_version", "core_version", "node_id", "node_type", "edge", "title", "mode", "extra", ], ) def test_whole_graph_identity_binding(change): source = copy.deepcopy(SOURCE) if change == "frontend": source["extra"]["frontendVersion"] = "1.0.0" elif change in ("provider", "plugin_version", "core_version"): index = 2 if change == "core_version" else 0 source["nodes"][index]["properties"]["cnr_id" if change == "provider" else "ver"] = "other" elif change == "edge": source["links"][0][2] = 9 elif change == "extra": source["nodes"].append({"id": 173, "type": "Unknown"}) else: source["nodes"][0][ {"node_id": "id", "node_type": "type", "title": "title", "mode": "mode"}[change] ] = "changed" assert not document(source)["fixed_version"]["matched"] @pytest.mark.parametrize( "change", ["missing", "sha", "citation", "lines", "pointer", "value", "text"] ) def test_document_evidence_is_bound_too(change): review = copy.deepcopy(REVIEW) block = review["fixed_version_document"] if change == "missing": del review["fixed_version_document"] elif change == "sha": review["source_sha"] = "wrong" elif change == "citation": block["sources"][0]["sha256"] = "0" * 64 elif change == "lines": block["sources"][0]["lines"] = [1, 2] elif change == "text": block["fields"][0]["effect"] = "unreviewed" else: block["fields"][0][change] = "changed" assert not document(review=review)["fixed_version"]["matched"] assert document(review=None)["fixed_version"]["matched"] is False assert "fixed_version" not in document(path="another/Minimax-H3提示词增强.json") async def test_existing_db_single_refresh_rollback_reimport_and_user_whole_row( tmp_path, monkeypatch ): reviews = copy.deepcopy(source_reviews._reviews()) previous = copy.deepcopy(reviews) del previous[SOURCE_PATH]["fixed_version_document"] monkeypatch.setattr(source_reviews, "_reviews", lambda: previous) await migrate_db(tmp_path / "db") conn = get_db(tmp_path / "db") companions = load_companions(REPO / "docs/hel-892/supplied-api/manifest.json") def run(): return import_library( conn, REPO / "example_ComfyUI_workflows", source_commit="fixed-document-test", companions=companions, ) first = run() assert first["counts"] == {"imported": 155, "user_excluded": 1} before = {r["source_repo_path"]: dict(r) for r in conn.execute("SELECT * FROM workflows")} assert run()["counts"] == {"skipped": 155, "user_excluded": 1} monkeypatch.setattr(source_reviews, "_reviews", lambda: reviews) refreshed = run() assert refreshed["counts"] == {"updated": 1, "skipped": 154, "user_excluded": 1} assert refreshed["states"] == {"pending_check": 16, "needs_conversion": 139} for row in conn.execute("SELECT * FROM workflows"): saved = dict(row) if row["source_repo_path"] != SOURCE_PATH: assert saved == before[row["source_repo_path"]] else: assert json.loads(row["doc_json"])["fixed_version"]["matched"] # Only documentation/audit bookkeeping changes; eligibility columns stay identical. for key in saved.keys() - { "doc_json", "batch_id", "imported_at", "library_fingerprint", }: assert saved[key] == before[SOURCE_PATH][key] assert rollback_batch(conn, refreshed["batch_id"])["files"][0]["result"] == "restored" row = dict( conn.execute("SELECT * FROM workflows WHERE source_repo_path=?", (SOURCE_PATH,)).fetchone() ) assert row == before[SOURCE_PATH] assert run()["counts"] == {"updated": 1, "skipped": 154, "user_excluded": 1} assert run()["counts"] == {"skipped": 155, "user_excluded": 1} conn.execute( "UPDATE workflows SET description=? WHERE source_repo_path=?", ("用户说明", SOURCE_PATH) ) conn.commit() snapshot = dict( conn.execute("SELECT * FROM workflows WHERE source_repo_path=?", (SOURCE_PATH,)).fetchone() ) assert len(snapshot) == 29 assert run()["counts"] == {"conflict": 1, "skipped": 154, "user_excluded": 1} assert ( dict( conn.execute( "SELECT * FROM workflows WHERE source_repo_path=?", (SOURCE_PATH,) ).fetchone() ) == snapshot ) for row in conn.execute("SELECT * FROM workflows"): assert ( not row["is_enabled"] and row["doc_completed_at"] is None and row["exec_verified_at"] is None ) conn.close()