"""Evidence-bound multi-agent decision record, not a performance benchmark.""" from dataclasses import asdict, dataclass, fields import hashlib import json import math import re IDENTITY = re.compile(r"[A-Za-z0-9][A-Za-z0-9_.:/@-]{0,127}") SHA256 = re.compile(r"[a-f0-9]{64}") def identity(value): if type(value) is not str or not IDENTITY.fullmatch(value): raise ValueError("exact bounded identity required") return value def sha256_text(value): if type(value) is not str or not SHA256.fullmatch(value): raise ValueError("exact lowercase SHA-256 required") return value def integer(value, lower, upper): if type(value) is not int or not lower <= value <= upper: raise ValueError("bounded non-boolean integer required") return value def ratio(value): if type(value) is not float or not math.isfinite(value) or not 0.0 < value <= 1.0: raise ValueError("finite exact-float ratio required") return value def exact_bool(value): if type(value) is not bool: raise ValueError("exact boolean required") return value def sequence(value, lower, upper): if type(value) not in (tuple, list): raise ValueError("bounded tuple or list required") integer(len(value), lower, upper) return tuple(value) def digest(value): encoded = json.dumps( value, sort_keys=True, separators=(",", ":"), allow_nan=False ).encode() return hashlib.sha256(encoded).hexdigest() def seal(record): if type(record.content_id) is not str: raise ValueError("content digest requires exact string") data = asdict(record) data.pop("content_id") return digest(data) def validate_record(record, cls): if type(record) is not cls: raise ValueError("concrete frozen record required") try: rebuilt = cls(**{field.name: getattr(record, field.name) for field in fields(cls)}) except (AttributeError, TypeError) as error: raise ValueError("malformed record") from error if record != rebuilt or record.content_id != rebuilt.content_id: raise ValueError("noncanonical or modified record") return rebuilt def scope_tuple(value): result = sequence(value, 8, 8) for item in result: identity(item) return result def identities(value, lower, upper): result = sequence(value, lower, upper) for item in result: identity(item) if len(set(result)) != len(result): raise ValueError("duplicate identity") return result @dataclass(frozen=True) class DecisionContract: scope: tuple = ( "decision-policy-v1", "task-schema-v1", "ownership-v1", "tool-boundary-v1", "context-budget-v1", "aggregation-v1", "evaluation-v1", "fixture-v1", ) minimum_parallel_branches: int = 2 max_workers: int = 4 single_context_limit_tokens: int = 16_000 max_coordination_ratio: float = 0.25 require_deterministic_merge: bool = True content_id: str = "" def __post_init__(self): object.__setattr__(self, "scope", scope_tuple(self.scope)) integer(self.minimum_parallel_branches, 2, 16) integer(self.max_workers, self.minimum_parallel_branches, 32) integer(self.single_context_limit_tokens, 1, 10_000_000) ratio(self.max_coordination_ratio) if exact_bool(self.require_deterministic_merge) is not True: raise ValueError("decision contract requires deterministic merge") expected = seal(self) if self.content_id and self.content_id != expected: raise ValueError("decision contract digest mismatch") object.__setattr__(self, "content_id", expected) @dataclass(frozen=True) class WorkUnit: scope: tuple task_id: str position: int unit_id: str owner: str tool_domain: str isolation_key: str estimated_context_tokens: int depends_on: tuple output_schema: str requires_isolated_credentials: bool read_only: bool content_id: str = "" def __post_init__(self): object.__setattr__(self, "scope", scope_tuple(self.scope)) for value in ( self.task_id, self.unit_id, self.owner, self.tool_domain, self.isolation_key, self.output_schema, ): identity(value) integer(self.position, 1, 64) integer(self.estimated_context_tokens, 1, 10_000_000) object.__setattr__(self, "depends_on", identities(self.depends_on, 0, 32)) exact_bool(self.requires_isolated_credentials) exact_bool(self.read_only) if self.unit_id in self.depends_on: raise ValueError("work unit cannot depend on itself") expected = seal(self) if self.content_id and self.content_id != expected: raise ValueError("work unit digest mismatch") object.__setattr__(self, "content_id", expected) @dataclass(frozen=True) class DecompositionRecord: scope: tuple task_id: str task_sha256: str contract_content_id: str evaluation_id: str units: tuple content_id: str = "" def __post_init__(self): object.__setattr__(self, "scope", scope_tuple(self.scope)) identity(self.task_id) sha256_text(self.task_sha256) sha256_text(self.contract_content_id) identity(self.evaluation_id) units = tuple(validate_record(unit, WorkUnit) for unit in sequence(self.units, 2, 33)) if tuple(unit.position for unit in units) != tuple(range(1, len(units) + 1)): raise ValueError("work-unit positions must be unique and contiguous") if any(unit.scope != self.scope or unit.task_id != self.task_id for unit in units): raise ValueError("work unit outside task scope") if len({unit.unit_id for unit in units}) != len(units): raise ValueError("duplicate work-unit identity") if len({unit.content_id for unit in units}) != len(units): raise ValueError("duplicate work-unit evidence") object.__setattr__(self, "units", units) expected = seal(self) if self.content_id and self.content_id != expected: raise ValueError("decomposition record digest mismatch") object.__setattr__(self, "content_id", expected) @dataclass(frozen=True) class DecisionReport: decision: str branch_count: int critical_path_units: int signals: tuple estimated_total_tokens: int coordination_ratio: float evidence_id: str claim: str = "LOCAL_DECISION_RECORD_NOT_MULTI_AGENT_BENCHMARK" def audit_decomposition( contract: DecisionContract, record: DecompositionRecord ) -> DecisionReport: """Decide whether a bounded fork/join plan justifies separate agent contexts.""" contract = validate_record(contract, DecisionContract) record = validate_record(record, DecompositionRecord) if record.scope != contract.scope or record.contract_content_id != contract.content_id: raise ValueError("decomposition belongs to another decision contract") units_by_id = {unit.unit_id: unit for unit in record.units} for unit in record.units: for dependency in unit.depends_on: target = units_by_id.get(dependency) if target is None: raise ValueError("dependency names an undeclared work unit") if target.position >= unit.position: raise ValueError("dependencies must point backward in the declared DAG") branches = record.units[:-1] merge = record.units[-1] if any(branch.depends_on for branch in branches): raise ValueError("this record accepts only independent fork branches") if set(merge.depends_on) != {branch.unit_id for branch in branches}: raise ValueError("merge must depend on every branch exactly once") branches_by_isolation = {} for branch in branches: branches_by_isolation.setdefault(branch.isolation_key, []).append(branch) if any( len(shared) > 1 and any(not branch.read_only for branch in shared) for shared in branches_by_isolation.values() ): raise ValueError("shared mutable isolation requires explicit serialization") if ( merge.tool_domain != "aggregation" or merge.isolation_key != "shared-merge" or merge.requires_isolated_credentials or not merge.read_only ): raise ValueError("final work unit must be a read-only deterministic aggregation") if len(branches) > contract.max_workers: raise ValueError("branch count exceeds worker contract") if any(branch.estimated_context_tokens > contract.single_context_limit_tokens for branch in branches): raise ValueError("a branch cannot fit its declared context budget") total_tokens = sum(unit.estimated_context_tokens for unit in record.units) coordination = merge.estimated_context_tokens / total_tokens parallel_frontier = len(branches) >= contract.minimum_parallel_branches context_pressure = ( sum(branch.estimated_context_tokens for branch in branches) > contract.single_context_limit_tokens ) isolated = [branch for branch in branches if branch.requires_isolated_credentials] credential_isolation = ( len(isolated) >= 2 and len({branch.tool_domain for branch in isolated}) == len(isolated) and len({branch.isolation_key for branch in isolated}) == len(isolated) ) bounded_coordination = coordination <= contract.max_coordination_ratio signals = [] if parallel_frontier: signals.append("parallel-frontier") if context_pressure: signals.append("context-pressure") if credential_isolation: signals.append("credential-isolation") if bounded_coordination: signals.append("bounded-coordination") justified = ( parallel_frontier and (context_pressure or credential_isolation) and bounded_coordination ) decision = ( "MULTI_AGENT_JUSTIFIED" if justified else "SINGLE_AGENT_OR_FIXED_WORKFLOW" ) evidence_id = digest( { "contract": contract.content_id, "record": record.content_id, "decision": decision, "signals": signals, "tokens": total_tokens, "coordination": f"{coordination:.12f}", } ) return DecisionReport( decision, len(branches), 2, tuple(signals), total_tokens, coordination, evidence_id, ) def illustrative_fixture(): contract = DecisionContract() task_id = "supplier-risk-review" branch_data = ( ("policy", "policy-owner", "policy-search", "credential-policy", 8_000), ("finance", "finance-owner", "finance-ledger", "credential-finance", 8_000), ("security", "security-owner", "security-catalog", "credential-security", 8_000), ) branches = tuple( WorkUnit( contract.scope, task_id, position, unit_id, owner, tool_domain, isolation_key, token_estimate, (), "finding-bundle-v1", True, True, ) for position, ( unit_id, owner, tool_domain, isolation_key, token_estimate, ) in enumerate(branch_data, start=1) ) merge = WorkUnit( contract.scope, task_id, 4, "synthesize", "decision-owner", "aggregation", "shared-merge", 3_000, tuple(branch.unit_id for branch in branches), "decision-record-v1", False, True, ) record = DecompositionRecord( contract.scope, task_id, digest("review supplier risk across policy, finance, and security evidence"), contract.content_id, "evaluation-2026-09-21", branches + (merge,), ) return contract, record def main(): report = audit_decomposition(*illustrative_fixture()) print("example=illustrative_only") print(f"decision={report.decision}") print(f"branches={report.branch_count};critical_path_units={report.critical_path_units}") print("signals=" + ",".join(report.signals)) print( f"estimated_tokens={report.estimated_total_tokens};" f"coordination_ratio={report.coordination_ratio:.3f}" ) print(f"claim={report.claim}") if __name__ == "__main__": main()