HEL-892: review remaining source semantics and prepare frontend export comparisons

Co-authored-by: multica-agent <github@multica.ai>
This commit is contained in:
leefer
2026-10-28 01:00:21 +08:00
co-authored by multica-agent
parent 8c666d2220
commit 1390489289
168 changed files with 92854 additions and 590 deletions
@@ -26,6 +26,7 @@ def audit(repo: Path, directory: Path) -> dict:
assert hashlib.sha1(raw).hexdigest() == entry["source_sha"]
assert doc["source_review"]["source_sha"] == entry["source_sha"]
nodes = {}
source_links = []
def visit(graph, scope=""):
ui = "nodes" in graph
@@ -37,10 +38,20 @@ def audit(repo: Path, directory: Path) -> dict:
if ui and "widgets_values" in node
else ([] if ui else node["inputs"])
)
if not ui:
source_links.extend(
{"scope": scope, "node_id": nid, "field": key,
"upstream_node_id": str(value[0]), "output_slot": value[1]}
for key, value in node["inputs"].items()
if isinstance(value, list) and len(value) == 2
)
source_links.extend({"scope": scope, "link": link}
for link in graph.get("links", []))
for sub in graph.get("definitions", {}).get("subgraphs", []):
visit(sub, scope + sub["id"] + "/")
visit(source)
assert doc["source_links"] == source_links
assert {n["node_id"]: n["source_values"] for n in doc["source_nodes"]} == nodes
for param in doc["params"]:
assert param["default"] == nodes[param["node_id"]][param["field"]]
@@ -51,6 +62,30 @@ def audit(repo: Path, directory: Path) -> dict:
checked_fields = doc["source_review"].get("reviewed_named_fields", [])
for field in checked_fields:
assert field["source_value"] == nodes[field["node_id"]][field["field"]]
semantic = doc["source_review"].get("semantic_review")
if semantic:
assert semantic["batch"] == "HEL-892-third"
assert semantic["operation_check"] in doc["steps"]
assert semantic["conclusions"] and semantic["unknowns"]
assert {(f["node_id"], f["field"]) for f in checked_fields} == {
(p["node_id"], p["field"]) for p in doc["params"]
}
for kind in ("nodes", "notes"):
for ref in semantic["evidence_refs"][kind]:
key, index = ref["pointer"].strip("/").split("/")
assert doc[key][int(index)]["node_id"] == ref["node_id"]
assert semantic["mechanical_inventory"] == {
"named_value_count": len(doc["params"]),
"note_count": len(doc["source_notes"]),
"link_count": len(doc["source_links"]),
"position_widget_node_count": len(
doc["source_review"]["evidence"]["unnamed_widget_node_ids"]
),
}
if not checked_fields:
assert semantic["named_parameter_finding"] == (
"未发现可由源文件确认的具名参数"
)
assert doc["status"] == {"imported": True, "doc_done": False, "exec_verified": False}
assert doc["source_review"]["complete"] is False
files.append(
@@ -65,6 +100,7 @@ def audit(repo: Path, directory: Path) -> dict:
"source_evidence": doc["source_review"]["evidence"],
"unconfirmed": doc["source_review"]["unconfirmed"],
"reviewed_named_fields": checked_fields,
"semantic_review": semantic,
}
)
return {
@@ -82,17 +118,61 @@ def audit(repo: Path, directory: Path) -> dict:
"unnamed_widget_nodes": sum(
len(f["source_evidence"]["unnamed_widget_node_ids"]) for f in files
),
"scope_limit": "人工审校只覆盖结构与用途局部;值/注释逐字保留是机械比对,非语义定稿",
"semantic_batch_files": sum(bool(f["semantic_review"]) for f in files),
"semantic_batch_without_named_fields": sum(
bool(f["semantic_review"]) and not f["reviewed_named_fields"] for f in files
),
"semantic_batch_named_fields": sum(
len(f["reviewed_named_fields"]) for f in files if f["semantic_review"]
),
"named_values_without_manual_field_review": sum(
f["source_evidence"]["named_value_count"] - len(f["reviewed_named_fields"])
for f in files
),
"named_values_without_verified_units_ranges_effects": sum(
f["source_evidence"]["named_value_count"] for f in files
),
"scope_limit": "人工结论与机械原值清单分开;源语义局部审校非完整说明定稿",
}
def audit_partition(repo: Path, report: dict, partition_path: Path) -> dict:
partition = json.loads(partition_path.read_text(encoding="utf-8"))
prior, added = partition["prior_16"], partition["new_140"]
prior_paths = {e["path"] for e in prior}
added_paths = {e["path"] for e in added}
assert len(prior) == len(prior_paths) == 16
assert len(added) == len(added_paths) == 140
assert prior_paths.isdisjoint(added_paths)
assert prior_paths | added_paths == {f["path"] for f in report["files"]}
reviews = json.loads((repo / "calliope-backend/src/calliope/comfyui/source_reviews.json")
.read_text(encoding="utf-8"))
for entry in prior:
review = reviews[entry["path"]]
assert review["reviewed_named_fields"] == entry["reviewed_named_fields"]
assert hashlib.sha256(json.dumps(review, ensure_ascii=False, sort_keys=True)
.encode()).hexdigest() == entry["review_sha256"]
by_path = {f["path"]: f for f in report["files"]}
for entry in prior + added:
assert entry["source_sha"] == by_path[entry["path"]]["source_sha"]
assert all(by_path[p]["semantic_review"] for p in added_paths)
assert all(not by_path[p]["semantic_review"] for p in prior_paths)
return {"prior_files": 16, "prior_named_fields": 42, "new_files": 140,
"new_named_fields": report["semantic_batch_named_fields"],
"new_without_named_fields": report["semantic_batch_without_named_fields"],
"disjoint_complete_sha_verified": True, "prior_review_payloads_unchanged": True}
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", type=Path, required=True)
parser.add_argument("--documents", type=Path, required=True)
parser.add_argument("--output", type=Path, required=True)
parser.add_argument("--partition", type=Path)
args = parser.parse_args()
report = audit(args.repo, args.documents)
if args.partition:
report["partition"] = audit_partition(args.repo, report, args.partition)
args.output.write_text(
json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
@@ -0,0 +1,219 @@
"""Offline, fail-closed comparison against source-bound original frontend exports.
This command never imports a workflow, enables one, calls a service, or executes it.
An equal result only establishes equality to the supplied export, not its provenance.
"""
from __future__ import annotations
import argparse
import hashlib
import json
from pathlib import Path
from calliope.comfyui.library import load_snapshot
from calliope.comfyui.ui2api import convert
def differences(expected, actual, pointer=""):
"""Keep types, absent keys, list order and nonzero output slots significant."""
if type(expected) is not type(actual):
return [{"path": pointer, "expected": expected, "actual": actual, "kind": "type"}]
if isinstance(expected, dict):
rows = []
for key in sorted(expected.keys() | actual.keys()):
child = pointer + "/" + key.replace("~", "~0").replace("/", "~1")
if key not in expected or key not in actual:
rows.append(
{
"path": child,
"kind": "missing_key",
"expected_present": key in expected,
"actual_present": key in actual,
"expected": expected.get(key),
"actual": actual.get(key),
}
)
else:
rows.extend(differences(expected[key], actual[key], child))
return rows
if isinstance(expected, list):
rows = []
for index in range(max(len(expected), len(actual))):
child = pointer + "/" + str(index)
if index >= len(expected) or index >= len(actual):
rows.append(
{
"path": child,
"kind": "missing_item",
"expected_present": index < len(expected),
"actual_present": index < len(actual),
"expected": expected[index] if index < len(expected) else None,
"actual": actual[index] if index < len(actual) else None,
}
)
else:
rows.extend(differences(expected[index], actual[index], child))
return rows
return (
[]
if expected == actual
else [{"path": pointer, "kind": "value", "expected": expected, "actual": actual}]
)
def preserved_fields(expected, actual, pointer=""):
if type(expected) is not type(actual):
return []
if isinstance(expected, dict):
return [
row
for key in sorted(expected.keys() & actual.keys())
for row in preserved_fields(
expected[key],
actual[key],
pointer + "/" + key.replace("~", "~0").replace("/", "~1"),
)
]
if isinstance(expected, list):
return [
row
for index, (left, right) in enumerate(zip(expected, actual))
for row in preserved_fields(left, right, pointer + "/" + str(index))
]
return [{"path": pointer, "value": expected}] if expected == actual else []
def compare_case(repo, exports, case, snapshot=None):
row = {**case, "executable": False, "execution_verified": False}
try:
raw = (repo / case["source_path"]).read_bytes()
if hashlib.sha1(raw).hexdigest() != case["source_sha"]:
return {**row, "status": "source_sha_mismatch"}
source = json.loads(raw.decode("utf-8-sig"))
missing = [
name
for name in (case["export_file"], case["binding_file"])
if not (exports / name).is_file()
]
if missing:
return {
**row,
"status": "missing_materials",
"missing": missing,
"cannot_check": case["comparison"],
"node_definitions_available": bool(snapshot),
"missing_definitions": [] if snapshot else [
"未提供可信节点定义;UI位置控件和插件行为不能仅凭源文件确认"
],
}
export_raw = (exports / case["export_file"]).read_bytes()
binding = json.loads((exports / case["binding_file"]).read_text(encoding="utf-8"))
# Binding is an operator statement, not automatic authentication of provenance.
required = {
"source_path": case["source_path"],
"source_sha": case["source_sha"],
"export_sha256": hashlib.sha256(export_raw).hexdigest(),
"original_frontend_export": True,
}
if any(
type(binding.get(k)) is not type(v) or binding.get(k) != v for k, v in required.items()
) or not all(
isinstance(binding.get(k), str) and binding[k].strip()
for k in ("exported_at", "frontend_version", "node_versions", "origin")
):
return {**row, "status": "invalid_binding", "required": required}
expected = json.loads(export_raw.decode("utf-8-sig"))
# A UI file is not an original API export, even when convert could accept it.
if not isinstance(expected, dict) or "nodes" in expected:
return {**row, "status": "invalid_export", "issues": ["必须为原始API图"]}
checked = convert(expected)
if checked.prompt is None:
return {**row, "status": "invalid_export", "issues": checked.issues}
result = convert(source, (snapshot or {}).get("object_info"))
row.update(
export_sha256=required["export_sha256"],
binding=binding,
provenance="仅记录提供者声明;真实性仍需审核",
)
if result.prompt is None:
return {
**row,
"status": "conversion_blocked",
"issues": result.issues,
"cannot_check": "转换器未生成完整prompt,不能逐字段/连线对照",
}
def split(graph):
return (
{
nid: {k: v for k, v in node.items() if k != "_meta"}
for nid, node in graph.items()
},
{nid: node["_meta"] for nid, node in graph.items() if "_meta" in node},
)
expected_graph, expected_meta = split(expected)
actual_graph, actual_meta = split(result.prompt)
delta = differences(expected_graph, actual_graph)
metadata = differences(expected_meta, actual_meta)
return {
**row,
"status": "different" if delta or metadata else "equal",
"differences": delta,
"metadata_differences": metadata,
"preserved_fields": preserved_fields(expected_graph, actual_graph),
"preserved_node_ids": sorted(expected.keys() & result.prompt.keys()),
"comparison_scope": "全部字段、类型、值及连线槽;_meta单列也影响equal",
}
except (OSError, ValueError, KeyError, TypeError, AttributeError) as exc:
return {**row, "status": "invalid_materials", "error": f"{type(exc).__name__}: {exc}"}
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--repo", type=Path, required=True)
parser.add_argument("--cases", type=Path, required=True)
parser.add_argument("--exports", type=Path, required=True)
parser.add_argument("--snapshot", type=Path)
parser.add_argument("--output", type=Path, required=True)
args = parser.parse_args()
cases = json.loads(args.cases.read_text(encoding="utf-8"))["cases"]
try:
snapshot = load_snapshot(args.snapshot)
except (OSError, ValueError, AttributeError) as exc:
report = {
"status": "invalid_snapshot",
"error": str(exc),
"cases": [],
"execution_verified": False,
}
else:
rows = [compare_case(args.repo, args.exports, case, snapshot) for case in cases]
report = {
"status": "equal"
if rows and all(r["status"] == "equal" for r in rows)
else "not_ready",
"cases": rows,
"execution_verified": False,
"snapshot_source": (snapshot or {}).get("source_url"),
"snapshot_captured_at": (snapshot or {}).get("captured_at"),
}
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(
json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8"
)
print(
json.dumps(
{
"status": report["status"],
"cases": [{"id": r["id"], "status": r["status"]} for r in report["cases"]],
},
ensure_ascii=False,
)
)
return 0 if report["status"] == "equal" else 1
if __name__ == "__main__":
raise SystemExit(main())