Add portable corpus, annotation provenance, admission, review and bounded agent-cycle contracts. Preserve dataset ownership and explicit research acceptance limits.
201 lines
8.6 KiB
Python
201 lines
8.6 KiB
Python
"""Publish source-reviewed agent ROIs only after a terminal root acceptance.
|
|
|
|
Retains all previous decisions and targets; no live-map or training side effect.
|
|
A release is assistant-reviewed TRAIN, never independent evaluation gold.
|
|
"""
|
|
|
|
import copy
|
|
from datetime import UTC, datetime
|
|
from pathlib import Path
|
|
|
|
from admission_store import Supervision, build, pixel_target
|
|
from agent_cycle import Cycle
|
|
from annotation_provenance import audit_unit
|
|
from dataset_store import checksum, confined, digest, read, write
|
|
from region_coverage import merge, raster_proposal, runs
|
|
|
|
|
|
def publish(store, identity, destination):
|
|
store = Path(store).resolve()
|
|
controller = Cycle(store)
|
|
try:
|
|
state = controller.status(identity)
|
|
finally:
|
|
controller.close()
|
|
if state["state"] != "closed" or state["root_review"]["verdict"] != "accepted":
|
|
raise ValueError("Root acceptance required before supervision publication")
|
|
units = [u for u in state["plan"]["units"] if u["id"] in state["root_review"]["admitted_units"]]
|
|
if not units:
|
|
raise ValueError("Root did not admit any units")
|
|
pointers = {digest(u["payload"]["supervision"]) for u in units}
|
|
if len(pointers) != 1:
|
|
raise ValueError("One immutable baseline release per iteration required")
|
|
pointer = units[0]["payload"]["supervision"]
|
|
output = confined(store, destination)
|
|
journal = store / "agent-reviews" / identity
|
|
if output == journal or output.is_relative_to(journal) or journal.is_relative_to(output):
|
|
raise ValueError("Output overlaps decision journal")
|
|
proposals = {t["unit"]: t["result"] for t in state["tasks"] if t["stage"] == "annotate"}
|
|
audit, decisions, changed = [], {}, set()
|
|
with Supervision(store, pointer["path"], pointer["sha256"]) as reader:
|
|
if output.is_relative_to(reader.root) or reader.root.is_relative_to(output):
|
|
raise ValueError("Output overlaps baseline")
|
|
for sample_id, spec in reader.manifest["records"].items():
|
|
decisions[sample_id] = read(reader.root / spec["path"])
|
|
entries = {e["sample_id"]: e for b in reader.training_batches("observed_paint") for e in b}
|
|
merged, explicit_unknown, touched = {}, {}, {}
|
|
for unit in units:
|
|
p = unit["payload"]
|
|
key = (p["sample_id"], p["view"])
|
|
e = entries[p["sample_id"]]
|
|
if e["split"] != "train" or e["physical_group"] != unit["physical_group"]:
|
|
raise ValueError("Physical split changed")
|
|
target = next(t for t in e["targets"] if t["view"] == p["view"])
|
|
original = pixel_target(target)
|
|
protected = bytearray(len(original)) if target["unknown"] else b""
|
|
for y, a, b in target["unknown"]:
|
|
protected[y * p["size"][0] + a : y * p["size"][0] + b] = bytes([1]) * (b - a)
|
|
record = raster_proposal(p, proposals[unit["id"]])
|
|
candidate, stats = merge(p, record, original, protected)
|
|
width = p["size"][0]
|
|
x0, y0, x1, y1 = p["roi"]
|
|
pixels = {y * width + x for y in range(y0, y1) for x in range(x0, x1)}
|
|
prior = touched.setdefault(key, set())
|
|
if prior & pixels:
|
|
raise ValueError("Overlapping units require one combined review")
|
|
prior.update(pixels)
|
|
out = merged.setdefault(key, bytearray(original))
|
|
ignored = explicit_unknown.setdefault(key, bytearray(protected or bytes(len(original))))
|
|
for i in pixels:
|
|
out[i] = candidate[i]
|
|
ignored[i] = int(candidate[i] == 255)
|
|
audit.append(
|
|
dict(
|
|
unit=unit["id"],
|
|
**stats,
|
|
provenance=audit_unit(
|
|
p,
|
|
record,
|
|
original,
|
|
candidate,
|
|
protected,
|
|
merged_sha256=stats["merged_sha256"],
|
|
),
|
|
)
|
|
)
|
|
changed.add(p["sample_id"])
|
|
for (sample_id, view), out in merged.items():
|
|
e = entries[sample_id]
|
|
target = next(t for t in e["targets"] if t["view"] == view)
|
|
record = runs(out, target["size"], view)
|
|
# Keep unreviewed complement ignored without claiming it was reviewed.
|
|
mask = bytes(255 if v else 0 for v in explicit_unknown[(sample_id, view)])
|
|
record["unknown"] = runs(mask, target["size"], view)["unknown"]
|
|
decision = copy.deepcopy(decisions[sample_id])
|
|
decision["observed_paint"] = [
|
|
record if t["view"] == view else t for t in decision["observed_paint"]
|
|
]
|
|
# Freeze time once for idempotent publication retries.
|
|
decision["reviewer"] = dict(id=state["plan"]["root_actor"], kind="assistant")
|
|
decision["reason"] = (
|
|
f"Agent iteration {identity}; independent source review + root acceptance; "
|
|
f"prior release {pointer['sha256']}; assistant-reviewed TRAIN only."
|
|
)
|
|
decisions[sample_id] = decision
|
|
journal.mkdir(parents=True, exist_ok=True)
|
|
immutable(journal / "cycle.json", state)
|
|
stamp_path = journal / "publication.json"
|
|
stamp = (
|
|
read(stamp_path)
|
|
if stamp_path.exists()
|
|
else dict(
|
|
utc=datetime.now(UTC).isoformat(),
|
|
iteration=identity,
|
|
root_review_sha256=digest(state["root_review"]),
|
|
baseline=pointer,
|
|
)
|
|
)
|
|
immutable(stamp_path, stamp)
|
|
for sample_id in changed:
|
|
decisions[sample_id]["reviewed_utc"] = stamp["utc"]
|
|
plan = dict(
|
|
schema_version="missioncore.semantic-admission-plan/v1",
|
|
corpus=reader.manifest["corpus"],
|
|
revisions=reader.manifest["revisions"],
|
|
decisions=[],
|
|
)
|
|
for sample_id, decision in sorted(decisions.items()):
|
|
path = journal / f"{sample_id}.json"
|
|
immutable(path, decision)
|
|
plan["decisions"].append(
|
|
dict(path=path.relative_to(store).as_posix(), sha256=checksum(path))
|
|
)
|
|
publish_audit(
|
|
journal,
|
|
dict(
|
|
iteration=identity,
|
|
units=audit,
|
|
changed_samples=sorted(changed),
|
|
automatic_training=False,
|
|
production_eligible=False,
|
|
),
|
|
)
|
|
immutable(journal / "plan.json", plan)
|
|
if (output / "supervision.json").exists():
|
|
with Supervision(store, destination, checksum(output / "supervision.json")) as existing:
|
|
if existing.manifest["plan_sha256"] != digest(plan):
|
|
raise ValueError("Destination contains a different release")
|
|
return dict(
|
|
path=destination,
|
|
sha256=checksum(output / "supervision.json"),
|
|
counts=existing.manifest["counts"],
|
|
)
|
|
return build(store, plan, destination)
|
|
|
|
|
|
def immutable(path, value):
|
|
if path.exists():
|
|
if read(path) != value:
|
|
raise ValueError("Published evidence changed")
|
|
else:
|
|
write(path, value)
|
|
|
|
|
|
def publish_audit(journal, current):
|
|
"""Preserve legacy audit bytes on retry; bind additive proof separately."""
|
|
path = journal / "audit.json"
|
|
sidecar = journal / "audit-provenance-v1.json"
|
|
if sidecar.exists():
|
|
if not path.exists():
|
|
raise ValueError("Provenance sidecar requires its original legacy audit")
|
|
# An existing sidecar always requires the original legacy projection and
|
|
# exact bytes binding, even if audit.json was replaced with current.
|
|
elif not path.exists() or read(path) == current:
|
|
immutable(path, current)
|
|
return
|
|
previous = read(path)
|
|
units = previous.get("units") if isinstance(previous, dict) else None
|
|
if (
|
|
not isinstance(units, list)
|
|
or not units
|
|
or any(not isinstance(unit, dict) or "provenance" in unit for unit in units)
|
|
):
|
|
raise ValueError("Published evidence changed")
|
|
legacy = dict(
|
|
current,
|
|
units=[
|
|
{key: value for key, value in unit.items() if key != "provenance"}
|
|
for unit in current["units"]
|
|
],
|
|
)
|
|
if previous != legacy:
|
|
raise ValueError("Published legacy audit differs from exact projection")
|
|
immutable(
|
|
sidecar,
|
|
dict(
|
|
schema="missioncore.annotation-provenance-audit/v1",
|
|
legacy_audit_sha256=checksum(path),
|
|
audit=current,
|
|
),
|
|
)
|