Fix: Make main_pm + task_type=code impossible

This commit is contained in:
Renn F
2026-06-27 19:52:01 +02:00
parent 5b931c367f
commit e202ce397d
17 changed files with 1439 additions and 33 deletions
+28
View File
@@ -711,6 +711,34 @@ def test_run_all_validators_raises_on_unknown_intent_action(
_validate.run_all_lifecycle_validators()
def test_next_hint_pr_fail_main_pm_root_steers_to_redelegate() -> None:
"""A ``pr_fail`` on a Main-PM branch-bearing root must steer the Main PM to
re-delegate the fixes, NOT re-submit the unchanged root. The root is an
assembled cell→root / root→master PR — coordination, not the Main PM's own
code — so re-submitting it is the 2026-06-27 infinite ``pr_fail`` loop."""
t = SimpleNamespace(team=spec.Team.MAIN_PM, branch_name="feature/main_pm/c80e19ff")
hint = _INTENT_VERBS["pr_fail"].next_hint(t)
assert "re-delegate" in hint
assert "do NOT re-submit" in hint
def test_next_hint_pr_fail_cell_dev_keeps_dev_revise() -> None:
"""A cell / dev task is revised in place by its dev, so ``pr_fail`` keeps the
dev-revise hint (the cell→root PR carries that dev's own code)."""
t = SimpleNamespace(team=spec.Team.BACKEND, branch_name="feature/backend/abc12345")
hint = _INTENT_VERBS["pr_fail"].next_hint(t)
assert hint == "idle - dev will revise and re-submit"
def test_next_hint_pr_fail_branchless_main_pm_keeps_dev_revise() -> None:
"""A branchless Main-PM umbrella (no ``branch_name``) assembles no PR of its
own, so the gate never lands a ``pr_fail`` on it — but defensively it keeps
the dev-revise hint rather than the re-delegate steer."""
t = SimpleNamespace(team=spec.Team.MAIN_PM, branch_name=None)
hint = _INTENT_VERBS["pr_fail"].next_hint(t)
assert hint == "idle - dev will revise and re-submit"
def test_unmigrated_is_pinned() -> None:
"""The known-debt set; remove an entry once that consumer is migrated."""
assert (
@@ -206,6 +206,49 @@ def test_findings_single_dict_coerced_to_list() -> None:
assert len(c.findings) == 1
def test_pr_review_issues_carry_free_text_change_requests() -> None:
# The in-path gate fails on free-text issues (not structured Finding
# objects, which require file/severity/expected/actual). Those issues now
# land in the additive `issues` slot instead of being flattened into the
# summary string alone — so a reader of notes_structured.pr_review gets the
# concrete change-requests, and the rendered TEXT mirror gains an Issues
# section.
c = validate_content(
"pr_review",
{
"summary": "PR review needs changes before this can merge.",
"verdict": "changes_requested",
"issues": ["seam mismatch on the rebase path", "docs lag the diff"],
},
)
assert isinstance(c, PrReviewContent)
assert c.issues == ["seam mismatch on the rebase path", "docs lag the diff"]
rendered = c.render_markdown()
assert "## Issues" in rendered
assert "seam mismatch on the rebase path" in rendered
assert "docs lag the diff" in rendered
def test_pr_review_issues_default_empty_and_single_scalar_coerced() -> None:
c = validate_content(
"pr_review",
{"summary": "Clean PR, no free-text issues to raise.", "verdict": "approved"},
)
assert isinstance(c, PrReviewContent)
assert c.issues == []
assert "## Issues" not in c.render_markdown()
coerced = validate_content(
"pr_review",
{
"summary": "One free-text issue passed as a bare string here.",
"verdict": "changes_requested",
"issues": "lone issue string",
},
)
assert coerced.issues == ["lone issue string"]
def test_where_to_look_single_string_coerced() -> None:
c = validate_content(
"resumption",
@@ -10,7 +10,9 @@ from roboco.foundation.policy.batch import (
is_batch_umbrella,
is_branchless_coordination,
is_valid_batch_shape,
main_pm_cannot_own_code,
)
from roboco.models.base import TaskType, Team
def test_umbrella_is_batch_id_set_and_top_level() -> None:
@@ -163,3 +165,27 @@ def test_valid_batch_shape_denies_cell_map_alongside_another_target() -> None:
product_id=uuid4(),
has_cell_projects=True,
)
def test_main_pm_cannot_own_code_predicate() -> None:
"""``main_pm`` + ``code`` must never coexist — the single invariant behind
the intake coercion, the create backstop, the reassign/escalation diversion,
and the claim guard. Accepts ORM enums or their .value strings."""
# The forbidden combo, in both enum and string form.
assert main_pm_cannot_own_code(team=Team.MAIN_PM, task_type=TaskType.CODE)
assert main_pm_cannot_own_code(
team=Team.MAIN_PM.value, task_type=TaskType.CODE.value
)
# A Main PM coordinating (planning / research / etc.) is fine.
assert not main_pm_cannot_own_code(team=Team.MAIN_PM, task_type=TaskType.PLANNING)
assert not main_pm_cannot_own_code(team=Team.MAIN_PM, task_type=TaskType.RESEARCH)
assert not main_pm_cannot_own_code(
team=Team.MAIN_PM, task_type=TaskType.DOCUMENTATION
)
# Code owned by any non-main_pm team (a cell dev, the board pre-approval) is fine.
assert not main_pm_cannot_own_code(team=Team.BACKEND, task_type=TaskType.CODE)
assert not main_pm_cannot_own_code(team=Team.FRONTEND, task_type=TaskType.CODE)
assert not main_pm_cannot_own_code(team=Team.BOARD, task_type=TaskType.CODE)
# Missing team or type cannot satisfy the invariant.
assert not main_pm_cannot_own_code(team=None, task_type=TaskType.CODE)
assert not main_pm_cannot_own_code(team=Team.MAIN_PM, task_type=None)
@@ -0,0 +1,232 @@
"""pr_fail delivers its change-requests to the owning PM, not just to GitHub.
The in-path ``pr_fail`` gate persists the reviewer's verdict to
``notes_structured.pr_review`` and posts it on the assembled PR — but historically
never pushed the concrete issues to any channel the owning PM reads (no a2a,
and ``_briefing_for`` / ``build_task_handoff`` read neither ``pr_reviewer_notes``
nor ``notes_structured.pr_review``). So the cell PM respawned into
``needs_revision`` saw a generic "needs revision" with zero actionable issues,
concluded there was nothing to rework, and re-submitted the same PR — an
infinite ``pr_fail`` loop (observed live on coordination root 9980d0a0 / PR #138).
The fix mirrors QA's ``fail_review`` a2a to the dev (qa.py:671-678): on
``pr_fail`` the gate now sends an a2a to the owner the runner just re-assigned
(the cell PM, via ``_revision_pm_for_task``) carrying the issues, so the PM
"knows" and can ``delegate`` a rework subtask or action the change-requests
directly. ``pr_pass`` is unaffected.
"""
from __future__ import annotations
from typing import Any
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from roboco.foundation.policy import lifecycle as spec_module
from roboco.services.gateway.choreographer import Choreographer, ChoreographerDeps
def _make_choreographer() -> Choreographer:
base: dict[str, Any] = {
"task": AsyncMock(),
"work_session": AsyncMock(),
"git": AsyncMock(),
"a2a": AsyncMock(),
"journal": AsyncMock(),
"audit": AsyncMock(),
"evidence_repo": AsyncMock(),
}
return Choreographer(ChoreographerDeps(**base))
def _stub_gate_path(
c: Choreographer,
*,
reviewer_id: Any,
t_before: Any,
t_after: Any,
) -> None:
"""Drive ``_gate_decision`` past preflight/tracing/post and into the new
a2a step without exercising the heavy ownership/tracing logic (those have
their own tests). The runner rebinding to ``t_after`` is what simulates the
PM re-assignment the real ``_revision_pm_for_task`` performs.
"""
agent = MagicMock(role="pr_reviewer", slug="be-pr-reviewer")
c._gate_preflight = AsyncMock( # type: ignore[method-assign]
return_value=(
t_before,
agent,
"pr_reviewer",
{},
spec_module.Context(actor_id=reviewer_id),
)
)
c._gate_tracing = AsyncMock(return_value=None) # type: ignore[method-assign]
c._record_gate_verdict = MagicMock() # type: ignore[method-assign]
c._post_gate_review_to_pr = AsyncMock() # type: ignore[method-assign]
runner = MagicMock()
runner.run_intent = AsyncMock(return_value=t_after)
c._verb_runner = MagicMock(return_value=runner) # type: ignore[method-assign]
@pytest.mark.asyncio
async def test_pr_fail_notifies_reassigned_owning_pm() -> None:
reviewer_id = uuid4()
pm_id = uuid4()
task_id = uuid4()
parent_id = uuid4()
t_before = MagicMock(
id=task_id,
assigned_to=reviewer_id, # owned by the reviewer until the runner runs
pr_number=138,
parent_task_id=parent_id,
status="awaiting_pr_review",
)
# The runner reassigns the task to the owning PM (needs_revision owner).
t_after = MagicMock(
id=task_id,
assigned_to=pm_id,
pr_number=138,
parent_task_id=parent_id,
status="needs_revision",
)
c = _make_choreographer()
_stub_gate_path(c, reviewer_id=reviewer_id, t_before=t_before, t_after=t_after)
await c.pr_fail(reviewer_id, task_id, ["seam mismatch", "docs lag the diff"])
c.a2a.send.assert_awaited_once()
kwargs = c.a2a.send.await_args.kwargs
assert kwargs["from_agent"] == reviewer_id
assert kwargs["to_agent"] == pm_id
assert kwargs["skill"] == "code_review"
assert kwargs["task_id"] == task_id
body = kwargs["body"]
assert "PR review needs changes." in body
assert "seam mismatch" in body
assert "docs lag the diff" in body
@pytest.mark.asyncio
async def test_pr_pass_does_not_notify_anyone() -> None:
reviewer_id = uuid4()
pm_id = uuid4()
task_id = uuid4()
t_before = MagicMock(
id=task_id,
assigned_to=reviewer_id,
pr_number=42,
parent_task_id=uuid4(),
status="awaiting_pr_review",
)
t_after = MagicMock(
id=task_id, assigned_to=pm_id, pr_number=42, status="awaiting_pm_review"
)
c = _make_choreographer()
_stub_gate_path(c, reviewer_id=reviewer_id, t_before=t_before, t_after=t_after)
await c.pr_pass(reviewer_id, task_id, "Assembled root scope is clean and covered.")
c.a2a.send.assert_not_awaited()
@pytest.mark.asyncio
async def test_pr_fail_skips_a2a_when_no_assignee() -> None:
"""If the runner left the task unassigned, there's nobody to notify — must
not raise and must not crash on ``a2a.send(None)``."""
reviewer_id = uuid4()
task_id = uuid4()
t_before = MagicMock(
id=task_id,
assigned_to=reviewer_id,
pr_number=9,
parent_task_id=uuid4(),
status="awaiting_pr_review",
)
t_after = MagicMock(
id=task_id, assigned_to=None, pr_number=9, status="needs_revision"
)
c = _make_choreographer()
_stub_gate_path(c, reviewer_id=reviewer_id, t_before=t_before, t_after=t_after)
env = await c.pr_fail(reviewer_id, task_id, ["one concrete issue here"])
c.a2a.send.assert_not_awaited()
assert env.status == "needs_revision"
@pytest.mark.asyncio
async def test_pr_fail_a2a_for_main_pm_root_steers_to_redelegate() -> None:
"""A Main-PM branch-bearing root is an assembled cell→root / root→master PR —
coordination, not the Main PM's own code. The ``pr_fail`` a2a body must steer
the Main PM to re-delegate the fixes and NOT re-submit the unchanged root
(the 2026-06-27 infinite ``pr_fail`` loop), while still carrying the concrete
issues. ``_revision_pm_for_task`` returns main-pm for a non-cell team, so the
recipient stays the Main PM — correct, since the Main PM re-delegates."""
reviewer_id = uuid4()
main_pm_id = uuid4()
task_id = uuid4()
t_before = MagicMock(
id=task_id,
assigned_to=reviewer_id,
pr_number=139,
parent_task_id=uuid4(),
status="awaiting_pr_review",
)
t_after = MagicMock(
id=task_id,
assigned_to=main_pm_id,
pr_number=139,
parent_task_id=uuid4(),
status="needs_revision",
)
# Team is read off the runner-rebound task. ``getattr(team, "value", team)``
# must yield ``"main_pm"``; a MagicMock team would not, so set the attribute
# explicitly. branch_name set => an assembled root, not a branchless umbrella.
t_after.team = spec_module.Team.MAIN_PM
t_after.branch_name = "feature/main_pm/c80e19ff"
c = _make_choreographer()
_stub_gate_path(c, reviewer_id=reviewer_id, t_before=t_before, t_after=t_after)
await c.pr_fail(reviewer_id, task_id, ["duplicate TimeseriesChart export"])
c.a2a.send.assert_awaited_once()
kwargs = c.a2a.send.await_args.kwargs
assert kwargs["to_agent"] == main_pm_id
body = kwargs["body"]
assert "PR review needs changes." in body
assert "duplicate TimeseriesChart export" in body
assert "re-delegate" in body
assert "do NOT re-submit" in body
@pytest.mark.asyncio
async def test_pr_fail_a2a_failure_is_swallowed() -> None:
"""The gate transition already committed; an a2a delivery failure must not
roll back the verdict or 500 the reviewer (same posture as the PR-post step,
and the inverse of the cell_pm_complete None-deref crash)."""
reviewer_id = uuid4()
pm_id = uuid4()
task_id = uuid4()
t_before = MagicMock(
id=task_id,
assigned_to=reviewer_id,
pr_number=7,
parent_task_id=uuid4(),
status="awaiting_pr_review",
)
t_after = MagicMock(
id=task_id, assigned_to=pm_id, pr_number=7, status="needs_revision"
)
c = _make_choreographer()
_stub_gate_path(c, reviewer_id=reviewer_id, t_before=t_before, t_after=t_after)
c.a2a.send = AsyncMock(side_effect=RuntimeError("db hiccup")) # type: ignore[method-assign]
env = await c.pr_fail(reviewer_id, task_id, ["a concrete actionable issue"])
# Verdict still landed — the owning PM is in needs_revision.
assert env.status == "needs_revision"
@@ -89,3 +89,68 @@ def test_record_gate_verdict_swallows_invalid_note() -> None:
# No exception, and the stale slot is left as-is rather than corrupted.
assert t.notes_structured is not None
assert t.notes_structured["pr_review"]["verdict"] == "passed"
def test_pr_fail_stores_issues_structurally_not_summary_only() -> None:
"""pr_fail's free-text issues must persist into the structured ``issues``
slot (so a reader of notes_structured.pr_review gets the concrete
change-requests), not be flattened into the summary string alone."""
c = _make_choreographer()
t = _TaskWithNoNotes()
c._record_gate_verdict(
t,
"pr_fail",
"Issues:\n- seam mismatch\n- docs lag the diff",
issues=("seam mismatch", "docs lag the diff"),
)
slot = t.notes_structured["pr_review"]
assert slot["verdict"] == "failed"
assert slot["issues"] == ["seam mismatch", "docs lag the diff"]
# The derived TEXT mirror surfaces them too, so pr_reviewer_notes carries
# the concrete change-requests for any future reader.
assert "seam mismatch" in t.pr_reviewer_notes
assert "docs lag the diff" in t.pr_reviewer_notes
def test_pr_fail_summary_does_not_duplicate_issues() -> None:
"""pr_fail's issues must render only under ## Issues, not also baked into
## Summary — otherwise the Task Details "PR Reviewer Notes" card shows each
issue twice (once under Summary, once under Issues). The summary is a
substantive non-issues sentence; the structured ``issues`` slot carries the
change-requests. ``notes`` (with the issues) still drives the GitHub PR post
and the a2a to the owning PM — those are raw text, not rendered through
``render_markdown``, so no duplication there."""
c = _make_choreographer()
t = _TaskWithNoNotes()
c._record_gate_verdict(
t,
"pr_fail",
"Issues:\n- seam mismatch\n- docs lag the diff",
issues=("seam mismatch", "docs lag the diff"),
)
slot = t.notes_structured["pr_review"]
assert slot["verdict"] == "failed"
# Issues live in the structured issues slot...
assert slot["issues"] == ["seam mismatch", "docs lag the diff"]
# ...NOT baked into the summary.
assert "seam mismatch" not in slot["summary"]
assert "docs lag the diff" not in slot["summary"]
# The rendered TEXT mirror surfaces each issue (under ## Issues)...
assert "seam mismatch" in t.pr_reviewer_notes
assert "docs lag the diff" in t.pr_reviewer_notes
# ...with both section headers present, and the summary is the substantive
# sentence (not the issues-joined string).
assert "## Summary" in t.pr_reviewer_notes
assert "## Issues" in t.pr_reviewer_notes
assert "requested changes" in t.pr_reviewer_notes
def test_pr_pass_leaves_issues_slot_empty() -> None:
c = _make_choreographer()
t = _TaskWithNoNotes()
c._record_gate_verdict(
t, "pr_pass", "Assembled root scope is clean; every criterion is covered."
)
slot = t.notes_structured["pr_review"]
assert slot["verdict"] == "passed"
assert slot.get("issues", []) == []
@@ -0,0 +1,183 @@
"""post_pr_review refuses a hand-formatted verdict body with no findings.
The tool's contract (flow_server.post_pr_review docstring) is explicit: ``body``
is a one-paragraph summary; when ``findings`` are given the GitHub comment is
GENERATED in the RoboCo format (summary + findings table + verdict) — "do not
hand-format it in body". Nothing enforced that, so a reviewer could pass
``findings=[]`` and dump a self-formatted ``## Summary`` / ``## Issues`` /
``## Verdict`` markdown blob into ``body`` — which the system posts verbatim
(``_resolve_post_body`` returns ``body`` as-is when there are no findings). The
deployed renderer emits ``## Findings`` (never ``## Issues``), so a ``## Issues``
section on the PR is proof the agent hand-formatted. Observed live: the reviewer
posted a body that listed the issues under BOTH ``## Summary`` and ``## Issues``
and then repeated the entire block twice — a duplicated, self-redundant
hand-formatted blob the contributor sees.
The guard: when ``findings`` is empty AND ``body`` carries verdict/section
markdown headers, reject with ``invalid_state`` and a remediation that points the
reviewer at the structured-findings path. The system never posts a hand-formatted
verdict, so the duplication cannot recur. A clean plain-note ``COMMENT`` with no
findings is still allowed (only verdict-shaped bodies are blocked), and a review
with structured findings is unaffected (the system generates the comment).
"""
from __future__ import annotations
from typing import Any
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from roboco.foundation.policy import lifecycle as spec_module
from roboco.services.gateway.choreographer import Choreographer, ChoreographerDeps
def _make_choreographer() -> Choreographer:
base: dict[str, Any] = {
"task": AsyncMock(),
"work_session": AsyncMock(),
"git": AsyncMock(),
"a2a": AsyncMock(),
"journal": AsyncMock(),
"audit": AsyncMock(),
"evidence_repo": AsyncMock(),
}
return Choreographer(ChoreographerDeps(**base))
def _stub_post_path(c: Choreographer, *, reviewer_id: Any, t: Any) -> None:
"""Drive ``post_pr_review`` past preflight + the verdict-consistency gate so
the hand-format guard is the thing under test. The runner / side-effects are
stubbed so a passing case does not hit GitHub or the DB transition."""
agent = MagicMock(role="pr_reviewer", slug="be-pr-reviewer")
c._post_pr_review_preflight = AsyncMock( # type: ignore[method-assign]
return_value=(
agent,
"pr_reviewer",
{},
spec_module.Context(actor_id=reviewer_id),
)
)
c._verdict_consistency_gate = AsyncMock(return_value=None) # type: ignore[method-assign]
c._project_slug_for = AsyncMock(return_value="proj") # type: ignore[method-assign]
c._resolve_post_body = MagicMock(return_value="generated body") # type: ignore[method-assign]
runner = MagicMock()
runner.run_intent = AsyncMock(return_value=t)
c._verb_runner = MagicMock(return_value=runner) # type: ignore[method-assign]
c._post_review_side_effects = AsyncMock() # type: ignore[method-assign]
def _task() -> Any:
return MagicMock(
id=uuid4(),
pr_number=200,
status="in_progress",
notes_structured=None,
pr_reviewer_notes="",
)
@pytest.mark.asyncio
async def test_hand_formatted_verdict_body_with_no_findings_is_rejected() -> None:
reviewer_id = uuid4()
task_id = uuid4()
c = _make_choreographer()
_stub_post_path(c, reviewer_id=reviewer_id, t=_task())
hand_formatted = (
"## Summary\nIssues:\n- [BLOCKER] seam mismatch\n"
"## Issues\n- [BLOCKER] seam mismatch\n## Verdict\nfailed"
)
env = await c.post_pr_review(reviewer_id, task_id, hand_formatted, "COMMENT")
body = env.as_dict()
assert body["error"] == "invalid_state"
assert "hand-formatted" in body["message"].lower()
assert "findings" in body["remediate"].lower()
# Nothing posted / transitioned — the guard fired before any side effect.
c.git.post_pr_review.assert_not_awaited()
c._verb_runner().run_intent.assert_not_awaited() # type: ignore[union-attr]
@pytest.mark.asyncio
async def test_hand_formatted_body_rejected_even_for_request_changes() -> None:
# pr_review_conflict already blocks REQUEST_CHANGES + no findings, but the
# guard is independent of event — a hand-formatted verdict must never post,
# whatever event the agent picked.
reviewer_id = uuid4()
task_id = uuid4()
c = _make_choreographer()
_stub_post_path(c, reviewer_id=reviewer_id, t=_task())
env = await c.post_pr_review(
reviewer_id, task_id, "## Verdict\nfailed\nbad", "REQUEST_CHANGES"
)
assert env.as_dict()["error"] == "invalid_state"
@pytest.mark.asyncio
async def test_clean_plain_note_with_no_findings_is_allowed() -> None:
# A genuine plain COMMENT note (no verdict headers, no findings) is a legit
# use of event=COMMENT — the guard must not block it.
reviewer_id = uuid4()
task_id = uuid4()
t = _task()
c = _make_choreographer()
_stub_post_path(c, reviewer_id=reviewer_id, t=t)
env = await c.post_pr_review(
reviewer_id,
task_id,
"Left a note for the contributor: the CI flake on job X is tracked separately.",
"COMMENT",
)
body = env.as_dict()
assert body.get("error") is None
assert body["status"] == "in_progress"
@pytest.mark.asyncio
async def test_structured_findings_with_summary_body_is_allowed() -> None:
# With structured findings the system generates the comment; the guard
# (scoped to empty findings) does not fire even if the summary body happens
# to contain a header-shaped word.
reviewer_id = uuid4()
task_id = uuid4()
t = _task()
c = _make_choreographer()
_stub_post_path(c, reviewer_id=reviewer_id, t=t)
env = await c.post_pr_review(
reviewer_id,
task_id,
"The 422 path is unguarded.",
"REQUEST_CHANGES",
findings=[
{
"file": "roboco/services/git.py",
"line": 42,
"severity": "blocker",
"expected": "retry as COMMENT",
"actual": "raises",
}
],
)
body = env.as_dict()
assert body.get("error") is None
@pytest.mark.asyncio
async def test_envelope_invalid_state_has_introspection_role() -> None:
# The rejection must carry role introspection like the other gates.
reviewer_id = uuid4()
task_id = uuid4()
c = _make_choreographer()
_stub_post_path(c, reviewer_id=reviewer_id, t=_task())
env = await c.post_pr_review(
reviewer_id, task_id, "## Summary\nstuff\n## Verdict\nfailed", "COMMENT"
)
assert env.error == "invalid_state"
# with_introspection(role="pr_reviewer") populated the introspection fields.
assert env.current_state is not None
assert env.valid_next_verbs is not None
@@ -0,0 +1,406 @@
"""``main_pm`` + ``code`` must never coexist — the impossibility guard.
The 2026-06-27 MegaTask meltdown traced to a Main-PM-owned root-subtask that
was ``task_type=code``: the git/PR/review layer treated it as a code root
(branch + PR + ``submit_root`` + the in-path ``pr_review`` gate + complete),
while the ownership/dispatch layer treated it as coordination (owned /
claimed / submitted / completed by the Main PM). The two layers never
reconciled — a ``pr_fail`` on the assembled code landed on a coordinator with
no code verb, who re-submitted the unchanged root → infinite loop. The CEO's
fix: *"It should be impossible to draft a task where main pm and task type
code COEXIST."*
This suite pins the layered backstop that closes the invariant at every site
where the combo can be created or re-handed:
* ``TaskService.create`` rejects ``main_pm`` + ``code`` (the HTTP-route /
direct-create backstop; intake coerces ``code``→``planning``).
* ``approve_and_start`` retypes a board-routed code task to ``planning`` when
it hands it to Main PM (the board→main-pm handoff is where a project code
task would otherwise become ``main_pm`` + ``code``).
* ``apply_escalation`` / ``reassign`` / ``reassign_active_claim`` divert a
``main_pm`` + ``code`` task handed to a Main-PM target to the pool — but
STILL allow reassigning it to a cell dev (the correct remediation).
* ``claim_task_for_agent`` rejects a Main-PM agent claiming a CODE task in an
execution state (claiming = owning through the lifecycle, not delegating),
while leaving the ``awaiting_pm_review`` review-claim path untouched (C8).
The single predicate every layer consults is
``roboco.foundation.policy.batch.main_pm_cannot_own_code`` (accepts ORM enums
or their ``.value`` strings); these tests exercise the service-layer sites
that call it.
"""
from __future__ import annotations
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from roboco.models.base import (
AgentRole,
Complexity,
TaskNature,
TaskStatus,
TaskType,
Team,
)
from roboco.models.task import TaskCreateRequest
from roboco.services.base import UnauthorizedError, ValidationError
from roboco.services.task import TaskService
def _bind(svc: TaskService, name: str, value: object) -> None:
object.__setattr__(svc, name, value)
def _service() -> TaskService:
session = MagicMock()
session.flush = AsyncMock()
session.commit = AsyncMock()
return TaskService(session)
def _task(
*,
team: Team,
task_type: TaskType,
status: TaskStatus = TaskStatus.PENDING,
assigned_to: object = None,
board_review_complete: bool = True,
) -> MagicMock:
return MagicMock(
id=uuid4(),
team=team,
task_type=task_type,
status=status,
assigned_to=assigned_to,
claimed_by=assigned_to,
active_claimant_id=assigned_to,
blocker_raised_by=None,
board_review_complete=board_review_complete,
dev_notes="",
)
def _agent(role: AgentRole = AgentRole.DEVELOPER) -> MagicMock:
return MagicMock(role=role, agent_id=uuid4())
def _perms() -> MagicMock:
p = MagicMock()
p.can_perform_task_action = MagicMock(return_value=True)
return p
# ---------------------------------------------------------------------------
# Site 1 — TaskService.create backstop (invariant #1: the combo on the task)
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_create_rejects_main_pm_plus_code() -> None:
svc = TaskService(
MagicMock(add=MagicMock(), flush=AsyncMock(), execute=AsyncMock())
)
req = TaskCreateRequest(
title="rogue main-pm code root",
description="should not persist",
acceptance_criteria=["ship it"],
team=Team.MAIN_PM,
created_by=uuid4(),
task_type=TaskType.CODE,
nature=TaskNature.TECHNICAL,
estimated_complexity=Complexity.MEDIUM,
project_id=uuid4(),
)
with pytest.raises(ValidationError, match="MAIN_PM"):
await svc.create(req)
@pytest.mark.asyncio
async def test_create_allows_main_pm_plus_planning() -> None:
# The backstop is the team+type combo, not main_pm alone — a Main-PM
# coordination root typed planning is the canonical shape, not a mismatch.
svc = TaskService(
MagicMock(add=MagicMock(), flush=AsyncMock(), execute=AsyncMock())
)
req = TaskCreateRequest(
title="main-pm coordination root",
description="fine",
acceptance_criteria=["coordinate the cells"],
team=Team.MAIN_PM,
created_by=uuid4(),
task_type=TaskType.PLANNING,
nature=TaskNature.TECHNICAL,
estimated_complexity=Complexity.MEDIUM,
project_id=uuid4(),
)
task = await svc.create(req)
assert task.task_type == TaskType.PLANNING
# ---------------------------------------------------------------------------
# Site 2 — approve_and_start retype (board→main-pm handoff)
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_approve_and_start_retypes_code_to_planning_for_main_pm(
monkeypatch: pytest.MonkeyPatch,
) -> None:
svc = _service()
main_pm_agent = MagicMock(id=uuid4(), slug="main-pm", role=AgentRole.MAIN_PM)
agent_svc = MagicMock()
agent_svc.get_by_slug = AsyncMock(return_value=main_pm_agent)
monkeypatch.setattr(
"roboco.services.agent.get_agent_service", lambda _session: agent_svc
)
task = _task(
team=Team.BOARD,
task_type=TaskType.CODE,
status=TaskStatus.PENDING,
board_review_complete=True,
)
_bind(svc, "get", AsyncMock(return_value=task))
_bind(svc, "_activate_batch_root_subtasks", AsyncMock())
_bind(svc, "_emit_task_event", AsyncMock())
await svc.approve_and_start(task.id)
# Handed to Main PM (team set) AND retyped off code in the same write.
assert task.team == Team.MAIN_PM
assert task.task_type == TaskType.PLANNING
@pytest.mark.asyncio
async def test_approve_and_start_leaves_planning_untouched(
monkeypatch: pytest.MonkeyPatch,
) -> None:
svc = _service()
main_pm_agent = MagicMock(id=uuid4(), slug="main-pm", role=AgentRole.MAIN_PM)
agent_svc = MagicMock()
agent_svc.get_by_slug = AsyncMock(return_value=main_pm_agent)
monkeypatch.setattr(
"roboco.services.agent.get_agent_service", lambda _session: agent_svc
)
task = _task(
team=Team.BOARD,
task_type=TaskType.PLANNING,
status=TaskStatus.PENDING,
board_review_complete=True,
)
_bind(svc, "get", AsyncMock(return_value=task))
_bind(svc, "_activate_batch_root_subtasks", AsyncMock())
_bind(svc, "_emit_task_event", AsyncMock())
await svc.approve_and_start(task.id)
assert task.team == Team.MAIN_PM
assert task.task_type == TaskType.PLANNING
# ---------------------------------------------------------------------------
# Site 3 — apply_escalation: divert a main_pm+code task → main-pm target to pool
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_apply_escalation_diverts_main_pm_code_to_main_pm_target() -> None:
svc = _service()
main_pm_target = uuid4()
task = _task(
team=Team.MAIN_PM,
task_type=TaskType.CODE,
status=TaskStatus.IN_PROGRESS,
assigned_to=uuid4(),
)
_bind(svc, "_is_board_advisory_agent", AsyncMock(return_value=False))
_bind(svc, "_is_main_pm_agent", AsyncMock(return_value=True))
release_mock = AsyncMock()
_bind(svc, "_release_code_task_to_pool", release_mock)
await svc.apply_escalation(
task=task,
target_agent_id=main_pm_target,
escalator_slug="cell-pm",
target_slug="main-pm",
reason="blocked",
)
release_mock.assert_awaited_once()
assert task.assigned_to != main_pm_target
@pytest.mark.asyncio
async def test_apply_escalation_does_not_divert_main_pm_code_to_cell_dev() -> None:
# The correct remediation for a legacy main_pm+code task is to reassign it
# to a cell dev who can actually fix the code — the guard must NOT block
# that, only block re-handing it BACK to a Main-PM target.
svc = _service()
cell_dev_target = uuid4()
task = _task(
team=Team.MAIN_PM,
task_type=TaskType.CODE,
status=TaskStatus.IN_PROGRESS,
assigned_to=uuid4(),
)
_bind(svc, "_is_board_advisory_agent", AsyncMock(return_value=False))
_bind(svc, "_is_main_pm_agent", AsyncMock(return_value=False))
release_mock = AsyncMock()
_bind(svc, "_release_code_task_to_pool", release_mock)
_bind(svc, "_emit_task_event", AsyncMock())
await svc.apply_escalation(
task=task,
target_agent_id=cell_dev_target,
escalator_slug="main-pm",
target_slug="be-dev-1",
reason="reassign to a dev to fix",
)
# Not diverted — proceeds to the normal escalation path.
release_mock.assert_not_awaited()
# ---------------------------------------------------------------------------
# Site 4 — reassign / reassign_active_claim diversion
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_reassign_diverts_main_pm_code_to_main_pm_target() -> None:
svc = _service()
main_pm_target = uuid4()
task = _task(team=Team.MAIN_PM, task_type=TaskType.CODE, assigned_to=uuid4())
_bind(svc, "get", AsyncMock(return_value=task))
_bind(svc, "_is_board_advisory_agent", AsyncMock(return_value=False))
_bind(svc, "_is_main_pm_agent", AsyncMock(return_value=True))
diverted = AsyncMock()
_bind(svc, "_divert_owned_task_to_pool", diverted)
# The cell-PM redirect must NOT be reached when the main-pm-code divert fires.
_bind(
svc,
"_resolve_cell_pm_redirect",
AsyncMock(
side_effect=AssertionError(
"cell-PM redirect must not run when main-pm-code divert fires"
)
),
)
result = await svc.reassign(task.id, main_pm_target)
assert result is task
diverted.assert_awaited_once()
@pytest.mark.asyncio
async def test_reassign_active_claim_diverts_main_pm_code_to_main_pm_target() -> None:
svc = _service()
main_pm_target = uuid4()
task = _task(
team=Team.MAIN_PM,
task_type=TaskType.CODE,
status=TaskStatus.IN_PROGRESS,
assigned_to=uuid4(),
)
_bind(svc, "get", AsyncMock(return_value=task))
_bind(svc, "_is_board_advisory_agent", AsyncMock(return_value=False))
_bind(svc, "_is_main_pm_agent", AsyncMock(return_value=True))
diverted = AsyncMock()
_bind(svc, "_divert_owned_task_to_pool", diverted)
_bind(
svc,
"_resolve_cell_pm_redirect",
AsyncMock(
side_effect=AssertionError(
"cell-PM redirect must not run when main-pm-code divert fires"
)
),
)
result = await svc.reassign_active_claim(task.id, main_pm_target)
assert result is task
diverted.assert_awaited_once()
# ---------------------------------------------------------------------------
# Site 5 — claim_task_for_agent: main-pm claiming code (execution state only)
# ---------------------------------------------------------------------------
@pytest.mark.asyncio
async def test_claim_rejects_main_pm_claiming_code_in_execution_state(
monkeypatch: pytest.MonkeyPatch,
) -> None:
svc = TaskService.__new__(TaskService)
svc.session = AsyncMock()
task = _task(team=Team.BACKEND, task_type=TaskType.CODE, status=TaskStatus.PENDING)
monkeypatch.setattr(svc, "_load_task_or_raise", AsyncMock(return_value=task))
plain_claim = AsyncMock(return_value=task)
monkeypatch.setattr(svc, "claim", plain_claim)
with pytest.raises(UnauthorizedError, match="MAIN_PM_NO_CODE"):
await svc.claim_task_for_agent(
task.id, _agent(role=AgentRole.MAIN_PM), _perms(), claim_target_slug=None
)
plain_claim.assert_not_awaited()
@pytest.mark.asyncio
async def test_claim_allows_main_pm_claiming_planning_in_execution_state(
monkeypatch: pytest.MonkeyPatch,
) -> None:
# A Main PM coordinates planning roots — claiming a planning task is the
# legitimate coordination path, not a mismatch.
svc = TaskService.__new__(TaskService)
svc.session = AsyncMock()
task = MagicMock(
team=Team.MAIN_PM,
task_type=TaskType.PLANNING,
status=TaskStatus.PENDING,
)
monkeypatch.setattr(svc, "_load_task_or_raise", AsyncMock(return_value=task))
claimed = MagicMock()
plain_claim = AsyncMock(return_value=claimed)
monkeypatch.setattr(svc, "claim", plain_claim)
result = await svc.claim_task_for_agent(
task.id, _agent(role=AgentRole.MAIN_PM), _perms(), claim_target_slug=None
)
assert result is claimed
plain_claim.assert_awaited_once()
@pytest.mark.asyncio
async def test_claim_does_not_reject_main_pm_code_in_awaiting_pm_review(
monkeypatch: pytest.MonkeyPatch,
) -> None:
# C8: awaiting_pm_review is a REVIEW state, not an execution state. A
# Main PM legitimately claims it to complete/merge — the code guard must
# not fire there (it runs only after the review-state early return).
svc = TaskService.__new__(TaskService)
svc.session = AsyncMock()
task = MagicMock(
team=Team.MAIN_PM,
task_type=TaskType.CODE,
status=TaskStatus.AWAITING_PM_REVIEW,
)
monkeypatch.setattr(svc, "_load_task_or_raise", AsyncMock(return_value=task))
review_claim = AsyncMock(return_value=task)
monkeypatch.setattr(svc, "_claim_review_state", review_claim)
plain_claim = AsyncMock(
side_effect=AssertionError("transitioning claim must not run for review state")
)
monkeypatch.setattr(svc, "claim", plain_claim)
result = await svc.claim_task_for_agent(
task.id, _agent(role=AgentRole.MAIN_PM), _perms(), claim_target_slug=None
)
assert result is task
review_claim.assert_awaited_once()
+10
View File
@@ -469,6 +469,9 @@ async def test_confirm_live_draft_product_routes_to_main_pm(db_session: Any) ->
assert row.team == Team.MAIN_PM
assert row.product_id == product_id
assert row.project_id is None
# A Main-PM coordination root is never code — intake coerces code->planning
# so main_pm + code can never coexist (the 2026-06-27 meltdown shape).
assert row.task_type == TaskType.PLANNING
# =============================================================================
@@ -556,6 +559,8 @@ async def test_confirm_live_batch_builds_umbrella_and_sequenced_subtasks(
assert umbrella.team == Team.MAIN_PM
assert umbrella.status == TaskStatus.PENDING
assert umbrella.branch_name is None # branchless
# A Main-PM coordination root is never code — the umbrella is planning-typed.
assert umbrella.task_type == TaskType.PLANNING
a, b, c = [await db_session.get(TaskTable, UUID(sid)) for sid in ids]
for sub in (a, b, c):
@@ -563,6 +568,11 @@ async def test_confirm_live_batch_builds_umbrella_and_sequenced_subtasks(
assert sub.batch_id == umbrella.batch_id
assert sub.team == Team.MAIN_PM
assert sub.status == TaskStatus.PENDING
# Each root-subtask is a Main-PM coordination root: code->planning coerced
# at intake so main_pm + code can never coexist (the 2026-06-27 meltdown
# shape). It still gets its own branch + PR + submit_root + pr_review gate
# — the gate is branch-keyed, not task_type-keyed.
assert sub.task_type == TaskType.PLANNING
assert a.project_id == project1
assert b.project_id == project1
assert c.project_id == project2