Files
roboco/tests/unit/gateway/test_choreographer_delegate_guards.py
T
cfde4369b1 Token optimization levers — claim-scoped briefing, payload caps, role-scoped optimal, notification-spawn cooldown (#292)
* feat(gateway): claim-scoped context briefing — heavy sections only on context-acquisition verbs

* feat(gateway): cap unbounded LLM-facing payloads — embedded diffs, notification bodies, handoff journal content, north star

* feat(mcp): role-scope the optimal server's tool groups; index management becomes dev/test-only

* feat(mcp): cap per-result content on kb/error/learning search, mentor sources, rag citations

* refactor(gateway): extract heavy-briefing sections + clip helper to keep xenon ranks

* feat(orchestrator): cross-tick cooldown for notification-triggered spawns

* feat(usage,orchestrator): scope spawn-waste to anthropic sessions; cap agent Bash output via settings env

* docs: claim-scoped briefing, payload caps, optimal role-scoping, notification-spawn cooldown

* test(mcp): type the mixed-item cap fixture explicitly

* fix(orchestrator): lazy-init the notification-spawn cooldown store

* fix(lifecycle): admin-override claim reconciliation + PM request_changes verb (S6 postmortem B3+B4)

B3 — admin_set_status now reconciles claim ownership when leaving BLOCKED:
review/queue targets clear claimed_by/claimed_at/active_claimant_id and
consume the pre-block snapshot (a stale escalation claim was stranding the
next claimant: give_me_work handed the task out while note() bounced
not_authorized — the live b8fe0494 wedge). The pending/in_progress restore
path also syncs active_claimant_id, and a REST PATCH unassign releases the
claim with it.

B4 — new PM verb request_changes: awaiting_pm_review -> needs_revision with
concrete issues. The PM previously had no reject at merge review (only
complete/escalate), so an AC/scope violation looped i_am_blocked->escalate
4x live. Full vertical: lifecycle transition + ActionSpec + IntentSpec,
TaskService.request_changes (routes like a QA fail — original dev for a
leaf, revision PM for assembled; issues appended to dev_notes), verb-runner
compose, choreographer verb (spec gate + non-empty issues + soup check +
a2a delivery of the reject reason), HTTP routes on both PM flows, MCP tool,
journal:decision tracing, PM prompts, regenerated lifecycle artifacts.

* fix(panel): stop scorecard fetches for fallback-roster placeholder ids

useAgents() serves the static AGENT_ROSTER (ids "1".."22") while agent
definitions load; the Scorecards tab fetched a member scorecard per row
immediately, firing 22 guaranteed-422 requests per refetch cycle. Through
the browser's per-origin connection limit those queued every metrics-page
query behind them (~10s of skeletons on every tab). Gate the fetch on a
real member id (agent UUID or the "ceo" alias).

* Upgraded uv.lock

* fix(sequencing): declared deps become real edges + full loop-breaker coverage + assembled-branch freshness (S6 postmortem B1/B2/B6 + breaker)

B1a — code delegations REQUIRE a collision surface: new TASK_AT_DELEGATE
completeness spec (conditional FieldRequirement, when=('task_type','code'))
enforced at the gateway delegate gate. A no-surface code sibling is
'parallel to everything' by analyzer design, which is how two devs ran the
CEO's explicitly-ordered work out of order (f3e1afc5: seq#1 started before
seq#0, zero dependency edges). PM prompts updated; REST/manual creation
(TASK_AT_CREATE) unchanged.

B1b — the CEO's declared 'Depends on' lists become real edges: DraftSurface
gains declared_depends_on; SequencingService.analyze unions declared edges
(validated: self/out-of-range rejected) with the derived collision rules,
cycle-checked by the existing toposort. confirm_live_batch/preview_batch
map each draft's depends_on through (string indices coerced); intake tool
doc + prompter role prompt instruct verbatim copying. The live S6 root got
1 of its 3 declared in-batch edges and started alongside still-running R3.

Breaker coverage — the progress-aware respawn circuit breaker
(_pm_respawn_should_gate: strike counting, status-advance reset,
tracing-gap budget, DB durability, one-shot CEO notification) was consulted
by only 3 spawn paths; the doc/QA/dev/PR-review/PR-gate/revision/board
paths spawned unguarded at fixed cadence (the 26-respawn fe-doc loop,
~$7.20). Now consulted at every task-keyed spawn site (14 total).

B2 — assembled-branch freshness: submit_up/submit_root auto-sync the
assembled branch when it has fallen behind its base (children are terminal
at submit time, so the rebase is safe; master is never written). A rebase
conflict is a hard reject naming the files instead of a blind re-review —
kills the needs_revision↔awaiting_pr_review ping-pong of re-submitting a
stale head. Leaf i_am_done already had the behind-base gate; claim-time
fetch-fresh cut already existed.

B6 — documenter revision-pass loop: the awaiting_documentation bail
rejections (i_am_blocked/unclaim) now name the actual exit (i_documented
re-affirm) and the documenter prompt gets an explicit revision-pass rule.

* fix(orchestration): assembly-integrity gate + dispatcher heartbeat (incidents #11, #1)

Assembly integrity — submit_up/submit_root refuse when a completed child's
commits are not patch-present in the assembled branch (git cherry —
rebase-safe; branch pruned after merge or any git error fails open). Live
incident #11: a completed revert subtask's merge was lost from the cell
branch and the review gate re-flagged the exact violation the revert fixed,
spawning another revision cycle.

Dispatcher heartbeat — a dispatcher.alive audit row every 5 minutes from
the dispatch loop. The 2026-07-01 outage was 4h25m of fleet-wide silence
with no way to distinguish 'loop dead' from 'no work'; the loop's stdout
died with the container while audit_log survives. CHANGELOG for tonight's
full sweep included.

* style: ruff format for the orchestration sweep

* refactor(gateway): fold the assembled-submit guards + trim complexity under the xenon gate

_assembled_submit_guards combines the #11 integrity check and B2 freshen for
submit_up/submit_root; lifecycle's invalid-source remediate and git's
per-child cherry probe extracted into helpers. Test harnesses built via
__new__ stub the respawn tracker (the breaker now runs on their paths).

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
2026-07-02 05:46:01 +02:00

331 lines
12 KiB
Python

"""Gate Set B: delegation-time guards in Choreographer.delegate.
Pre-gateway behavior: a PM could only call ``task_create`` while spawned
in-context, which only happened after the orchestrator saw them claim
and start a parent task. That implicit gate is restored explicitly here:
- PARENT_NOT_CLAIMED: parent must be in_progress AND assigned_to PM.
- SUBTASK_CAP: 8 children = soft warn (allowed), >12 = hard block.
"""
from __future__ import annotations
from datetime import UTC, datetime
from typing import Any
from unittest.mock import AsyncMock, MagicMock
from uuid import uuid4
import pytest
from roboco.services.base import ValidationError
from roboco.services.gateway.choreographer import (
Choreographer,
ChoreographerDeps,
DelegateInputs,
)
def _make_deps(**overrides: Any) -> ChoreographerDeps:
base: dict[str, Any] = {
"task": AsyncMock(),
"work_session": AsyncMock(),
"git": AsyncMock(),
"a2a": AsyncMock(),
"journal": AsyncMock(),
"audit": AsyncMock(),
"evidence_repo": AsyncMock(),
}
base.update(overrides)
repo = base["evidence_repo"]
for method in (
"list_unread_a2a",
"list_unread_mentions",
"list_pending_notifications",
"task_metadata_gaps",
"recent_team_activity",
"blockers_in_lane",
"journal_highlights_for_task",
):
getattr(repo, method).return_value = []
# C8: default-fresh journal:decision so PM-decision gate passes.
# Tests that exercise the gate boundary stub their own value.
# The check matches MagicMock and AsyncMock (the two default sentinel
# types pytest's unittest.mock leaves on un-stubbed return_values).
_ldef = base["journal"].latest_decision_at.return_value
if type(_ldef).__name__ in ("MagicMock", "AsyncMock"):
base["journal"].latest_decision_at.return_value = datetime.now(UTC)
return ChoreographerDeps(**base)
def _delegate_inputs() -> DelegateInputs:
return DelegateInputs(
title="Implement endpoint",
description="Add /v1/foo endpoint with tests",
assigned_to="be-dev-1",
team="backend",
task_type="code",
nature="technical",
acceptance_criteria=["GET /v1/foo returns 200 with body"],
intends_to_touch=["backend/api/routers/foo.py"],
)
@pytest.mark.asyncio
async def test_delegate_blocks_when_parent_not_in_progress() -> None:
"""Parent in 'pending' status (PM never called i_will_plan) blocks delegate."""
pm_id = uuid4()
parent_id = uuid4()
parent = MagicMock(
id=parent_id,
project_id=uuid4(),
status="pending",
assigned_to=pm_id,
)
task_svc = AsyncMock()
task_svc.get.return_value = parent
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
task_svc.get_subtasks.return_value = []
deps = _make_deps(task=task_svc)
c = Choreographer(deps)
env = await c.delegate(pm_id, parent_id, _delegate_inputs())
body = env.as_dict()
# The spec's create_subtask gate requires the parent in_progress.
# Per Section 6 of the design doc, rejection messages now come from
# the spec — the spec rejects with 'invalid_state' citing the
# source-status set, not the gateway-specific i_will_plan hint.
assert body["error"] == "invalid_state"
assert "in_progress" in body["message"]
task_svc.create_subtask.assert_not_awaited()
@pytest.mark.asyncio
async def test_delegate_blocks_when_parent_assigned_to_other_agent() -> None:
"""Parent claimed by a different PM cannot be delegated against by us."""
pm_id = uuid4()
other_pm_id = uuid4()
parent_id = uuid4()
parent = MagicMock(
id=parent_id,
project_id=uuid4(),
status="in_progress",
assigned_to=other_pm_id,
quick_context="Decomposition planned; cells implement their slice next.",
)
task_svc = AsyncMock()
task_svc.get.return_value = parent
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
task_svc.get_subtasks.return_value = []
deps = _make_deps(task=task_svc)
c = Choreographer(deps)
env = await c.delegate(pm_id, parent_id, _delegate_inputs())
body = env.as_dict()
assert body["error"] == "not_authorized"
assert "i_will_plan" in body["remediate"]
task_svc.create_subtask.assert_not_awaited()
@pytest.mark.asyncio
async def test_delegate_allows_when_parent_in_progress_and_owned() -> None:
pm_id = uuid4()
parent_id = uuid4()
parent = MagicMock(
id=parent_id,
project_id=uuid4(),
status="in_progress",
assigned_to=pm_id,
quick_context="Decomposition planned; cells implement their slice next.",
)
new_task = MagicMock(id=uuid4())
task_svc = AsyncMock()
task_svc.get.return_value = parent
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
task_svc.get_subtasks.return_value = []
task_svc.create_subtask.return_value = new_task
deps = _make_deps(task=task_svc)
c = Choreographer(deps)
env = await c.delegate(pm_id, parent_id, _delegate_inputs())
body = env.as_dict()
assert body["error"] is None
assert body["status"] == "created"
task_svc.create_subtask.assert_awaited_once()
@pytest.mark.asyncio
async def test_delegate_blocks_when_subtask_cap_exceeded() -> None:
"""13+ subtasks = hard block (cap is 12)."""
pm_id = uuid4()
parent_id = uuid4()
parent = MagicMock(
id=parent_id,
project_id=uuid4(),
status="in_progress",
assigned_to=pm_id,
quick_context="Decomposition planned; cells implement their slice next.",
)
too_many = [MagicMock(id=uuid4()) for _ in range(13)]
task_svc = AsyncMock()
task_svc.get.return_value = parent
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
task_svc.get_subtasks.return_value = too_many
deps = _make_deps(task=task_svc)
c = Choreographer(deps)
env = await c.delegate(pm_id, parent_id, _delegate_inputs())
body = env.as_dict()
assert body["error"] == "invalid_state"
assert "13" in body["message"] or "consolidate" in body["remediate"].lower()
task_svc.create_subtask.assert_not_awaited()
@pytest.mark.asyncio
async def test_delegate_allows_when_subtask_cap_within_soft_zone() -> None:
"""8-12 subtasks: warn-but-allow."""
pm_id = uuid4()
parent_id = uuid4()
parent = MagicMock(
id=parent_id,
project_id=uuid4(),
status="in_progress",
assigned_to=pm_id,
quick_context="Decomposition planned; cells implement their slice next.",
)
many = [MagicMock(id=uuid4()) for _ in range(10)]
new_task = MagicMock(id=uuid4())
task_svc = AsyncMock()
task_svc.get.return_value = parent
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
task_svc.get_subtasks.return_value = many
task_svc.create_subtask.return_value = new_task
deps = _make_deps(task=task_svc)
c = Choreographer(deps)
env = await c.delegate(pm_id, parent_id, _delegate_inputs())
body = env.as_dict()
assert body["error"] is None
task_svc.create_subtask.assert_awaited_once()
@pytest.mark.asyncio
async def test_delegate_allows_at_zero_subtasks() -> None:
"""Empty subtask list is the common case."""
pm_id = uuid4()
parent_id = uuid4()
parent = MagicMock(
id=parent_id,
project_id=uuid4(),
status="in_progress",
assigned_to=pm_id,
quick_context="Decomposition planned; cells implement their slice next.",
)
new_task = MagicMock(id=uuid4())
task_svc = AsyncMock()
task_svc.get.return_value = parent
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
task_svc.get_subtasks.return_value = []
task_svc.create_subtask.return_value = new_task
deps = _make_deps(task=task_svc)
c = Choreographer(deps)
env = await c.delegate(pm_id, parent_id, _delegate_inputs())
body = env.as_dict()
assert body["error"] is None
@pytest.mark.asyncio
async def test_delegate_blocks_at_exact_cap_plus_one() -> None:
"""Cap is 12; 13th attempt blocks."""
pm_id = uuid4()
parent_id = uuid4()
parent = MagicMock(
id=parent_id,
project_id=uuid4(),
status="in_progress",
assigned_to=pm_id,
quick_context="Decomposition planned; cells implement their slice next.",
)
# Already 12 children — adding the 13th must be blocked.
twelve = [MagicMock(id=uuid4()) for _ in range(12)]
task_svc = AsyncMock()
task_svc.get.return_value = parent
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
task_svc.get_subtasks.return_value = twelve
deps = _make_deps(task=task_svc)
c = Choreographer(deps)
env = await c.delegate(pm_id, parent_id, _delegate_inputs())
body = env.as_dict()
assert body["error"] == "invalid_state"
task_svc.create_subtask.assert_not_awaited()
@pytest.mark.asyncio
async def test_delegate_blocks_when_parent_quick_context_empty() -> None:
"""delegate obligates the PM's quick_context resumption section on the
parent; an empty quick_context (PM never called note(scope='handoff'))
fails the tracing gate before any subtask is created."""
pm_id = uuid4()
parent_id = uuid4()
parent = MagicMock(
id=parent_id,
project_id=uuid4(),
status="in_progress",
assigned_to=pm_id,
quick_context="",
)
task_svc = AsyncMock()
task_svc.get.return_value = parent
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
task_svc.get_subtasks.return_value = []
deps = _make_deps(task=task_svc)
c = Choreographer(deps)
env = await c.delegate(pm_id, parent_id, _delegate_inputs())
body = env.as_dict()
assert body["error"] == "tracing_gap"
assert "quick_context>=min" in body["missing"]
task_svc.create_subtask.assert_not_awaited()
@pytest.mark.asyncio
async def test_delegate_past_max_depth_returns_invalid_state_not_500() -> None:
"""Bug B: delegating past MAX_TASK_DEPTH raised a bare ValueError that
escaped uncaught as a 500 ExceptionGroup. ``_validate_parent_depth`` now
raises ``ValidationError`` (a ServiceError), and the choreographer
translates it to an ``invalid_state`` envelope whose remediate carries the
"create as a sibling" instruction — so the PM gets a clean, actionable
rejection instead of a crash, and the agent loop doesn't respawn-blind.
"""
pm_id = uuid4()
parent_id = uuid4()
parent = MagicMock(
id=parent_id,
project_id=uuid4(),
status="in_progress",
assigned_to=pm_id,
quick_context="Decomposition planned; cells implement their slice next.",
)
depth_msg = (
"Task hierarchy would exceed MAX_TASK_DEPTH=4. Create this work as a "
"sibling of the deepest task instead of a further nested subtask."
)
task_svc = AsyncMock()
task_svc.get.return_value = parent
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
task_svc.get_subtasks.return_value = []
# create_subtask -> create -> _validate_parent_depth raises ValidationError.
task_svc.create_subtask.side_effect = ValidationError(
depth_msg, field="parent_task_id"
)
deps = _make_deps(task=task_svc)
c = Choreographer(deps)
env = await c.delegate(pm_id, parent_id, _delegate_inputs())
body = env.as_dict()
assert body["error"] == "invalid_state"
assert "MAX_TASK_DEPTH" in body["message"]
# The remediation must reach the agent — the whole point of the fix.
assert "sibling" in body["remediate"]
task_svc.create_subtask.assert_awaited_once()