Co-authored-by: multica <multica@users.noreply.github.com> Co-authored-by: multica-agent <github@multica.ai>
469 lines
19 KiB
Python
469 lines
19 KiB
Python
"""Bounded offline provenance, with explicit roles and file/pin Git closure.
|
||
|
||
No date-based candidate ranking. No original workflow or upstream code execution.
|
||
"""
|
||
|
||
import ast
|
||
import hashlib
|
||
import re
|
||
import subprocess
|
||
from pathlib import Path
|
||
|
||
AUTHOR = "4846a27a-ba87-49c9-939d-7275f63efcc7"
|
||
CHIEF = "bbcc1179-3a55-48e7-a72e-c84cf79f41cb"
|
||
CODE = "calliope-backend/src/calliope/comfyui/fixed_document.py"
|
||
HEX = re.compile(r"(?<![0-9a-fA-F])([0-9a-fA-F]{7,40})(?![0-9a-fA-F])")
|
||
|
||
|
||
def sha(raw):
|
||
return hashlib.sha256(raw).hexdigest()
|
||
|
||
|
||
def literal(node, env):
|
||
"""Only own code's literal constants; never eval/import historical modules."""
|
||
if isinstance(node, ast.Constant):
|
||
return node.value
|
||
if isinstance(node, ast.Name) and node.id in env:
|
||
return env[node.id]
|
||
if isinstance(node, ast.Dict):
|
||
return {literal(k, env): literal(v, env) for k, v in zip(node.keys, node.values)}
|
||
if isinstance(node, ast.BinOp) and isinstance(node.op, ast.Add):
|
||
left, right = literal(node.left, env), literal(node.right, env)
|
||
if isinstance(left, str) and isinstance(right, str):
|
||
return left + right
|
||
raise ValueError("not a supported literal")
|
||
|
||
|
||
class GitFacts:
|
||
def __init__(self, root):
|
||
self.root = Path(root)
|
||
self.resolutions = {}
|
||
self.code = {}
|
||
self.parent_cache = {}
|
||
self.origin_cache = {}
|
||
self.blobs = {}
|
||
|
||
def git(self, *args):
|
||
return subprocess.check_output(["git", *args], cwd=self.root).decode().strip()
|
||
|
||
def resolve(self, token):
|
||
if token not in self.resolutions:
|
||
matches = self.git("rev-parse", "--disambiguate=" + token).splitlines()
|
||
status = "ambiguous" if len(matches) > 1 else "missing"
|
||
full = None
|
||
if len(matches) == 1:
|
||
status = (
|
||
"unique_commit"
|
||
if self.git("cat-file", "-t", matches[0]) == "commit"
|
||
else "not_commit"
|
||
)
|
||
full = matches[0] if status == "unique_commit" else None
|
||
self.resolutions[token] = dict(
|
||
token=token, status=status, commit=full, object_matches=matches
|
||
)
|
||
return self.resolutions[token]
|
||
|
||
def definitions(self, commit):
|
||
if commit not in self.code:
|
||
present = self.git("ls-tree", commit, "--", CODE)
|
||
if not present:
|
||
self.code[commit] = dict(definitions={}, state="code_file_absent")
|
||
else:
|
||
raw = subprocess.check_output(["git", "show", commit + ":" + CODE], cwd=self.root)
|
||
env = {}
|
||
for node in ast.parse(raw).body:
|
||
if isinstance(node, ast.Assign) and len(node.targets) == 1:
|
||
target = node.targets[0]
|
||
if isinstance(target, ast.Name):
|
||
try:
|
||
env[target.id] = literal(node.value, env)
|
||
except ValueError:
|
||
pass
|
||
definitions = env.get("DEFINITIONS", {})
|
||
assert isinstance(definitions, dict)
|
||
self.code[commit] = dict(
|
||
definitions=definitions,
|
||
state="literal_AST",
|
||
path=CODE,
|
||
git_blob=self.git("rev-parse", commit + ":" + CODE),
|
||
sha256=sha(raw),
|
||
)
|
||
return self.code[commit]["definitions"]
|
||
|
||
def parents(self, commit):
|
||
if commit not in self.parent_cache:
|
||
self.parent_cache[commit] = self.git(
|
||
"rev-list", "--parents", "-n", "1", commit
|
||
).split()[1:]
|
||
return self.parent_cache[commit]
|
||
|
||
def changes(self, commit):
|
||
current = self.definitions(commit)
|
||
previous = [self.definitions(p) for p in self.parents(commit)]
|
||
return {p: pin for p, pin in current.items() if all(old.get(p) != pin for old in previous)}
|
||
|
||
def origins(self, path, pin):
|
||
key = path + "#" + pin
|
||
if key not in self.origin_cache:
|
||
commits = self.git("log", "--format=%H", "-S", pin, "--", CODE).splitlines()
|
||
self.origin_cache[key] = [c for c in commits if self.changes(c).get(path) == pin]
|
||
return self.origin_cache[key]
|
||
|
||
def blob(self, commit, path):
|
||
key = commit + ":" + path
|
||
if key not in self.blobs:
|
||
data = self.git("ls-tree", "-z", commit, "--", path)
|
||
self.blobs[key] = data.split()[2] if data else None
|
||
return self.blobs[key]
|
||
|
||
def ancestor(self, earlier, later):
|
||
result = subprocess.run(
|
||
["git", "merge-base", "--is-ancestor", earlier, later],
|
||
cwd=self.root,
|
||
capture_output=True,
|
||
)
|
||
assert result.returncode in (0, 1)
|
||
return result.returncode == 0
|
||
|
||
|
||
def role(content, start, end):
|
||
before = content[max(0, start - 80) : start]
|
||
after = content[end : end + 32]
|
||
gap = r"[\s`*::=((]*$"
|
||
if re.search(r"受测(?:实现)?(?:与|及)最终\s*(?:head)?(?:均为)?" + gap, before, re.I):
|
||
return "delivery_and_tested"
|
||
if re.search(r"最终" + gap, before) and re.search(
|
||
r"(?:实现|提交|head)[^。;;\n]{0,70}", before, re.I
|
||
):
|
||
return "delivery_head"
|
||
if re.search(r"(?:基线|基点)[^\n;;。`]{0,16}" + gap, before):
|
||
return "baseline"
|
||
if re.search(r"(?:旧版|旧代码|回退)[^\n;;。`]{0,16}" + gap, before):
|
||
return "rollback_or_old"
|
||
patterns = [
|
||
("tested_implementation", r"(?:受测[^\n;;。`]{0,24}|实现(?:提交)?)"),
|
||
("baseline", r"(?:基线(?:提交)?|增量基点|基点|baseline|BASE)"),
|
||
("dependency_or_source", r"(?:依赖(?:提交)?|源码(?:提交)?|来源提交)"),
|
||
("rollback_or_old", r"(?:回退(?:提交)?|旧(?:版|提交|head|代码)|原提交)"),
|
||
("successor_record", r"(?:后继(?:提交|head)?|记录后继)"),
|
||
("delivery_head", r"(?:提交已推送|已提交并推送|已提交推送|已推送|推送|提交|head|commit)"),
|
||
]
|
||
if re.search(r"原提交" + gap, before) and re.match(r"[`\s]*已(?:普通)?推送", after):
|
||
return "delivery_transport_recovery"
|
||
for name, pattern in patterns:
|
||
if re.search(pattern + gap, before, re.I):
|
||
return name
|
||
if re.match(r"[`\s]*(?:旧代码|旧版|基线|为.*中间提交)", after):
|
||
return "rollback_or_old"
|
||
return "unclassified_reference"
|
||
|
||
|
||
def references(message, git):
|
||
content = message["content"]
|
||
rows = []
|
||
for m in HEX.finditer(content):
|
||
begin = content.rfind("\n", 0, m.start()) + 1
|
||
end = content.find("\n", m.end())
|
||
if end == -1:
|
||
end = len(content)
|
||
rows.append(
|
||
dict(
|
||
token=m[1],
|
||
role=role(content, m.start(), m.end()),
|
||
resolution=git.resolve(m[1]),
|
||
excerpt=content[begin:end],
|
||
span=[m.start(), m.end()],
|
||
)
|
||
)
|
||
return rows
|
||
|
||
|
||
def explicit_multi_scope(content, count):
|
||
numbers = {
|
||
"两": 2,
|
||
"二": 2,
|
||
"三": 3,
|
||
"四": 4,
|
||
"五": 5,
|
||
"六": 6,
|
||
"七": 7,
|
||
"八": 8,
|
||
"九": 9,
|
||
"十": 10,
|
||
"十一": 11,
|
||
}
|
||
for m in re.finditer(
|
||
r"(?<!\d)(\d+|十一|十|[两二三四五六七八九])(?:张)?[\u4e00-\u9fff]{0,8}?(?:图|份|个文件)",
|
||
content,
|
||
):
|
||
actual = int(m[1]) if m[1].isdigit() else numbers[m[1]]
|
||
if actual == count:
|
||
return m[0]
|
||
return None
|
||
|
||
|
||
def scope_proof(path, pin, commit, message, git, base):
|
||
if git.definitions(commit).get(path) != pin:
|
||
return dict(ok=False, reason="head_file_pin_does_not_match")
|
||
changes = git.changes(commit)
|
||
if changes.get(path) != pin:
|
||
return dict(ok=False, reason="pin_inherited_not_changed_for_this_file")
|
||
basename = Path(path).name
|
||
explicit_file = path in message["content"] or basename in message["content"]
|
||
count_claim = explicit_multi_scope(message["content"], len(changes))
|
||
if len(changes) != 1 and not explicit_file and not count_claim:
|
||
return dict(ok=False, reason="multi_file_delta_without_explicit_delivery_scope")
|
||
blob = git.blob(commit, path)
|
||
if not blob or blob != git.blob(base, path):
|
||
return dict(ok=False, reason="original_source_blob_not_bound_to_frozen_file")
|
||
return dict(
|
||
ok=True,
|
||
reason="file_pin_introduced_or_changed_in_declared_commit",
|
||
implementation_commit=commit,
|
||
code_path=CODE,
|
||
pin=pin,
|
||
original_git_blob=blob,
|
||
frozen_base=base,
|
||
exact_file_in_text=explicit_file,
|
||
explicit_multi_file_claim=count_claim,
|
||
code_pin_delta=changes,
|
||
code_byte_evidence={k: v for k, v in git.code[commit].items() if k != "definitions"},
|
||
)
|
||
|
||
|
||
def candidate(path, pin, message, refs, git, base):
|
||
heads = [
|
||
r
|
||
for r in refs
|
||
if r["role"] in ("delivery_head", "delivery_transport_recovery", "delivery_and_tested")
|
||
and r["resolution"]["status"] == "unique_commit"
|
||
]
|
||
tested = [
|
||
r
|
||
for r in refs
|
||
if r["role"] in ("tested_implementation", "delivery_and_tested")
|
||
and r["resolution"]["status"] == "unique_commit"
|
||
]
|
||
accepted, rejected = [], []
|
||
for head in heads:
|
||
commit = head["resolution"]["commit"]
|
||
direct = scope_proof(path, pin, commit, message, git, base)
|
||
linked = []
|
||
if not direct["ok"]:
|
||
for test in tested:
|
||
earlier = test["resolution"]["commit"]
|
||
proof = scope_proof(path, pin, earlier, message, git, base)
|
||
if (
|
||
proof["ok"]
|
||
and git.definitions(commit).get(path) == pin
|
||
and git.ancestor(earlier, commit)
|
||
):
|
||
linked.append(proof)
|
||
local_failure = "本地提交" in head["excerpt"] and bool(
|
||
re.search(r"推送[^。\n]{0,30}(?:失败|均报)", message["content"])
|
||
)
|
||
if local_failure:
|
||
rejected.append(dict(head=commit, reason="explicit_local_only_push_failure"))
|
||
elif direct["ok"] or len(linked) == 1:
|
||
chosen = direct if direct["ok"] else linked[0]
|
||
tested_commits = {
|
||
t["resolution"]["commit"]
|
||
for t in tested
|
||
if t["resolution"]["commit"] == chosen["implementation_commit"]
|
||
}
|
||
accepted.append(
|
||
dict(
|
||
delivery_head=commit,
|
||
head_role=head["role"],
|
||
head_excerpt=head["excerpt"],
|
||
implementation_proof=chosen,
|
||
explicit_tested_implementation=next(iter(tested_commits))
|
||
if len(tested_commits) == 1
|
||
else "unknown",
|
||
successor_record=commit != chosen["implementation_commit"],
|
||
)
|
||
)
|
||
else:
|
||
rejected.append(dict(head=commit, reason=direct["reason"], tested_links=len(linked)))
|
||
unique = {a["delivery_head"]: a for a in accepted}
|
||
return dict(
|
||
comment_id=message["id"],
|
||
content_utf8_sha256=sha(message["content"].encode()),
|
||
candidate_accepted=len(unique) == 1,
|
||
head_proofs=list(unique.values()),
|
||
rejected_heads=rejected,
|
||
references=refs,
|
||
reason="unique_explicit_head_with_file_pin_closure"
|
||
if len(unique) == 1
|
||
else "ambiguous_multiple_heads"
|
||
if len(unique) > 1
|
||
else "no_explicit_delivery_head_with_file_pin_closure",
|
||
)
|
||
|
||
|
||
def review_language(content):
|
||
"""Accept only affirmative audit clauses about this batch; progress is unknown."""
|
||
affirmative, negative = [], []
|
||
for clause in re.split(r"[。!!\n]", content):
|
||
if re.search(
|
||
r"(?:审核|审查|复核).{0,6}(?:未|不|暂未|尚未)通过|未通过(?:审核|审查|复核)", clause
|
||
):
|
||
negative.append(clause)
|
||
continue
|
||
if re.search(
|
||
r"(?:审核|审查|复核)(?:已)?通过|通过(?:独立)?(?:功能与界面)?(?:审核|审查|复核)", clause
|
||
):
|
||
if re.search(
|
||
r"(?:未|不|没|尚未|暂未|没有|不能|待|等待|拟|若|如|要求)[^,,;;。]{0,12}(?:审核|审查|复核|通过)",
|
||
clause,
|
||
):
|
||
negative.append(clause)
|
||
elif re.search(r"(?:上[一]?批|前批|旧批|上一份|据说|可能|假设|[??])", clause):
|
||
negative.append(clause)
|
||
elif re.search(r"^(?:目前|现有|累计|覆盖|全部\d+)", clause.strip()):
|
||
continue
|
||
else:
|
||
affirmative.append(clause)
|
||
if affirmative and not negative:
|
||
return dict(status="affirmative_audit_relay", clauses=affirmative)
|
||
return dict(
|
||
status="unknown", affirmative_clauses=affirmative, rejected_or_negative_clauses=negative
|
||
)
|
||
|
||
|
||
class Attributor:
|
||
def __init__(self, root, messages, base, instruction=None):
|
||
self.git = GitFacts(root)
|
||
self.messages = messages
|
||
self.base = base
|
||
self.instruction = instruction
|
||
self.own = [m for m in messages if m["author_id"] == AUTHOR and not m.get("parent_id")]
|
||
self.refs = {m["id"]: references(m, self.git) for m in self.own}
|
||
|
||
def select(self, path, pin, prior_comment=None):
|
||
origins = self.git.origins(path, pin)
|
||
matrix = []
|
||
for message in self.own:
|
||
refs = self.refs[message["id"]]
|
||
mention = path in message["content"] or Path(path).name in message["content"]
|
||
pin_mention = any(
|
||
pin.startswith(m[1])
|
||
for m in re.finditer(
|
||
r"(?<![0-9a-f])([0-9a-f]{8,64})(?![0-9a-f])", message["content"]
|
||
)
|
||
)
|
||
origin_mention = any(r["resolution"]["commit"] in origins for r in refs)
|
||
changed_head = any(
|
||
r["role"]
|
||
in (
|
||
"delivery_head",
|
||
"delivery_transport_recovery",
|
||
"tested_implementation",
|
||
"delivery_and_tested",
|
||
)
|
||
and r["resolution"]["status"] == "unique_commit"
|
||
and self.git.changes(r["resolution"]["commit"]).get(path) == pin
|
||
for r in refs
|
||
)
|
||
if (
|
||
mention
|
||
or pin_mention
|
||
or origin_mention
|
||
or changed_head
|
||
or message["id"] == prior_comment
|
||
):
|
||
row = candidate(path, pin, message, refs, self.git, self.base)
|
||
row["candidate_inclusion"] = dict(
|
||
file_mention=mention,
|
||
pin_mention=pin_mention,
|
||
origin_reference=origin_mention,
|
||
changed_head=changed_head,
|
||
previously_selected=message["id"] == prior_comment,
|
||
)
|
||
matrix.append(row)
|
||
accepted = [r for r in matrix if r["candidate_accepted"]]
|
||
# Require a unique causal pin origin and a unique attributable delivery comment.
|
||
selected = accepted[0] if len(accepted) == len(origins) == 1 else None
|
||
result = dict(
|
||
source_repo_path=path,
|
||
pin=pin,
|
||
definition_pin_introductions=origins,
|
||
delivery_comment_id=selected["comment_id"] if selected else "unknown",
|
||
selection_rule=(
|
||
"unique causal pin origin and explicit file-scoped delivery; no time ranking"
|
||
),
|
||
ambiguity="none" if selected else "unknown: no unique origin/delivery evidence",
|
||
candidates=matrix,
|
||
)
|
||
if selected:
|
||
proof = selected["head_proofs"][0]
|
||
result.update(
|
||
delivery_head=proof["delivery_head"],
|
||
tested_implementation=proof["explicit_tested_implementation"],
|
||
file_pin_implementation_commit=proof["implementation_proof"][
|
||
"implementation_commit"
|
||
],
|
||
successor_record=proof["successor_record"],
|
||
)
|
||
result["review_basis"] = self.review(path, pin, result)
|
||
return result
|
||
|
||
def review(self, path, pin, result):
|
||
selected = result["delivery_comment_id"]
|
||
progress = [
|
||
m
|
||
for m in self.messages
|
||
if selected != "unknown" and m.get("parent_id") == selected and m["author_id"] == CHIEF
|
||
]
|
||
records = [
|
||
dict(
|
||
comment_id=m["id"],
|
||
parent_id=selected,
|
||
quote=m["content"],
|
||
classification=review_language(m["content"]),
|
||
)
|
||
for m in progress
|
||
]
|
||
positive = [
|
||
r for r in records if r["classification"]["status"] == "affirmative_audit_relay"
|
||
]
|
||
rejected = [r for r in records if r["classification"].get("rejected_or_negative_clauses")]
|
||
if len(positive) == 1 and not rejected:
|
||
return dict(
|
||
kind="chief_relay",
|
||
delivery_comment_id=selected,
|
||
affirmative_record=positive[0],
|
||
all_parent_records=records,
|
||
independent_report_reopened=False,
|
||
)
|
||
# An old instruction relay is distinct from a chief comment and from a main-card receipt.
|
||
if self.instruction and selected != "unknown" and not rejected:
|
||
text = self.instruction["current_section"]
|
||
for clause in re.split(r"[。\n]", text):
|
||
if review_language(clause)["status"] != "affirmative_audit_relay":
|
||
continue
|
||
for m in HEX.finditer(clause):
|
||
resolved = self.git.resolve(m[1])
|
||
commit = resolved["commit"]
|
||
if (
|
||
commit in result["definition_pin_introductions"]
|
||
and self.git.changes(commit).get(path) == pin
|
||
):
|
||
return dict(
|
||
kind="historical_issue_instruction_relay",
|
||
quote=clause,
|
||
source="prior175/current-instruction.json#/current_section",
|
||
source_sha256=sha(text.encode()),
|
||
implementation_commit=commit,
|
||
delivery_comment_id=selected,
|
||
independent_report_reopened=False,
|
||
all_parent_records=records,
|
||
)
|
||
return dict(
|
||
kind="unknown",
|
||
reason="no unambiguous affirmative audit for the selected delivery",
|
||
delivery_comment_id=selected,
|
||
all_parent_records=records,
|
||
limitation="not a claim that historical audit failed; no main-card history bulk fetch",
|
||
)
|