From af4d1307fe1b0ec5a5f52ff30782af395b4413d5 Mon Sep 17 00:00:00 2001 From: James Wiesebron Date: Wed, 22 Apr 2026 15:34:02 -0700 Subject: [PATCH 1/2] Fix #1889 + #1890: bridge contract decisions at phase_gate; harden plan HITL gate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit #1889: When an agent registered questions via egg-contract add-decision / add-feedback during refine/plan, those entries lived only in the contract JSON. The orchestrator's decision queue was blind to them, so approving the phase_gate via the HTTP API/MCP silently discarded them and the next phase's agents had to guess. Added _queue_and_await_contract_decisions which, after phase_gate approval, promotes unresolved contract-scoped decisions/feedback into orchestrator choice/feedback decisions, waits for each, and syncs resolutions back to the contract. #1890: Wrapped the call sites for _populate_contract_from_plan and _sync_pipeline_decisions_to_contract in try/except — an uncaught escape was enough to skip the HITL gate below, stalling the pipeline until the overseer intervened. Also made handle_consensus_confirmed_signal idempotent with respect to the message store: a role that already emitted a final (or pending_acks) CONFIRMED in the current phase no longer writes another, so the agent's retry-loop "for i in 1..10; do egg-orch consensus confirmed; done" stops polluting the bus. Co-Authored-By: Claude Opus 4.7 (1M context) --- orchestrator/routes/pipelines.py | 216 ++++++++++++++- orchestrator/routes/signals.py | 154 ++++++++--- .../tests/test_brc_phase_propagation.py | 8 +- .../test_consensus_confirmed_idempotent.py | 181 +++++++++++++ .../tests/test_contract_decision_bridge.py | 255 ++++++++++++++++++ 5 files changed, 767 insertions(+), 47 deletions(-) create mode 100644 orchestrator/tests/test_consensus_confirmed_idempotent.py create mode 100644 orchestrator/tests/test_contract_decision_bridge.py diff --git a/orchestrator/routes/pipelines.py b/orchestrator/routes/pipelines.py index 05f0588760..21ddc9a3fd 100644 --- a/orchestrator/routes/pipelines.py +++ b/orchestrator/routes/pipelines.py @@ -10,6 +10,7 @@ import sys import threading import time +from collections.abc import Callable from datetime import UTC, datetime from pathlib import Path from typing import TYPE_CHECKING, Any, Literal @@ -8747,6 +8748,168 @@ def _sync_pipeline_decisions_to_contract( ) +def _queue_and_await_contract_decisions( + dq: Any, + worktree_repo_path: Path, + pipeline_id: str, + pipeline_identifier: int | str, + phase: PipelinePhase, +) -> None: + """Promote unresolved contract decisions/feedback into the orchestrator queue. + + Agents register architectural questions via ``egg-contract add-decision`` + and ``add-feedback``. Those writes only touch ``.egg-state/contracts/ + {identifier}.json`` — the orchestrator's decision queue never sees them, + so approving the phase_gate silently drops the questions and the next + phase's agents have to guess (issue #1889). + + This helper bridges contract-scoped questions for the current phase into + the orchestrator queue after phase_gate approval, so HTTP/MCP callers + (e.g. the ``/sdlc`` skill's Phase 4 handler) surface them as individual + ``choice`` / ``feedback`` decisions. Resolutions are written back to + the contract so implement-phase agents see the human's answers. + """ + try: + from egg_contracts.loader import load_contract, save_contract + except ImportError: + logger.warning( + "egg_contracts not available, skipping contract decision bridge", + pipeline_id=pipeline_id, + ) + return + + try: + contract = load_contract(pipeline_identifier, worktree_repo_path) + except Exception as e: + logger.debug( + "Contract not loadable, skipping contract decision bridge", + pipeline_id=pipeline_id, + error=str(e), + ) + return + + phase_value = phase.value + pending_decisions = [ + d + for d in contract.decisions + if not d.resolved and (d.phase is None or getattr(d.phase, "value", d.phase) == phase_value) + ] + fb = contract.feedback + pending_feedback = None + if fb is not None and not fb.submitted: + fb_phase_val = getattr(fb.phase, "value", fb.phase) if fb.phase is not None else None + if fb_phase_val is None or fb_phase_val == phase_value: + pending_feedback = fb + + if not pending_decisions and pending_feedback is None: + return + + logger.info( + "Bridging contract decisions/feedback into orchestrator queue", + pipeline_id=pipeline_id, + phase=phase_value, + decision_count=len(pending_decisions), + has_feedback=pending_feedback is not None, + ) + + def _save_contract_update(mutator: Callable[[Any], bool]) -> None: + try: + latest = load_contract(pipeline_identifier, worktree_repo_path) + except Exception as e: + logger.warning( + "Could not reload contract to persist bridged resolution", + pipeline_id=pipeline_id, + error=str(e), + ) + return + if not mutator(latest): + return + try: + save_contract(latest, worktree_repo_path) + except Exception as e: + logger.warning( + "Failed to save contract after bridged resolution", + pipeline_id=pipeline_id, + error=str(e), + ) + + for contract_decision in pending_decisions: + options_labels = [opt.label for opt in contract_decision.options] + queued = dq.queue_decision( + question=contract_decision.question, + context=( + f"Open contract question {contract_decision.id}, " + f"registered by an agent during the {phase_value} phase." + ), + options=options_labels, + decision_type="choice", + phase=phase, + ) + resolved = dq.wait_for_decision(queued.id) + if resolved.status != DecisionStatus.RESOLVED: + continue + resolution_str = (resolved.resolution or "").strip() + + def _apply( + latest: Any, _cd_id: str = contract_decision.id, _res: str = resolution_str + ) -> bool: + for d in latest.decisions: + if d.id == _cd_id: + d.resolved = True + d.resolution = _res + d.resolved_by = "human" + d.resolved_at = datetime.now(UTC) + return True + return False + + _save_contract_update(_apply) + + if pending_feedback is not None: + questions_payload = [ + {"id": q.id, "question": q.question, "answer": ""} for q in pending_feedback.questions + ] + queued = dq.queue_decision( + question=f"Open feedback request {pending_feedback.id}", + context=( + f"Open contract feedback {pending_feedback.id}, " + f"registered by an agent during the {phase_value} phase." + ), + options=[], + decision_type="feedback", + questions=questions_payload, + phase=phase, + ) + resolved = dq.wait_for_decision(queued.id) + if resolved.status == DecisionStatus.RESOLVED: + answers: dict[str, str] = {} + try: + payload = json.loads(resolved.resolution or "") + if isinstance(payload, dict): + raw_answers = payload.get("answers") + if isinstance(raw_answers, dict): + answers = {str(k): str(v) for k, v in raw_answers.items()} + except (json.JSONDecodeError, TypeError): + pass + + if answers: + fb_id = pending_feedback.id + + def _apply_fb( + latest: Any, _fb_id: str = fb_id, _answers: dict[str, str] = answers + ) -> bool: + if latest.feedback is None or latest.feedback.id != _fb_id: + return False + for q in latest.feedback.questions: + if q.id in _answers: + q.answer = _answers[q.id] + latest.feedback.submitted = True + latest.feedback.submitted_by = "human" + latest.feedback.submitted_at = datetime.now(UTC) + return True + + _save_contract_update(_apply_fb) + + def _persist_phase_gate_resolution( repo_path: Path, pipeline_id: str, @@ -10140,10 +10303,22 @@ def _health_monitor_poll(monitor, stop_event: threading.Event, interval: float = # Called on every successful plan completion (including after # HITL revision) so the contract reflects the latest approved # plan, not a previously rejected draft. + # + # Wrapped in try/except at the call site: #1890 showed an escape + # of an uncaught exception here skipped the HITL gate below, + # leaving the pipeline stalled until the overseer intervened. if current_phase.value == "plan": - _populate_contract_from_plan( - worktree_repo_path, pipeline_id, pipeline_mode, pipeline.issue_number - ) + try: + _populate_contract_from_plan( + worktree_repo_path, pipeline_id, pipeline_mode, pipeline.issue_number + ) + except Exception as pop_err: + logger.warning( + "Failed to populate contract from plan (continuing)", + pipeline_id=pipeline_id, + phase=current_phase.value, + error=str(pop_err), + ) # After refine and plan phases: sync substantive HITL decisions # (non-phase-gate) to the contract so implement-phase agents @@ -10151,9 +10326,17 @@ def _health_monitor_poll(monitor, stop_event: threading.Event, interval: float = # phases — refine decisions inform the plan, plan decisions # inform the implementation. if current_phase.value in _HITL_GATE_PHASES: - _sync_pipeline_decisions_to_contract( - worktree_repo_path, pipeline_id, pipeline_mode, pipeline.issue_number - ) + try: + _sync_pipeline_decisions_to_contract( + worktree_repo_path, pipeline_id, pipeline_mode, pipeline.issue_number + ) + except Exception as sync_err: + logger.warning( + "Failed to sync pipeline decisions to contract (continuing)", + pipeline_id=pipeline_id, + phase=current_phase.value, + error=str(sync_err), + ) # Write BRC consensus history for this phase before committing # statefiles so the history file is included in the commit. @@ -10498,6 +10681,27 @@ def _health_monitor_poll(monitor, stop_event: threading.Event, interval: float = _emit_pipeline_event(pipeline, "phase.revision_requested") continue # Re-enter outer loop → re-run phase with feedback + # Before advancing, surface any contract-scoped decisions / + # feedback the phase's agents registered via ``egg-contract``. + # Without this bridge, approving the phase_gate silently + # discards them (#1889). Wrapped in try/except so a bug + # here can never strand the pipeline. + try: + _queue_and_await_contract_decisions( + dq, + worktree_repo_path, + pipeline_id, + _pipeline_identifier(pipeline.issue_number, pipeline_id), + current_phase, + ) + except Exception as bridge_err: + logger.warning( + "Contract decision bridge failed (continuing)", + pipeline_id=pipeline_id, + phase=current_phase.value, + error=str(bridge_err), + ) + # Approved — resume and advance with get_pipeline_state_lock(pipeline_id): pipeline = store.load_pipeline(pipeline_id) diff --git a/orchestrator/routes/signals.py b/orchestrator/routes/signals.py index 3441357150..79cd5eb260 100644 --- a/orchestrator/routes/signals.py +++ b/orchestrator/routes/signals.py @@ -1238,12 +1238,65 @@ def _write_consensus_confirmed_marker(pipeline_id: str, agent_role: str, repo_pa ) +def _existing_confirmed_for_role( + pipeline_id: str, + agent_role: str, + phase: str | None, +) -> tuple[bool, bool]: + """Return (has_final, has_pending_acks) for prior CONFIRMED messages. + + Scans the message store for prior ``CONSENSUS_CONFIRMED`` messages + from ``agent_role`` in ``phase``. Used for idempotency so that + repeated ``egg-orch consensus confirmed`` invocations don't pollute + the bus with duplicate messages (see #1890). + + - ``has_final``: a non-pending_acks CONFIRMED message already exists. + - ``has_pending_acks``: a pending_acks CONFIRMED message exists. + """ + try: + from message_store import get_message_store + except ImportError: + try: + from ..message_store import get_message_store # type: ignore[no-redef] + except ImportError: + return (False, False) + + try: + store = get_message_store() + messages = store.get_messages(pipeline_id, limit=10000) + except Exception: + return (False, False) + + has_final = False + has_pending = False + for m in messages: + if getattr(m, "from_role", None) != agent_role: + continue + if str(getattr(m, "message_type", "")) != "CONSENSUS_CONFIRMED": + continue + msg_phase = getattr(m, "phase", None) + if phase is not None and msg_phase is not None and msg_phase != phase: + continue + metadata = getattr(m, "metadata", None) or {} + if metadata.get("pending_acks"): + has_pending = True + else: + has_final = True + return (has_final, has_pending) + + def handle_consensus_confirmed_signal( pipeline_id: str, data: dict[str, Any], repo_path: Path, ) -> tuple[Response, int]: - """Handle CONSENSUS_CONFIRMED signal from an agent.""" + """Handle CONSENSUS_CONFIRMED signal from an agent. + + Idempotent with respect to the message store: repeated invocations + from the same agent in the same phase do not pollute the bus with + duplicate CONFIRMED messages (see #1890). The underlying consensus + tracker still observes each call so its own state stays in sync. + """ agent_role = data.get("agent_role") if not agent_role: return make_error_response("Missing agent_role") @@ -1313,26 +1366,33 @@ def handle_consensus_confirmed_signal( pipeline_id=pipeline_id, confirmed_roles=sorted(confirmed_roles), ) - # Write the CONSENSUS_CONFIRMED message - store.add_message( - Message( - pipeline_id=pipeline_id, - from_role=agent_role, - to_role="all", - message_type=MessageType.CONSENSUS_CONFIRMED, - subject=f"Confirmed by {agent_role}", - body="", - phase=_phase, - metadata={"consensus_reached": True, "fallback": "message_bus"}, + # Idempotency: only write the CONFIRMED message if this + # role hasn't already emitted a final one in this phase. + has_final, _ = _existing_confirmed_for_role(pipeline_id, agent_role, _phase) + if not has_final: + store.add_message( + Message( + pipeline_id=pipeline_id, + from_role=agent_role, + to_role="all", + message_type=MessageType.CONSENSUS_CONFIRMED, + subject=f"Confirmed by {agent_role}", + body="", + phase=_phase, + metadata={ + "consensus_reached": True, + "fallback": "message_bus", + }, + ) ) - ) - _write_consensus_confirmed_marker(pipeline_id, agent_role, repo_path) + _write_consensus_confirmed_marker(pipeline_id, agent_role, repo_path) return make_success_response( f"Confirmation recorded for {agent_role} (message-bus fallback)", data={ "status": "confirmed", "consensus_reached": True, "fallback": "message_bus", + "idempotent": has_final, }, ) except Exception as fallback_err: @@ -1354,7 +1414,37 @@ def handle_consensus_confirmed_signal( # pending_acks=True metadata) so the message-bus fallback in # check_consensus() can detect when all agents have *attempted* # confirmation even if the tracker rejected some (#1615). + current_phase = _resolve_pipeline_phase(pipeline_id, repo_path) + has_final, has_pending = _existing_confirmed_for_role( + pipeline_id, agent_role, current_phase + ) + if result.get("status") == "pending_acks": + # Dedupe pending_acks writes once an agent has already emitted one + # (or a final) in this phase — the fallback check only needs one + # to detect "attempted confirmation" (#1615). + if not has_pending and not has_final: + from message_store import Message, MessageType, get_message_store + + store = get_message_store() + store.add_message( + Message( + pipeline_id=pipeline_id, + from_role=agent_role, + to_role="all", + message_type=MessageType.CONSENSUS_CONFIRMED, + subject=f"Confirmed by {agent_role} (pending_acks)", + body=result.get("message", ""), + phase=current_phase, + metadata={"pending_acks": True}, + ) + ) + return make_success_response(result["message"], data=result, status_code=202) + + # Final CONFIRMED: skip if this role has already emitted one in this + # phase. Prevents the ``egg-orch consensus confirmed`` retry-loop + # from spraying the bus with duplicates (#1890). + if not has_final: from message_store import Message, MessageType, get_message_store store = get_message_store() @@ -1364,37 +1454,23 @@ def handle_consensus_confirmed_signal( from_role=agent_role, to_role="all", message_type=MessageType.CONSENSUS_CONFIRMED, - subject=f"Confirmed by {agent_role} (pending_acks)", - body=result.get("message", ""), - phase=_resolve_pipeline_phase(pipeline_id, repo_path), - metadata={"pending_acks": True}, + subject=f"Confirmed by {agent_role}", + body="", + phase=current_phase, + metadata={"consensus_reached": result.get("consensus_reached", False)}, ) ) - return make_success_response(result["message"], data=result, status_code=202) - from message_store import Message, MessageType, get_message_store - - store = get_message_store() - store.add_message( - Message( - pipeline_id=pipeline_id, - from_role=agent_role, - to_role="all", - message_type=MessageType.CONSENSUS_CONFIRMED, - subject=f"Confirmed by {agent_role}", - body="", - phase=_resolve_pipeline_phase(pipeline_id, repo_path), - metadata={"consensus_reached": result.get("consensus_reached", False)}, - ) - ) - - # Write consensus-confirmed marker so auto-commit can detect that - # BRC review is complete and skip pushing unreviewed WIP (#1473). - _write_consensus_confirmed_marker(pipeline_id, agent_role, repo_path) + # Write consensus-confirmed marker so auto-commit can detect that + # BRC review is complete and skip pushing unreviewed WIP (#1473). + _write_consensus_confirmed_marker(pipeline_id, agent_role, repo_path) + payload = dict(result) + if has_final: + payload["idempotent"] = True return make_success_response( f"Confirmation recorded for {agent_role}", - data=result, + data=payload, ) except ValueError as e: logger.error("Failed to process consensus confirmed", pipeline_id=pipeline_id, error=str(e)) diff --git a/orchestrator/tests/test_brc_phase_propagation.py b/orchestrator/tests/test_brc_phase_propagation.py index 1cef7f613f..b862861be2 100644 --- a/orchestrator/tests/test_brc_phase_propagation.py +++ b/orchestrator/tests/test_brc_phase_propagation.py @@ -569,7 +569,11 @@ def test_confirmed_fallback_uses_local_phase( mock_msg_store = MagicMock() - # Return enough CONFIRMED messages to trigger the fallback path + # Return enough CONFIRMED messages to trigger the fallback path. + # `coder` is omitted — it's the role sending this signal, so its + # CONFIRMED is added via the fallback's confirmed_roles.add(agent_role) + # line. This also verifies idempotency doesn't short-circuit the + # fallback write when the sender has no prior CONFIRMED (#1890). existing_confirmed = [ _make_brc_message( pipeline_id="issue-42", @@ -579,7 +583,7 @@ def test_confirmed_fallback_uses_local_phase( body="", phase="implement", ) - for role in ["coder", "tester", "reviewer_code", "documenter", "reviewer_contract"] + for role in ["tester", "reviewer_code", "documenter", "reviewer_contract"] ] mock_msg_store.get_messages.return_value = existing_confirmed diff --git a/orchestrator/tests/test_consensus_confirmed_idempotent.py b/orchestrator/tests/test_consensus_confirmed_idempotent.py new file mode 100644 index 0000000000..6d45759456 --- /dev/null +++ b/orchestrator/tests/test_consensus_confirmed_idempotent.py @@ -0,0 +1,181 @@ +"""Tests for handle_consensus_confirmed_signal idempotency. + +The ``egg-orch consensus confirmed`` CLI is invoked by agents after they +ACK all peers, often inside a retry loop. Before #1890, every invocation +wrote a fresh CONSENSUS_CONFIRMED message to the bus — a single agent +could flood the bus with dozens of duplicates. The signal handler now +short-circuits duplicate writes when the role has already emitted a +CONFIRMED for the current phase. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from unittest.mock import MagicMock, patch + +import pytest +from flask import Flask +from message_store import MessageType + + +@pytest.fixture +def app(): + a = Flask(__name__) + return a + + +@pytest.fixture +def mock_pipeline(): + pip = MagicMock() + pip.current_phase = MagicMock() + pip.current_phase.value = "implement" + pip.config = MagicMock() + pip.config.repo = None + return pip + + +def _fake_message(from_role: str, phase: str, *, pending_acks: bool = False) -> MagicMock: + m = MagicMock() + m.from_role = from_role + m.phase = phase + m.message_type = str(MessageType.CONSENSUS_CONFIRMED) + m.metadata = {"pending_acks": True} if pending_acks else {"consensus_reached": True} + return m + + +def test_tracker_path_is_idempotent_for_final_confirmed(app, mock_pipeline): + """Second CONFIRMED from same role in same phase is not written.""" + mock_store = MagicMock() + mock_store.load_pipeline.return_value = mock_pipeline + + tracker = MagicMock() + tracker.handle_confirmed.return_value = { + "status": "confirmed", + "consensus_reached": True, + } + + msg_store = MagicMock() + msg_store.get_messages.return_value = [ + _fake_message("coder", "implement"), + ] + + with ( + app.app_context(), + patch("routes.signals._resolve_pipeline_phase", return_value="implement"), + patch("routes.signals._write_consensus_confirmed_marker"), + patch("routes.signals.get_state_store", return_value=mock_store), + patch("peer_consensus.get_peer_consensus_tracker", return_value=tracker), + patch("message_store.get_message_store", return_value=msg_store), + ): + from routes.signals import handle_consensus_confirmed_signal + + response, status_code = handle_consensus_confirmed_signal( + "issue-42", {"agent_role": "coder"}, Path("/tmp/repo") + ) + + assert status_code == 200 + data = json.loads(response.data) + assert data["data"].get("idempotent") is True + msg_store.add_message.assert_not_called() + + +def test_tracker_path_writes_first_confirmed(app, mock_pipeline): + """First CONFIRMED from a role is still recorded.""" + mock_store = MagicMock() + mock_store.load_pipeline.return_value = mock_pipeline + + tracker = MagicMock() + tracker.handle_confirmed.return_value = { + "status": "confirmed", + "consensus_reached": True, + } + + msg_store = MagicMock() + msg_store.get_messages.return_value = [] + + with ( + app.app_context(), + patch("routes.signals._resolve_pipeline_phase", return_value="implement"), + patch("routes.signals._write_consensus_confirmed_marker"), + patch("routes.signals.get_state_store", return_value=mock_store), + patch("peer_consensus.get_peer_consensus_tracker", return_value=tracker), + patch("message_store.get_message_store", return_value=msg_store), + ): + from routes.signals import handle_consensus_confirmed_signal + + response, status_code = handle_consensus_confirmed_signal( + "issue-42", {"agent_role": "coder"}, Path("/tmp/repo") + ) + + assert status_code == 200 + msg_store.add_message.assert_called_once() + + +def test_pending_acks_path_is_idempotent(app, mock_pipeline): + """Repeated pending_acks invocations don't write duplicates.""" + mock_store = MagicMock() + mock_store.load_pipeline.return_value = mock_pipeline + + tracker = MagicMock() + tracker.handle_confirmed.return_value = { + "status": "pending_acks", + "message": "waiting for re-ACKs", + } + + msg_store = MagicMock() + msg_store.get_messages.return_value = [ + _fake_message("architect", "plan", pending_acks=True), + ] + + with ( + app.app_context(), + patch("routes.signals._resolve_pipeline_phase", return_value="plan"), + patch("routes.signals._write_consensus_confirmed_marker"), + patch("routes.signals.get_state_store", return_value=mock_store), + patch("peer_consensus.get_peer_consensus_tracker", return_value=tracker), + patch("message_store.get_message_store", return_value=msg_store), + ): + from routes.signals import handle_consensus_confirmed_signal + + response, status_code = handle_consensus_confirmed_signal( + "issue-42", {"agent_role": "architect"}, Path("/tmp/repo") + ) + + assert status_code == 202 + msg_store.add_message.assert_not_called() + + +def test_pending_to_final_transition_still_writes(app, mock_pipeline): + """Transition from pending_acks to final CONFIRMED still records a message.""" + mock_store = MagicMock() + mock_store.load_pipeline.return_value = mock_pipeline + + tracker = MagicMock() + tracker.handle_confirmed.return_value = { + "status": "confirmed", + "consensus_reached": True, + } + + msg_store = MagicMock() + # Only a pending_acks exists — the role hasn't emitted a final yet. + msg_store.get_messages.return_value = [ + _fake_message("architect", "plan", pending_acks=True), + ] + + with ( + app.app_context(), + patch("routes.signals._resolve_pipeline_phase", return_value="plan"), + patch("routes.signals._write_consensus_confirmed_marker"), + patch("routes.signals.get_state_store", return_value=mock_store), + patch("peer_consensus.get_peer_consensus_tracker", return_value=tracker), + patch("message_store.get_message_store", return_value=msg_store), + ): + from routes.signals import handle_consensus_confirmed_signal + + response, status_code = handle_consensus_confirmed_signal( + "issue-42", {"agent_role": "architect"}, Path("/tmp/repo") + ) + + assert status_code == 200 + msg_store.add_message.assert_called_once() diff --git a/orchestrator/tests/test_contract_decision_bridge.py b/orchestrator/tests/test_contract_decision_bridge.py new file mode 100644 index 0000000000..11d0036d2d --- /dev/null +++ b/orchestrator/tests/test_contract_decision_bridge.py @@ -0,0 +1,255 @@ +"""Tests for the contract-decision bridge at phase_gate approval. + +When an agent registers questions via ``egg-contract add-decision`` / +``egg-contract add-feedback`` during refine/plan, those entries live only +in the contract JSON — the orchestrator's decision queue is blind to +them. ``_queue_and_await_contract_decisions`` promotes those contract +questions to orchestrator decisions after phase_gate approval so HTTP/MCP +callers surface them individually. + +See: https://github.com/jwbron/egg/issues/1889 +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +from models import DecisionStatus, HITLDecision, PipelinePhase + + +def _make_contract_file( + repo: Path, + identifier: str, + *, + decisions: list[dict[str, Any]] | None = None, + feedback: dict[str, Any] | None = None, +) -> Path: + """Write a minimal valid contract JSON for tests.""" + contracts_dir = repo / ".egg-state" / "contracts" + contracts_dir.mkdir(parents=True, exist_ok=True) + payload: dict[str, Any] = { + "schema_version": "1.0", + "pipeline_id": identifier, + "issue": {"number": 42, "title": "t", "body": "b", "url": "https://example/42"}, + "pr": None, + "branch": "egg/test", + "current_phase": "refine", + "phases": [], + "decisions": decisions or [], + "feedback": feedback, + "audit_log": [], + "agent_executions": [], + } + path = contracts_dir / f"{identifier}.json" + path.write_text(json.dumps(payload)) + return path + + +class _FakeQueue: + """Minimal stand-in for DecisionQueue used in tests. + + Auto-resolves every queued decision with a caller-provided resolution, + mirroring the shape of DecisionQueue.queue_decision / wait_for_decision. + """ + + def __init__(self, resolutions: list[str]) -> None: + self._resolutions = list(resolutions) + self.queued: list[HITLDecision] = [] + self._counter = 0 + + def queue_decision( + self, + question: str, + context: str = "", + options: list[str] | None = None, + decision_type: str = "choice", + questions: list[dict[str, str]] | None = None, + phase: PipelinePhase | None = None, + content_changed: bool | None = None, + ) -> HITLDecision: + self._counter += 1 + resolution = self._resolutions.pop(0) if self._resolutions else "" + decision = HITLDecision( + id=f"orch-{self._counter}", + question=question, + context=context, + options=options or [], + decision_type=decision_type, # type: ignore[arg-type] + questions=questions or [], + phase=phase, + status=DecisionStatus.RESOLVED, + resolution=resolution, + ) + self.queued.append(decision) + return decision + + def wait_for_decision(self, decision_id: str) -> HITLDecision: + for d in self.queued: + if d.id == decision_id: + return d + raise AssertionError(f"decision {decision_id} not queued") + + +def test_bridge_promotes_unresolved_hitl_decisions(tmp_path: Path) -> None: + from routes.pipelines import _queue_and_await_contract_decisions + + identifier = "issue-42" + _make_contract_file( + tmp_path, + identifier, + decisions=[ + { + "id": "decision-1", + "question": "Which database?", + "type": "hitl", + "phase": "refine", + "options": [ + {"id": "opt-1", "label": "Postgres", "description": None}, + {"id": "opt-2", "label": "SQLite", "description": None}, + ], + "resolved": False, + "resolution": None, + "resolved_by": None, + "resolved_at": None, + "debounce_until": None, + }, + { + "id": "decision-2", + "question": "Already answered", + "type": "hitl", + "phase": "refine", + "options": [], + "resolved": True, + "resolution": "done", + "resolved_by": "human", + "resolved_at": "2026-04-01T00:00:00+00:00", + "debounce_until": None, + }, + ], + ) + dq = _FakeQueue(resolutions=["Postgres"]) + + _queue_and_await_contract_decisions( + dq, + tmp_path, + "pipeline-id", + identifier, + PipelinePhase.REFINE, + ) + + # Exactly one promotion — the already-resolved one is skipped. + assert len(dq.queued) == 1 + assert dq.queued[0].question == "Which database?" + assert dq.queued[0].options == ["Postgres", "SQLite"] + assert dq.queued[0].decision_type == "choice" + + data = json.loads((tmp_path / ".egg-state/contracts/issue-42.json").read_text()) + decision_1 = next(d for d in data["decisions"] if d["id"] == "decision-1") + assert decision_1["resolved"] is True + assert decision_1["resolution"] == "Postgres" + assert decision_1["resolved_by"] == "human" + assert decision_1["resolved_at"] is not None + + +def test_bridge_promotes_unsubmitted_feedback(tmp_path: Path) -> None: + from routes.pipelines import _queue_and_await_contract_decisions + + identifier = "issue-42" + _make_contract_file( + tmp_path, + identifier, + feedback={ + "id": "feedback-1", + "phase": "refine", + "questions": [ + {"id": "Q1", "question": "What volume?", "answer": None}, + {"id": "Q2", "question": "Legacy support?", "answer": None}, + ], + "submitted": False, + "submitted_by": None, + "submitted_at": None, + "comment_id": None, + "debounce_until": None, + }, + ) + dq = _FakeQueue( + resolutions=[ + json.dumps( + { + "action": "submit_feedback", + "answers": {"Q1": "~10 RPS", "Q2": "no"}, + } + ) + ] + ) + + _queue_and_await_contract_decisions( + dq, + tmp_path, + "pipeline-id", + identifier, + PipelinePhase.REFINE, + ) + + assert len(dq.queued) == 1 + assert dq.queued[0].decision_type == "feedback" + assert {q["id"] for q in dq.queued[0].questions} == {"Q1", "Q2"} + + data = json.loads((tmp_path / ".egg-state/contracts/issue-42.json").read_text()) + fb = data["feedback"] + assert fb["submitted"] is True + assert fb["submitted_by"] == "human" + answers = {q["id"]: q["answer"] for q in fb["questions"]} + assert answers == {"Q1": "~10 RPS", "Q2": "no"} + + +def test_bridge_skips_decisions_for_other_phases(tmp_path: Path) -> None: + from routes.pipelines import _queue_and_await_contract_decisions + + identifier = "issue-42" + _make_contract_file( + tmp_path, + identifier, + decisions=[ + { + "id": "decision-1", + "question": "For plan phase only", + "type": "hitl", + "phase": "plan", + "options": [], + "resolved": False, + "resolution": None, + "resolved_by": None, + "resolved_at": None, + "debounce_until": None, + } + ], + ) + dq = _FakeQueue(resolutions=[]) + + _queue_and_await_contract_decisions( + dq, + tmp_path, + "pipeline-id", + identifier, + PipelinePhase.REFINE, + ) + + # A plan-scoped decision must not be surfaced at the refine phase_gate. + assert dq.queued == [] + + +def test_bridge_is_noop_when_contract_missing(tmp_path: Path) -> None: + from routes.pipelines import _queue_and_await_contract_decisions + + dq = _FakeQueue(resolutions=[]) + _queue_and_await_contract_decisions( + dq, + tmp_path, + "pipeline-id", + "issue-999", + PipelinePhase.REFINE, + ) + assert dq.queued == [] From eafe8b89b5e3ce819d597c0fc66040ca4f28a457 Mon Sep 17 00:00:00 2001 From: "egg-reviewer[bot]" <261018737+egg-reviewer[bot]@users.noreply.github.com> Date: Wed, 22 Apr 2026 22:53:45 +0000 Subject: [PATCH 2/2] Address review feedback: filter contract decisions by type=hitl, harden feedback persistence MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add type==hitl filter to pending_decisions so AUTO decisions are never promoted as human choice decisions (blocking review feedback). - Mark feedback as submitted even when the resolution JSON doesn't match the expected {answers: {...}} structure — the human responded and shouldn't be asked again. - Add clarifying comments on the 10k message limit tradeoff and phase-null matching behavior in _existing_confirmed_for_role. - Add two new tests: test_bridge_skips_auto_decisions and test_bridge_marks_feedback_submitted_on_unparseable_resolution. --- orchestrator/routes/pipelines.py | 40 +++++----- orchestrator/routes/signals.py | 9 +++ .../tests/test_contract_decision_bridge.py | 79 +++++++++++++++++++ 3 files changed, 110 insertions(+), 18 deletions(-) diff --git a/orchestrator/routes/pipelines.py b/orchestrator/routes/pipelines.py index 21ddc9a3fd..d4deb09e3d 100644 --- a/orchestrator/routes/pipelines.py +++ b/orchestrator/routes/pipelines.py @@ -8792,7 +8792,9 @@ def _queue_and_await_contract_decisions( pending_decisions = [ d for d in contract.decisions - if not d.resolved and (d.phase is None or getattr(d.phase, "value", d.phase) == phase_value) + if not d.resolved + and getattr(d.type, "value", d.type) == "hitl" + and (d.phase is None or getattr(d.phase, "value", d.phase) == phase_value) ] fb = contract.feedback pending_feedback = None @@ -8891,23 +8893,25 @@ def _apply( except (json.JSONDecodeError, TypeError): pass - if answers: - fb_id = pending_feedback.id - - def _apply_fb( - latest: Any, _fb_id: str = fb_id, _answers: dict[str, str] = answers - ) -> bool: - if latest.feedback is None or latest.feedback.id != _fb_id: - return False - for q in latest.feedback.questions: - if q.id in _answers: - q.answer = _answers[q.id] - latest.feedback.submitted = True - latest.feedback.submitted_by = "human" - latest.feedback.submitted_at = datetime.now(UTC) - return True - - _save_contract_update(_apply_fb) + fb_id = pending_feedback.id + + def _apply_fb( + latest: Any, _fb_id: str = fb_id, _answers: dict[str, str] = answers + ) -> bool: + if latest.feedback is None or latest.feedback.id != _fb_id: + return False + for q in latest.feedback.questions: + if q.id in _answers: + q.answer = _answers[q.id] + # Always mark submitted after resolution — even if + # individual answers didn't parse, the human responded + # and shouldn't be asked again. + latest.feedback.submitted = True + latest.feedback.submitted_by = "human" + latest.feedback.submitted_at = datetime.now(UTC) + return True + + _save_contract_update(_apply_fb) def _persist_phase_gate_resolution( diff --git a/orchestrator/routes/signals.py b/orchestrator/routes/signals.py index 79cd5eb260..ac30745540 100644 --- a/orchestrator/routes/signals.py +++ b/orchestrator/routes/signals.py @@ -1263,6 +1263,11 @@ def _existing_confirmed_for_role( try: store = get_message_store() + # Fetch a generous window of recent messages. get_messages returns + # the *newest* N, so an extremely old CONFIRMED in a >10k-message + # pipeline could be missed — but that's the safe failure direction + # (a duplicate write, not a lost write). Don't lower this limit + # without understanding that tradeoff. messages = store.get_messages(pipeline_id, limit=10000) except Exception: return (False, False) @@ -1275,6 +1280,10 @@ def _existing_confirmed_for_role( if str(getattr(m, "message_type", "")) != "CONSENSUS_CONFIRMED": continue msg_phase = getattr(m, "phase", None) + # A null msg_phase is treated as matching any phase. In practice + # all CONSENSUS_CONFIRMED writes set a phase, but if one somehow + # doesn't, counting it as a match is the conservative choice + # (prevents a duplicate rather than allowing one). if phase is not None and msg_phase is not None and msg_phase != phase: continue metadata = getattr(m, "metadata", None) or {} diff --git a/orchestrator/tests/test_contract_decision_bridge.py b/orchestrator/tests/test_contract_decision_bridge.py index 11d0036d2d..7f05601e42 100644 --- a/orchestrator/tests/test_contract_decision_bridge.py +++ b/orchestrator/tests/test_contract_decision_bridge.py @@ -241,6 +241,85 @@ def test_bridge_skips_decisions_for_other_phases(tmp_path: Path) -> None: assert dq.queued == [] +def test_bridge_skips_auto_decisions(tmp_path: Path) -> None: + """AUTO decisions must not be promoted — only HITL ones.""" + from routes.pipelines import _queue_and_await_contract_decisions + + identifier = "issue-42" + _make_contract_file( + tmp_path, + identifier, + decisions=[ + { + "id": "decision-auto", + "question": "Auto-resolved question", + "type": "auto", + "phase": "refine", + "options": [], + "resolved": False, + "resolution": None, + "resolved_by": None, + "resolved_at": None, + "debounce_until": None, + }, + ], + ) + dq = _FakeQueue(resolutions=[]) + + _queue_and_await_contract_decisions( + dq, + tmp_path, + "pipeline-id", + identifier, + PipelinePhase.REFINE, + ) + + # AUTO decisions must not be surfaced as human choice decisions. + assert dq.queued == [] + + +def test_bridge_marks_feedback_submitted_on_unparseable_resolution(tmp_path: Path) -> None: + """Feedback is marked submitted even when the resolution JSON doesn't parse.""" + from routes.pipelines import _queue_and_await_contract_decisions + + identifier = "issue-42" + _make_contract_file( + tmp_path, + identifier, + feedback={ + "id": "feedback-1", + "phase": "refine", + "questions": [ + {"id": "Q1", "question": "What volume?", "answer": None}, + ], + "submitted": False, + "submitted_by": None, + "submitted_at": None, + "comment_id": None, + "debounce_until": None, + }, + ) + # Resolution is a plain string, not the expected {"answers": {...}} JSON. + dq = _FakeQueue(resolutions=["just a freeform string"]) + + _queue_and_await_contract_decisions( + dq, + tmp_path, + "pipeline-id", + identifier, + PipelinePhase.REFINE, + ) + + data = json.loads((tmp_path / ".egg-state/contracts/issue-42.json").read_text()) + fb = data["feedback"] + # Feedback must be marked submitted even though answers didn't parse — + # the human responded and shouldn't be asked again. + assert fb["submitted"] is True + assert fb["submitted_by"] == "human" + # Individual question answers remain None since the format didn't match. + assert fb["questions"][0]["answer"] is None + + def test_bridge_is_noop_when_contract_missing(tmp_path: Path) -> None: from routes.pipelines import _queue_and_await_contract_decisions