diff --git a/loopx/control_plane/turn_driver/executor.py b/loopx/control_plane/turn_driver/executor.py index a8bbd0e4b5..748c8612c1 100644 --- a/loopx/control_plane/turn_driver/executor.py +++ b/loopx/control_plane/turn_driver/executor.py @@ -487,7 +487,7 @@ def validate_loopx_turn_host_result( errors.append("host result completed_phases must be host_execute, typed_result") material = kind in MATERIAL_HOST_RESULT_KINDS - normalized = { + normalized: dict[str, object] = { "schema_version": LOOPX_TURN_RESULT_SCHEMA_VERSION, "turn_key": turn_key, "result_kind": kind.value if kind else None, diff --git a/loopx/control_plane/turn_driver/subagent_execution_contracts.py b/loopx/control_plane/turn_driver/subagent_execution_contracts.py new file mode 100644 index 0000000000..8a3ed99c53 --- /dev/null +++ b/loopx/control_plane/turn_driver/subagent_execution_contracts.py @@ -0,0 +1,510 @@ +"""Contracts, constants, opaque-reference validation, and child task packet builders.""" + +from __future__ import annotations + +from collections.abc import Mapping, Sequence +import hashlib +import json +import re +from typing import Literal, TypedDict + +from ..runtime.public_safety import validate_public_safe_value as validate_public_safe_value + +SUBAGENT_EXECUTION_TOPOLOGY_SCHEMA_VERSION = "subagent_execution_topology_v0" +SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION = ( + "subagent_host_execution_receipt_v0" +) +SUBAGENT_CONTROL_PLANE_RECONCILIATION_SCHEMA_VERSION = ( + "subagent_control_plane_reconciliation_v0" +) +CHILD_EXECUTION_TASK_PACKET_SCHEMA_VERSION = "child_execution_task_packet_v0" +CHILD_EXECUTION_GUARD_SCHEMA_VERSION = "child_execution_guard_v0" +CHILD_EXECUTION_REJECTION_SCHEMA_VERSION = "child_execution_rejection_v0" +MAX_CHILD_EXECUTION_RECEIPTS = 32 +MAX_EFFECT_CLASSES = 8 +MAX_EVIDENCE_REFS = 12 +EXECUTION_KINDS = frozenset({"ephemeral_child"}) +RECEIPT_STATUSES = frozenset( + {"running", "completed", "failed", "cancelled", "rejected"} +) +KNOWN_EFFECT_CLASSES = frozenset( + { + "local_read", + "network_read", + "held_workspace_write", + "external_write", + "production_action", + "credential_use", + "monitor", + } +) +CHILD_CONTEXT_MODES = frozenset({"fresh", "forked_snapshot", "resume"}) +CHILD_CONTEXT_INHERITANCE = { + "fresh": "none", + "forked_snapshot": "parent_conversation_snapshot", + "resume": "existing_child_session", +} +CHILD_FALLBACK_ACTIONS = ( + "retry_fresh", + "replace_child", + "serial_takeover", + "ignore_optional_result", +) +# Keep this grammar shared by runtime validation and the host-result JSON schema. +# Slash-delimited opaque ids remain valid, but filesystem-shaped values do not. +OPAQUE_REF_PATTERN = ( + r"^(?![A-Za-z][A-Za-z0-9+.-]*:/)" + r"(?!\.{1,2}(?:/|$))" + r"(?!.*?/\.{1,2}(?:/|$))" + r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,191}$" +) +_OPAQUE_REF = re.compile(OPAQUE_REF_PATTERN) +_RECEIPT_FIELDS = frozenset( + { + "schema_version", + "bundle_id", + "lane_id", + "goal_id", + "todo_id", + "execution_kind", + "runtime_id", + "worker_ref", + "source_state_ref", + "task_packet_digest", + "context_mode", + "workspace_ref", + "status", + "effect_classes", + "evidence_refs", + "raw_transcript_copied", + } +) +HOST_RESULT_FIELDS = frozenset({"child_execution_receipts"}) + + +class ChildExecutionLane(TypedDict): + """Typed record describing an admitted ephemeral child execution lane.""" + + lane_id: str + todo_id: str + execution_kind: Literal["ephemeral_child"] + admission_ref: str + effect_boundary: Literal["held_workspace_write", "held_evidence_only"] + allowed_effect_classes: list[str] + workspace_requirement: Literal["independent_git_worktree", "not_required"] + workspace_ref: str | None + task_packet: dict[str, object] + task_packet_digest: str + + +class ChildReceiptItemSchema(TypedDict): + """Typed JSON schema shape for one child execution receipt item.""" + + type: Literal["object"] + properties: dict[str, object] + required: list[str] + additionalProperties: bool + + +class ChildExecutionReceiptsSchema(TypedDict): + """Typed JSON schema shape for the child_execution_receipts array.""" + + type: Literal["array"] + items: ChildReceiptItemSchema + maxItems: int + + +class ChildExecutionTopologyError(ValueError): + """Structured fail-local pre-spawn validation error for child lanes.""" + + def __init__(self, *, reason_code: str, detail: str) -> None: + self.reason_code = reason_code + super().__init__(f"{reason_code}: {detail}") + + +def _mapping(value: object) -> dict[str, object]: + return {str(k): v for k, v in value.items()} if isinstance(value, Mapping) else {} + + +def _opaque_ref( + value: object, + *, + field: str, + required: bool = True, +) -> str | None: + if value is None or value == "": + text = "" + elif not isinstance(value, str): + raise ValueError(f"{field} must be a string") + else: + text = value.strip() + if not text: + if required: + raise ValueError(f"{field} is required") + return None + validate_public_safe_value(text, path=field) + if not _OPAQUE_REF.fullmatch(text): + raise ValueError( + f"{field} must be an opaque 1-192 character public-safe reference" + ) + return text + + +def _opaque_refs( + value: object, + *, + field: str, + limit: int, + allowed: frozenset[str] | None = None, +) -> list[str]: + if not isinstance(value, list): + raise ValueError(f"{field} must be a list") + if len(value) > limit: + raise ValueError(f"{field} accepts at most {limit} items") + seen: set[str] = set() + for item in value: + ref = _opaque_ref(item, field=f"{field}[]") + assert ref is not None + if allowed is not None and ref not in allowed: + raise ValueError(f"{field} contains unsupported value: {ref}") + seen.add(ref) + return sorted(seen) + + +def _canonical_sha256_hex(value: Mapping[str, object]) -> str: + return hashlib.sha256( + json.dumps( + dict(value), + ensure_ascii=True, + sort_keys=True, + separators=(",", ":"), + ).encode("utf-8") + ).hexdigest() + + +def _digest(value: Mapping[str, object]) -> str: + return _canonical_sha256_hex(value)[:16] + + +def _sha256_ref(value: Mapping[str, object]) -> str: + return "sha256:" + _canonical_sha256_hex(value) + + +def subagent_bundle_id(*, turn_key: str) -> str: + return "bundle_" + _digest({"turn_key": turn_key}) + + +def subagent_lane_id(*, bundle_id: str, todo_id: str) -> str: + return "lane_" + _digest({"bundle_id": bundle_id, "todo_id": todo_id}) + + +def _required_text(value: object, *, field: str) -> str: + text = str(value or "").strip() + if not text: + raise ChildExecutionTopologyError( + reason_code="child_task_packet_incomplete", + detail=f"{field} is required before child launch", + ) + return text + + +def _child_guard_policy(brief: Mapping[str, object]) -> dict[str, object]: + if brief.get("child_guard_policy") != "prevention_first_v0": + raise ChildExecutionTopologyError( + reason_code="child_task_packet_incomplete", + detail="child_guard_policy is missing or not fail-local", + ) + return { + "schema_version": CHILD_EXECUTION_GUARD_SCHEMA_VERSION, + "pre_spawn": "require_complete_task_packet", + "on_deviation": "project_stop_and_quarantine_child", + "evidence_disposition": "candidate_until_parent_accepts", + "parent_blocked": False, + "parent_continuation": "continue", + "fallback_actions": list(CHILD_FALLBACK_ACTIONS), + } + + +def _child_context_contract(operation: Mapping[str, object]) -> dict[str, object]: + mode = _required_text( + operation.get("recommended_context"), + field="recommended_context", + ) + available_contexts = operation.get("available_contexts") + if not isinstance(available_contexts, list): + raise ChildExecutionTopologyError( + reason_code="child_task_packet_incomplete", + detail="available_contexts must be explicit", + ) + if mode not in CHILD_CONTEXT_MODES: + raise ChildExecutionTopologyError( + reason_code="child_task_packet_incomplete", + detail="recommended_context is unsupported", + ) + if mode not in available_contexts: + raise ChildExecutionTopologyError( + reason_code="child_task_packet_incomplete", + detail="recommended_context is not available on the selected host", + ) + return { + "mode": mode, + "inheritance": CHILD_CONTEXT_INHERITANCE[mode], + } + + +def _child_task_packet( + *, + operation: Mapping[str, object], + brief: Mapping[str, object], + todo_id: str, + source_state_ref: str, + allowed_effect_classes: Sequence[str], + workspace_requirement: str, + workspace_ref: str | None, +) -> dict[str, object]: + required_capabilities = brief.get("required_capabilities") + required_write_scopes = brief.get("required_write_scopes") + acceptance = brief.get("acceptance") + if not isinstance(required_capabilities, list): + raise ChildExecutionTopologyError( + reason_code="child_task_packet_incomplete", + detail="required_capabilities must be explicit", + ) + if not isinstance(required_write_scopes, list): + raise ChildExecutionTopologyError( + reason_code="child_task_packet_incomplete", + detail="required_write_scopes must be explicit", + ) + if ( + not isinstance(acceptance, list) + or not acceptance + or not all(isinstance(item, str) and item.strip() for item in acceptance) + ): + raise ChildExecutionTopologyError( + reason_code="child_task_packet_incomplete", + detail="acceptance must be a non-empty string list", + ) + validation_declared = brief.get("validation_declared") is True + validation: dict[str, object] = { + "declared": validation_declared, + "authority_ref": ( + f"todo:{todo_id}:completion_validation" if validation_declared else None + ), + "execution_owner": "registered_parent", + "command_disclosed": False, + "label": str(brief.get("validation_label") or "").strip() or None, + "policy": ( + "registered parent runs declared todo completion validation; " + "child reports relevant validation evidence" + if validation_declared + else _required_text( + brief.get("validation_policy"), + field="validation_policy", + ) + ), + } + execution_policy = brief.get("execution_policy") + task_packet: dict[str, object] = { + "schema_version": CHILD_EXECUTION_TASK_PACKET_SCHEMA_VERSION, + "todo_id": todo_id, + "objective": _required_text(brief.get("objective"), field="objective"), + "action_kind": _required_text( + brief.get("action_kind"), + field="action_kind", + ), + "target_key": str(brief.get("target_key") or "").strip() or None, + "deliverable": ( + "held_workspace_change_with_evidence" + if required_write_scopes + else "public_safe_evidence" + ), + "acceptance": [item.strip() for item in acceptance], + "context_refs": [ + _required_text(brief.get("authority_artifact"), field="authority_artifact"), + _required_text(brief.get("latest_state_ref"), field="latest_state_ref"), + source_state_ref, + ], + "task_domain": _required_text( + brief.get("task_domain"), + field="task_domain", + ), + "task_repository": str(brief.get("task_repository") or "").strip() or None, + "allowed_capabilities": list(required_capabilities), + "allowed_write_scopes": list(required_write_scopes), + "allowed_effect_classes": list(allowed_effect_classes), + "forbidden_effect_classes": sorted( + KNOWN_EFFECT_CLASSES - set(allowed_effect_classes) + ), + "workspace_requirement": workspace_requirement, + "workspace_ref": workspace_ref, + "context": _child_context_contract(operation), + "execution_budget": ( + dict(execution_policy) if isinstance(execution_policy, Mapping) else {} + ), + "output_contract": _required_text( + brief.get("expected_output"), + field="expected_output", + ), + "acceptance_mode": ( + "parent_validation_then_review" + if validation["declared"] + else "parent_review_only" + ), + "validation": validation, + "guard": _child_guard_policy(brief), + } + if not task_packet["execution_budget"]: + raise ChildExecutionTopologyError( + reason_code="child_task_packet_incomplete", + detail="execution_policy must define the child budget", + ) + validate_public_safe_value(task_packet, path="child_task_packet") + return task_packet + + +def _child_pre_spawn_rejection( + operation: Mapping[str, object], + *, + reason_code: str, +) -> dict[str, object]: + try: + todo_id = _opaque_ref( + operation.get("todo_id"), + field="pre_spawn_rejection.todo_id", + required=False, + ) + except ValueError: + todo_id = None + return { + "schema_version": CHILD_EXECUTION_REJECTION_SCHEMA_VERSION, + "todo_id": todo_id, + "stage": "pre_spawn", + "reason_codes": [reason_code], + "launch_allowed": False, + "recommended_child_action": "do_not_launch", + "parent_blocked": False, + "parent_continuation": "continue", + "fallback_actions": list(CHILD_FALLBACK_ACTIONS), + } + + +def _child_execution_lane( + operation: Mapping[str, object], + *, + bundle_id: str, + source_state_ref: str, +) -> ChildExecutionLane: + todo_id = _opaque_ref( + operation.get("todo_id"), + field="topology.lanes[].todo_id", + ) + assert todo_id is not None + brief = _mapping(operation.get("brief")) + write_scopes = brief.get("required_write_scopes") + has_workspace_write = isinstance(write_scopes, list) and bool(write_scopes) + required_capabilities = brief.get("required_capabilities") + uses_network = ( + isinstance(required_capabilities, list) + and "network" in required_capabilities + ) + effect_boundary: Literal["held_workspace_write", "held_evidence_only"] = ( + "held_workspace_write" if has_workspace_write else "held_evidence_only" + ) + allowed_effect_classes = ["local_read"] + if uses_network: + allowed_effect_classes.append("network_read") + if has_workspace_write: + allowed_effect_classes.append("held_workspace_write") + lane_id = subagent_lane_id( + bundle_id=bundle_id, + todo_id=todo_id, + ) + workspace_ref = f"workspace:{lane_id}" if has_workspace_write else None + workspace_requirement: Literal["independent_git_worktree", "not_required"] = ( + "independent_git_worktree" if has_workspace_write else "not_required" + ) + task_packet = _child_task_packet( + operation=operation, + brief=brief, + todo_id=todo_id, + source_state_ref=source_state_ref, + allowed_effect_classes=allowed_effect_classes, + workspace_requirement=workspace_requirement, + workspace_ref=workspace_ref, + ) + return { + "lane_id": lane_id, + "todo_id": todo_id, + "execution_kind": "ephemeral_child", + "admission_ref": f"task_orchestration_contract_v2:{todo_id}", + "effect_boundary": effect_boundary, + "allowed_effect_classes": allowed_effect_classes, + "workspace_requirement": workspace_requirement, + "workspace_ref": workspace_ref, + "task_packet": task_packet, + "task_packet_digest": _sha256_ref(task_packet), + } + + +def child_execution_receipts_json_schema() -> ChildExecutionReceiptsSchema: + """Return the strict JSON schema for child_execution_receipts host output.""" + opaque_ref: dict[str, object] = { + "type": "string", + "pattern": OPAQUE_REF_PATTERN, + "maxLength": 192, + } + nullable_ref: dict[str, object] = { + "anyOf": [ + dict(opaque_ref), + {"type": "null"}, + ] + } + properties: dict[str, object] = { + "schema_version": { + "type": "string", + "enum": [SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION], + }, + "bundle_id": dict(opaque_ref), + "lane_id": dict(opaque_ref), + "goal_id": dict(opaque_ref), + "todo_id": dict(opaque_ref), + "execution_kind": { + "type": "string", + "enum": sorted(EXECUTION_KINDS), + }, + "runtime_id": dict(opaque_ref), + "worker_ref": dict(opaque_ref), + "source_state_ref": dict(opaque_ref), + "task_packet_digest": dict(opaque_ref), + "context_mode": { + "type": "string", + "enum": sorted(CHILD_CONTEXT_MODES), + }, + "workspace_ref": nullable_ref, + "status": { + "type": "string", + "enum": sorted(RECEIPT_STATUSES), + }, + "effect_classes": { + "type": "array", + "items": {"type": "string", "enum": sorted(KNOWN_EFFECT_CLASSES)}, + "maxItems": MAX_EFFECT_CLASSES, + }, + "evidence_refs": { + "type": "array", + "items": dict(opaque_ref), + "minItems": 1, + "maxItems": MAX_EVIDENCE_REFS, + }, + "raw_transcript_copied": {"type": "boolean", "enum": [False]}, + } + return { + "type": "array", + "items": { + "type": "object", + "properties": properties, + "required": list(properties), + "additionalProperties": False, + }, + "maxItems": MAX_CHILD_EXECUTION_RECEIPTS, + } diff --git a/loopx/control_plane/turn_driver/subagent_execution_reconciliation.py b/loopx/control_plane/turn_driver/subagent_execution_reconciliation.py new file mode 100644 index 0000000000..0a0b677e48 --- /dev/null +++ b/loopx/control_plane/turn_driver/subagent_execution_reconciliation.py @@ -0,0 +1,401 @@ +"""Host receipt normalization and parent-child topology reconciliation.""" + +from __future__ import annotations + +from collections.abc import Iterable, Mapping, Sequence + +from .subagent_execution_contracts import ( + CHILD_CONTEXT_MODES, + CHILD_EXECUTION_GUARD_SCHEMA_VERSION, + CHILD_FALLBACK_ACTIONS, + EXECUTION_KINDS, + KNOWN_EFFECT_CLASSES, + MAX_CHILD_EXECUTION_RECEIPTS, + MAX_EFFECT_CLASSES, + MAX_EVIDENCE_REFS, + RECEIPT_STATUSES, + SUBAGENT_CONTROL_PLANE_RECONCILIATION_SCHEMA_VERSION, + SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION, + _RECEIPT_FIELDS, + _mapping, + _opaque_ref, + _opaque_refs, +) + + +def _normalize_single_receipt( + raw: Mapping[str, object], + *, + index: int, +) -> dict[str, object]: + field = f"child_execution_receipts[{index}]" + raw_keys = set(raw) + unknown = sorted(raw_keys - _RECEIPT_FIELDS) + if unknown: + raise ValueError( + f"{field} contains unsupported fields: {', '.join(unknown)}" + ) + missing = sorted(_RECEIPT_FIELDS - raw_keys) + if missing: + raise ValueError(f"{field} is missing fields: {', '.join(missing)}") + if ( + raw.get("schema_version") + != SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION + ): + raise ValueError(f"{field} has an unsupported schema_version") + execution_kind = str(raw.get("execution_kind") or "").strip() + if execution_kind not in EXECUTION_KINDS: + raise ValueError(f"{field}.execution_kind is unsupported") + context_mode = str(raw.get("context_mode") or "").strip() + if context_mode not in CHILD_CONTEXT_MODES: + raise ValueError(f"{field}.context_mode is unsupported") + status = str(raw.get("status") or "").strip() + if status not in RECEIPT_STATUSES: + raise ValueError(f"{field}.status is unsupported") + if raw.get("raw_transcript_copied") is not False: + raise ValueError(f"{field}.raw_transcript_copied must be false") + return { + "schema_version": SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION, + "bundle_id": _opaque_ref(raw.get("bundle_id"), field=f"{field}.bundle_id"), + "lane_id": _opaque_ref(raw.get("lane_id"), field=f"{field}.lane_id"), + "goal_id": _opaque_ref(raw.get("goal_id"), field=f"{field}.goal_id"), + "todo_id": _opaque_ref(raw.get("todo_id"), field=f"{field}.todo_id"), + "execution_kind": execution_kind, + "runtime_id": _opaque_ref( + raw.get("runtime_id"), field=f"{field}.runtime_id" + ), + "worker_ref": _opaque_ref( + raw.get("worker_ref"), field=f"{field}.worker_ref" + ), + "source_state_ref": _opaque_ref( + raw.get("source_state_ref"), field=f"{field}.source_state_ref" + ), + "task_packet_digest": _opaque_ref( + raw.get("task_packet_digest"), field=f"{field}.task_packet_digest" + ), + "context_mode": context_mode, + "workspace_ref": _opaque_ref( + raw.get("workspace_ref"), + field=f"{field}.workspace_ref", + required=False, + ), + "status": status, + "effect_classes": _opaque_refs( + raw.get("effect_classes"), + field=f"{field}.effect_classes", + limit=MAX_EFFECT_CLASSES, + allowed=KNOWN_EFFECT_CLASSES, + ), + "evidence_refs": _opaque_refs( + raw.get("evidence_refs"), + field=f"{field}.evidence_refs", + limit=MAX_EVIDENCE_REFS, + ), + "raw_transcript_copied": False, + } + + +def normalize_subagent_host_execution_receipts( + value: object, +) -> list[dict[str, object]]: + """Validate and normalize host-reported child execution receipts.""" + if value is None: + return [] + if not isinstance(value, list): + raise ValueError("child_execution_receipts must be a list") + if len(value) > MAX_CHILD_EXECUTION_RECEIPTS: + raise ValueError( + "child_execution_receipts accepts at most " + f"{MAX_CHILD_EXECUTION_RECEIPTS} items" + ) + receipts: list[dict[str, object]] = [] + for index, raw in enumerate(value): + if not isinstance(raw, Mapping): + raise ValueError(f"child_execution_receipts[{index}] must be an object") + receipts.append(_normalize_single_receipt(raw, index=index)) + return receipts + + +def _lane_reason_codes( + *, + topology: Mapping[str, object], + lane: Mapping[str, object], + receipt: Mapping[str, object], + duplicate_count: int, +) -> list[str]: + reasons: list[str] = [] + if duplicate_count: + reasons.append("orphaned_worker_result") + if receipt.get("bundle_id") != topology.get("bundle_id"): + reasons.append("orphaned_worker_result") + if receipt.get("goal_id") != topology.get("goal_id"): + reasons.append("missing_todo_lineage") + if receipt.get("todo_id") != lane.get("todo_id"): + reasons.append("missing_todo_lineage") + if receipt.get("execution_kind") != lane.get("execution_kind"): + reasons.append("execution_kind_mismatch") + if receipt.get("source_state_ref") != topology.get("source_state_ref"): + reasons.append("source_state_stale") + if receipt.get("task_packet_digest") != lane.get("task_packet_digest"): + reasons.append("task_packet_mismatch") + expected_context_mode = _mapping( + _mapping(lane.get("task_packet")).get("context") + ).get("mode") + if receipt.get("context_mode") != expected_context_mode: + reasons.append("context_mode_mismatch") + raw_allowed = lane.get("allowed_effect_classes") + allowed_effects = ( + set(raw_allowed) + if isinstance(raw_allowed, Iterable) and not isinstance(raw_allowed, (str, bytes)) + else set() + ) + raw_effects = receipt.get("effect_classes") + receipt_effects = ( + raw_effects + if isinstance(raw_effects, Iterable) and not isinstance(raw_effects, (str, bytes)) + else () + ) + if any(effect not in allowed_effects for effect in receipt_effects): + reasons.append("side_effect_boundary_exceeded") + if receipt.get("status") == "completed" and not receipt.get("evidence_refs"): + reasons.append("aggregate_settlement_without_lane_evidence") + if ( + lane.get("workspace_requirement") == "independent_git_worktree" + and receipt.get("workspace_ref") != lane.get("workspace_ref") + ): + reasons.append("workspace_mismatch") + return sorted(set(reasons)) + + +def _lane_status( + receipt: Mapping[str, object] | None, + *, + reason_codes: Sequence[str], +) -> str: + if receipt is None or receipt.get("status") == "running": + return "incomplete" + if reason_codes: + return "drifted" + if receipt.get("status") == "cancelled": + return "cancelled" + if receipt.get("status") in {"failed", "rejected"}: + return "rejected" + return "aligned" + + +def _lane_reconciliation( + *, + topology: Mapping[str, object], + lane: Mapping[str, object], + observed: Sequence[Mapping[str, object]], +) -> tuple[dict[str, object], list[dict[str, object]]]: + receipt = observed[0] if observed else None + duplicate_receipts = [dict(item) for item in observed[1:]] + reason_codes = ( + ["worker_receipt_missing"] + if receipt is None + else _lane_reason_codes( + topology=topology, + lane=lane, + receipt=receipt, + duplicate_count=len(duplicate_receipts), + ) + ) + status = _lane_status(receipt, reason_codes=reason_codes) + raw_fallbacks = _mapping( + _mapping(lane.get("task_packet")).get("guard") + ).get("fallback_actions") + fallbacks = ( + list(raw_fallbacks) + if isinstance(raw_fallbacks, Sequence) + and not isinstance(raw_fallbacks, (str, bytes)) + else [] + ) + result: dict[str, object] = { + "lane_id": str(lane.get("lane_id") or ""), + "todo_id": lane.get("todo_id"), + "execution_kind": lane.get("execution_kind"), + "status": status, + "reason_codes": reason_codes, + "receipt_present": receipt is not None, + "evidence_disposition": ( + "quarantined" + if status in {"drifted", "rejected", "cancelled"} + else "candidate" + if status == "incomplete" + else "candidate_for_parent_acceptance" + ), + "recommended_child_action": ( + "stop_child" + if status in {"drifted", "rejected", "cancelled"} + else "wait_for_child" + if status == "incomplete" + else "return_to_parent" + ), + "parent_blocked": False, + "parent_continuation": "continue", + "fallback_actions": fallbacks, + } + if receipt is not None: + raw_effects = receipt.get("effect_classes") + raw_evidence = receipt.get("evidence_refs") + result.update( + { + "worker_ref": receipt.get("worker_ref"), + "workspace_ref": receipt.get("workspace_ref"), + "effect_classes": ( + list(raw_effects) + if isinstance(raw_effects, Sequence) + and not isinstance(raw_effects, (str, bytes)) + else [] + ), + ( + "quarantined_evidence_refs" + if status in {"drifted", "rejected", "cancelled"} + else "candidate_evidence_refs" + ): ( + list(raw_evidence) + if isinstance(raw_evidence, Sequence) + and not isinstance(raw_evidence, (str, bytes)) + else [] + ), + } + ) + return result, duplicate_receipts + + +def _orphaned_receipt_projection( + receipt: Mapping[str, object], + *, + unadmitted: bool, +) -> dict[str, object]: + raw_evidence = receipt.get("evidence_refs") + return { + "lane_id": str(receipt.get("lane_id") or "") or None, + "worker_ref": receipt.get("worker_ref"), + "reason_codes": ( + ["unadmitted_child_spawn", "orphaned_worker_result"] + if unadmitted + else ["orphaned_worker_result"] + ), + "evidence_disposition": "quarantined", + "recommended_child_action": "stop_child", + "parent_blocked": False, + "parent_continuation": "continue", + "fallback_actions": list(CHILD_FALLBACK_ACTIONS), + "quarantined_evidence_refs": ( + list(raw_evidence) + if isinstance(raw_evidence, Sequence) + and not isinstance(raw_evidence, (str, bytes)) + else [] + ), + } + + +def _mapping_list(raw: object) -> list[Mapping[str, object]]: + if not isinstance(raw, Sequence) or isinstance(raw, (str, bytes)): + return [] + return [row for row in raw if isinstance(row, Mapping)] + + +def reconcile_subagent_execution( + topology: Mapping[str, object] | None, + receipts: Sequence[Mapping[str, object]], +) -> dict[str, object] | None: + """Reconcile planned topology lanes against normalized child execution receipts.""" + if not topology and not receipts: + return None + topology_map: Mapping[str, object] = topology or {} + planned_lanes = _mapping_list(topology_map.get("lanes")) + receipts_by_lane: dict[str, list[Mapping[str, object]]] = {} + for receipt in receipts: + receipts_by_lane.setdefault(str(receipt.get("lane_id") or ""), []).append( + receipt + ) + lane_results: list[dict[str, object]] = [] + status_counts = { + "aligned": 0, + "incomplete": 0, + "rejected": 0, + "cancelled": 0, + "drifted": 0, + } + duplicate_receipts: list[dict[str, object]] = [] + for lane in planned_lanes: + lane_id = str(lane.get("lane_id") or "") + observed = receipts_by_lane.pop(lane_id, []) + lane_result, duplicates = _lane_reconciliation( + topology=topology_map, + lane=lane, + observed=observed, + ) + lane_results.append(lane_result) + duplicate_receipts.extend(duplicates) + status_counts[str(lane_result["status"])] += 1 + orphaned_receipts = [ + _orphaned_receipt_projection(receipt, unadmitted=True) + for _lane_id, lane_receipts in sorted(receipts_by_lane.items()) + for receipt in lane_receipts + ] + orphaned_receipts.extend( + _orphaned_receipt_projection(receipt, unadmitted=False) + for receipt in duplicate_receipts + ) + orphaned_count = len(orphaned_receipts) + pre_spawn_rejections = [ + dict(item) for item in _mapping_list(topology_map.get("pre_spawn_rejections")) + ] + payload: dict[str, object] = { + "schema_version": SUBAGENT_CONTROL_PLANE_RECONCILIATION_SCHEMA_VERSION, + "bundle_id": topology_map.get("bundle_id"), + "topology_present": bool(topology), + "observation_only": True, + "settlement_enforced": False, + "child_guard": { + "schema_version": CHILD_EXECUTION_GUARD_SCHEMA_VERSION, + "enforced_boundaries": ["pre_spawn_task_packet"], + "validated_observations": [ + "receipt_task_packet_binding", + "context_mode_binding", + "workspace_boundary", + "effect_boundary", + ], + "projected_dispositions": [ + "stop_child", + "quarantine_evidence", + "continue_parent", + "fallback_actions", + ], + "unsupported_boundaries": [ + "evidence_acceptance_enforcement", + "live_host_tool_interception", + "automatic_host_child_termination", + ], + "parent_acceptance_required": True, + }, + "parent_blocked": False, + "parent_continuation": "continue", + "status": ( + "drifted" + if status_counts["drifted"] or orphaned_count + else "guarded" + if pre_spawn_rejections + or status_counts["rejected"] + or status_counts["cancelled"] + else "incomplete" + if status_counts["incomplete"] + else "reconciled" + ), + "counts": { + "planned": len(planned_lanes), + "pre_spawn_rejected": len(pre_spawn_rejections), + "observed": len(receipts), + **status_counts, + "orphaned": orphaned_count, + }, + "lanes": lane_results, + "orphaned_receipts": orphaned_receipts, + } + if pre_spawn_rejections: + payload["pre_spawn_rejections"] = pre_spawn_rejections + return payload diff --git a/loopx/control_plane/turn_driver/subagent_execution_topology.py b/loopx/control_plane/turn_driver/subagent_execution_topology.py index 99b4d5effa..28874dd192 100644 --- a/loopx/control_plane/turn_driver/subagent_execution_topology.py +++ b/loopx/control_plane/turn_driver/subagent_execution_topology.py @@ -1,101 +1,80 @@ +"""Coordinator-child execution topology projection and host result wiring.""" + from __future__ import annotations -import hashlib -import json -import re -from collections.abc import Mapping, Sequence -from typing import Any +from collections.abc import Mapping, MutableMapping, Sequence +from typing import Protocol from ..agent_context import envelope_agent_context -from ..runtime.public_safety import validate_public_safe_value - - -SUBAGENT_EXECUTION_TOPOLOGY_SCHEMA_VERSION = "subagent_execution_topology_v0" -SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION = ( - "subagent_host_execution_receipt_v0" -) -SUBAGENT_CONTROL_PLANE_RECONCILIATION_SCHEMA_VERSION = ( - "subagent_control_plane_reconciliation_v0" -) -CHILD_EXECUTION_TASK_PACKET_SCHEMA_VERSION = "child_execution_task_packet_v0" -CHILD_EXECUTION_GUARD_SCHEMA_VERSION = "child_execution_guard_v0" -CHILD_EXECUTION_REJECTION_SCHEMA_VERSION = "child_execution_rejection_v0" -MAX_CHILD_EXECUTION_RECEIPTS = 32 -MAX_EFFECT_CLASSES = 8 -MAX_EVIDENCE_REFS = 12 -EXECUTION_KINDS = frozenset({"ephemeral_child"}) -RECEIPT_STATUSES = frozenset( - {"running", "completed", "failed", "cancelled", "rejected"} +from .subagent_execution_contracts import ( + CHILD_CONTEXT_INHERITANCE as CHILD_CONTEXT_INHERITANCE, + CHILD_CONTEXT_MODES as CHILD_CONTEXT_MODES, + CHILD_EXECUTION_GUARD_SCHEMA_VERSION as CHILD_EXECUTION_GUARD_SCHEMA_VERSION, + CHILD_EXECUTION_REJECTION_SCHEMA_VERSION as CHILD_EXECUTION_REJECTION_SCHEMA_VERSION, + CHILD_EXECUTION_TASK_PACKET_SCHEMA_VERSION as CHILD_EXECUTION_TASK_PACKET_SCHEMA_VERSION, + CHILD_FALLBACK_ACTIONS as CHILD_FALLBACK_ACTIONS, + EXECUTION_KINDS as EXECUTION_KINDS, + HOST_RESULT_FIELDS as HOST_RESULT_FIELDS, + KNOWN_EFFECT_CLASSES as KNOWN_EFFECT_CLASSES, + MAX_CHILD_EXECUTION_RECEIPTS as MAX_CHILD_EXECUTION_RECEIPTS, + MAX_EFFECT_CLASSES as MAX_EFFECT_CLASSES, + MAX_EVIDENCE_REFS as MAX_EVIDENCE_REFS, + OPAQUE_REF_PATTERN as OPAQUE_REF_PATTERN, + RECEIPT_STATUSES as RECEIPT_STATUSES, + SUBAGENT_CONTROL_PLANE_RECONCILIATION_SCHEMA_VERSION as SUBAGENT_CONTROL_PLANE_RECONCILIATION_SCHEMA_VERSION, + SUBAGENT_EXECUTION_TOPOLOGY_SCHEMA_VERSION as SUBAGENT_EXECUTION_TOPOLOGY_SCHEMA_VERSION, + SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION as SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION, + ChildExecutionLane as ChildExecutionLane, + ChildExecutionReceiptsSchema as ChildExecutionReceiptsSchema, + ChildExecutionTopologyError as ChildExecutionTopologyError, + ChildReceiptItemSchema as ChildReceiptItemSchema, + _OPAQUE_REF as _OPAQUE_REF, + _RECEIPT_FIELDS as _RECEIPT_FIELDS, + _child_context_contract as _child_context_contract, + _child_execution_lane as _child_execution_lane, + _child_guard_policy as _child_guard_policy, + _child_pre_spawn_rejection, + _child_task_packet as _child_task_packet, + _digest as _digest, + _mapping, + _opaque_ref as _opaque_ref, + _opaque_refs as _opaque_refs, + _required_text as _required_text, + _sha256_ref as _sha256_ref, + child_execution_receipts_json_schema as child_execution_receipts_json_schema, + subagent_bundle_id as subagent_bundle_id, + subagent_lane_id as subagent_lane_id, ) -KNOWN_EFFECT_CLASSES = frozenset( - { - "local_read", - "network_read", - "held_workspace_write", - "external_write", - "production_action", - "credential_use", - "monitor", - } -) -CHILD_CONTEXT_MODES = frozenset({"fresh", "forked_snapshot", "resume"}) -CHILD_CONTEXT_INHERITANCE = { - "fresh": "none", - "forked_snapshot": "parent_conversation_snapshot", - "resume": "existing_child_session", -} -CHILD_FALLBACK_ACTIONS = ( - "retry_fresh", - "replace_child", - "serial_takeover", - "ignore_optional_result", -) -# Keep this grammar shared by runtime validation and the host-result JSON schema. -# Slash-delimited opaque ids remain valid, but filesystem-shaped values do not. -OPAQUE_REF_PATTERN = ( - r"^(?![A-Za-z][A-Za-z0-9+.-]*:/)" - r"(?!\.{1,2}(?:/|$))" - r"(?!.*?/\.{1,2}(?:/|$))" - r"[A-Za-z0-9][A-Za-z0-9._:/-]{0,191}$" -) -_OPAQUE_REF = re.compile(OPAQUE_REF_PATTERN) -_RECEIPT_FIELDS = frozenset( - { - "schema_version", - "bundle_id", - "lane_id", - "goal_id", - "todo_id", - "execution_kind", - "runtime_id", - "worker_ref", - "source_state_ref", - "task_packet_digest", - "context_mode", - "workspace_ref", - "status", - "effect_classes", - "evidence_refs", - "raw_transcript_copied", - } +from .subagent_execution_reconciliation import ( + _lane_reason_codes as _lane_reason_codes, + _lane_reconciliation as _lane_reconciliation, + _lane_status as _lane_status, + _orphaned_receipt_projection as _orphaned_receipt_projection, + normalize_subagent_host_execution_receipts as normalize_subagent_host_execution_receipts, + reconcile_subagent_execution as reconcile_subagent_execution, ) -HOST_RESULT_FIELDS = frozenset({"child_execution_receipts"}) -class ChildExecutionTopologyError(ValueError): - def __init__(self, *, reason_code: str, detail: str) -> None: - self.reason_code = reason_code - super().__init__(f"{reason_code}: {detail}") +class _EnvelopeAgentContextFn(Protocol): + def __call__( + self, + envelope: Mapping[str, object], + *, + phase: str, + observations: Mapping[str, object] | None = None, + ) -> dict[str, object] | None: ... def subagent_execution_topology( - plan: Mapping[str, Any], -) -> Mapping[str, Any] | None: + plan: Mapping[str, object], +) -> Mapping[str, object] | None: + """Return the plan's subagent_execution_topology mapping when present.""" topology = plan.get("subagent_execution_topology") return topology if isinstance(topology, Mapping) else None -def subagent_host_result_fields(plan: Mapping[str, Any]) -> frozenset[str]: +def subagent_host_result_fields(plan: Mapping[str, object]) -> frozenset[str]: + """Return additional host-result fields admitted when subagent topology is present.""" return ( HOST_RESULT_FIELDS if subagent_execution_topology(plan) is not None @@ -103,343 +82,14 @@ def subagent_host_result_fields(plan: Mapping[str, Any]) -> frozenset[str]: ) -def _mapping(value: Any) -> dict[str, Any]: - return dict(value) if isinstance(value, Mapping) else {} - - -def _opaque_ref( - value: Any, - *, - field: str, - required: bool = True, -) -> str | None: - if value is None or value == "": - text = "" - elif not isinstance(value, str): - raise ValueError(f"{field} must be a string") - else: - text = value.strip() - if not text: - if required: - raise ValueError(f"{field} is required") - return None - validate_public_safe_value(text, path=field) - if not _OPAQUE_REF.fullmatch(text): - raise ValueError( - f"{field} must be an opaque 1-192 character public-safe reference" - ) - return text - - -def _opaque_refs( - value: Any, - *, - field: str, - limit: int, - allowed: frozenset[str] | None = None, -) -> list[str]: - if not isinstance(value, list): - raise ValueError(f"{field} must be a list") - if len(value) > limit: - raise ValueError(f"{field} accepts at most {limit} items") - result: list[str] = [] - for item in value: - ref = _opaque_ref(item, field=f"{field}[]") - assert ref is not None - if allowed is not None and ref not in allowed: - raise ValueError(f"{field} contains unsupported value: {ref}") - if ref not in result: - result.append(ref) - return sorted(result) - - -def _digest(value: Mapping[str, Any]) -> str: - return hashlib.sha256( - json.dumps( - dict(value), - ensure_ascii=True, - sort_keys=True, - separators=(",", ":"), - ).encode("utf-8") - ).hexdigest()[:16] - - -def _sha256_ref(value: Mapping[str, Any]) -> str: - return "sha256:" + hashlib.sha256( - json.dumps( - dict(value), - ensure_ascii=True, - sort_keys=True, - separators=(",", ":"), - ).encode("utf-8") - ).hexdigest() - - -def subagent_bundle_id(*, turn_key: str) -> str: - return "bundle_" + _digest({"turn_key": turn_key}) - - -def subagent_lane_id(*, bundle_id: str, todo_id: str) -> str: - return "lane_" + _digest({"bundle_id": bundle_id, "todo_id": todo_id}) - - -def _required_text(value: Any, *, field: str) -> str: - text = str(value or "").strip() - if not text: - raise ChildExecutionTopologyError( - reason_code="child_task_packet_incomplete", - detail=f"{field} is required before child launch", - ) - return text - - -def _child_guard_policy(brief: Mapping[str, Any]) -> dict[str, Any]: - if brief.get("child_guard_policy") != "prevention_first_v0": - raise ChildExecutionTopologyError( - reason_code="child_task_packet_incomplete", - detail="child_guard_policy is missing or not fail-local", - ) - return { - "schema_version": CHILD_EXECUTION_GUARD_SCHEMA_VERSION, - "pre_spawn": "require_complete_task_packet", - "on_deviation": "project_stop_and_quarantine_child", - "evidence_disposition": "candidate_until_parent_accepts", - "parent_blocked": False, - "parent_continuation": "continue", - "fallback_actions": list(CHILD_FALLBACK_ACTIONS), - } - - -def _child_context_contract(operation: Mapping[str, Any]) -> dict[str, Any]: - mode = _required_text( - operation.get("recommended_context"), - field="recommended_context", - ) - available_contexts = operation.get("available_contexts") - if not isinstance(available_contexts, list): - raise ChildExecutionTopologyError( - reason_code="child_task_packet_incomplete", - detail="available_contexts must be explicit", - ) - if mode not in CHILD_CONTEXT_MODES: - raise ChildExecutionTopologyError( - reason_code="child_task_packet_incomplete", - detail="recommended_context is unsupported", - ) - if mode not in available_contexts: - raise ChildExecutionTopologyError( - reason_code="child_task_packet_incomplete", - detail="recommended_context is not available on the selected host", - ) - return { - "mode": mode, - "inheritance": CHILD_CONTEXT_INHERITANCE[mode], - } - - -def _child_task_packet( - *, - operation: Mapping[str, Any], - brief: Mapping[str, Any], - todo_id: str, - source_state_ref: str, - allowed_effect_classes: Sequence[str], - workspace_requirement: str, - workspace_ref: str | None, -) -> dict[str, Any]: - required_capabilities = brief.get("required_capabilities") - required_write_scopes = brief.get("required_write_scopes") - acceptance = brief.get("acceptance") - if not isinstance(required_capabilities, list): - raise ChildExecutionTopologyError( - reason_code="child_task_packet_incomplete", - detail="required_capabilities must be explicit", - ) - if not isinstance(required_write_scopes, list): - raise ChildExecutionTopologyError( - reason_code="child_task_packet_incomplete", - detail="required_write_scopes must be explicit", - ) - if ( - not isinstance(acceptance, list) - or not acceptance - or not all(isinstance(item, str) and item.strip() for item in acceptance) - ): - raise ChildExecutionTopologyError( - reason_code="child_task_packet_incomplete", - detail="acceptance must be a non-empty string list", - ) - validation_declared = brief.get("validation_declared") is True - validation = { - "declared": validation_declared, - "authority_ref": ( - f"todo:{todo_id}:completion_validation" - if validation_declared - else None - ), - "execution_owner": "registered_parent", - "command_disclosed": False, - "label": str(brief.get("validation_label") or "").strip() or None, - "policy": ( - "registered parent runs declared todo completion validation; " - "child reports relevant validation evidence" - if validation_declared - else _required_text( - brief.get("validation_policy"), - field="validation_policy", - ) - ), - } - execution_policy = brief.get("execution_policy") - task_packet = { - "schema_version": CHILD_EXECUTION_TASK_PACKET_SCHEMA_VERSION, - "todo_id": todo_id, - "objective": _required_text(brief.get("objective"), field="objective"), - "action_kind": _required_text( - brief.get("action_kind"), - field="action_kind", - ), - "target_key": str(brief.get("target_key") or "").strip() or None, - "deliverable": ( - "held_workspace_change_with_evidence" - if required_write_scopes - else "public_safe_evidence" - ), - "acceptance": [item.strip() for item in acceptance], - "context_refs": [ - _required_text(brief.get("authority_artifact"), field="authority_artifact"), - _required_text(brief.get("latest_state_ref"), field="latest_state_ref"), - source_state_ref, - ], - "task_domain": _required_text( - brief.get("task_domain"), - field="task_domain", - ), - "task_repository": str(brief.get("task_repository") or "").strip() or None, - "allowed_capabilities": list(required_capabilities), - "allowed_write_scopes": list(required_write_scopes), - "allowed_effect_classes": list(allowed_effect_classes), - "forbidden_effect_classes": sorted( - KNOWN_EFFECT_CLASSES - set(allowed_effect_classes) - ), - "workspace_requirement": workspace_requirement, - "workspace_ref": workspace_ref, - "context": _child_context_contract(operation), - "execution_budget": ( - dict(execution_policy) if isinstance(execution_policy, Mapping) else {} - ), - "output_contract": _required_text( - brief.get("expected_output"), - field="expected_output", - ), - "acceptance_mode": ( - "parent_validation_then_review" - if validation["declared"] - else "parent_review_only" - ), - "validation": validation, - "guard": _child_guard_policy(brief), - } - if not task_packet["execution_budget"]: - raise ChildExecutionTopologyError( - reason_code="child_task_packet_incomplete", - detail="execution_policy must define the child budget", - ) - validate_public_safe_value(task_packet, path="child_task_packet") - return task_packet - - -def _child_pre_spawn_rejection( - operation: Mapping[str, Any], - *, - reason_code: str, -) -> dict[str, Any]: - try: - todo_id = _opaque_ref( - operation.get("todo_id"), - field="pre_spawn_rejection.todo_id", - required=False, - ) - except ValueError: - todo_id = None - return { - "schema_version": CHILD_EXECUTION_REJECTION_SCHEMA_VERSION, - "todo_id": todo_id, - "stage": "pre_spawn", - "reason_codes": [reason_code], - "launch_allowed": False, - "recommended_child_action": "do_not_launch", - "parent_blocked": False, - "parent_continuation": "continue", - "fallback_actions": list(CHILD_FALLBACK_ACTIONS), - } - - -def _child_execution_lane( - operation: Mapping[str, Any], - *, - bundle_id: str, - source_state_ref: str, -) -> dict[str, Any]: - todo_id = _opaque_ref( - operation.get("todo_id"), - field="topology.lanes[].todo_id", - ) - assert todo_id is not None - brief = _mapping(operation.get("brief")) - write_scopes = brief.get("required_write_scopes") - has_workspace_write = isinstance(write_scopes, list) and bool(write_scopes) - required_capabilities = brief.get("required_capabilities") - uses_network = ( - isinstance(required_capabilities, list) - and "network" in required_capabilities - ) - effect_boundary = ( - "held_workspace_write" if has_workspace_write else "held_evidence_only" - ) - allowed_effect_classes = ["local_read"] - if uses_network: - allowed_effect_classes.append("network_read") - if has_workspace_write: - allowed_effect_classes.append("held_workspace_write") - lane_id = subagent_lane_id( - bundle_id=bundle_id, - todo_id=todo_id, - ) - workspace_ref = f"workspace:{lane_id}" if has_workspace_write else None - workspace_requirement = ( - "independent_git_worktree" if has_workspace_write else "not_required" - ) - task_packet = _child_task_packet( - operation=operation, - brief=brief, - todo_id=todo_id, - source_state_ref=source_state_ref, - allowed_effect_classes=allowed_effect_classes, - workspace_requirement=workspace_requirement, - workspace_ref=workspace_ref, - ) - return { - "lane_id": lane_id, - "todo_id": todo_id, - "execution_kind": "ephemeral_child", - "admission_ref": f"task_orchestration_contract_v2:{todo_id}", - "effect_boundary": effect_boundary, - "allowed_effect_classes": allowed_effect_classes, - "workspace_requirement": workspace_requirement, - "workspace_ref": workspace_ref, - "task_packet": task_packet, - "task_packet_digest": _sha256_ref(task_packet), - } - - def build_subagent_execution_topology( *, - turn_envelope: Mapping[str, Any], - child_operations: Sequence[Mapping[str, Any]], + turn_envelope: Mapping[str, object], + child_operations: Sequence[Mapping[str, object]], turn_key: str, source_state_ref: str, -) -> dict[str, Any] | None: +) -> dict[str, object] | None: + """Build bounded coordinator-child execution topology for adaptive turns.""" if not child_operations: return None orchestration = _mapping(turn_envelope.get("task_orchestration_contract")) @@ -472,8 +122,8 @@ def build_subagent_execution_topology( and configured_max_children > 0 else len(child_operations) ) - lanes: list[dict[str, Any]] = [] - pre_spawn_rejections: list[dict[str, Any]] = [] + lanes: list[ChildExecutionLane] = [] + pre_spawn_rejections: list[dict[str, object]] = [] allowed_effect_classes: set[str] = set() for operation in child_operations: if len(lanes) >= max_children: @@ -529,17 +179,24 @@ def build_subagent_execution_topology( def bind_child_operations_to_topology( - child_operations: Sequence[Mapping[str, Any]], - topology: Mapping[str, Any] | None, -) -> list[dict[str, Any]]: + child_operations: Sequence[Mapping[str, object]], + topology: Mapping[str, object] | None, +) -> list[dict[str, object]]: + """Bind child operations to their admitted topology lanes.""" if not topology: return [dict(operation) for operation in child_operations] + raw_lanes = topology.get("lanes") + lane_items = ( + raw_lanes + if isinstance(raw_lanes, Sequence) and not isinstance(raw_lanes, (str, bytes)) + else () + ) lanes_by_todo = { str(lane.get("todo_id") or ""): lane - for lane in topology.get("lanes") or [] + for lane in lane_items if isinstance(lane, Mapping) } - bound_operations: list[dict[str, Any]] = [] + bound_operations: list[dict[str, object]] = [] for operation in child_operations: lane = _mapping(lanes_by_todo.get(str(operation.get("todo_id") or ""))) if not lane: @@ -561,9 +218,10 @@ def bind_child_operations_to_topology( def subagent_host_request_projection( - plan: Mapping[str, Any], -) -> dict[str, Any]: - projection: dict[str, Any] = {} + plan: Mapping[str, object], +) -> dict[str, object]: + """Project delegation context, child operations, and topology for host request.""" + projection: dict[str, object] = {} context = plan.get("delegation_context") if isinstance(context, Mapping): projection["delegation_context"] = dict(context) @@ -576,427 +234,13 @@ def subagent_host_request_projection( return projection -def child_execution_receipts_json_schema() -> dict[str, Any]: - opaque_ref = { - "type": "string", - "pattern": OPAQUE_REF_PATTERN, - "maxLength": 192, - } - nullable_ref = { - "anyOf": [ - dict(opaque_ref), - {"type": "null"}, - ] - } - properties = { - "schema_version": { - "type": "string", - "enum": [SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION], - }, - "bundle_id": dict(opaque_ref), - "lane_id": dict(opaque_ref), - "goal_id": dict(opaque_ref), - "todo_id": dict(opaque_ref), - "execution_kind": { - "type": "string", - "enum": sorted(EXECUTION_KINDS), - }, - "runtime_id": dict(opaque_ref), - "worker_ref": dict(opaque_ref), - "source_state_ref": dict(opaque_ref), - "task_packet_digest": dict(opaque_ref), - "context_mode": { - "type": "string", - "enum": sorted(CHILD_CONTEXT_MODES), - }, - "workspace_ref": nullable_ref, - "status": { - "type": "string", - "enum": sorted(RECEIPT_STATUSES), - }, - "effect_classes": { - "type": "array", - "items": {"type": "string", "enum": sorted(KNOWN_EFFECT_CLASSES)}, - "maxItems": MAX_EFFECT_CLASSES, - }, - "evidence_refs": { - "type": "array", - "items": dict(opaque_ref), - "minItems": 1, - "maxItems": MAX_EVIDENCE_REFS, - }, - "raw_transcript_copied": {"type": "boolean", "enum": [False]}, - } - return { - "type": "array", - "items": { - "type": "object", - "properties": properties, - "required": list(properties), - "additionalProperties": False, - }, - "maxItems": MAX_CHILD_EXECUTION_RECEIPTS, - } - - -def normalize_subagent_host_execution_receipts( - value: Any, -) -> list[dict[str, Any]]: - if value is None: - return [] - if not isinstance(value, list): - raise ValueError("child_execution_receipts must be a list") - if len(value) > MAX_CHILD_EXECUTION_RECEIPTS: - raise ValueError( - "child_execution_receipts accepts at most " - f"{MAX_CHILD_EXECUTION_RECEIPTS} items" - ) - receipts: list[dict[str, Any]] = [] - for index, raw in enumerate(value): - field = f"child_execution_receipts[{index}]" - if not isinstance(raw, Mapping): - raise ValueError(f"{field} must be an object") - unknown = sorted(set(raw) - _RECEIPT_FIELDS) - if unknown: - raise ValueError( - f"{field} contains unsupported fields: {', '.join(unknown)}" - ) - missing = sorted(_RECEIPT_FIELDS - set(raw)) - if missing: - raise ValueError(f"{field} is missing fields: {', '.join(missing)}") - if ( - raw.get("schema_version") - != SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION - ): - raise ValueError(f"{field} has an unsupported schema_version") - execution_kind = str(raw.get("execution_kind") or "").strip() - if execution_kind not in EXECUTION_KINDS: - raise ValueError(f"{field}.execution_kind is unsupported") - context_mode = str(raw.get("context_mode") or "").strip() - if context_mode not in CHILD_CONTEXT_MODES: - raise ValueError(f"{field}.context_mode is unsupported") - status = str(raw.get("status") or "").strip() - if status not in RECEIPT_STATUSES: - raise ValueError(f"{field}.status is unsupported") - raw_transcript_copied = raw.get("raw_transcript_copied") - if raw_transcript_copied is not False: - raise ValueError(f"{field}.raw_transcript_copied must be false") - receipt = { - "schema_version": SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION, - "bundle_id": _opaque_ref( - raw.get("bundle_id"), - field=f"{field}.bundle_id", - ), - "lane_id": _opaque_ref(raw.get("lane_id"), field=f"{field}.lane_id"), - "goal_id": _opaque_ref(raw.get("goal_id"), field=f"{field}.goal_id"), - "todo_id": _opaque_ref(raw.get("todo_id"), field=f"{field}.todo_id"), - "execution_kind": execution_kind, - "runtime_id": _opaque_ref( - raw.get("runtime_id"), - field=f"{field}.runtime_id", - ), - "worker_ref": _opaque_ref( - raw.get("worker_ref"), - field=f"{field}.worker_ref", - ), - "source_state_ref": _opaque_ref( - raw.get("source_state_ref"), - field=f"{field}.source_state_ref", - ), - "task_packet_digest": _opaque_ref( - raw.get("task_packet_digest"), - field=f"{field}.task_packet_digest", - ), - "context_mode": context_mode, - "workspace_ref": _opaque_ref( - raw.get("workspace_ref"), - field=f"{field}.workspace_ref", - required=False, - ), - "status": status, - "effect_classes": _opaque_refs( - raw.get("effect_classes"), - field=f"{field}.effect_classes", - limit=MAX_EFFECT_CLASSES, - allowed=KNOWN_EFFECT_CLASSES, - ), - "evidence_refs": _opaque_refs( - raw.get("evidence_refs"), - field=f"{field}.evidence_refs", - limit=MAX_EVIDENCE_REFS, - ), - "raw_transcript_copied": False, - } - validate_public_safe_value( - { - key: item - for key, item in receipt.items() - if key != "raw_transcript_copied" - }, - path=field, - ) - receipts.append(receipt) - return receipts - - -def _lane_reason_codes( - *, - topology: Mapping[str, Any], - lane: Mapping[str, Any], - receipt: Mapping[str, Any], - duplicate_count: int, -) -> list[str]: - reasons: list[str] = [] - if duplicate_count: - reasons.append("orphaned_worker_result") - if receipt.get("bundle_id") != topology.get("bundle_id"): - reasons.append("orphaned_worker_result") - if receipt.get("goal_id") != topology.get("goal_id"): - reasons.append("missing_todo_lineage") - if receipt.get("todo_id") != lane.get("todo_id"): - reasons.append("missing_todo_lineage") - if receipt.get("execution_kind") != lane.get("execution_kind"): - reasons.append("execution_kind_mismatch") - if receipt.get("source_state_ref") != topology.get("source_state_ref"): - reasons.append("source_state_stale") - if receipt.get("task_packet_digest") != lane.get("task_packet_digest"): - reasons.append("task_packet_mismatch") - expected_context_mode = _mapping( - _mapping(lane.get("task_packet")).get("context") - ).get("mode") - if receipt.get("context_mode") != expected_context_mode: - reasons.append("context_mode_mismatch") - allowed_effects = set(lane.get("allowed_effect_classes") or []) - if any( - effect not in allowed_effects for effect in receipt.get("effect_classes") or [] - ): - reasons.append("side_effect_boundary_exceeded") - if receipt.get("status") == "completed" and not receipt.get("evidence_refs"): - reasons.append("aggregate_settlement_without_lane_evidence") - if ( - lane.get("workspace_requirement") == "independent_git_worktree" - and receipt.get("workspace_ref") != lane.get("workspace_ref") - ): - reasons.append("workspace_mismatch") - return sorted(set(reasons)) - - -def _lane_status( - receipt: Mapping[str, Any] | None, - *, - reason_codes: Sequence[str], -) -> str: - if receipt is None or receipt.get("status") == "running": - return "incomplete" - if reason_codes: - return "drifted" - if receipt.get("status") == "cancelled": - return "cancelled" - if receipt.get("status") in {"failed", "rejected"}: - return "rejected" - return "aligned" - - -def _lane_reconciliation( - *, - topology: Mapping[str, Any], - lane: Mapping[str, Any], - observed: Sequence[Mapping[str, Any]], -) -> tuple[dict[str, Any], list[dict[str, Any]]]: - receipt = observed[0] if observed else None - duplicate_receipts = [dict(item) for item in observed[1:]] - reason_codes = ( - ["worker_receipt_missing"] - if receipt is None - else _lane_reason_codes( - topology=topology, - lane=lane, - receipt=receipt, - duplicate_count=len(duplicate_receipts), - ) - ) - status = _lane_status(receipt, reason_codes=reason_codes) - result = { - "lane_id": str(lane.get("lane_id") or ""), - "todo_id": lane.get("todo_id"), - "execution_kind": lane.get("execution_kind"), - "status": status, - "reason_codes": reason_codes, - "receipt_present": receipt is not None, - "evidence_disposition": ( - "quarantined" - if status in {"drifted", "rejected", "cancelled"} - else "candidate" - if status == "incomplete" - else "candidate_for_parent_acceptance" - ), - "recommended_child_action": ( - "stop_child" - if status in {"drifted", "rejected", "cancelled"} - else "wait_for_child" - if status == "incomplete" - else "return_to_parent" - ), - "parent_blocked": False, - "parent_continuation": "continue", - "fallback_actions": list( - _mapping(_mapping(lane.get("task_packet")).get("guard")).get( - "fallback_actions" - ) - or [] - ), - } - if receipt is not None: - result.update( - { - "worker_ref": receipt.get("worker_ref"), - "workspace_ref": receipt.get("workspace_ref"), - "effect_classes": list(receipt.get("effect_classes") or []), - ( - "quarantined_evidence_refs" - if status in {"drifted", "rejected", "cancelled"} - else "candidate_evidence_refs" - ): list(receipt.get("evidence_refs") or []), - } - ) - return result, duplicate_receipts - - -def _orphaned_receipt_projection( - receipt: Mapping[str, Any], - *, - unadmitted: bool, -) -> dict[str, Any]: - return { - "lane_id": str(receipt.get("lane_id") or "") or None, - "worker_ref": receipt.get("worker_ref"), - "reason_codes": ( - ["unadmitted_child_spawn", "orphaned_worker_result"] - if unadmitted - else ["orphaned_worker_result"] - ), - "evidence_disposition": "quarantined", - "recommended_child_action": "stop_child", - "parent_blocked": False, - "parent_continuation": "continue", - "fallback_actions": list(CHILD_FALLBACK_ACTIONS), - "quarantined_evidence_refs": list(receipt.get("evidence_refs") or []), - } - - -def reconcile_subagent_execution( - topology: Mapping[str, Any] | None, - receipts: Sequence[Mapping[str, Any]], -) -> dict[str, Any] | None: - if not topology and not receipts: - return None - planned_lanes = [ - dict(lane) - for lane in (topology or {}).get("lanes") or [] - if isinstance(lane, Mapping) - ] - receipts_by_lane: dict[str, list[dict[str, Any]]] = {} - for receipt in receipts: - receipts_by_lane.setdefault(str(receipt.get("lane_id") or ""), []).append( - dict(receipt) - ) - lane_results: list[dict[str, Any]] = [] - status_counts = { - "aligned": 0, - "incomplete": 0, - "rejected": 0, - "cancelled": 0, - "drifted": 0, - } - duplicate_receipts: list[dict[str, Any]] = [] - for lane in planned_lanes: - lane_id = str(lane.get("lane_id") or "") - observed = receipts_by_lane.pop(lane_id, []) - lane_result, duplicates = _lane_reconciliation( - topology=topology or {}, - lane=lane, - observed=observed, - ) - lane_results.append(lane_result) - duplicate_receipts.extend(duplicates) - status_counts[str(lane_result["status"])] += 1 - orphaned_receipts = [ - _orphaned_receipt_projection(receipt, unadmitted=True) - for lane_id, lane_receipts in sorted(receipts_by_lane.items()) - for receipt in lane_receipts - ] - orphaned_receipts.extend( - _orphaned_receipt_projection(receipt, unadmitted=False) - for receipt in duplicate_receipts - ) - orphaned_count = len(orphaned_receipts) - pre_spawn_rejections = [ - dict(item) - for item in (topology or {}).get("pre_spawn_rejections") or [] - if isinstance(item, Mapping) - ] - payload = { - "schema_version": SUBAGENT_CONTROL_PLANE_RECONCILIATION_SCHEMA_VERSION, - "bundle_id": (topology or {}).get("bundle_id"), - "topology_present": bool(topology), - "observation_only": True, - "settlement_enforced": False, - "child_guard": { - "schema_version": CHILD_EXECUTION_GUARD_SCHEMA_VERSION, - "enforced_boundaries": ["pre_spawn_task_packet"], - "validated_observations": [ - "receipt_task_packet_binding", - "context_mode_binding", - "workspace_boundary", - "effect_boundary", - ], - "projected_dispositions": [ - "stop_child", - "quarantine_evidence", - "continue_parent", - "fallback_actions", - ], - "unsupported_boundaries": [ - "evidence_acceptance_enforcement", - "live_host_tool_interception", - "automatic_host_child_termination", - ], - "parent_acceptance_required": True, - }, - "parent_blocked": False, - "parent_continuation": "continue", - "status": ( - "drifted" - if status_counts["drifted"] or orphaned_count - else "guarded" - if pre_spawn_rejections - or status_counts["rejected"] - or status_counts["cancelled"] - else "incomplete" - if status_counts["incomplete"] - else "reconciled" - ), - "counts": { - "planned": len(planned_lanes), - "pre_spawn_rejected": len(pre_spawn_rejections), - "observed": len(receipts), - **status_counts, - "orphaned": orphaned_count, - }, - "lanes": lane_results, - "orphaned_receipts": orphaned_receipts, - } - if pre_spawn_rejections: - payload["pre_spawn_rejections"] = pre_spawn_rejections - return payload - - def observe_subagent_host_result( - plan: Mapping[str, Any], - result: Mapping[str, Any], - normalized: dict[str, Any], + plan: Mapping[str, object], + result: Mapping[str, object], + normalized: MutableMapping[str, object], errors: list[str], ) -> None: + """Normalize child execution receipts and attach reconciliation onto host result.""" try: receipts = normalize_subagent_host_execution_receipts( result.get("child_execution_receipts") @@ -1004,11 +248,8 @@ def observe_subagent_host_result( except ValueError as exc: errors.append(str(exc)) receipts = [] - topology = ( - plan.get("subagent_execution_topology") - if isinstance(plan.get("subagent_execution_topology"), Mapping) - else None - ) + raw_topology = plan.get("subagent_execution_topology") + topology = raw_topology if isinstance(raw_topology, Mapping) else None if receipts: normalized["child_execution_receipts"] = receipts reconciliation = reconcile_subagent_execution(topology, receipts) @@ -1016,23 +257,29 @@ def observe_subagent_host_result( normalized["subagent_reconciliation"] = reconciliation from ..quota.turn_envelope import read_turn_plan_work - context = envelope_agent_context( + raw_counts = reconciliation["counts"] + observations: dict[str, object] = {"reconciliation_counts": raw_counts} + envelope_fn: _EnvelopeAgentContextFn = envelope_agent_context + context = envelope_fn( read_turn_plan_work(plan), phase="after_delegate_result", - observations={"reconciliation_counts": reconciliation["counts"]}, + observations=observations, ) if context is not None: normalized["agent_context"] = context def subagent_execution_payload_projection( - journal: Mapping[str, Any], -) -> dict[str, Any]: + journal: Mapping[str, object], +) -> dict[str, object]: + """Extract subagent reconciliation and post-delegation agent context from journal.""" host_result = _mapping(journal.get("host_result")) reconciliation = host_result.get("subagent_reconciliation") if not isinstance(reconciliation, Mapping): return {} - projection = {"subagent_reconciliation": dict(reconciliation)} + projection: dict[str, object] = { + "subagent_reconciliation": dict(reconciliation) + } context = host_result.get("agent_context") if isinstance(context, Mapping): projection["agent_context"] = dict(context) diff --git a/tests/control_plane/test_subagent_execution_topology_contract.py b/tests/control_plane/test_subagent_execution_topology_contract.py new file mode 100644 index 0000000000..206f3a5d95 --- /dev/null +++ b/tests/control_plane/test_subagent_execution_topology_contract.py @@ -0,0 +1,414 @@ +"""Contract, parity, efficiency, and failure-mode tests for subagent topology.""" + +from __future__ import annotations + +import ast +from collections.abc import Mapping +from pathlib import Path +import re +from types import MappingProxyType + +import pytest + +from loopx.control_plane.turn_driver import ( + subagent_execution_contracts, + subagent_execution_reconciliation, + subagent_execution_topology, +) +from loopx.control_plane.turn_driver.subagent_execution_topology import ( + CHILD_CONTEXT_INHERITANCE, + CHILD_CONTEXT_MODES, + CHILD_EXECUTION_GUARD_SCHEMA_VERSION, + CHILD_EXECUTION_REJECTION_SCHEMA_VERSION, + CHILD_EXECUTION_TASK_PACKET_SCHEMA_VERSION, + CHILD_FALLBACK_ACTIONS, + EXECUTION_KINDS, + HOST_RESULT_FIELDS, + KNOWN_EFFECT_CLASSES, + MAX_CHILD_EXECUTION_RECEIPTS, + MAX_EFFECT_CLASSES, + MAX_EVIDENCE_REFS, + OPAQUE_REF_PATTERN, + RECEIPT_STATUSES, + SUBAGENT_CONTROL_PLANE_RECONCILIATION_SCHEMA_VERSION, + SUBAGENT_EXECUTION_TOPOLOGY_SCHEMA_VERSION, + SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION, + ChildExecutionTopologyError, + _child_execution_lane, + _child_task_packet, + _opaque_ref, + _opaque_refs, + bind_child_operations_to_topology, + build_subagent_execution_topology, + child_execution_receipts_json_schema, + normalize_subagent_host_execution_receipts, + observe_subagent_host_result, + reconcile_subagent_execution, + subagent_bundle_id, + subagent_execution_payload_projection, + subagent_host_request_projection, + subagent_host_result_fields, + subagent_lane_id, +) + + +def _sample_brief( + *, + write_scopes: list[str] | None = None, + validation_declared: bool = True, + execution_policy: Mapping[str, object] | None = None, + extra: Mapping[str, object] | None = None, +) -> dict[str, object]: + brief: dict[str, object] = { + "child_guard_policy": "prevention_first_v0", + "objective": "Verify scoped module contract cleanly", + "action_kind": "verify", + "target_key": "scope:lane-1", + "task_domain": "control_plane", + "task_repository": "loopx", + "authority_artifact": "artifact:goal-contract", + "latest_state_ref": "state:head-1", + "required_capabilities": ["filesystem", "network"], + "required_write_scopes": [] if write_scopes is None else list(write_scopes), + "acceptance": ["All unit checks pass", "Zero private paths emitted"], + "validation_declared": validation_declared, + "validation_policy": "parent validates output contract", + "expected_output": "compact_evidence_bundle", + "execution_policy": ( + {"max_turns": 4, "max_minutes": 5} + if execution_policy is None + else dict(execution_policy) + ), + } + if extra: + brief.update(extra) + return brief + + +def _sample_operation( + todo_id: str = "todo_child001", + *, + recommended_context: str = "fresh", + brief: Mapping[str, object] | None = None, +) -> dict[str, object]: + return { + "todo_id": todo_id, + "recommended_context": recommended_context, + "available_contexts": ["fresh", "forked_snapshot"], + "brief": dict(brief) if brief is not None else _sample_brief(), + } + + +def _sample_envelope( + *, + max_children: object = 2, + mode: str = "adaptive", + include_agent_context: bool = False, +) -> dict[str, object]: + envelope: dict[str, object] = { + "goal_id": "goal-fixture", + "agent_id": "agent-coord", + "task_orchestration_contract": { + "schema_version": "task_orchestration_contract_v2", + "mode": mode, + "coordinator_agent_id": "coord-1", + "max_children": max_children, + }, + } + if include_agent_context: + envelope["agent_context"] = { + "schema_version": "agent_context_v0", + "scope": { + "goal_id": "goal-fixture", + "agent_id": "agent-coord", + "todo_id": "todo_1", + }, + } + return envelope + + +def _sample_receipt( + topology: Mapping[str, object], + *, + lane_index: int = 0, + status: str = "completed", + workspace_ref: str | None = None, + evidence_refs: list[str] | None = None, + effect_classes: list[str] | None = None, + context_mode: str = "fresh", +) -> dict[str, object]: + raw_lanes = topology["lanes"] + assert isinstance(raw_lanes, list) + lane = raw_lanes[lane_index] + assert isinstance(lane, Mapping) + return { + "schema_version": SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION, + "bundle_id": topology["bundle_id"], + "lane_id": lane["lane_id"], + "goal_id": topology["goal_id"], + "todo_id": lane["todo_id"], + "execution_kind": lane["execution_kind"], + "runtime_id": "codex-cli", + "worker_ref": "worker:child-1", + "source_state_ref": topology["source_state_ref"], + "task_packet_digest": lane["task_packet_digest"], + "context_mode": context_mode, + "workspace_ref": workspace_ref, + "status": status, + "effect_classes": ["local_read"] if effect_classes is None else list(effect_classes), + "evidence_refs": ["artifact:result-1"] if evidence_refs is None else list(evidence_refs), + "raw_transcript_copied": False, + } + + +def test_subagent_topology_module_budgets_and_reexports() -> None: + root = Path(subagent_execution_topology.__file__).resolve().parents[3] + module_paths = [ + root / "loopx/control_plane/turn_driver/subagent_execution_topology.py", + root / "loopx/control_plane/turn_driver/subagent_execution_contracts.py", + root / "loopx/control_plane/turn_driver/subagent_execution_reconciliation.py", + ] + internal_edges: dict[str, set[str]] = {} + for path in module_paths: + src = path.read_text(encoding="utf-8") + lines = src.splitlines() + limit = 650 if path.name == "subagent_execution_topology.py" else 750 + assert len(lines) <= limit, f"{path.name} exceeded {limit} LOC ({len(lines)})" + assert not re.search(r"#\s*type:\s*ignore", src), f"type ignore in {path.name}" + tree = ast.parse(src, filename=str(path)) + assert not any(isinstance(n, ast.Name) and n.id == "Any" for n in ast.walk(tree)) + internal_edges[path.stem] = { + n.module + for n in ast.walk(tree) + if isinstance(n, ast.ImportFrom) and n.module and n.module.startswith("subagent_execution") + } + + assert not internal_edges["subagent_execution_contracts"] + assert "subagent_execution_topology" not in internal_edges["subagent_execution_reconciliation"] + + pairs = [ + (SUBAGENT_EXECUTION_TOPOLOGY_SCHEMA_VERSION, subagent_execution_contracts.SUBAGENT_EXECUTION_TOPOLOGY_SCHEMA_VERSION), + (SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION, subagent_execution_contracts.SUBAGENT_HOST_EXECUTION_RECEIPT_SCHEMA_VERSION), + (SUBAGENT_CONTROL_PLANE_RECONCILIATION_SCHEMA_VERSION, subagent_execution_contracts.SUBAGENT_CONTROL_PLANE_RECONCILIATION_SCHEMA_VERSION), + (CHILD_EXECUTION_TASK_PACKET_SCHEMA_VERSION, subagent_execution_contracts.CHILD_EXECUTION_TASK_PACKET_SCHEMA_VERSION), + (CHILD_EXECUTION_GUARD_SCHEMA_VERSION, subagent_execution_contracts.CHILD_EXECUTION_GUARD_SCHEMA_VERSION), + (CHILD_EXECUTION_REJECTION_SCHEMA_VERSION, subagent_execution_contracts.CHILD_EXECUTION_REJECTION_SCHEMA_VERSION), + (MAX_CHILD_EXECUTION_RECEIPTS, subagent_execution_contracts.MAX_CHILD_EXECUTION_RECEIPTS), + (MAX_EFFECT_CLASSES, subagent_execution_contracts.MAX_EFFECT_CLASSES), + (MAX_EVIDENCE_REFS, subagent_execution_contracts.MAX_EVIDENCE_REFS), + (EXECUTION_KINDS, subagent_execution_contracts.EXECUTION_KINDS), + (RECEIPT_STATUSES, subagent_execution_contracts.RECEIPT_STATUSES), + (KNOWN_EFFECT_CLASSES, subagent_execution_contracts.KNOWN_EFFECT_CLASSES), + (CHILD_CONTEXT_MODES, subagent_execution_contracts.CHILD_CONTEXT_MODES), + (CHILD_CONTEXT_INHERITANCE, subagent_execution_contracts.CHILD_CONTEXT_INHERITANCE), + (CHILD_FALLBACK_ACTIONS, subagent_execution_contracts.CHILD_FALLBACK_ACTIONS), + (OPAQUE_REF_PATTERN, subagent_execution_contracts.OPAQUE_REF_PATTERN), + (HOST_RESULT_FIELDS, subagent_execution_contracts.HOST_RESULT_FIELDS), + (ChildExecutionTopologyError, subagent_execution_contracts.ChildExecutionTopologyError), + (subagent_bundle_id, subagent_execution_contracts.subagent_bundle_id), + (subagent_lane_id, subagent_execution_contracts.subagent_lane_id), + (child_execution_receipts_json_schema, subagent_execution_contracts.child_execution_receipts_json_schema), + (normalize_subagent_host_execution_receipts, subagent_execution_reconciliation.normalize_subagent_host_execution_receipts), + (reconcile_subagent_execution, subagent_execution_reconciliation.reconcile_subagent_execution), + ] + for exported, canonical in pairs: + assert exported is canonical + + +def test_immutable_mappingproxy_and_empty_container_parity() -> None: + assert build_subagent_execution_topology( + turn_envelope=_sample_envelope(), child_operations=[], turn_key="t1", source_state_ref="state:1" + ) is None + assert build_subagent_execution_topology( + turn_envelope=MappingProxyType({"task_orchestration_contract": None}), + child_operations=[_sample_operation()], + turn_key="t1", + source_state_ref="state:1", + ) is None + assert build_subagent_execution_topology( + turn_envelope=_sample_envelope(mode="serial"), + child_operations=[_sample_operation()], + turn_key="t1", + source_state_ref="state:1", + ) is None + + # Boolean/zero max_children falls back to len(child_operations). + env_bool = MappingProxyType(_sample_envelope(max_children=True)) + op_ok = MappingProxyType(_sample_operation("todo_1", brief=MappingProxyType(_sample_brief(write_scopes=["loopx/a.py"])))) + op_bad = MappingProxyType(_sample_operation("todo_2", brief=MappingProxyType(_sample_brief(execution_policy={})))) + topo = build_subagent_execution_topology( + turn_envelope=env_bool, + child_operations=[op_ok, op_bad], + turn_key="turn-k1", + source_state_ref="state:abc", + ) + assert topo is not None + assert topo["topology"] == "ephemeral_children" + env_block = topo["execution_envelope"] + assert isinstance(env_block, dict) and env_block["max_children"] == 2 + assert topo["rationale_codes"] == ["admitted_ephemeral_child_lanes", "child_launch_rejected"] + bound = bind_child_operations_to_topology([op_ok, op_bad], MappingProxyType(topo)) + assert len(bound) == 1 and bound[0]["todo_id"] == "todo_1" + assert bound[0]["workspace_ref"] == f"workspace:{bound[0]['lane_id']}" + assert bind_child_operations_to_topology([op_ok], {}) == [dict(op_ok)] + assert bind_child_operations_to_topology([op_ok], None) == [dict(op_ok)] + + # Empty child_operations list is omitted, while empty {} mappings stay present. + req = subagent_host_request_projection( + MappingProxyType({"delegation_context": {}, "child_operations": [], "subagent_execution_topology": {}}) + ) + assert req == {"delegation_context": {}, "subagent_execution_topology": {}} + assert subagent_host_result_fields({}) == frozenset() + assert subagent_host_result_fields({"subagent_execution_topology": {}}) == HOST_RESULT_FIELDS + + +def test_efficiency_dedup_and_single_pass_receipt_safety(monkeypatch: pytest.MonkeyPatch) -> None: + deduped = _opaque_refs( + ["ref:b", "ref:a", "ref:b", "ref:c", "ref:a"], + field="evidence_refs", + limit=MAX_EVIDENCE_REFS, + ) + assert deduped == ["ref:a", "ref:b", "ref:c"] + + topo = build_subagent_execution_topology( + turn_envelope=_sample_envelope(max_children=2), + child_operations=[_sample_operation("todo_1"), _sample_operation("todo_2")], + turn_key="turn-eff", + source_state_ref="state:1", + ) + assert topo is not None + receipt = _sample_receipt(topo, lane_index=0, effect_classes=["local_read", "local_read"]) + + safety_calls: list[str] = [] + orig_validate = subagent_execution_contracts.validate_public_safe_value + + def counting_validate(value: object, *, path: str = "public_payload") -> None: + safety_calls.append(path) + orig_validate(value, path=path) + + monkeypatch.setattr(subagent_execution_contracts, "validate_public_safe_value", counting_validate) + normalized = normalize_subagent_host_execution_receipts([MappingProxyType(receipt)]) + assert len(normalized) == 1 and normalized[0]["effect_classes"] == ["local_read"] + # Validates 8 required string refs + 2 effect_classes items + 1 evidence_refs item without full-dict re-walk. + assert len(safety_calls) == 11 + assert not any(call == "child_execution_receipts[0]" for call in safety_calls) + + # Reconciliation works cleanly over immutable MappingProxyType lanes and receipts. + raw_lanes = topo["lanes"] + assert isinstance(raw_lanes, list) + frozen_lanes = [ + MappingProxyType(lane) for lane in raw_lanes if isinstance(lane, Mapping) + ] + frozen_topo = MappingProxyType({**topo, "lanes": frozen_lanes}) + rec = reconcile_subagent_execution( + frozen_topo, [MappingProxyType(normalized[0]), MappingProxyType(normalized[0])] + ) + assert rec is not None and rec["status"] == "drifted" + counts = rec["counts"] + assert isinstance(counts, dict) and counts["orphaned"] == 1 and counts["incomplete"] == 1 + + +def test_reconciliation_dispositions_and_host_observation_wiring() -> None: + assert reconcile_subagent_execution(None, []) is None + assert reconcile_subagent_execution({}, []) is None + + topo = build_subagent_execution_topology( + turn_envelope=_sample_envelope(max_children=1, include_agent_context=True), + child_operations=[_sample_operation("todo_1"), _sample_operation("todo_2")], + turn_key="turn-rec", + source_state_ref="state:1", + ) + assert topo is not None + receipt = _sample_receipt(topo, status="completed") + norm: dict[str, object] = {} + errors: list[str] = [] + observe_subagent_host_result( + {"subagent_execution_topology": topo, "turn_envelope": _sample_envelope(include_agent_context=True)}, + {"child_execution_receipts": [receipt]}, + norm, + errors, + ) + assert errors == [] + assert "child_execution_receipts" in norm + rec = norm["subagent_reconciliation"] + assert isinstance(rec, Mapping) and rec["status"] == "guarded" + assert "pre_spawn_rejections" in rec + projected = subagent_execution_payload_projection({"host_result": norm}) + assert "subagent_reconciliation" in projected + assert subagent_execution_payload_projection({"host_result": {}}) == {} + + +def test_negative_validation_paths_and_fail_closed_guards() -> None: + assert normalize_subagent_host_execution_receipts(None) == [] + bad_cases: tuple[object, ...] = ( + "bad", + {}, + [object()] * (MAX_CHILD_EXECUTION_RECEIPTS + 1), + ["not-dict"], + ) + for bad_receipts in bad_cases: + with pytest.raises(ValueError): + normalize_subagent_host_execution_receipts(bad_receipts) + + topo = build_subagent_execution_topology( + turn_envelope=_sample_envelope(max_children=1), + child_operations=[_sample_operation("todo_1")], + turn_key="turn-neg", + source_state_ref="state:1", + ) + assert topo is not None + base = _sample_receipt(topo) + + bad_variants: list[dict[str, object]] = [ + {**base, "extra": 1}, + {k: v for k, v in base.items() if k != "evidence_refs"}, + {**base, "schema_version": "wrong_v1"}, + {**base, "execution_kind": "persistent"}, + {**base, "context_mode": "unknown"}, + {**base, "status": "paused"}, + {**base, "raw_transcript_copied": True}, + {**base, "evidence_refs": "not-list"}, + {**base, "evidence_refs": ["../escape"]}, + {**base, "effect_classes": ["unknown_effect"]}, + {**base, "effect_classes": ["local_read" for _ in range(MAX_EFFECT_CLASSES + 1)]}, + {**base, "evidence_refs": [f"artifact:r{i}" for i in range(MAX_EVIDENCE_REFS + 1)]}, + {**base, "worker_ref": "/etc/private/path"}, + {**base, "workspace_ref": "".join(["sk", "-", "fixture0000000000000000"])}, + ] + for bad in bad_variants: + with pytest.raises(ValueError): + normalize_subagent_host_execution_receipts([bad]) + + norm: dict[str, object] = {} + errors: list[str] = [] + observe_subagent_host_result( + {"subagent_execution_topology": topo}, + {"child_execution_receipts": "bad-type"}, + norm, + errors, + ) + assert errors == ["child_execution_receipts must be a list"] + assert "child_execution_receipts" not in norm + assert isinstance(norm["subagent_reconciliation"], Mapping) + + with pytest.raises(ValueError, match="must be a string"): + _opaque_ref(123, field="x") + with pytest.raises(ChildExecutionTopologyError, match="child_task_packet_incomplete"): + _child_task_packet( + operation=_sample_operation(recommended_context="resume"), + brief=_sample_brief(), + todo_id="todo_1", + source_state_ref="state:1", + allowed_effect_classes=["local_read"], + workspace_requirement="not_required", + workspace_ref=None, + ) + with pytest.raises(ChildExecutionTopologyError, match="acceptance"): + _child_execution_lane( + _sample_operation(brief=_sample_brief(extra={"acceptance": [" "]})), + bundle_id="bundle_1", + source_state_ref="state:1", + ) + schema = child_execution_receipts_json_schema() + assert schema["maxItems"] == MAX_CHILD_EXECUTION_RECEIPTS + assert "task_packet_digest" in schema["items"]["properties"]