Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
144 changes: 141 additions & 3 deletions orchestrator/routes/signals.py
Original file line number Diff line number Diff line change
Expand Up @@ -1086,6 +1086,122 @@ def _validate_planner_role_alignment(
)


def _validate_producer_draft_present(
phase: str,
pipeline_id: str,
payload: dict[str, Any],
repo_path: Path,
*,
pipeline_state: Any | None = None,
worktree_path: Path | None = None,
) -> None:
"""Reject a producer proposal whose canonical phase draft is absent at the
proposed commit (#3016).

The refine/plan operator gate, the contract populator, and the resume path all
read the phase artifact from the canonical
``.egg-state/drafts/{prefix}-{analysis|plan}.md`` path (``_get_draft_path``). A
producer that commits its draft to some other path — or not at all — still
reaches BRC consensus and completes the phase; only later does the gate report
"No <analysis|plan> draft was found on the work branch", a silent
deterministic-input failure. (Observed: a refiner that committed
``.egg-state/agent-outputs/refiner-refine.md`` — a path no code reads — instead
of ``.egg-state/drafts/<n>-analysis.md``.)

refine and plan are always concurrent, so the producer always issues
``consensus_propose``. Validating here — before ``handle_propose`` records the
proposal — turns a missing draft into a 400 the producer (still alive) can fix by
re-proposing with the draft at the right path, instead of the failure surfacing a
phase later. The caller's ``except`` block maps the raised ``ValueError`` to a
400, so no reviewer cycle is wasted on a structurally-broken proposal.

Existence-only by design. Format/template conformance is intentionally *not*
enforced here — that would risk false-rejecting a legitimate-but-differently-
structured draft (see #3016 / #3017); the gate and reviewers remain the content
backstop.

Graceful degradation: when the proposal carries no commit SHA, the pipeline has
no branch, the draft path can't be derived, or ``git show`` errors for an
infrastructure reason (timeout / git failure), this returns silently. It raises
only when it can positively confirm the draft is absent (or empty) at a resolved,
branch-verified commit — ``handle_consensus_propose_signal`` has already run
``_verify_commit_on_branch`` (which fetches the commit), so a non-zero ``git
show`` here reliably means "path absent at commit", not "commit unknown".

``pipeline_state`` / ``worktree_path`` are threaded in by
``handle_consensus_propose_signal`` to reuse the lookups it already performed for
``_verify_commit_on_branch``; the function loads them itself when called directly
(e.g. from unit tests).
"""
commit_sha = (payload.get("commit_sha") or "").strip()
if not commit_sha:
return

if pipeline_state is None:
try:
pipeline_state = get_state_store(repo_path).load_pipeline(pipeline_id)
except StateStoreError:
return

if not pipeline_state.branch:
return

# Lazy import to avoid pulling the ~21k-line ``routes.pipelines`` module into
# ``signals`` import time (matches ``_validate_planner_role_alignment``).
try:
from routes.pipelines import _get_draft_path
except ImportError:
try:
from .pipelines import _get_draft_path # type: ignore[no-redef]
except ImportError:
return

draft_rel = _get_draft_path(
phase,
issue_number=pipeline_state.issue_number,
pipeline_id=pipeline_id,
)
if not draft_rel:
return

if worktree_path is None:
worktree_path = resolve_worktree_path(pipeline_id, repo_path)

# Read the draft as committed at the proposed SHA, not from the working tree
# (which can lag HEAD — see #2723). The preceding ``_verify_commit_on_branch``
# already fetched the commit, so it is reachable in the worktree.
try:
result = subprocess.run(
["git", "-C", str(worktree_path), "show", f"{commit_sha}:{draft_rel}"],
capture_output=True,
text=True,
timeout=15,
check=False,
)
except Exception as exc:
logger.warning(
"producer draft presence check: git show failed (non-blocking)",
pipeline_id=pipeline_id,
phase=phase,
commit_sha=commit_sha,
error=str(exc),
)
return

if result.returncode == 0 and result.stdout.strip():
return # Draft present and non-empty — nothing to reject.

label = "analysis" if phase == "refine" else phase
raise ValueError(
f"{phase.capitalize()} proposal rejected: no {label} draft found at "
f"`{draft_rel}` in the proposed commit ({commit_sha[:8]}). The phase gate, "
f"contract population, and resume all read the {label} from this exact path "
f"— a draft committed to a different path (or an empty one) is invisible to "
f"them. Write your {label} to `{draft_rel}`, commit and push it, then "
f"re-propose."
)


