From 48a2123bc24269c1d9fd61e02187ad3cb456e321 Mon Sep 17 00:00:00 2001 From: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:36:28 +0800 Subject: [PATCH] refactor(issue-fix): consolidate maintainer-correction admission and slim pr_lifecycle Signed-off-by: LoopX Agent <337587101+loopx-agent@users.noreply.github.com> --- loopx/canary/module_metric_baseline.json | 3 - .../issue_fix/correction_settlement.py | 821 +++++++++++- loopx/capabilities/issue_fix/pr_lifecycle.py | 1112 ++--------------- ...sue_fix_maintainer_correction_admission.py | 13 +- 4 files changed, 933 insertions(+), 1016 deletions(-) diff --git a/loopx/canary/module_metric_baseline.json b/loopx/canary/module_metric_baseline.json index 9e224aaf1d..f141343d48 100644 --- a/loopx/canary/module_metric_baseline.json +++ b/loopx/canary/module_metric_baseline.json @@ -42,9 +42,6 @@ "any_count": 5, "dict_any_count": 0 }, - "loopx/capabilities/issue_fix/pr_lifecycle.py": { - "lines": 2056 - }, "loopx/capabilities/reward_memory/utility_reducer.py": { "any_count": 0, "dict_any_count": 0, diff --git a/loopx/capabilities/issue_fix/correction_settlement.py b/loopx/capabilities/issue_fix/correction_settlement.py index 55478c4316..d9908f5c16 100644 --- a/loopx/capabilities/issue_fix/correction_settlement.py +++ b/loopx/capabilities/issue_fix/correction_settlement.py @@ -1,26 +1,101 @@ -"""Maintainer-correction settlement and origin-request binding helpers.""" +"""Maintainer-correction admission, transition, settlement, and origin-request binding.""" from __future__ import annotations +import hashlib +import ipaddress import json import os -from collections.abc import Mapping -from pathlib import Path -from typing import NotRequired, TypedDict +import re +from collections.abc import Mapping, Sequence +from datetime import datetime, timezone +from pathlib import Path, PurePosixPath +from typing import Any, NotRequired, TypedDict +from urllib.parse import urlsplit -from ...agent_registry import load_goal_from_registry -from ...control_plane.goals.activation import goal_is_stopped from ...control_plane.projects.registry_codec import ( SOURCE_SESSION_PROFILE_ID, load_project_registry, ) +from ...control_plane.runtime.public_safety import public_safe_compact_text from ...control_plane.runtime.time import now_utc_iso -from ...control_plane.todos.mutation_api import add_goal_todo from ...domain_packs.issue_fix import ( issue_fix_maintainer_correction_entries, read_issue_fix_pr_lifecycle_ledger_row, upsert_issue_fix_pr_lifecycle_ledger_jsonl, ) -from .pr_lifecycle import recheck_issue_fix_maintainer_correction_effect_gates +from .github_public import MAINTAINER_ASSOCIATIONS + + +ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION = ( + "issue_fix_maintainer_correction_input_v0" +) +ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION_V1 = ( + "issue_fix_maintainer_correction_input_v1" +) +MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSIONS = { + ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION, + ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION_V1, +} +ISSUE_FIX_MAINTAINER_CORRECTION_ADMISSION_SCHEMA_VERSION = ( + "issue_fix_maintainer_correction_admission_v0" +) +ISSUE_FIX_MAINTAINER_CORRECTION_LEDGER_ENTRY_SCHEMA_VERSION = ( + "issue_fix_maintainer_correction_ledger_entry_v0" +) +MAINTAINER_CORRECTION_OPERATION_ID_PREFIX = "issue-fix-correction:" +MAINTAINER_CORRECTION_KINDS = { + "actionable_patch", + "semantic_ambiguity", + "missing_authority", + "unchanged", +} +MAINTAINER_CORRECTION_SOURCE_KINDS = {"review", "maintainer_comment"} +MAINTAINER_CORRECTION_SOURCE_EVENT_KINDS = { + "issue_comment", + "review", + "review_comment", +} +MAINTAINER_CORRECTION_SOURCE_EVENT_FIELDS = { + "kind", + "id", + "html_url", + "author_login", + "author_association", + "created_at", + "updated_at", +} +MAINTAINER_CORRECTION_ADMISSION_BASES = {"host_asserted", "provider_verified"} +MAINTAINER_CORRECTION_DISPOSITIONS = {"accepted", "context_only", "superseded"} +MAINTAINER_CORRECTION_REJECTION_REASONS = { + "source_event_not_observed", + "source_event_revision_mismatch", + "stale_revision", + "self_or_bot_author", + "author_not_maintainer", + "terminal_pr_state", + "goal_not_active", + "origin_request_cancelled", + "origin_request_unreadable", +} +# GitHub Apps post as `[bot]`; without a configured LoopX actor login this +# suffix is the only self/bot signal available from body-free event metadata. +BOT_LOGIN_SUFFIX = "[bot]" +_GITHUB_LOGIN_PATTERN = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})(?:\[bot\])?") +_PROVIDER_EVENT_ID_PATTERN = re.compile(r"[0-9]{1,20}") +WRITE_SCOPES = {"write", "publish", "external_review_request"} +MAINTAINER_CORRECTION_INPUT_FIELDS = { + "schema_version", + "correction_kind", + "source_kind", + "source_ref", + "summary", + "verification_plan", + "pr_update_path", + "user_question", + "missing_authority_scopes", + "source_event", +} +TERMINAL_PR_STATES = {"MERGED", "CLOSED"} # Set to "1" to abort between the accepted ledger entry write and its Todo @@ -34,6 +109,731 @@ } +def _upper_label(value: Any, default: str = "UNKNOWN") -> str: + text = str(value or "").strip().upper() + return text or default + + +def _timestamp(value: Any) -> datetime | None: + text = str(value or "").strip() + if not text: + return None + try: + parsed = datetime.fromisoformat(text.replace("Z", "+00:00")) + except ValueError: + return None + return parsed if parsed.tzinfo is not None else None + + +def build_issue_fix_transition_preview( + *, + decision: str, + action_kind: str, + priority: str, + reason: str, + depends_on: Sequence[str] = ("issue_fix_pr_lifecycle_monitor",), + role: str = "agent", + task_class: str = "continuous_monitor", + text: str | None = None, + terminal_state_precedence: bool = False, + material_change: bool = False, + **extra: Any, +) -> dict[str, Any]: + """Return a non-mutating PR lifecycle transition preview payload.""" + + if text is None: + text = f"[{priority}] {reason}" + return { + "schema_version": "issue_fix_pr_lifecycle_transition_v0", + "decision": decision, + "command_preview": "loopx todo transition", + "role": role, + "priority": priority, + "task_class": task_class, + "action_kind": action_kind, + "reason": reason, + "text": text, + "depends_on": list(depends_on), + "would_write": False, + "requires_execute_flag": True, + "terminal_state_precedence": terminal_state_precedence, + "material_change": material_change, + **extra, + } + + +def _compact_public_text(value: Any, *, field: str, limit: int) -> str: + raw = " ".join(str(value or "").strip().split()) + if len(raw) > limit: + raise ValueError(f"maintainer correction {field} exceeds the compact limit") + if "" in raw or "\x00" in raw: + raise ValueError( + f"maintainer correction {field} must not contain control-plane markup" + ) + text = public_safe_compact_text(value, limit=limit) + if not text: + raise ValueError( + f"maintainer correction {field} must be compact and public-safe" + ) + return " ".join(text.split()) + + +def _public_source_reference(value: Any) -> str: + reference = _compact_public_text(value, field="source_ref", limit=300) + if "://" in reference: + parsed = urlsplit(reference) + if ( + parsed.scheme != "https" + or not parsed.netloc + or parsed.username + or parsed.password + or parsed.query + ): + raise ValueError( + "maintainer correction source_ref URL must be public https without user info or query" + ) + hostname = (parsed.hostname or "").lower() + if hostname == "localhost" or hostname.endswith((".localhost", ".local")): + raise ValueError( + "maintainer correction source_ref must not target a local host" + ) + try: + address = ipaddress.ip_address(hostname) + except ValueError: + address = None + if address and ( + address.is_private + or address.is_loopback + or address.is_link_local + or address.is_reserved + ): + raise ValueError( + "maintainer correction source_ref must target a public host" + ) + return reference + if reference.startswith(("/", "~")) or re.match(r"^[A-Za-z]:[\\/]", reference): + raise ValueError("maintainer correction source_ref must not be a local path") + path = PurePosixPath(reference.replace("\\", "/")) + if path.as_posix() == "." or ".." in path.parts: + raise ValueError("maintainer correction source_ref must be repo-relative") + return path.as_posix() + + +def _normalise_provider_event_id(value: Any) -> str: + if isinstance(value, bool): + raise ValueError("maintainer correction source_event id must be a provider id") + text = str(value if value is not None else "").strip() + if not _PROVIDER_EVENT_ID_PATTERN.fullmatch(text): + raise ValueError("maintainer correction source_event id must be a numeric provider id") + return text + + +def _normalise_author_login(value: Any, *, field: str) -> str: + text = str(value or "").strip() + if not _GITHUB_LOGIN_PATTERN.fullmatch(text): + raise ValueError(f"maintainer correction {field} must be a public provider login") + return text + + +def _normalise_event_timestamp(value: Any, *, field: str) -> str: + text = str(value or "").strip() + parsed = _timestamp(text) + if parsed is None: + raise ValueError( + f"maintainer correction {field} must be a timezone-aware ISO timestamp" + ) + return parsed.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") + + +def normalise_issue_fix_maintainer_correction_source_event( + value: Any, +) -> dict[str, Any]: + """Normalise the provider event that carried a maintainer correction. + + Only identity and revision metadata survive; no body field is accepted. + """ + + if not isinstance(value, Mapping): + raise ValueError("maintainer correction source_event must be an object") + unknown_fields = set(value) - MAINTAINER_CORRECTION_SOURCE_EVENT_FIELDS + if unknown_fields: + raise ValueError( + "maintainer correction source_event contains unsupported fields: " + + ", ".join(sorted(str(field) for field in unknown_fields)) + ) + kind = str(value.get("kind") or "").strip() + if kind not in MAINTAINER_CORRECTION_SOURCE_EVENT_KINDS: + raise ValueError( + "maintainer correction source_event kind must be issue_comment, review, or review_comment" + ) + html_url = _public_source_reference(value.get("html_url")) + if "://" not in html_url: + raise ValueError("maintainer correction source_event html_url must be a public https URL") + return { + "kind": kind, + "id": _normalise_provider_event_id(value.get("id")), + "html_url": html_url, + "author_login": _normalise_author_login( + value.get("author_login"), field="source_event author_login" + ), + "author_association": _upper_label(value.get("author_association"), "NONE"), + "created_at": _normalise_event_timestamp( + value.get("created_at"), field="source_event created_at" + ), + "updated_at": _normalise_event_timestamp( + value.get("updated_at"), field="source_event updated_at" + ), + "body_captured": False, + } + + +def normalise_issue_fix_maintainer_correction_input( + value: Mapping[str, Any], +) -> dict[str, Any]: + unknown_fields = set(value) - MAINTAINER_CORRECTION_INPUT_FIELDS + if unknown_fields: + raise ValueError( + "maintainer correction input contains unsupported fields: " + + ", ".join(sorted(str(field) for field in unknown_fields)) + ) + schema_version = value.get("schema_version") + if schema_version not in MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSIONS: + raise ValueError( + "maintainer correction schema_version must be " + "issue_fix_maintainer_correction_input_v0 or issue_fix_maintainer_correction_input_v1" + ) + provider_verified = ( + schema_version == ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION_V1 + ) + if provider_verified: + if "source_event" not in value: + raise ValueError( + "issue_fix_maintainer_correction_input_v1 requires source_event" + ) + source_event: dict[str, Any] | None = ( + normalise_issue_fix_maintainer_correction_source_event( + value.get("source_event") + ) + ) + else: + if "source_event" in value: + raise ValueError( + "source_event requires schema_version issue_fix_maintainer_correction_input_v1" + ) + source_event = None + correction_kind = str(value.get("correction_kind") or "").strip() + if correction_kind not in MAINTAINER_CORRECTION_KINDS: + raise ValueError( + "maintainer correction correction_kind must be actionable_patch, semantic_ambiguity, missing_authority, or unchanged" + ) + source_kind = str(value.get("source_kind") or "").strip() + if source_kind not in MAINTAINER_CORRECTION_SOURCE_KINDS: + raise ValueError( + "maintainer correction source_kind must be review or maintainer_comment" + ) + source_ref = _public_source_reference(value.get("source_ref")) + summary = _compact_public_text(value.get("summary"), field="summary", limit=400) + verification_plan = "" + pr_update_path = "" + user_question = "" + missing_authority_scopes: list[str] = [] + if correction_kind == "actionable_patch": + verification_plan = _compact_public_text( + value.get("verification_plan"), field="verification_plan", limit=300 + ) + pr_update_path = _compact_public_text( + value.get("pr_update_path"), field="pr_update_path", limit=240 + ) + elif correction_kind == "semantic_ambiguity": + user_question = _compact_public_text( + value.get("user_question"), field="user_question", limit=300 + ) + elif correction_kind == "missing_authority": + raw_scopes = value.get("missing_authority_scopes") + if not isinstance(raw_scopes, Sequence) or isinstance(raw_scopes, (str, bytes)): + raise ValueError("missing_authority requires missing_authority_scopes") + for raw_scope in raw_scopes: + scope = str(raw_scope or "").strip() + if scope not in WRITE_SCOPES: + raise ValueError("maintainer correction authority scope is unsupported") + if scope not in missing_authority_scopes: + missing_authority_scopes.append(scope) + if not missing_authority_scopes: + raise ValueError("missing_authority requires at least one authority scope") + # The fingerprint covers the compacted correction content under the v0 + # field set, so existing v0 ledger rows keep their recorded fingerprints and + # a v1 event carrying identical content hashes the same; event identity + # lives in the operation id, not here. + content = { + "schema_version": ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION, + "correction_kind": correction_kind, + "source_kind": source_kind, + "source_ref": source_ref, + "summary": summary, + "verification_plan": verification_plan or None, + "pr_update_path": pr_update_path or None, + "user_question": user_question or None, + "missing_authority_scopes": missing_authority_scopes, + "raw_body_captured": False, + "raw_comment_captured": False, + "raw_provider_payload_captured": False, + "local_paths_captured": False, + } + fingerprint = hashlib.sha256( + json.dumps(content, sort_keys=True, separators=(",", ":")).encode("utf-8") + ).hexdigest()[:16] + normalized = { + **content, + "schema_version": str(schema_version), + "source_event": source_event, + "admission_basis": "provider_verified" if provider_verified else "host_asserted", + } + normalized["correction_fingerprint"] = fingerprint + return normalized + + +def issue_fix_maintainer_correction_operation_id( + correction: Mapping[str, Any], *, repo: str, pr_ref: str +) -> str: + """Return the stable Todo operation id for one correction revision.""" + + source_event = correction.get("source_event") + if isinstance(source_event, Mapping): + identity = [ + repo, + pr_ref, + str(source_event.get("kind")), + str(source_event.get("id")), + str(source_event.get("updated_at")), + ] + else: + identity = [repo, pr_ref, str(correction.get("correction_fingerprint"))] + digest = hashlib.sha256( + json.dumps(identity, separators=(",", ":")).encode("utf-8") + ).hexdigest()[:24] + return f"{MAINTAINER_CORRECTION_OPERATION_ID_PREFIX}{digest}" + + +def _provider_event_entries(value: Any) -> list[Mapping[str, Any]]: + if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): + return [item for item in value if isinstance(item, Mapping)] + return [] + + +def normalise_issue_fix_pr_source_events( + provider_payload: Mapping[str, Any] | None, +) -> dict[str, Any]: + """Project body-free PR comment/review metadata into verifiable events. + + Reviews expose ``submitted_at`` instead of ``updated_at``; that timestamp + stands in as the review revision because GitHub does not re-time edits of a + review summary through the list endpoint. + """ + + payload = provider_payload if isinstance(provider_payload, Mapping) else {} + groups = ( + ("issue_comment", payload.get("comments") or payload.get("issueComments")), + ("review", payload.get("reviews")), + ("review_comment", payload.get("reviewComments") or payload.get("review_comments")), + ) + available = any( + isinstance(raw, Sequence) and not isinstance(raw, (str, bytes)) + for _kind, raw in groups + ) + events: list[dict[str, Any]] = [] + for kind, raw in groups: + for item in _provider_event_entries(raw): + raw_id = item.get("id") + if isinstance(raw_id, bool) or raw_id is None: + continue + event_id = str(raw_id).strip() + if not _PROVIDER_EVENT_ID_PATTERN.fullmatch(event_id): + continue + author = item.get("author") or item.get("user") + if isinstance(author, Mapping): + author = author.get("login") + updated_at = ( + item.get("updated_at") + or item.get("updatedAt") + or item.get("submitted_at") + or item.get("submittedAt") + ) + created_at = item.get("created_at") or item.get("createdAt") + events.append( + { + "kind": kind, + "id": event_id, + "author_login": str(author or "").strip()[:60] or None, + "author_association": _upper_label( + item.get("author_association") + or item.get("authorAssociation"), + "NONE", + ), + "created_at": ( + _normalise_event_timestamp(created_at, field="created_at") + if _timestamp(created_at) else None + ), + "updated_at": ( + _normalise_event_timestamp(updated_at, field="updated_at") + if _timestamp(updated_at) else None + ), + "body_captured": False, + } + ) + return { + "status": "available" if available else "unavailable", + "events": events, + "body_captured": False, + } + + +def _same_instant(left: Any, right: Any) -> bool: + left_time = _timestamp(left) + right_time = _timestamp(right) + return left_time is not None and right_time is not None and left_time == right_time + + +def _is_bot_or_self_login(login: Any) -> bool: + text = str(login or "").strip().lower() + return text.endswith(BOT_LOGIN_SUFFIX) + + +def _observed_source_events( + source_events: Mapping[str, Any] | None, source_event: Mapping[str, Any] +) -> list[Mapping[str, Any]]: + raw_events = source_events.get("events") if isinstance(source_events, Mapping) else [] + if not isinstance(raw_events, Sequence) or isinstance(raw_events, (str, bytes)): + return [] + return [ + event + for event in raw_events + if isinstance(event, Mapping) + and event.get("kind") == source_event.get("kind") + and str(event.get("id")) == str(source_event.get("id")) + ] + + +def _latest_accepted_revision( + prior_entries: Sequence[Mapping[str, Any]], *, source_event: Mapping[str, Any] +) -> dict[str, Any] | None: + latest: dict[str, Any] | None = None + for entry in prior_entries: + event = entry.get("source_event") + if not isinstance(event, Mapping): + continue + if event.get("kind") != source_event.get("kind") or str( + event.get("id") + ) != str(source_event.get("id")): + continue + if entry.get("disposition") not in {"accepted", "superseded"}: + continue + candidate_time = _timestamp(event.get("updated_at")) + if candidate_time is None: + continue + latest_time = ( + _timestamp(latest["source_event"].get("updated_at")) if latest else None + ) + if latest_time is None or candidate_time > latest_time: + latest = dict(entry) + return latest + + +def evaluate_issue_fix_maintainer_correction_admission( + correction: Mapping[str, Any], + *, + observation: Mapping[str, Any], + source_events: Mapping[str, Any] | None, + prior_entries: Sequence[Mapping[str, Any]] | None, + prior_ledger_read: bool, + recorded_at: str | None, +) -> dict[str, Any]: + """Run the deterministic admission gates for one maintainer correction. + + Returns the admission record plus the ledger entries this run touches: + the entry for this correction and any earlier revision it supersedes. + """ + + repo = str(observation.get("repo") or "") + pr_ref = str(observation.get("pr_ref") or "") + operation_id = issue_fix_maintainer_correction_operation_id( + correction, repo=repo, pr_ref=pr_ref + ) + source_event = correction.get("source_event") + admission_basis = str(correction.get("admission_basis") or "host_asserted") + prior = issue_fix_maintainer_correction_entries( + {"maintainer_corrections": prior_entries} + ) + existing_entry = next( + (entry for entry in prior if entry.get("operation_id") == operation_id), None + ) + gates: list[dict[str, Any]] = [] + reason: str | None = None + verified_event: dict[str, Any] | None = None + provider_events_status = ( + str(source_events.get("status") or "unavailable") + if isinstance(source_events, Mapping) + else "unavailable" + ) + + def record(name: str, passed: bool, failure_reason: str | None = None) -> None: + nonlocal reason + gates.append({"gate": name, "passed": passed}) + if not passed and reason is None: + reason = failure_reason + + if isinstance(source_event, Mapping): + observed = _observed_source_events(source_events, source_event) + if not observed: + record("source_event_observed", False, "source_event_not_observed") + elif not any( + _same_instant(event.get("updated_at"), source_event.get("updated_at")) + for event in observed + ): + record("source_event_observed", False, "source_event_revision_mismatch") + else: + record("source_event_observed", True) + provider_event = observed[0] + verified_event = { + **dict(source_event), + "author_login": str( + provider_event.get("author_login") or source_event.get("author_login") + ), + "author_association": _upper_label( + provider_event.get("author_association"), + str(source_event.get("author_association") or "NONE"), + ), + "created_at": _normalise_event_timestamp( + provider_event.get("created_at") or source_event.get("created_at"), + field="source_event created_at", + ), + } + effective_event = verified_event or dict(source_event) + latest_prior = _latest_accepted_revision(prior, source_event=source_event) + prior_time = ( + _timestamp(latest_prior["source_event"].get("updated_at")) + if latest_prior + else None + ) + incoming_time = _timestamp(source_event.get("updated_at")) + revision_relation = "first" + if prior_time is not None and incoming_time is not None: + if incoming_time < prior_time: + revision_relation = "stale" + elif incoming_time == prior_time: + revision_relation = "replay" + else: + revision_relation = "newer" + record("revision_not_stale", revision_relation != "stale", "stale_revision") + record( + "not_self_or_bot_author", + not _is_bot_or_self_login(effective_event.get("author_login")), + "self_or_bot_author", + ) + record( + "author_is_maintainer", + _upper_label(effective_event.get("author_association"), "NONE") + in MAINTAINER_ASSOCIATIONS, + "author_not_maintainer", + ) + else: + effective_event = None + latest_prior = None + revision_relation = "replay" if existing_entry else "first" + record( + "pr_state_not_terminal", + str(observation.get("state") or "") not in TERMINAL_PR_STATES, + "terminal_pr_state", + ) + + accepted = reason is None + replay = existing_entry is not None and ( + not accepted or existing_entry.get("disposition") in {"accepted", "superseded"} + ) + if replay: + entry = dict(existing_entry) + else: + entry = { + "schema_version": ISSUE_FIX_MAINTAINER_CORRECTION_LEDGER_ENTRY_SCHEMA_VERSION, + "operation_id": operation_id, + "source_event": effective_event, + "correction_fingerprint": correction.get("correction_fingerprint"), + "correction_kind": correction.get("correction_kind"), + "admission_basis": admission_basis, + "disposition": "accepted" if accepted else "context_only", + "reason": reason, + "todo_id": None, + "accepted_head_sha": observation.get("head_commit_ref") if accepted else None, + "recorded_at": recorded_at, + "superseded_by": None, + "body_captured": False, + } + touched_entries = [entry] + superseded_operation_id = None + if ( + accepted + and revision_relation == "newer" + and latest_prior is not None + and latest_prior.get("operation_id") != operation_id + ): + superseded_operation_id = str(latest_prior.get("operation_id")) + touched_entries.append( + { + **latest_prior, + "disposition": "superseded", + "superseded_by": operation_id, + } + ) + return { + "schema_version": ISSUE_FIX_MAINTAINER_CORRECTION_ADMISSION_SCHEMA_VERSION, + "operation_id": operation_id, + "admission_basis": admission_basis, + "disposition": "accepted" if accepted else "context_only", + "reason": reason, + "host_summary_mismatch": bool( + existing_entry is not None + and correction.get("correction_fingerprint") + != existing_entry.get("correction_fingerprint") + ), + "gates": gates, + "revision_relation": revision_relation, + "replay": replay, + "supersedes_operation_id": superseded_operation_id, + "provider_events_status": provider_events_status, + "prior_ledger_read": bool(prior_ledger_read), + "source_event": effective_event, + "entries": touched_entries, + "body_captured": False, + } + + +def recheck_issue_fix_maintainer_correction_effect_gates( + entry: Mapping[str, Any], + *, + observation: Mapping[str, Any], + ledger_entries: Sequence[Mapping[str, Any]] | None, + goal_stopped: bool, + source_events: Mapping[str, Any] | None = None, +) -> str | None: + """Re-run the effect-time gates for an accepted entry just before its Todo write.""" + + source_event = entry.get("source_event") + if isinstance(source_event, Mapping): + observed = _observed_source_events(source_events, source_event) + if not observed: + return "source_event_not_observed" + current_event = next( + ( + event + for event in observed + if _same_instant(event.get("updated_at"), source_event.get("updated_at")) + ), + None, + ) + if current_event is None: + return "source_event_revision_mismatch" + latest = _latest_accepted_revision( + issue_fix_maintainer_correction_entries( + {"maintainer_corrections": ledger_entries} + ), + source_event=source_event, + ) + if latest is not None and latest.get("operation_id") != entry.get("operation_id"): + latest_time = _timestamp(latest["source_event"].get("updated_at")) + own_time = _timestamp(source_event.get("updated_at")) + if latest_time is not None and own_time is not None and own_time < latest_time: + return "stale_revision" + if _is_bot_or_self_login(current_event.get("author_login")): + return "self_or_bot_author" + if ( + _upper_label(current_event.get("author_association"), "NONE") + not in MAINTAINER_ASSOCIATIONS + ): + return "author_not_maintainer" + if str(observation.get("state") or "") in TERMINAL_PR_STATES: + return "terminal_pr_state" + if goal_stopped: + return "goal_not_active" + return None + + +def maintainer_correction_transition( + correction: Mapping[str, Any], + *, + pr_permalink: str, +) -> dict[str, Any]: + """Build the transition preview dict for one admitted maintainer correction.""" + + correction_kind = str(correction.get("correction_kind")) + source_ref = str(correction.get("source_ref")) + summary = str(correction.get("summary")) + source_event = correction.get("source_event") + # Todo creation dedupes identical active text, so distinct provider events + # or revisions with the same wording must name the event they came from. + event_suffix = ( + f" Source event: {source_event.get('kind')} {source_event.get('id')}" + f" updated {source_event.get('updated_at')}." + if isinstance(source_event, Mapping) + else "" + ) + if correction_kind == "actionable_patch": + verification_plan = str(correction.get("verification_plan")) + pr_update_path = str(correction.get("pr_update_path")) + return build_issue_fix_transition_preview( + decision="runnable_successor", + action_kind="issue_fix_maintainer_correction_patch", + priority="P0", + task_class="advancement_task", + reason="Maintainer correction is bounded and actionable; create one claimed patch successor.", + text=( + f"[P0] Apply maintainer correction for {pr_permalink} from {source_ref}: " + f"{summary} Verify: {verification_plan} Update PR via: {pr_update_path}" + f"{event_suffix}" + ), + material_change=True, + required_write_scopes=["write", "publish"], + ) + if correction_kind == "semantic_ambiguity": + return build_issue_fix_transition_preview( + decision="user_gate", + action_kind="clarify_issue_fix_maintainer_correction", + priority="P0", + role="user", + task_class="user_gate", + reason="Maintainer correction changes or leaves the intended behavior ambiguous.", + text=( + f"[P0] Clarify maintainer correction for {pr_permalink} from {source_ref}: " + f"{correction.get('user_question')} Context: {summary}{event_suffix}" + ), + material_change=True, + ) + if correction_kind == "missing_authority": + scopes = ", ".join( + str(value) for value in correction.get("missing_authority_scopes") or [] + ) + return build_issue_fix_transition_preview( + decision="user_gate", + action_kind="grant_issue_fix_maintainer_correction_authority", + priority="P0", + role="user", + task_class="user_gate", + reason="The correction is understood but the required write authority is not active.", + text=( + f"[P0] Grant or decline [{scopes}] authority for maintainer correction " + f"{source_ref} on {pr_permalink}: {summary}{event_suffix}" + ), + material_change=True, + missing_authority_scopes=list( + correction.get("missing_authority_scopes") or [] + ), + ) + return build_issue_fix_transition_preview( + decision="monitor_continuation", + action_kind="issue_fix_maintainer_correction_unchanged_monitor", + priority="P2", + reason="Maintainer correction is unchanged; keep the monitor quiet and create no successor.", + ) + + def _require_origin_registry(registry_path: Path) -> None: """Check the origin profile before looking up the request in its store.""" try: @@ -47,6 +847,9 @@ def _require_origin_registry(registry_path: Path) -> None: def _goal_stopped_for_correction(registry_path: Path | None, goal_id: str | None) -> bool: if registry_path is None or not goal_id: return False + from ...agent_registry import load_goal_from_registry + from ...control_plane.goals.activation import goal_is_stopped + try: goal = load_goal_from_registry(registry_path, goal_id) if goal is None: @@ -80,6 +883,8 @@ def _write_maintainer_correction_todo( operation_id: str, intent: _CorrectionTodoIntent, ) -> dict[str, object]: + from ...control_plane.todos.mutation_api import add_goal_todo + role = str(intent.get("role") or "agent") return add_goal_todo( registry_path=registry_path, diff --git a/loopx/capabilities/issue_fix/pr_lifecycle.py b/loopx/capabilities/issue_fix/pr_lifecycle.py index febfca6428..4dc025b2da 100644 --- a/loopx/capabilities/issue_fix/pr_lifecycle.py +++ b/loopx/capabilities/issue_fix/pr_lifecycle.py @@ -1,21 +1,30 @@ from __future__ import annotations import hashlib -import ipaddress import json -import re import subprocess from collections.abc import Mapping, Sequence -from datetime import datetime, timezone -from pathlib import PurePosixPath from typing import Any -from urllib.parse import quote, urlsplit +from urllib.parse import quote -from ...control_plane.runtime.public_safety import public_safe_compact_text from ...domain_packs.issue_fix import issue_fix_maintainer_correction_entries +from .correction_settlement import ( + MAINTAINER_CORRECTION_ADMISSION_BASES, + MAINTAINER_CORRECTION_DISPOSITIONS, + MAINTAINER_CORRECTION_OPERATION_ID_PREFIX, + MAINTAINER_CORRECTION_REJECTION_REASONS, + TERMINAL_PR_STATES as TERMINAL_PR_STATES, + _timestamp, + _upper_label, + build_issue_fix_transition_preview as _transition_preview, + evaluate_issue_fix_maintainer_correction_admission, + maintainer_correction_transition as _maintainer_correction_transition, + normalise_issue_fix_maintainer_correction_input as normalise_issue_fix_maintainer_correction_input, + normalise_issue_fix_pr_source_events, +) from .github_public import ( - MAINTAINER_ASSOCIATIONS, + MAINTAINER_ASSOCIATIONS as MAINTAINER_ASSOCIATIONS, fetch_github_pull_request_event_metadata, ) from .metadata_preview import ( @@ -28,76 +37,6 @@ ISSUE_FIX_PR_GROUPED_MONITOR_PROJECTION_SCHEMA_VERSION = ( "issue_fix_pr_grouped_monitor_projection_v1" ) -ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION = ( - "issue_fix_maintainer_correction_input_v0" -) -ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION_V1 = ( - "issue_fix_maintainer_correction_input_v1" -) -MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSIONS = { - ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION, - ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION_V1, -} -ISSUE_FIX_MAINTAINER_CORRECTION_ADMISSION_SCHEMA_VERSION = ( - "issue_fix_maintainer_correction_admission_v0" -) -ISSUE_FIX_MAINTAINER_CORRECTION_LEDGER_ENTRY_SCHEMA_VERSION = ( - "issue_fix_maintainer_correction_ledger_entry_v0" -) -MAINTAINER_CORRECTION_OPERATION_ID_PREFIX = "issue-fix-correction:" -MAINTAINER_CORRECTION_KINDS = { - "actionable_patch", - "semantic_ambiguity", - "missing_authority", - "unchanged", -} -MAINTAINER_CORRECTION_SOURCE_KINDS = {"review", "maintainer_comment"} -MAINTAINER_CORRECTION_SOURCE_EVENT_KINDS = { - "issue_comment", - "review", - "review_comment", -} -MAINTAINER_CORRECTION_SOURCE_EVENT_FIELDS = { - "kind", - "id", - "html_url", - "author_login", - "author_association", - "created_at", - "updated_at", -} -MAINTAINER_CORRECTION_ADMISSION_BASES = {"host_asserted", "provider_verified"} -MAINTAINER_CORRECTION_DISPOSITIONS = {"accepted", "context_only", "superseded"} -MAINTAINER_CORRECTION_REJECTION_REASONS = { - "source_event_not_observed", - "source_event_revision_mismatch", - "stale_revision", - "self_or_bot_author", - "author_not_maintainer", - "terminal_pr_state", - "goal_not_active", - "origin_request_cancelled", - "origin_request_unreadable", -} -# GitHub Apps post as `[bot]`; without a configured LoopX actor login this -# suffix is the only self/bot signal available from body-free event metadata. -BOT_LOGIN_SUFFIX = "[bot]" -_GITHUB_LOGIN_PATTERN = re.compile(r"[A-Za-z0-9](?:[A-Za-z0-9-]{0,38})(?:\[bot\])?") -_PROVIDER_EVENT_ID_PATTERN = re.compile(r"[0-9]{1,20}") -WRITE_SCOPES = {"write", "publish", "external_review_request"} -MAINTAINER_CORRECTION_INPUT_FIELDS = { - "schema_version", - "correction_kind", - "source_kind", - "source_ref", - "summary", - "verification_plan", - "pr_update_path", - "user_question", - "missing_authority_scopes", - "source_event", -} -TERMINAL_PR_STATES = {"MERGED", "CLOSED"} FAILING_CHECK_STATES = { "ACTION_REQUIRED", "CANCELLED", @@ -140,18 +79,6 @@ """.strip() -def _upper_label(value: Any, default: str = "UNKNOWN") -> str: - text = str(value or "").strip().upper() - return text or default - - -def _compact_label(value: Any, default: str) -> str: - text = str(value or "").strip() - if not text: - return default - return "_".join(text.replace("/", "_").replace("-", "_").split()).lower() - - def _safe_bool(value: Any) -> bool: return bool(value) if isinstance(value, bool) else False @@ -166,17 +93,6 @@ def _safe_count(value: Any) -> int | None: return number if number >= 0 else None -def _timestamp(value: Any) -> datetime | None: - text = str(value or "").strip() - if not text: - return None - try: - parsed = datetime.fromisoformat(text.replace("Z", "+00:00")) - except ValueError: - return None - return parsed if parsed.tzinfo is not None else None - - def _review_response_observation( provider_payload: Mapping[str, Any], *, review_decision: str ) -> dict[str, Any]: @@ -224,680 +140,6 @@ def _review_response_observation( } -def _compact_public_text(value: Any, *, field: str, limit: int) -> str: - raw = " ".join(str(value or "").strip().split()) - if len(raw) > limit: - raise ValueError(f"maintainer correction {field} exceeds the compact limit") - if "" in raw or "\x00" in raw: - raise ValueError( - f"maintainer correction {field} must not contain control-plane markup" - ) - text = public_safe_compact_text(value, limit=limit) - if not text: - raise ValueError( - f"maintainer correction {field} must be compact and public-safe" - ) - return " ".join(text.split()) - - -def _public_source_reference(value: Any) -> str: - reference = _compact_public_text(value, field="source_ref", limit=300) - if "://" in reference: - parsed = urlsplit(reference) - if ( - parsed.scheme != "https" - or not parsed.netloc - or parsed.username - or parsed.password - or parsed.query - ): - raise ValueError( - "maintainer correction source_ref URL must be public https without user info or query" - ) - hostname = (parsed.hostname or "").lower() - if hostname == "localhost" or hostname.endswith((".localhost", ".local")): - raise ValueError( - "maintainer correction source_ref must not target a local host" - ) - try: - address = ipaddress.ip_address(hostname) - except ValueError: - address = None - if address and ( - address.is_private - or address.is_loopback - or address.is_link_local - or address.is_reserved - ): - raise ValueError( - "maintainer correction source_ref must target a public host" - ) - return reference - if reference.startswith(("/", "~")) or re.match(r"^[A-Za-z]:[\\/]", reference): - raise ValueError("maintainer correction source_ref must not be a local path") - path = PurePosixPath(reference.replace("\\", "/")) - if path.as_posix() == "." or ".." in path.parts: - raise ValueError("maintainer correction source_ref must be repo-relative") - return path.as_posix() - - -def _normalise_provider_event_id(value: Any) -> str: - if isinstance(value, bool): - raise ValueError("maintainer correction source_event id must be a provider id") - text = str(value if value is not None else "").strip() - if not _PROVIDER_EVENT_ID_PATTERN.fullmatch(text): - raise ValueError("maintainer correction source_event id must be a numeric provider id") - return text - - -def _normalise_author_login(value: Any, *, field: str) -> str: - text = str(value or "").strip() - if not _GITHUB_LOGIN_PATTERN.fullmatch(text): - raise ValueError(f"maintainer correction {field} must be a public provider login") - return text - - -def _normalise_event_timestamp(value: Any, *, field: str) -> str: - text = str(value or "").strip() - parsed = _timestamp(text) - if parsed is None: - raise ValueError( - f"maintainer correction {field} must be a timezone-aware ISO timestamp" - ) - return parsed.astimezone(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") - - -def normalise_issue_fix_maintainer_correction_source_event( - value: Any, -) -> dict[str, Any]: - """Normalise the provider event that carried a maintainer correction. - - Only identity and revision metadata survive; no body field is accepted. - """ - - if not isinstance(value, Mapping): - raise ValueError("maintainer correction source_event must be an object") - unknown_fields = set(value) - MAINTAINER_CORRECTION_SOURCE_EVENT_FIELDS - if unknown_fields: - raise ValueError( - "maintainer correction source_event contains unsupported fields: " - + ", ".join(sorted(str(field) for field in unknown_fields)) - ) - kind = str(value.get("kind") or "").strip() - if kind not in MAINTAINER_CORRECTION_SOURCE_EVENT_KINDS: - raise ValueError( - "maintainer correction source_event kind must be issue_comment, review, or review_comment" - ) - html_url = _public_source_reference(value.get("html_url")) - if "://" not in html_url: - raise ValueError("maintainer correction source_event html_url must be a public https URL") - return { - "kind": kind, - "id": _normalise_provider_event_id(value.get("id")), - "html_url": html_url, - "author_login": _normalise_author_login( - value.get("author_login"), field="source_event author_login" - ), - "author_association": _upper_label(value.get("author_association"), "NONE"), - "created_at": _normalise_event_timestamp( - value.get("created_at"), field="source_event created_at" - ), - "updated_at": _normalise_event_timestamp( - value.get("updated_at"), field="source_event updated_at" - ), - "body_captured": False, - } - - -def normalise_issue_fix_maintainer_correction_input( - value: Mapping[str, Any], -) -> dict[str, Any]: - unknown_fields = set(value) - MAINTAINER_CORRECTION_INPUT_FIELDS - if unknown_fields: - raise ValueError( - "maintainer correction input contains unsupported fields: " - + ", ".join(sorted(str(field) for field in unknown_fields)) - ) - schema_version = value.get("schema_version") - if schema_version not in MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSIONS: - raise ValueError( - "maintainer correction schema_version must be " - "issue_fix_maintainer_correction_input_v0 or issue_fix_maintainer_correction_input_v1" - ) - provider_verified = ( - schema_version == ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION_V1 - ) - if provider_verified: - if "source_event" not in value: - raise ValueError( - "issue_fix_maintainer_correction_input_v1 requires source_event" - ) - source_event: dict[str, Any] | None = ( - normalise_issue_fix_maintainer_correction_source_event( - value.get("source_event") - ) - ) - else: - if "source_event" in value: - raise ValueError( - "source_event requires schema_version issue_fix_maintainer_correction_input_v1" - ) - source_event = None - correction_kind = str(value.get("correction_kind") or "").strip() - if correction_kind not in MAINTAINER_CORRECTION_KINDS: - raise ValueError( - "maintainer correction correction_kind must be actionable_patch, semantic_ambiguity, missing_authority, or unchanged" - ) - source_kind = str(value.get("source_kind") or "").strip() - if source_kind not in MAINTAINER_CORRECTION_SOURCE_KINDS: - raise ValueError( - "maintainer correction source_kind must be review or maintainer_comment" - ) - source_ref = _public_source_reference(value.get("source_ref")) - summary = _compact_public_text(value.get("summary"), field="summary", limit=400) - verification_plan = "" - pr_update_path = "" - user_question = "" - missing_authority_scopes: list[str] = [] - if correction_kind == "actionable_patch": - verification_plan = _compact_public_text( - value.get("verification_plan"), field="verification_plan", limit=300 - ) - pr_update_path = _compact_public_text( - value.get("pr_update_path"), field="pr_update_path", limit=240 - ) - elif correction_kind == "semantic_ambiguity": - user_question = _compact_public_text( - value.get("user_question"), field="user_question", limit=300 - ) - elif correction_kind == "missing_authority": - raw_scopes = value.get("missing_authority_scopes") - if not isinstance(raw_scopes, Sequence) or isinstance(raw_scopes, (str, bytes)): - raise ValueError("missing_authority requires missing_authority_scopes") - for raw_scope in raw_scopes: - scope = str(raw_scope or "").strip() - if scope not in WRITE_SCOPES: - raise ValueError("maintainer correction authority scope is unsupported") - if scope not in missing_authority_scopes: - missing_authority_scopes.append(scope) - if not missing_authority_scopes: - raise ValueError("missing_authority requires at least one authority scope") - # The fingerprint covers the compacted correction content under the v0 - # field set, so existing v0 ledger rows keep their recorded fingerprints and - # a v1 event carrying identical content hashes the same; event identity - # lives in the operation id, not here. - content = { - "schema_version": ISSUE_FIX_MAINTAINER_CORRECTION_INPUT_SCHEMA_VERSION, - "correction_kind": correction_kind, - "source_kind": source_kind, - "source_ref": source_ref, - "summary": summary, - "verification_plan": verification_plan or None, - "pr_update_path": pr_update_path or None, - "user_question": user_question or None, - "missing_authority_scopes": missing_authority_scopes, - "raw_body_captured": False, - "raw_comment_captured": False, - "raw_provider_payload_captured": False, - "local_paths_captured": False, - } - fingerprint = hashlib.sha256( - json.dumps(content, sort_keys=True, separators=(",", ":")).encode("utf-8") - ).hexdigest()[:16] - normalized = { - **content, - "schema_version": str(schema_version), - "source_event": source_event, - "admission_basis": "provider_verified" if provider_verified else "host_asserted", - } - normalized["correction_fingerprint"] = fingerprint - return normalized - - -def issue_fix_maintainer_correction_operation_id( - correction: Mapping[str, Any], *, repo: str, pr_ref: str -) -> str: - """Return the stable Todo operation id for one correction revision.""" - - source_event = correction.get("source_event") - if isinstance(source_event, Mapping): - identity = [ - repo, - pr_ref, - str(source_event.get("kind")), - str(source_event.get("id")), - str(source_event.get("updated_at")), - ] - else: - identity = [repo, pr_ref, str(correction.get("correction_fingerprint"))] - digest = hashlib.sha256( - json.dumps(identity, separators=(",", ":")).encode("utf-8") - ).hexdigest()[:24] - return f"{MAINTAINER_CORRECTION_OPERATION_ID_PREFIX}{digest}" - - -def _provider_event_entries(value: Any) -> list[Mapping[str, Any]]: - if isinstance(value, Sequence) and not isinstance(value, (str, bytes)): - return [item for item in value if isinstance(item, Mapping)] - return [] - - -def normalise_issue_fix_pr_source_events( - provider_payload: Mapping[str, Any] | None, -) -> dict[str, Any]: - """Project body-free PR comment/review metadata into verifiable events. - - Reviews expose ``submitted_at`` instead of ``updated_at``; that timestamp - stands in as the review revision because GitHub does not re-time edits of a - review summary through the list endpoint. - """ - - payload = provider_payload if isinstance(provider_payload, Mapping) else {} - groups = ( - ("issue_comment", payload.get("comments") or payload.get("issueComments")), - ("review", payload.get("reviews")), - ("review_comment", payload.get("reviewComments") or payload.get("review_comments")), - ) - available = any( - isinstance(raw, Sequence) and not isinstance(raw, (str, bytes)) - for _kind, raw in groups - ) - events: list[dict[str, Any]] = [] - for kind, raw in groups: - for item in _provider_event_entries(raw): - raw_id = item.get("id") - if isinstance(raw_id, bool) or raw_id is None: - continue - event_id = str(raw_id).strip() - if not _PROVIDER_EVENT_ID_PATTERN.fullmatch(event_id): - continue - author = item.get("author") or item.get("user") - if isinstance(author, Mapping): - author = author.get("login") - updated_at = ( - item.get("updated_at") - or item.get("updatedAt") - or item.get("submitted_at") - or item.get("submittedAt") - ) - created_at = item.get("created_at") or item.get("createdAt") - events.append( - { - "kind": kind, - "id": event_id, - "author_login": str(author or "").strip()[:60] or None, - "author_association": _upper_label( - item.get("author_association") - or item.get("authorAssociation"), - "NONE", - ), - "created_at": ( - _normalise_event_timestamp(created_at, field="created_at") - if _timestamp(created_at) else None - ), - "updated_at": ( - _normalise_event_timestamp(updated_at, field="updated_at") - if _timestamp(updated_at) else None - ), - "body_captured": False, - } - ) - return { - "status": "available" if available else "unavailable", - "events": events, - "body_captured": False, - } - - -def _same_instant(left: Any, right: Any) -> bool: - left_time = _timestamp(left) - right_time = _timestamp(right) - return left_time is not None and right_time is not None and left_time == right_time - - -def _is_bot_or_self_login(login: Any) -> bool: - text = str(login or "").strip().lower() - return text.endswith(BOT_LOGIN_SUFFIX) - - -def _latest_accepted_revision( - prior_entries: Sequence[Mapping[str, Any]], *, source_event: Mapping[str, Any] -) -> dict[str, Any] | None: - latest: dict[str, Any] | None = None - for entry in prior_entries: - event = entry.get("source_event") - if not isinstance(event, Mapping): - continue - if event.get("kind") != source_event.get("kind") or str( - event.get("id") - ) != str(source_event.get("id")): - continue - if entry.get("disposition") not in {"accepted", "superseded"}: - continue - candidate_time = _timestamp(event.get("updated_at")) - if candidate_time is None: - continue - latest_time = ( - _timestamp(latest["source_event"].get("updated_at")) if latest else None - ) - if latest_time is None or candidate_time > latest_time: - latest = dict(entry) - return latest - - -def evaluate_issue_fix_maintainer_correction_admission( - correction: Mapping[str, Any], - *, - observation: Mapping[str, Any], - source_events: Mapping[str, Any] | None, - prior_entries: Sequence[Mapping[str, Any]] | None, - prior_ledger_read: bool, - recorded_at: str | None, -) -> dict[str, Any]: - """Run the deterministic admission gates for one maintainer correction. - - Returns the admission record plus the ledger entries this run touches: - the entry for this correction and any earlier revision it supersedes. - """ - - repo = str(observation.get("repo") or "") - pr_ref = str(observation.get("pr_ref") or "") - operation_id = issue_fix_maintainer_correction_operation_id( - correction, repo=repo, pr_ref=pr_ref - ) - source_event = correction.get("source_event") - admission_basis = str(correction.get("admission_basis") or "host_asserted") - prior = issue_fix_maintainer_correction_entries( - {"maintainer_corrections": prior_entries} - ) - existing_entry = next( - (entry for entry in prior if entry.get("operation_id") == operation_id), None - ) - gates: list[dict[str, Any]] = [] - reason: str | None = None - verified_event: dict[str, Any] | None = None - provider_events_status = ( - str(source_events.get("status") or "unavailable") - if isinstance(source_events, Mapping) - else "unavailable" - ) - - def record(name: str, passed: bool, failure_reason: str | None = None) -> None: - nonlocal reason - gates.append({"gate": name, "passed": passed}) - if not passed and reason is None: - reason = failure_reason - - if isinstance(source_event, Mapping): - observed = [ - event - for event in ( - source_events.get("events") if isinstance(source_events, Mapping) else [] - ) - if isinstance(event, Mapping) - and event.get("kind") == source_event.get("kind") - and str(event.get("id")) == str(source_event.get("id")) - ] - if not observed: - record("source_event_observed", False, "source_event_not_observed") - elif not any( - _same_instant(event.get("updated_at"), source_event.get("updated_at")) - for event in observed - ): - record("source_event_observed", False, "source_event_revision_mismatch") - else: - record("source_event_observed", True) - provider_event = observed[0] - verified_event = { - **dict(source_event), - "author_login": str( - provider_event.get("author_login") or source_event.get("author_login") - ), - "author_association": _upper_label( - provider_event.get("author_association"), - str(source_event.get("author_association") or "NONE"), - ), - "created_at": _normalise_event_timestamp( - provider_event.get("created_at") or source_event.get("created_at"), - field="source_event created_at", - ), - } - effective_event = verified_event or dict(source_event) - latest_prior = _latest_accepted_revision(prior, source_event=source_event) - prior_time = ( - _timestamp(latest_prior["source_event"].get("updated_at")) - if latest_prior - else None - ) - incoming_time = _timestamp(source_event.get("updated_at")) - revision_relation = "first" - if prior_time is not None and incoming_time is not None: - if incoming_time < prior_time: - revision_relation = "stale" - elif incoming_time == prior_time: - revision_relation = "replay" - else: - revision_relation = "newer" - record("revision_not_stale", revision_relation != "stale", "stale_revision") - record( - "not_self_or_bot_author", - not _is_bot_or_self_login(effective_event.get("author_login")), - "self_or_bot_author", - ) - record( - "author_is_maintainer", - _upper_label(effective_event.get("author_association"), "NONE") - in MAINTAINER_ASSOCIATIONS, - "author_not_maintainer", - ) - else: - effective_event = None - latest_prior = None - revision_relation = "replay" if existing_entry else "first" - record( - "pr_state_not_terminal", - str(observation.get("state") or "") not in TERMINAL_PR_STATES, - "terminal_pr_state", - ) - - accepted = reason is None - replay = existing_entry is not None and ( - not accepted or existing_entry.get("disposition") in {"accepted", "superseded"} - ) - if replay: - entry = dict(existing_entry) - else: - entry = { - "schema_version": ISSUE_FIX_MAINTAINER_CORRECTION_LEDGER_ENTRY_SCHEMA_VERSION, - "operation_id": operation_id, - "source_event": effective_event, - "correction_fingerprint": correction.get("correction_fingerprint"), - "correction_kind": correction.get("correction_kind"), - "admission_basis": admission_basis, - "disposition": "accepted" if accepted else "context_only", - "reason": reason, - "todo_id": None, - "accepted_head_sha": observation.get("head_commit_ref") if accepted else None, - "recorded_at": recorded_at, - "superseded_by": None, - "body_captured": False, - } - touched_entries = [entry] - superseded_operation_id = None - if ( - accepted - and revision_relation == "newer" - and latest_prior is not None - and latest_prior.get("operation_id") != operation_id - ): - superseded_operation_id = str(latest_prior.get("operation_id")) - touched_entries.append( - { - **latest_prior, - "disposition": "superseded", - "superseded_by": operation_id, - } - ) - return { - "schema_version": ISSUE_FIX_MAINTAINER_CORRECTION_ADMISSION_SCHEMA_VERSION, - "operation_id": operation_id, - "admission_basis": admission_basis, - "disposition": "accepted" if accepted else "context_only", - "reason": reason, - "host_summary_mismatch": bool( - existing_entry is not None - and correction.get("correction_fingerprint") - != existing_entry.get("correction_fingerprint") - ), - "gates": gates, - "revision_relation": revision_relation, - "replay": replay, - "supersedes_operation_id": superseded_operation_id, - "provider_events_status": provider_events_status, - "prior_ledger_read": bool(prior_ledger_read), - "source_event": effective_event, - "entries": touched_entries, - "body_captured": False, - } - - -def recheck_issue_fix_maintainer_correction_effect_gates( - entry: Mapping[str, Any], - *, - observation: Mapping[str, Any], - ledger_entries: Sequence[Mapping[str, Any]] | None, - goal_stopped: bool, - source_events: Mapping[str, Any] | None = None, -) -> str | None: - """Re-run the effect-time gates for an accepted entry just before its Todo write.""" - - source_event = entry.get("source_event") - if isinstance(source_event, Mapping): - observed = [ - event - for event in ( - source_events.get("events") if isinstance(source_events, Mapping) else [] - ) - if isinstance(event, Mapping) - and event.get("kind") == source_event.get("kind") - and str(event.get("id")) == str(source_event.get("id")) - ] - if not observed: - return "source_event_not_observed" - current_event = next( - (event for event in observed - if _same_instant(event.get("updated_at"), source_event.get("updated_at"))), - None, - ) - if current_event is None: - return "source_event_revision_mismatch" - latest = _latest_accepted_revision( - issue_fix_maintainer_correction_entries( - {"maintainer_corrections": ledger_entries} - ), - source_event=source_event, - ) - if latest is not None and latest.get("operation_id") != entry.get("operation_id"): - latest_time = _timestamp(latest["source_event"].get("updated_at")) - own_time = _timestamp(source_event.get("updated_at")) - if latest_time is not None and own_time is not None and own_time < latest_time: - return "stale_revision" - if _is_bot_or_self_login(current_event.get("author_login")): - return "self_or_bot_author" - if ( - _upper_label(current_event.get("author_association"), "NONE") - not in MAINTAINER_ASSOCIATIONS - ): - return "author_not_maintainer" - if str(observation.get("state") or "") in TERMINAL_PR_STATES: - return "terminal_pr_state" - if goal_stopped: - return "goal_not_active" - return None - -def _maintainer_correction_transition( - correction: Mapping[str, Any], - *, - pr_permalink: str, -) -> dict[str, Any]: - correction_kind = str(correction.get("correction_kind")) - source_ref = str(correction.get("source_ref")) - summary = str(correction.get("summary")) - source_event = correction.get("source_event") - # Todo creation dedupes identical active text, so distinct provider events - # or revisions with the same wording must name the event they came from. - event_suffix = ( - f" Source event: {source_event.get('kind')} {source_event.get('id')}" - f" updated {source_event.get('updated_at')}." - if isinstance(source_event, Mapping) - else "" - ) - if correction_kind == "actionable_patch": - verification_plan = str(correction.get("verification_plan")) - pr_update_path = str(correction.get("pr_update_path")) - return _transition_preview( - decision="runnable_successor", - action_kind="issue_fix_maintainer_correction_patch", - priority="P0", - task_class="advancement_task", - reason="Maintainer correction is bounded and actionable; create one claimed patch successor.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - text=( - f"[P0] Apply maintainer correction for {pr_permalink} from {source_ref}: " - f"{summary} Verify: {verification_plan} Update PR via: {pr_update_path}" - f"{event_suffix}" - ), - ) | { - "terminal_state_precedence": False, - "material_change": True, - "required_write_scopes": ["write", "publish"], - } - if correction_kind == "semantic_ambiguity": - return _transition_preview( - decision="user_gate", - action_kind="clarify_issue_fix_maintainer_correction", - priority="P0", - role="user", - task_class="user_gate", - reason="Maintainer correction changes or leaves the intended behavior ambiguous.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - text=( - f"[P0] Clarify maintainer correction for {pr_permalink} from {source_ref}: " - f"{correction.get('user_question')} Context: {summary}{event_suffix}" - ), - ) | {"terminal_state_precedence": False, "material_change": True} - if correction_kind == "missing_authority": - scopes = ", ".join( - str(value) for value in correction.get("missing_authority_scopes") or [] - ) - return _transition_preview( - decision="user_gate", - action_kind="grant_issue_fix_maintainer_correction_authority", - priority="P0", - role="user", - task_class="user_gate", - reason="The correction is understood but the required write authority is not active.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - text=( - f"[P0] Grant or decline [{scopes}] authority for maintainer correction " - f"{source_ref} on {pr_permalink}: {summary}{event_suffix}" - ), - ) | { - "terminal_state_precedence": False, - "material_change": True, - "missing_authority_scopes": list( - correction.get("missing_authority_scopes") or [] - ), - } - return _transition_preview( - decision="monitor_continuation", - action_kind="issue_fix_maintainer_correction_unchanged_monitor", - priority="P2", - reason="Maintainer correction is unchanged; keep the monitor quiet and create no successor.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - ) | {"terminal_state_precedence": False, "material_change": False} - - def _normalise_check_item(item: Mapping[str, Any]) -> str: state = ( item.get("conclusion") @@ -966,35 +208,6 @@ def _check_rollup(payload: Mapping[str, Any]) -> dict[str, Any]: } -def _transition_preview( - *, - decision: str, - action_kind: str, - priority: str, - reason: str, - depends_on: Sequence[str], - role: str = "agent", - task_class: str = "continuous_monitor", - text: str | None = None, -) -> dict[str, Any]: - if text is None: - text = f"[{priority}] {reason}" - return { - "schema_version": "issue_fix_pr_lifecycle_transition_v0", - "decision": decision, - "command_preview": "loopx todo transition", - "role": role, - "priority": priority, - "task_class": task_class, - "action_kind": action_kind, - "reason": reason, - "text": text, - "depends_on": list(depends_on), - "would_write": False, - "requires_execute_flag": True, - } - - def _build_observation( *, repo: str, @@ -1191,11 +404,9 @@ def _decide_transition(observation: Mapping[str, Any]) -> dict[str, Any]: "PR is merged; close the monitor with no follow-up even if stale " "review metadata still says review is required." ), - depends_on=["issue_fix_pr_lifecycle_monitor"], - ) | { - "terminal_state_precedence": True, - "material_change": True, - } + terminal_state_precedence=True, + material_change=True, + ) if state == "CLOSED": return _transition_preview( decision="no_followup", @@ -1203,11 +414,9 @@ def _decide_transition(observation: Mapping[str, Any]) -> dict[str, Any]: priority="P1", task_class="terminal_transition", reason="PR is closed without an open continuation; close the monitor.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - ) | { - "terminal_state_precedence": True, - "material_change": True, - } + terminal_state_precedence=True, + material_change=True, + ) if failing_checks: return _transition_preview( decision="runnable_successor", @@ -1215,11 +424,8 @@ def _decide_transition(observation: Mapping[str, Any]) -> dict[str, Any]: priority="P0", task_class="advancement_task", reason="PR checks are failing; inspect public check summary and plan a fix.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - ) | { - "terminal_state_precedence": False, - "material_change": True, - } + material_change=True, + ) if review_decision == "CHANGES_REQUESTED": if review_response_status == "changes_addressed_awaiting_rereview": return _transition_preview( @@ -1230,22 +436,15 @@ def _decide_transition(observation: Mapping[str, Any]) -> dict[str, Any]: "Review changes have a newer repair commit and every fetched " "review thread is resolved; wait for reviewer re-approval." ), - depends_on=["issue_fix_pr_lifecycle_monitor"], - ) | { - "terminal_state_precedence": False, - "material_change": False, - } + ) return _transition_preview( decision="runnable_successor", action_kind="issue_fix_review_changes_replan", priority="P0", task_class="advancement_task", reason="Maintainer review requested changes; derive a follow-up patch or blocker.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - ) | { - "terminal_state_precedence": False, - "material_change": True, - } + material_change=True, + ) if merge_state in BRANCH_REPLAN_MERGE_STATES: return _transition_preview( decision="runnable_successor", @@ -1253,11 +452,8 @@ def _decide_transition(observation: Mapping[str, Any]) -> dict[str, Any]: priority="P1", task_class="advancement_task", reason="PR branch is stale or conflicted; decide rebase, blocker note, or no-follow-up.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - ) | { - "terminal_state_precedence": False, - "material_change": True, - } + material_change=True, + ) if is_draft: return _transition_preview( decision="user_gate", @@ -1266,32 +462,21 @@ def _decide_transition(observation: Mapping[str, Any]) -> dict[str, Any]: role="user", task_class="user_gate", reason="PR is still draft; owner must approve marking ready or keep monitoring.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - ) | { - "terminal_state_precedence": False, - "material_change": True, - } + material_change=True, + ) if pending_checks: return _transition_preview( decision="monitor_continuation", action_kind="issue_fix_pr_checks_pending_monitor", priority="P2", reason="PR checks are still pending; continue monitor without spawning work.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - ) | { - "terminal_state_precedence": False, - "material_change": False, - } + ) return _transition_preview( decision="monitor_continuation", action_kind="issue_fix_pr_wait_for_review_or_merge_monitor", priority="P2", reason="No actionable PR state change; keep watching for CI, review, merge, or maintainer signal.", - depends_on=["issue_fix_pr_lifecycle_monitor"], - ) | { - "terminal_state_precedence": False, - "material_change": False, - } + ) def _fetch_github_review_response_metadata( @@ -1729,69 +914,59 @@ def build_issue_fix_pr_lifecycle_monitor_packet( return packet +def _require_false_flags( + mapping: Mapping[str, Any], prefix: str, keys: Sequence[str], errors: list[str] +) -> None: + for key in keys: + if mapping.get(key) is not False: + errors.append(f"{prefix} {key} must be false") + + def validate_issue_fix_pr_lifecycle_monitor_packet( packet: Mapping[str, Any], ) -> dict[str, Any]: errors: list[str] = [] if packet.get("schema_version") != ISSUE_FIX_PR_LIFECYCLE_MONITOR_SCHEMA_VERSION: errors.append("packet schema_version must be issue_fix_pr_lifecycle_monitor_v0") - for key in ( - "external_writes_performed", - "issue_body_captured", - "comment_bodies_captured", - "maintainer_correction_body_captured", - "response_payloads_captured", - "raw_check_logs_captured", - "local_paths_captured", - "private_repo_state_read", - "destructive_git_used", - ): - if packet.get(key) is not False: - errors.append(f"packet {key} must be false") + _require_false_flags( + packet, + "packet", + ( + "external_writes_performed", "issue_body_captured", "comment_bodies_captured", + "maintainer_correction_body_captured", "response_payloads_captured", + "raw_check_logs_captured", "local_paths_captured", "private_repo_state_read", + "destructive_git_used", + ), + errors, + ) observation = packet.get("observation") if not isinstance(observation, Mapping): errors.append("observation is required") observation = {} if observation.get("kind") != "pull_request": errors.append("observation kind must be pull_request") - for key in ( - "body_captured", - "comment_bodies_captured", - "timeline_captured", - "log_output_captured", - "response_payload_captured", - ): - if observation.get(key) is not False: - errors.append(f"observation {key} must be false") + _require_false_flags( + observation, + "observation", + ("body_captured", "comment_bodies_captured", "timeline_captured", "log_output_captured", "response_payload_captured"), + errors, + ) checks = observation.get("checks") if isinstance(checks, Mapping): - if checks.get("raw_status_captured") is not False: - errors.append("checks raw_status_captured must be false") - if checks.get("log_output_captured") is not False: - errors.append("checks log_output_captured must be false") + _require_false_flags(checks, "checks", ("raw_status_captured", "log_output_captured"), errors) else: errors.append("observation checks are required") review_response = observation.get("review_response") - if not isinstance(review_response, Mapping): - errors.append("observation review_response is required") + if isinstance(review_response, Mapping): + _require_false_flags(review_response, "review_response", ("raw_reviews_captured", "raw_thread_comments_captured"), errors) else: - if review_response.get("raw_reviews_captured") is not False: - errors.append("review_response raw_reviews_captured must be false") - if review_response.get("raw_thread_comments_captured") is not False: - errors.append( - "review_response raw_thread_comments_captured must be false" - ) + errors.append("observation review_response is required") transition = packet.get("transition") if not isinstance(transition, Mapping): errors.append("transition is required") transition = {} decision = transition.get("decision") - if decision not in { - "runnable_successor", - "monitor_continuation", - "user_gate", - "no_followup", - }: + if decision not in {"runnable_successor", "monitor_continuation", "user_gate", "no_followup"}: errors.append("transition decision is invalid") if transition.get("would_write") is not False: errors.append("transition would_write must be false") @@ -1800,10 +975,7 @@ def validate_issue_fix_pr_lifecycle_monitor_packet( state = observation.get("state") if state in TERMINAL_PR_STATES and decision != "no_followup": errors.append("terminal PR state must choose no_followup") - if ( - state in TERMINAL_PR_STATES - and transition.get("terminal_state_precedence") is not True - ): + if state in TERMINAL_PR_STATES and transition.get("terminal_state_precedence") is not True: errors.append("terminal PR state must record terminal_state_precedence") if transition.get("material_change") is True and decision == "monitor_continuation": errors.append("material PR change must not choose monitor_continuation") @@ -1812,14 +984,12 @@ def validate_issue_fix_pr_lifecycle_monitor_packet( if not isinstance(correction, Mapping): errors.append("maintainer_correction must be an object") else: - for key in ( - "raw_body_captured", - "raw_comment_captured", - "raw_provider_payload_captured", - "local_paths_captured", - ): - if correction.get(key) is not False: - errors.append(f"maintainer_correction {key} must be false") + _require_false_flags( + correction, + "maintainer_correction", + ("raw_body_captured", "raw_comment_captured", "raw_provider_payload_captured", "local_paths_captured"), + errors, + ) if packet.get("maintainer_correction_fingerprint") != correction.get( "correction_fingerprint" ): @@ -1935,122 +1105,56 @@ def validate_issue_fix_pr_lifecycle_monitor_packet( } +def _kv_bullets(mapping: Mapping[str, Any], keys: Sequence[str]) -> list[str]: + return [f"- {key}: `{mapping.get(key)}`" for key in keys] + + +def _append_section(lines: list[str], title: str, rows: Sequence[str]) -> None: + lines.extend(["", f"## {title}", "", *rows]) + + def render_issue_fix_pr_lifecycle_monitor_markdown(payload: dict[str, Any]) -> str: lines = [ "# LoopX Issue Fix PR Lifecycle", "", - f"- ok: `{payload.get('ok')}`", - f"- schema_version: `{payload.get('schema_version')}`", - f"- external_reads_performed: `{payload.get('external_reads_performed')}`", - f"- external_writes_performed: `{payload.get('external_writes_performed')}`", - f"- todo_write_performed: `{payload.get('todo_write_performed')}`", - f"- observation_fingerprint: `{payload.get('observation_fingerprint')}`", + *_kv_bullets( + payload, + ( + "ok", "schema_version", "external_reads_performed", + "external_writes_performed", "todo_write_performed", "observation_fingerprint", + ), + ), ] observation = payload.get("observation") if isinstance(observation, Mapping): - checks = ( - observation.get("checks") - if isinstance(observation.get("checks"), Mapping) - else {} - ) - lines.extend( - [ - "", - "## Observation", - "", - f"- repo: `{observation.get('repo')}`", - f"- pr_ref: `{observation.get('pr_ref')}`", - f"- state: `{observation.get('state')}`", - f"- review_decision: `{observation.get('review_decision')}`", - f"- merge_state_status: `{observation.get('merge_state_status')}`", - f"- checks: `{checks.get('aggregate')}`", - ] + raw_checks = observation.get("checks") + checks: Mapping[str, Any] = raw_checks if isinstance(raw_checks, Mapping) else {} + _append_section( + lines, + "Observation", + [*_kv_bullets(observation, ("repo", "pr_ref", "state", "review_decision", "merge_state_status")), f"- checks: `{checks.get('aggregate')}`"], ) transition = payload.get("transition") if isinstance(transition, Mapping): - lines.extend( - [ - "", - "## Transition", - "", - f"- decision: `{transition.get('decision')}`", - f"- action_kind: `{transition.get('action_kind')}`", - f"- material_change: `{transition.get('material_change')}`", - f"- terminal_state_precedence: `{transition.get('terminal_state_precedence')}`", - f"- reason: {transition.get('reason')}", - ] - ) - grouped_monitor = payload.get("grouped_monitor_projection") - if isinstance(grouped_monitor, Mapping): - lines.extend( - [ - "", - "## Grouped Monitor Projection", - "", - f"- state_bucket: `{grouped_monitor.get('state_bucket')}`", - f"- target_key: `{grouped_monitor.get('target_key')}`", - f"- member_operation: `{grouped_monitor.get('member_operation')}`", - f"- creates_per_pr_continuous_monitor_todo: " - f"`{grouped_monitor.get('creates_per_pr_continuous_monitor_todo')}`", - f"- per_pr_material_action: " - f"`{grouped_monitor.get('per_pr_material_action')}`", - ] - ) - correction = payload.get("maintainer_correction") - if isinstance(correction, Mapping): - lines.extend( - [ - "", - "## Maintainer Correction", - "", - f"- correction_kind: `{correction.get('correction_kind')}`", - f"- source_kind: `{correction.get('source_kind')}`", - f"- source_ref: `{correction.get('source_ref')}`", - f"- correction_fingerprint: `{correction.get('correction_fingerprint')}`", - ] - ) - admission = payload.get("maintainer_correction_admission") - if isinstance(admission, Mapping): - lines.extend( - [ - "", - "## Maintainer Correction Admission", - "", - f"- admission_basis: `{admission.get('admission_basis')}`", - f"- disposition: `{admission.get('disposition')}`", - f"- reason: `{admission.get('reason')}`", - f"- operation_id: `{admission.get('operation_id')}`", - ] - ) - domain_state = payload.get("domain_state_projection") - if isinstance(domain_state, Mapping): - lines.extend( - [ - "", - "## Domain State Projection", - "", - f"- domain_pack: `{domain_state.get('domain_pack')}`", - f"- default_filename: `{domain_state.get('default_filename')}`", - f"- write_performed: `{domain_state.get('write_performed')}`", - f"- path_recorded: `{domain_state.get('path_recorded')}`", - ] + _append_section( + lines, + "Transition", + [*_kv_bullets(transition, ("decision", "action_kind", "material_change", "terminal_state_precedence")), f"- reason: {transition.get('reason')}"], ) + for key, title, fields in ( + ("grouped_monitor_projection", "Grouped Monitor Projection", ("state_bucket", "target_key", "member_operation", "creates_per_pr_continuous_monitor_todo", "per_pr_material_action")), + ("maintainer_correction", "Maintainer Correction", ("correction_kind", "source_kind", "source_ref", "correction_fingerprint")), + ("maintainer_correction_admission", "Maintainer Correction Admission", ("admission_basis", "disposition", "reason", "operation_id")), + ("domain_state_projection", "Domain State Projection", ("domain_pack", "default_filename", "write_performed", "path_recorded")), + ): + section = payload.get(key) + if isinstance(section, Mapping): + _append_section(lines, title, _kv_bullets(section, fields)) validation = payload.get("validation") if isinstance(validation, Mapping): - errors = ( - validation.get("errors") - if isinstance(validation.get("errors"), list) - else [] - ) - lines.extend( - [ - "", - "## Validation", - "", - f"- validation_ok: `{validation.get('ok')}`", - f"- error_count: `{len(errors)}`", - ] - ) + raw_errors = validation.get("errors") + errors = raw_errors if isinstance(raw_errors, list) else [] + _append_section(lines, "Validation", (f"- validation_ok: `{validation.get('ok')}`", f"- error_count: `{len(errors)}`")) if payload.get("error"): - lines.extend(["", "## Error", "", str(payload.get("error"))]) + _append_section(lines, "Error", (str(payload.get("error")),)) return "\n".join(lines) + "\n" diff --git a/tests/capabilities/test_issue_fix_maintainer_correction_admission.py b/tests/capabilities/test_issue_fix_maintainer_correction_admission.py index a8fa7106f7..aa35f0cec0 100644 --- a/tests/capabilities/test_issue_fix_maintainer_correction_admission.py +++ b/tests/capabilities/test_issue_fix_maintainer_correction_admission.py @@ -15,6 +15,7 @@ import pytest +from loopx.control_plane.goals.activation import build_goal_activation from loopx.control_plane.testing.canary_harness import import_fixture_authority from loopx.domain_packs.issue_fix import ( default_issue_fix_domain_state_ledger_path, @@ -400,7 +401,17 @@ def test_t05_missing_event_metadata_is_context_only(harness: Harness) -> None: @pytest.mark.parametrize("provider", ["file", "sqlite"]) def test_t06_stopped_goal_refuses_at_effect_time(tmp_path: Path, provider: str) -> None: - h = Harness(tmp_path, provider, goal_overrides={"activation_state": "stopped"}) + h = Harness( + tmp_path, + provider, + goal_overrides={ + "activation": build_goal_activation( + state="stopped", + updated_at="2026-06-20T09:00:00Z", + reason="Owner stopped goal before correction settlement.", + ) + }, + ) event = _event("6001") payload = h.run_json(metadata=_metadata([event]), correction=_correction_v1(event)) admission = payload["maintainer_correction_admission"]