Files
aigc-home/docs/hel-892/batch175-closure-evidence/audit.py
T

735 lines
30 KiB
Python

"""Read-only closure ledger. Treat every
workflow string as data, never code."""
import collections
import csv
import hashlib
import json
import os
import sqlite3
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[3]
HERE = Path(__file__).resolve().parent
LOCAL = ROOT / ".local-evidence/batch175-closure"
OUTPUT = LOCAL / sys.argv[1]
BASE = "c73d76527593707121cf4b137c4d594eeecd8230"
RESOURCE = "calliope-backend/src/calliope/comfyui/source_reviews.json"
sys.path.insert(0, str(ROOT / "calliope-backend/src"))
sys.path.insert(0, str(ROOT / "docs/hel-892/history-attribution-correction"))
def sha(raw):
return hashlib.sha256(raw).hexdigest()
def canonical(v):
return json.dumps(v, ensure_ascii=False, sort_keys=True, separators=(",", ":")).encode()
def typed(v):
if isinstance(v, dict):
return ["object", [[k, typed(x)] for k, x in sorted(v.items())]]
if isinstance(v, list):
return ["array", [typed(x) for x in v]]
return [type(v).__name__, v]
def ptr(v, pointer):
assert pointer.startswith("/")
for part in pointer[1:].split("/"):
part = part.replace("~1", "/").replace("~0", "~")
v = v[int(part)] if isinstance(v, list) else v[part]
return v
def esc(s):
return str(s).replace("~", "~0").replace("/", "~1")
def write(name, value):
with (OUTPUT / name).open("x", encoding="utf-8") as f:
json.dump(value, f, ensure_ascii=False, indent=2)
f.write("\n")
def history():
rows = []
reads = json.loads((LOCAL / "history-reads.json").read_bytes())
for read in reads:
for r in json.loads((LOCAL / "threads" / (read["root"] + ".json")).read_bytes()):
rows.append(
{
k: r[k]
for k in ("id", "author_id", "content", "created_at", "parent_id")
if k in r
}
)
return rows
def graphs(raw):
yield "root", "", raw
for i, graph in enumerate(raw.get("definitions", {}).get("subgraphs", [])):
yield str(graph["id"]), f"/definitions/subgraphs/{i}", graph
def main():
from calliope.comfyui.delivery_scope import exclusion_for
from calliope.comfyui.fixed_document import DEFINITIONS
from scripts.audit_library_documents import audit
assert OUTPUT.parent == LOCAL
OUTPUT.mkdir()
preflight = json.loads((LOCAL / "preflight.json").read_bytes())
sha_paths = collections.defaultdict(list)
for baseline in json.loads((LOCAL / "baseline-files.json").read_bytes())["files"]:
sha_paths[baseline["sha256"]].append(baseline["path"])
assert preflight["base"] == BASE
reviews = json.loads((ROOT / RESOURCE).read_bytes())
all_paths = {
p.relative_to(ROOT).as_posix()
for p in (ROOT / "example_ComfyUI_workflows").rglob("*")
if p.is_file()
}
excluded = {p for p in all_paths if exclusion_for(p)}
targets = all_paths - excluded
blocks = {
p: r["fixed_version_document"] for p, r in reviews.items() if "fixed_version_document" in r
}
assert len(all_paths) == 156 and len(excluded) == 1
assert targets == set(DEFINITIONS) == set(blocks) and not excluded.intersection(blocks)
with sqlite3.connect(f"file:{LOCAL / 'library.db'}?mode=ro", uri=True) as conn:
conn.row_factory = sqlite3.Row
rows = {r["source_repo_path"]: dict(r) for r in conn.execute("SELECT * FROM workflows")}
assert set(rows) == targets
exported = json.loads((LOCAL / "export/manifest.json").read_bytes())
exports = {r["path"]: r for r in exported}
assert set(exports) == targets and len(exported) == 155
result = audit(ROOT, LOCAL / "export")
write("existing-library-audit.json", result)
pinfiles = {}
for p in (ROOT / "docs/hel-892").rglob("pins.json"):
if HERE in p.parents:
continue
for source, pin in json.loads(p.read_bytes()).items():
if DEFINITIONS.get(source) == pin:
pinfiles[source] = p
from attribution import Attributor
messages = history()
write("historical-comment-texts.json", messages)
instruction = json.loads((LOCAL / "instruction.json").read_bytes())
attributor = Attributor(
ROOT,
messages,
BASE,
{"current_section": instruction["description"].split("\n---\n", 1)[0]},
)
write(
"current-instruction.json",
{
**{k: v for k, v in instruction.items() if k != "description"},
"description_sha256": sha(instruction["description"].encode()),
"current_section": instruction["description"].split("\n---\n", 1)[0],
},
)
ledgers, proofs, notes, identities, sources, remaining = [], [], [], [], [], []
totaltypes = collections.Counter()
for ordinal, path in enumerate(sorted(targets), 1):
rawbytes = (ROOT / path).read_bytes()
raw = json.loads(rawbytes.decode("utf-8-sig"))
b, row = blocks[path], rows[path]
doc = json.loads(row["doc_json"])
fixed = dict(doc["fixed_version"])
assert fixed.pop("matched") is True and typed(fixed) == typed(b), path
assert typed(doc) == typed(
json.loads((LOCAL / "export" / exports[path]["document"]).read_bytes())
)
assert b["source_sha1"] == row["source_sha"] == hashlib.sha1(rawbytes).hexdigest()
assert b["source_sha256"] == sha(rawbytes)
assert b["canonical_sha256"] == sha(canonical(raw))
assert sha(canonical(b)) == DEFINITIONS[path]
assert (
row["is_enabled"] == 0
and row["doc_completed_at"] is None
and row["exec_verified_at"] is None
)
assert doc["status"] == {"doc_done": False, "exec_verified": False, "imported": True}
assert doc["dependencies"]["check_state"] == "unchecked"
assert doc["dependencies"]["checked_at"] is None
evidence = RESOURCE + "#/" + esc(path) + "/fixed_version_document"
pointers, ftypes = [], collections.Counter()
for i, f in enumerate(b["fields"]):
value = ptr(raw, f["pointer"])
assert typed(value) == typed(f["value"]), (path, i, f["pointer"])
assert type(value).__name__ == f["json_type"], (path, i)
named = f.get("named_pointer")
named_is_pointer = isinstance(named, str) and named.startswith("/")
if named_is_pointer:
namedvalue = ptr(raw, named)
if "named_value" in f:
assert typed(namedvalue) == typed(f["named_value"]), (path, i, named)
pointers.append(f["pointer"])
ftypes[type(value).__name__] += 1
proofs.append(
dict(
source_repo_path=path,
field_index=i,
pointer=f["pointer"],
json_type=f["json_type"],
recursive_typed_sha256=sha(canonical(typed(value))),
value_sha256=sha(canonical(value)),
named_pointer=named,
named_value_present="named_value" in f,
named_value_sha256=sha(canonical(ptr(raw, named)))
if named_is_pointer
else None,
named_check=(
"explicit_named_value_equal"
if "named_value" in f
else "independent_original_read_no_parallel_equality_contract"
)
if named_is_pointer
else "unknown/not_a_pointer"
if named
else "not_recorded",
block_evidence=evidence + f"/fields/{i}",
checked_equal=True,
)
)
assert len(pointers) == len(set(pointers)), path
assert len(pointers) == b["counts"]["saved_fields"], path
totaltypes.update(ftypes)
raw_nodes, raw_notes, link_count, subgraphs = [], [], 0, []
for scope, prefix, graph in graphs(raw):
ui = "nodes" in graph
node_items = (
[(prefix + f"/nodes/{i}", n) for i, n in enumerate(graph["nodes"])]
if ui
else [("/" + esc(k), dict(n, id=k)) for k, n in graph.items()]
)
if prefix:
subgraphs.append(
dict(
id=scope,
pointer=prefix,
nodes=len(node_items),
inputs=len(graph.get("inputs", [])),
outputs=len(graph.get("outputs", [])),
edges=len(graph.get("links", [])),
)
)
link_count += (
len(graph.get("links", []))
if ui
else sum(
isinstance(v, list) and len(v) == 2
for _, n in node_items
for v in n["inputs"].values()
)
)
for nodeptr, n in node_items:
cls = n.get("type", n.get("class_type"))
props = n.get("properties", {})
raw_nodes.append(
dict(
node_id=str(n["id"]),
scope=scope,
pointer=nodeptr,
class_type=cls,
declared_properties=props,
declaration_evidence=path + "#" + nodeptr,
raw_version_declaration=props.get("ver"),
raw_provider_declaration=props.get("cnr_id", props.get("aux_id")),
)
)
if cls in ("Note", "MarkdownNote"):
raw_notes.append(
dict(
node_id=str(n["id"]),
scope=scope,
pointer=nodeptr + "/widgets_values",
value=n.get("widgets_values", []),
)
)
# Check doc.source_notes by actual raw node and recursive JSON type, not newer block schema.
docnotes = doc["source_notes"]
for i, n in enumerate(docnotes):
candidates = [
n0
for n0 in raw_notes
if (
n0["node_id"] == n["node_id"]
or n0["scope"] + "/" + n0["node_id"] == n["node_id"]
)
]
assert len(candidates) == 1, (path, n["node_id"])
v = candidates[0]
assert typed(n["content"]) == typed(v["value"]), (path, n["node_id"])
notes.append(
dict(
source_repo_path=path,
doc_note_index=i,
node_id=n["node_id"],
pointer=v["pointer"],
typed_sha256=sha(canonical(typed(v["value"]))),
content=n["content"],
raw_equal=True,
counting_rule="one doc.source_notes entry; not strings/fields",
)
)
commentproof = []
if "comments" in b:
for i, c in enumerate(b["comments"]):
v = ptr(raw, c["pointer"])
rule = "direct_original_value"
if isinstance(v, list) and len(v) == 1 and isinstance(v[0], str):
text = v[0]
rule = "single_string_in_original_widget_array; container is not text"
else:
text = v
assert typed(text) == typed(c["text"]), (path, i, c["pointer"])
commentproof.append(
dict(
index=i,
pointer=c["pointer"],
utf8_sha256=sha(v.encode()) if isinstance(v, str) else None,
recursive_typed_sha256=sha(canonical(typed(v))),
text_sha256=sha(text.encode()) if isinstance(text, str) else None,
comparison_rule=rule,
)
)
bindings = b.get("node_bindings")
bindcounts = collections.Counter()
bindingrecords = []
for i, n in enumerate(bindings or []):
explicit = n.get("implementation_verified")
state = (
"explicit_exact_static_binding"
if explicit is True
else "explicit_unverified"
if explicit is False
else "candidate_reference_only"
if n.get("candidates")
else "unknown"
)
version = n.get("source_version", n.get("version"))
no_identity = (
not version
or "未知" in str(version)
or "unknown" in str(version).lower()
or str(n.get("source_id", "")).startswith("unknown")
)
identity_state = (
"explicit_exact_static_binding"
if explicit is True
else "no_accurate_identity_in_record"
if no_identity
else "specific_declared_implementation_not_obtained_or_matched"
if not n.get("candidates")
else "candidate_static_reference_exact_identity_not_explicitly_certified"
)
bindcounts[state] += 1
bindingrecords.append(
dict(
index=i,
status=state,
identity_state=identity_state,
record=n,
evidence=evidence + f"/node_bindings/{i}",
)
)
identities.append(
dict(
source_repo_path=path,
raw_node_records=raw_nodes,
binding_key_present=bindings is not None,
binding_records=bindingrecords,
missing_binding_policy="unknown; no class-name/source-count "
"inference; candidates are not "
"exact identity",
)
)
pinfile = pinfiles.get(path)
commit = (
subprocess.check_output(
["git", "log", "-1", "--format=%H", "--", str(pinfile.relative_to(ROOT))], cwd=ROOT
)
.decode()
.strip()
if pinfile
else subprocess.check_output(
[
"git",
"log",
"-1",
"--format=%H",
"-S",
DEFINITIONS[path],
"--",
"calliope-backend/src/calliope/comfyui/fixed_document.py",
],
cwd=ROOT,
)
.decode()
.strip()
)
attribution_result = attributor.select(path, DEFINITIONS[path])
delivery = next(
(m for m in messages if m["id"] == attribution_result["delivery_comment_id"]),
None,
)
reviewbasis = attribution_result["review_basis"]
source_records = []
for i, s in enumerate(b["sources"]):
local = s.get("local_file")
resolved = (pinfile.parent / local).resolve() if pinfile and local else None
exists = bool(resolved and resolved.is_file() and resolved.is_relative_to(ROOT))
checked_sha = sha(resolved.read_bytes()) if exists else None
resolution_basis = "relative_to_pin_record_directory"
matched_paths = sha_paths.get(s.get("sha256"), [])
if not exists and matched_paths:
resolved = ROOT / matched_paths[0]
exists = True
checked_sha = sha(resolved.read_bytes())
resolution_basis = (
"existing_tracked_SHA256_match_only; not an identity/relative-base inference"
)
state = (
"byte_sha_matches"
if checked_sha and checked_sha == s.get("sha256")
else "unknown_local_resolution"
if not exists
else "byte_sha_differs_record"
)
# A source text is not a provider identity or an acquired declared version.
source_records.append(
dict(
index=i,
id=s.get("id"),
commit=s.get("commit"),
sha256=s.get("sha256"),
file=s.get("file"),
local_file=local,
resolved_repo_path=resolved.relative_to(ROOT).as_posix() if exists else None,
local_byte_status=state,
actual_sha256=checked_sha,
evidence=evidence + f"/sources/{i}",
resolution_basis=resolution_basis,
all_tracked_paths_with_recorded_sha=matched_paths,
acquired_at=s.get("acquisition_time", "unknown"),
reverified_at=s.get("reverified_at", "unknown"),
)
)
sources.append(
dict(
source_repo_path=path, source_text_count=len(source_records), records=source_records
)
)
issues = json.loads(row["import_issues"])
params = doc["params"]
needs = [
dict(
layer="L1-local",
minimum="先读取现有准确source条目、字段evidence及boundary原文,分开"
"记录已证与unknown",
reason="有来源文本不等于本节点准确身份/安装/恢复",
evidence=evidence + "/versions",
)
]
if bindings is None or any(
n["status"] != "explicit_exact_static_binding" for n in bindingrecords
):
needs.append(
dict(
layer="L2-exact-material",
minimum="仅补identity-records本文件未验证实例所声明版本的注册/类"
"/schema/依赖与commit或发布成员绑定;无身份先确定提供方和版本",
reason="候选/同名/宿主版本不能替代准确身份",
evidence="identity-records.json#" + path,
)
)
if row["import_state"] == "needs_conversion":
needs.append(
dict(
layer="L3-mapping",
minimum="本文件逐import_issues定位不支持项,先离线拟定字段/端口/子图"
"/proxy/缓存映射及失败关闭对照;涉及产品语义修正交总管协调具体选择",
reason="当前转换入口未给可直接使用资格",
issues=issues,
evidence="qualification-records.json#" + path,
)
)
else:
needs.append(
dict(
layer="L3-mapping",
minimum="复核现有API或配套逐字段/连线/输入输出映射,必要时取得对应版本真实前端导出",
reason="pending_check只是现有入口资格,不是新增可靠转换或前端恢复认证",
issues=issues,
evidence="qualification-records.json#" + path,
)
)
needs.extend(
[
dict(
layer="L4-target-readonly",
minimum="后续获授权时仅核本文件dependencies中的节点/模型、目录/设备/安装版"
"本与素材许可,先列差异",
reason="当前unchecked,无目标定义/安装和目录事实",
evidence="qualification-records.json#" + path,
),
dict(
layer="L5-authorized-run",
minimum="身份/映射/素材条件齐备后申请本文件代表分支运行,核history、真实输出和前"
"端恢复;计时实测",
reason="exec_verified=false;资源/耗时unknown,不估算或提前填时间",
evidence="qualification-records.json#" + path,
),
]
)
unresolved = [
dict(
node_id=n["record"].get("node_id"),
class_type=n["record"].get("class_type"),
declared_version=n["record"].get(
"source_version", n["record"].get("version", "unknown")
),
source_id=n["record"].get("source_id", "unknown"),
status=n["status"],
identity_state=n["identity_state"],
evidence=n["evidence"],
)
for n in bindingrecords
if n["status"] != "explicit_exact_static_binding"
]
declarations = [
dict(
node_id=n["node_id"],
scope=n["scope"],
class_type=n["class_type"],
declared_version=n["raw_version_declaration"],
declared_provider=n["raw_provider_declaration"],
evidence=n["declaration_evidence"],
)
for n in raw_nodes
]
remaining.append(
dict(
source_repo_path=path,
blockers=needs,
raw_instance_declarations=declarations,
unverified_binding_records=unresolved,
exact_static_bindings=[
n["evidence"]
for n in bindingrecords
if n["status"] == "explicit_exact_static_binding"
],
original_boundaries=b.get("boundaries", "unknown:key_absent"),
field_boundaries=evidence + "/fields",
graph_boundaries=evidence + "/boundaries"
if "boundaries" in b
else "unknown: key absent; consult versions/flow and doc.dependencies",
)
)
ledger = dict(
ordinal=ordinal,
source_repo_path=path,
source_sha1=b["source_sha1"],
source_sha256=b["source_sha256"],
pin=DEFINITIONS[path],
block_evidence=evidence,
pin_evidence=str(pinfile.relative_to(ROOT))
if pinfile
else "fixed_document.py#DEFINITIONS",
latest_pin_record_commit=commit or "unknown",
delivery_comment_id=delivery["id"] if delivery else "unknown",
review_basis=reviewbasis,
delivery_lookup_rule=attribution_result["selection_rule"],
definition_pin_introductions=attribution_result["definition_pin_introductions"],
delivery_head=attribution_result.get("delivery_head", "unknown"),
tested_implementation=attribution_result.get("tested_implementation", "unknown"),
saved_fields=len(pointers),
saved_json_types=dict(ftypes),
saved_count_rule="len(actual fixed block.fields); each "
"original pointer recursively "
"typed; named parallel pointers "
"separate, not extra fields",
saved_locations_by_shape=dict(
collections.Counter(
"api_named"
if "/inputs/" in f["pointer"]
and not f["pointer"].startswith("/nodes/")
and not f["pointer"].startswith("/definitions/")
else "named_only"
if "widgets_values_named" in f["pointer"]
else "widget_position"
for f in b["fields"]
)
),
doc_source_notes=len(docnotes),
source_note_nodes=len(raw_notes),
note_count_rule="len(actual doc.source_notes), full "
"widget content recursively equal; "
"Note/MarkdownNote source classes "
"independent",
block_comments_key_present="comments" in b,
block_comments_count=len(b["comments"]) if "comments" in b else "unknown:key_absent",
block_comment_proof=commentproof,
original_shape="canvas_with_subgraph_boundaries"
if subgraphs
else "canvas"
if "nodes" in raw
else "API",
root_node_instances=len(raw["nodes"]) if "nodes" in raw else len(raw),
definition_node_records=sum(s["nodes"] for s in subgraphs),
node_class_count=len({n["class_type"] for n in raw_nodes}),
subgraph_boundaries=subgraphs,
original_edge_records=link_count,
binding_key_present=bindings is not None,
binding_record_counts=dict(bindcounts)
if bindings is not None
else "unknown:key_absent",
identity_state_record_counts=dict(
collections.Counter(n["identity_state"] for n in bindingrecords)
)
if bindings is not None
else "unknown:key_absent",
source_text_records=len(source_records),
source_text_count_rule="len(block.sources), NOT unique "
"providers/classes/instances/declared "
"acquired commits",
exact_implementation_status="see explicit per-binding status; absent "
"records unknown; static "
"reference is not target installation",
defaults_units_ranges_basis=evidence
+ "/fields/*/{schema_default,unit,limits,evidence}; source value never "
"presumed schema default",
import_state=row["import_state"],
existing_conversion_qualification="pending_check_existing_API_or_companion"
if row["import_state"] == "pending_check"
else "needs_conversion",
series_new_reliable_conversions=0,
is_enabled=row["is_enabled"],
draft=doc["draft"],
doc_done=doc["status"]["doc_done"],
doc_completed_at=row["doc_completed_at"],
exec_verified=doc["status"]["exec_verified"],
exec_verified_at=row["exec_verified_at"],
dependency_check=doc["dependencies"]["check_state"],
original_named_params=sum(
p.get("value_origin") != "supplied_api_companion" for p in params
),
companion_params=sum(p.get("value_origin") == "supplied_api_companion" for p in params),
unnamed_widget_nodes=len(doc["source_review"]["evidence"]["unnamed_widget_node_ids"]),
remaining_evidence="remaining-work.json#" + path,
)
ledgers.append(ledger)
assert len(ledgers) == 155 and sum(x["saved_fields"] for x in ledgers) == 10761
assert len(notes) == 287
quals = []
for path, row in sorted(rows.items()):
d = json.loads(row["doc_json"])
quals.append(
dict(
source_repo_path=path,
import_state=row["import_state"],
is_enabled=row["is_enabled"],
doc_completed_at=row["doc_completed_at"],
exec_verified_at=row["exec_verified_at"],
status=d["status"],
dependencies=d["dependencies"],
import_issues=json.loads(row["import_issues"]),
output_map=row["output_map"],
output_map_source=row["output_map_source"],
source_sha=row["source_sha"],
source_commit=row["source_commit"],
columns=len(row),
doc_typed_sha256=sha(canonical(typed(d))),
)
)
write("qualification-records.json", quals)
write("ledger.json", ledgers)
write("saved-value-proof.json", proofs)
write("notes-proof.json", notes)
write("identity-records.json", identities)
write("source-text-records.json", sources)
write("remaining-work.json", remaining)
keys = [
"ordinal",
"source_repo_path",
"source_sha1",
"source_sha256",
"pin",
"latest_pin_record_commit",
"delivery_comment_id",
"saved_fields",
"doc_source_notes",
"block_comments_key_present",
"block_comments_count",
"original_shape",
"root_node_instances",
"definition_node_records",
"node_class_count",
"original_edge_records",
"binding_key_present",
"source_text_records",
"import_state",
"existing_conversion_qualification",
"series_new_reliable_conversions",
"is_enabled",
"draft",
"doc_done",
"doc_completed_at",
"exec_verified",
"exec_verified_at",
"dependency_check",
]
with (OUTPUT / "ledger.csv").open("x", encoding="utf-8-sig", newline="") as f:
writer = csv.DictWriter(f, fieldnames=keys)
writer.writeheader()
writer.writerows({k: r[k] for k in keys} for r in ledgers)
totals = dict(
base=BASE,
source_directory_entries=156,
excluded=list(excluded),
targets=155,
definitions=155,
fixed_blocks=155,
actual_library_rows=155,
saved_fields=10761,
source_notes=287,
saved_json_types=dict(totaltypes),
states=dict(collections.Counter(x["import_state"] for x in ledgers)),
original_named_params=sum(x["original_named_params"] for x in ledgers),
unnamed_widget_nodes=sum(x["unnamed_widget_nodes"] for x in ledgers),
companion_params=sum(x["companion_params"] for x in ledgers),
missing_comments_keys=sum(not x["block_comments_key_present"] for x in ledgers),
missing_binding_keys=sum(not x["binding_key_present"] for x in ledgers),
delivery_unresolved=sum(x["delivery_comment_id"] == "unknown" for x in ledgers),
review_basis_unknown=sum(x["review_basis"]["kind"] == "unknown" for x in ledgers),
full_documents=0,
new_reliable_conversions=0,
real_executions=0,
enabled=0,
evidence_scope="fresh isolated offline DB only; online "
"state unknown; not a new "
"browser/build/run certification",
)
assert totals["states"] == {"pending_check": 16, "needs_conversion": 139}
assert (
totals["original_named_params"],
totals["unnamed_widget_nodes"],
totals["companion_params"],
) == (1217, 3660, 294)
write("summary.json", totals)
print(json.dumps(totals, ensure_ascii=False))
if __name__ == "__main__":
os.environ["PYTHONDONTWRITEBYTECODE"] = "1"
main()