"""Versioned B1 structural adapter; development tooling, defaults unfrozen. No semantic leakage certification, input generation, or request-role inference. """ import json from pathlib import Path import re import sys BASE = Path(__file__).resolve().parent sys.path.insert(0, str(BASE.parent/"permitted-observations")) import assemble_observation as observation CONTRACT = "b1-generic-continuation/1.0" TEMPLATE_PATH = BASE.parent/"baseline-prompts"/"b1-continuation.txt" TEMPLATE_SHA256 = "25f117b6f9f326cef23c6f80c012b983eb9a16952746b54c794bcf7ff43de4aa" PLACEHOLDERS = ("TASK_PACKET_JSON", "CURRENT_ARTIFACT_JSON", "EARLIER_ARTIFACTS_JSON", "PREVIOUS_INSTRUCTIONS_JSON") def continuation_attempts(run, slots): """Partition archived worker requests explicitly; preserve unsuccessful attempts. The archive has worker roles, not a continuation role. Role alone cannot separate a common initial request from a B1 continuation. Slot declarations are coordinator assertions, not semantic or historical proof of request kind. """ observation.require(isinstance(slots, list), "B1 request_slots must be an array") workers = {a["attempt_id"]: a for a in run["attempts"] if a["phase"] == "adaptation" and a["role"] == "worker"} declared = {} for slot in slots: observation.keys(slot, ("attempt_id", "kind"), "B1 request slot") aid = observation.text(slot["attempt_id"], "B1 worker attempt ID") observation.require(aid in workers and aid not in declared, "unknown/duplicate B1 worker request slot") observation.require(slot["kind"] in ("initial", "continuation"), "unsupported B1 request kind") declared[aid] = slot["kind"] observation.require(set(declared) == set(workers), "every archived adaptation worker attempt needs an explicit B1 request slot, including failures and retries") initial_roots = [aid for aid, kind in declared.items() if kind == "initial" and workers[aid]["retry_of"] is None] observation.require(len(initial_roots) <= 1, "B1 permits one common initial request plus its retries, not multiple initial roots") for aid, attempt in workers.items(): parent = attempt["retry_of"] observation.require(parent is None or (parent in declared and declared[parent] == declared[aid]), "B1 retry cannot change initial/continuation designation") return {aid: workers[aid] for aid, kind in declared.items() if kind == "continuation"} def decode_blocks(content): """Check fixed literal template segments around exactly four JSON values. B1's existing placeholder convention does not require canonical JSON. Accept compact or indented JSON without normalizing the recorded bytes. Fixed wrapper text, block order, separators and terminal newline stay exact. """ template_bytes = TEMPLATE_PATH.read_bytes() observation.require(observation.sha(template_bytes) == TEMPLATE_SHA256, "B1 adapter template hash mismatch") rendered = content.decode("utf-8") observation.require(observation.MARKER.search(rendered) is None, "B1 input has unresolved placeholders") template = template_bytes.decode("utf-8") parts = re.split(r"(\{\{[A-Z_]+\}\})", template) observation.require(parts[1::2] == ["{{"+p+"}}" for p in PLACEHOLDERS], "unsupported B1 template placeholders") cursor, values = 0, {} decoder = json.JSONDecoder() for index, name in enumerate(PLACEHOLDERS): prefix = parts[index*2] observation.require(rendered.startswith(prefix, cursor), "B1 input does not have the unchanged template wrapper") cursor += len(prefix) # JSON value whitespace is permitted; no operational text is stripped. start = cursor while cursor < len(rendered) and rendered[cursor] in " \t\r\n": cursor += 1 _, end = decoder.raw_decode(rendered, cursor) values[name] = observation.parse_json(rendered[start:end].encode("utf-8"), "B1 "+name) cursor = end observation.require(rendered[cursor:] == parts[-1], "B1 input does not have the unchanged template wrapper") return values def validate_input(content, bounds, task_id, public_packet_sha256): observation.require(len(content) <= bounds["max_input_bytes"], "B1 input byte bound exceeded") values = decode_blocks(content) packet = values["TASK_PACKET_JSON"] observation.text(packet, "B1 immutable public packet") observation.require(observation.sha(packet.encode("utf-8")) == public_packet_sha256, "B1 immutable public packet hash mismatch") requirements, sources = observation.task_identifiers(packet, task_id) observation.require(task_id not in requirements | sources, "ambiguous B1 task identity") used = {task_id, *requirements, *sources} def identity(value, label): observation.text(value, label) observation.require(value not in used, "duplicate/ambiguous B1 input identity") used.add(value) earlier = values["EARLIER_ARTIFACTS_JSON"] previous = values["PREVIOUS_INSTRUCTIONS_JSON"] observation.require(isinstance(earlier, list) and len(earlier) <= 2, "excess/invalid B1 artifact history") observation.require(isinstance(previous, list) and len(previous) <= 12, "excess/invalid B1 instruction history") for artifact in [values["CURRENT_ARTIFACT_JSON"], *earlier]: observation.keys(artifact, ("artifact_id", "text"), "B1 artifact") identity(artifact["artifact_id"], "B1 artifact ID") observation.require(isinstance(artifact["text"], str), "B1 artifact text must be a string") artifact["text"].encode("utf-8") for instruction in previous: observation.keys(instruction, ("instruction_id", "text"), "B1 prior instruction") identity(instruction["instruction_id"], "B1 instruction ID") observation.text(instruction["text"], "B1 submitted instruction text") return values