def _resolve_pipeline_phase(pipeline_id: str, repo_path: Path) -> str:
"""Resolve the current phase for a pipeline, with graceful fallback.

Expand Down Expand Up @@ -1284,10 +1400,32 @@ def handle_consensus_propose_signal(
# rejected proposals.
if agent_role == "tester":
_validate_tester_check_coverage(pipeline_id, payload, repo_path)
# Validate task_planner proposals don't misassign tasks to roles
# whose blocklist forbids their files (#2527). Same placement
# rule: BEFORE handle_propose so the tracker isn't mutated.
# Reject a refine producer whose analysis draft is missing at the
# canonical path the gate reads — before handle_propose records it, so
# the gate can't later false-negative on a draft committed off-path
# (#3016). Same placement rule: BEFORE handle_propose.
elif agent_role == "refiner":
_validate_producer_draft_present(
"refine",
pipeline_id,
payload,
repo_path,
pipeline_state=pipeline_state,
worktree_path=worktree_path,
)
# Validate task_planner proposals: (a) the plan draft is present at the
# canonical path (#3016 — same deterministic-input guard as refine), and
# (b) no task is misassigned to a role whose blocklist forbids its files
# (#2527). Both run BEFORE handle_propose so the tracker isn't mutated.
elif agent_role == "task_planner":
_validate_producer_draft_present(
"plan",
pipeline_id,
payload,
repo_path,
pipeline_state=pipeline_state,
worktree_path=worktree_path,
)
_validate_planner_role_alignment(
pipeline_id,
payload,
Expand Down
198 changes: 195 additions & 3 deletions orchestrator/tests/test_pipeline_prompts.py
Original file line number Diff line number Diff line change
Expand Up @@ -2383,11 +2383,15 @@ def test_rejected_proposal_does_not_mutate_tracker(self):
mock_tracker = MagicMock()
mock_tracker.handle_propose = MagicMock(return_value={"version": 1})

# Two subprocess calls happen in this path:
# Four subprocess calls happen in this path (task_planner):
# 1. _verify_commit_on_branch's git fetch
# 2. _verify_commit_on_branch's git branch --contains
# 3. _validate_planner_role_alignment's git show
# The first two return success; the third returns the misassigned plan.
# 3. _validate_producer_draft_present's git show (#3016) — plan
# present at the commit, so the presence guard passes
# 4. _validate_planner_role_alignment's git show — returns the
# misassigned plan, so the alignment guard raises
# The first two return success; calls 3 and 4 both read the plan draft
# at the proposed commit, so both return the (misassigned) plan.
side_effect = [
subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr=""),
subprocess.CompletedProcess(
Expand All @@ -2402,6 +2406,12 @@ def test_rejected_proposal_does_not_mutate_tracker(self):
stdout=self._PLAN_WITH_MISASSIGNED_TASK,
stderr="",
),
subprocess.CompletedProcess(
args=[],
returncode=0,
stdout=self._PLAN_WITH_MISASSIGNED_TASK,
stderr="",
),
]

app = Flask(__name__)
Expand Down Expand Up @@ -2438,6 +2448,188 @@ def test_rejected_proposal_does_not_mutate_tracker(self):
mock_tracker.handle_propose.assert_not_called()


class TestProducerDraftPresentValidation:
"""Tests for ``_validate_producer_draft_present`` in ``signals.py`` (#3016).

A refine/plan producer that commits its draft to a non-canonical path (or not
at all) used to reach BRC consensus and complete the phase, after which the
operator gate — which reads ``.egg-state/drafts/{prefix}-{analysis|plan}.md``
via ``_get_draft_path`` — reported "No <analysis|plan> draft was found". This
validator runs at ``CONSENSUS_PROPOSE`` (always issued in concurrent refine/
plan), reads the draft at the proposed commit via ``git show``, and rejects
(400) when it is absent so the still-alive producer re-proposes with the draft
at the right path.
"""

@staticmethod
def _patched_store(issue_number: int | None = 3016, branch: str = "egg/issue-3016"):
mock_pipeline = MagicMock()
mock_pipeline.issue_number = issue_number
mock_pipeline.branch = branch
mock_pipeline.mode = None
mock_store = MagicMock()
mock_store.load_pipeline.return_value = mock_pipeline
return patch("routes.signals.get_state_store", return_value=mock_store)

@staticmethod
def _patched_subprocess(stdout: str, returncode: int = 0):
result = subprocess.CompletedProcess(
args=[], returncode=returncode, stdout=stdout, stderr=""
)
return patch("routes.signals.subprocess.run", return_value=result)

@staticmethod
def _patched_worktree():
return patch("routes.signals.resolve_worktree_path", return_value=Path("/tmp/wt"))

def test_skips_when_commit_sha_missing(self):
"""No commit SHA on payload → nothing to validate against."""
from routes.signals import _validate_producer_draft_present

# No other patches needed — the bail-out happens before any git access.
_validate_producer_draft_present("refine", "issue-3016", {}, Path("/tmp"))
_validate_producer_draft_present("refine", "issue-3016", {"commit_sha": ""}, Path("/tmp"))

def test_accepts_when_refine_draft_present(self):
"""Analysis draft present and non-empty at the proposed commit → no raise."""
from routes.signals import _validate_producer_draft_present

with (
self._patched_store(),
self._patched_worktree(),
self._patched_subprocess("# Analysis: something real\n\n## Problem\n..."),
):
_validate_producer_draft_present(
"refine", "issue-3016", {"commit_sha": "abc1234"}, Path("/tmp/repo")
)

def test_rejects_when_refine_draft_absent(self):
"""``git show`` non-zero (analysis draft absent at commit) → raises."""
from routes.signals import _validate_producer_draft_present

with (
self._patched_store(),
self._patched_worktree(),
self._patched_subprocess("", returncode=128),
):
with pytest.raises(ValueError, match="no analysis draft found"):
_validate_producer_draft_present(
"refine", "issue-3016", {"commit_sha": "abc1234"}, Path("/tmp/repo")
)

def test_rejects_when_refine_draft_empty(self):
"""Draft exists but is empty/whitespace-only → still rejected."""
from routes.signals import _validate_producer_draft_present

with (
self._patched_store(),
self._patched_worktree(),
self._patched_subprocess(" \n \n"),
):
with pytest.raises(ValueError, match="no analysis draft found"):
_validate_producer_draft_present(
"refine", "issue-3016", {"commit_sha": "abc1234"}, Path("/tmp/repo")
)

def test_rejects_when_plan_draft_absent_names_plan_path(self):
"""Plan-phase rejection names the plan draft, not analysis."""
from routes.signals import _validate_producer_draft_present

with (
self._patched_store(),
self._patched_worktree(),
self._patched_subprocess("", returncode=128),
):
with pytest.raises(ValueError, match=r"no plan draft found.*-plan\.md"):
_validate_producer_draft_present(
"plan", "issue-3016", {"commit_sha": "abc1234"}, Path("/tmp/repo")
)

def test_skips_when_git_show_errors(self):
"""A git/infra failure (not a clean non-zero exit) → graceful skip.

Distinguishes infrastructure failure (don't false-reject) from a
definitive absent-at-commit signal (a clean non-zero return, which the
``test_rejects_*`` cases cover).
"""
from routes.signals import _validate_producer_draft_present

with (
self._patched_store(),
self._patched_worktree(),
patch(
"routes.signals.subprocess.run",
side_effect=subprocess.TimeoutExpired(cmd="git", timeout=15),
),
):
# Should not raise — infra failures degrade gracefully.
_validate_producer_draft_present(
"refine", "issue-3016", {"commit_sha": "abc1234"}, Path("/tmp/repo")
)

def test_skips_when_pipeline_has_no_branch(self):
"""A pipeline with ``branch=None`` → graceful skip (no git context)."""
from routes.signals import _validate_producer_draft_present

with (
self._patched_store(branch=None),
self._patched_worktree(),
):
_validate_producer_draft_present(
"refine", "issue-3016", {"commit_sha": "abc1234"}, Path("/tmp/repo")
)

def test_refiner_proposal_rejected_when_analysis_missing_does_not_mutate_tracker(self):
"""End-to-end: a refiner proposal whose analysis draft is missing at the
proposed commit is rejected at ``handle_consensus_propose_signal`` with a
400 BEFORE the tracker is mutated (mirrors the planner guarantee #2527).
"""
from flask import Flask
from routes.signals import handle_consensus_propose_signal

mock_tracker = MagicMock()
mock_tracker.handle_propose = MagicMock(return_value={"version": 1})

# Three subprocess calls in the refiner path:
# 1. _verify_commit_on_branch's git fetch
# 2. _verify_commit_on_branch's git branch --contains
# 3. _validate_producer_draft_present's git show — non-zero (absent)
side_effect = [
subprocess.CompletedProcess(args=[], returncode=0, stdout="", stderr=""),
subprocess.CompletedProcess(
args=[], returncode=0, stdout=" origin/egg/issue-3016\n", stderr=""
),
subprocess.CompletedProcess(args=[], returncode=128, stdout="", stderr=""),
]

app = Flask(__name__)
with (
app.app_context(),
self._patched_store(),
self._patched_worktree(),
patch("routes.signals.subprocess.run", side_effect=side_effect),
patch("peer_consensus.get_peer_consensus_tracker", return_value=mock_tracker),
):
data = {
"agent_role": "refiner",
"payload": {
"summary": (
"Analysis v1: evaluated three options for the deterministic "
"draft-path guard and recommended option A"
),
"artifacts": [".egg-state/agent-outputs/refiner-refine.md"],
"commit_sha": "abc1234",
},
}
response, status_code = handle_consensus_propose_signal(
"issue-3016", data, Path("/tmp/repo")
)
assert status_code == 400
data_out = response.get_json()
assert "no analysis draft found" in data_out.get("message", "")
mock_tracker.handle_propose.assert_not_called()


class TestReadTesterGapsNamespacedEdgeCases:
"""Additional edge-case tests for _read_tester_gaps with identifier."""

Expand Down
Loading