mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
* feat(batch): batch_id + collision descriptor columns
Sequenced batch intake ("Mega task") foundation: tasks.batch_id (indexed)
groups a batch of top-level tasks created together; intends_to_touch (text[]),
adds_migration and touches_shared (bool, NOT NULL default false) are the
per-task collision surface the SequencingService will read to wire dependency
waves. Mirrored on the Task model + TaskCreateRequest and wired through
TaskService.create. Migration 046 (real upgrade->downgrade->upgrade verified
vs a throwaway pgvector PG); a non-batch task declares no surface (defaults).
Task 1 of the 0.11.0 sequenced-batch-intake plan.
* feat(batch): flag + draft collision descriptors
Default-off ROBOCO_BATCH_INTAKE_ENABLED (config + FEATURE_FLAGS + panel card);
the propose_draft tool doc + the TS DraftProposal gain the per-task collision
surface intends_to_touch / adds_migration / touches_shared. The draft is a loose
dict so the descriptors ride it through the relay intact (test asserts the
forwarded payload); the analyzer (Task 3) reads them to wire dependency waves.
Task 2 of the 0.11.0 sequenced-batch-intake plan.
* feat(batch): deterministic collision-sequencing analyzer
SequencingService.analyze turns a batch's per-task collision surfaces into a
dependency DAG + execution waves — correctness in CODE, not agent judgment.
Rules in order: file overlap serializes (more-important first), migrations form
a serial chain (no concurrent Alembic heads), touches_shared runs last, cell
contention warns (never serializes); then dedupe, existence + cycle check, and
Kahn topological layering. Pure (no DB/services); SequencingError on a cycle or
out-of-range edge.
Golden test reproduces the CEO's hand-sequenced 4 waves of the 11-item
guard-core-app batch (the effort that deadlocked the Main PM): S6 alone last,
the R1/R3/R4 migration chain, R2/R3/S8 serialized on the shared threat service,
S1/S2/S7 in one parallel wave.
Task 3 of the 0.11.0 sequenced-batch-intake plan.
* chore(batch): brand the user-facing surfaces "MegaTask"
The user-facing name is MegaTask: the feature-flag label is "MegaTask intake",
the panel flag-card and the config description lead with MegaTask. Internal
names stay technical (batch_intake_enabled, batch_id, SequencingService).
* chore(batch): drop the feature flag — MegaTask is a core intake scope
MegaTask is additive and opt-in by its own nature (the Prompter proposes a
batch only when the CEO asks for several tasks; single-task intake is
unchanged), so there is no risk surface a flag protects — 'don't create a
MegaTask' is the off switch. Remove batch_intake_enabled from config, the
FEATURE_FLAGS registry, the panel flag card, and its tests. MegaTask will be
a third scope option in the Intake modal (single-cell / multi-project /
MegaTask), not a toggle.
* feat(batch): MegaTask identity predicate + orchestrator branchless recognition
The single source of truth for the umbrella's exemptions: pure
is_batch_umbrella / is_batch_root_subtask / is_branchless_coordination
(foundation/policy/batch.py) — an umbrella has a batch_id and is top-level; a
root-subtask shares the batch_id but is parented. The orchestrator's
_is_coordination_task now consults is_branchless_coordination, so a MegaTask
umbrella is recognized as doing no git of its own (git-exempt at spawn-readiness
/ stuck-detection) exactly like a product fan-out root. Non-batch behavior is
identical (the predicate reduces to the old no-project+product check; the
orchestrator coordination suite stays green), and the umbrella branch is inert
until the create path exists.
First slice of the MegaTask umbrella enforcement (branchless guard).
* feat(batch): branchless umbrella guard across the git-exemption sites
A MegaTask umbrella does no git of its own — every git-exemption site in
TaskService now consults the shared is_branchless_coordination predicate
instead of an inline product-only check, so the umbrella's exemptions
cannot drift between sites:
- the claimed->in_progress branch gate (GitContext.is_coordination) lets
an unbranched umbrella reach in_progress and delegate;
- _ensure_branch_for_task short-circuits an umbrella to "" instead of the
misconfigured raise (the claim path ignores the return, treating it as
branchless);
- CEO-reject routing sends a rejected umbrella to the Main PM in PENDING
(needs_revision is developer-claim-only and would deadlock it).
Covers both shapes via the predicate (product fan-out root OR umbrella);
a batch root-subtask keeps its own branch/PR. Adds orchestrator
recognition tests for the umbrella plus claim/branch/reject integration
tests.
* feat(batch): umbrella assembles no PR; completes branchless
submit_root now hard-rejects a MegaTask umbrella up front (a preflight
that also folds in the unknown-role refusal to stay within the
return-count budget): the umbrella spans many projects with no single
master, so each root-subtask opens and is reviewed on its own PR — the
umbrella never enters the in-path review gate. The Main PM completes it
directly once every root-subtask is terminal.
Umbrella completion needs no new code: it is branchless (no branch_name),
so _main_pm_complete_guard already accepts it from in_progress, checks
all_subtasks_terminal, and main_pm_complete walks it to awaiting_pm_review
and escalates to the CEO with no PR creation — exactly the product
fan-out root path. Adds the submit_root-reject and umbrella-completion
gateway tests; pins batch_id=None on the normal-root submit_root test
(a MagicMock auto-attr would otherwise read as an umbrella).
* feat(batch): MegaTask create path — umbrella + sequenced root-subtasks
PrompterService.confirm_live_batch turns N confirmed drafts into a real
MegaTask: it builds each draft's collision surface, runs the pure
SequencingService to get conflict-free waves, creates the branchless
umbrella (batch_id, no project/product), then one root-subtask per draft
(own project, parent=umbrella, sequence=wave index, descriptors), and
wires the analyzer's edges through add_dependency so the existing
dependency-gate runs the waves in order. The route picks the start path
like a single confirm: 'board' holds the root-subtasks in BACKLOG for the
batch review; 'main_pm' creates them PENDING so wave 0 dispatches at once.
create_task_from_draft gains a BatchPlacement (parent/batch/sequence/
team_override) and forwards the collision descriptors; the exactly-one-
target rule (here and the TaskService.create invariant) is relaxed for an
umbrella, which legitimately targets neither. New route
POST /live/{session}/confirm-batch + BatchConfirmRequest mirror the single
confirm. Adds the structural-invariant + board-hold + empty-batch tests.
* feat(batch): release MegaTask root-subtasks on CEO approval; board awareness
The board route holds a MegaTask's root-subtasks in BACKLOG so the work
waits for the batch review. approve_and_start (CEO gate #1, board->Main PM)
now releases them via _activate_batch_root_subtasks: each held child flips
BACKLOG -> PENDING + team=main_pm so the dependency-gate dispatches wave 0.
No-op for a non-umbrella; idempotent (children past BACKLOG untouched).
The Product Owner and Head of Marketing identity prompts gain a MegaTask
section so they review the whole batch + wave plan and adjust scope before
sign-off (they review drafts; the umbrella is their unit). Also extracts
the create() target invariant into _require_target_or_umbrella to keep the
method under the complexity gate after the umbrella exemption. Adds the
umbrella-approval activation test.
* feat(batch): multi-project intake scope for MegaTask
A MegaTask spans several possibly-unrelated repos, so the intake chat can
now be scoped to an explicit project list (not just one project or one
product). StartLiveRequest gains project_ids; /live/start threads it
through start/spawn_intake_session -> _spawn_intake_container ->
_clone_intake_scope. The multi-repo clone machinery already existed for
products; _intake_scope_slugs now also resolves an explicit project_ids
set (split into _slugs_for_project_ids / _slugs_for_product), cloning each
repo with the first as the primary cwd and the siblings readable. Scope
validation is now 'exactly one of project_slug / product_id / project_ids'
via the shared _require_one_intake_scope. Adds scope-resolution, spawn,
and route tests for the MegaTask path.
* feat(batch): propose_batch intake tool (MegaTask multi-draft hand-off)
The intake agent can now hand the panel a whole MegaTask in one tool call.
Both intake paths gain propose_batch alongside propose_draft:
- Claude (intake_driver): a propose_batch tool registered on the in-SDK
MCP server + allowlisted; the driver intercepts the ToolUseBlock and
emits ONE StreamChunk(kind="batch") carrying {drafts:[...], title}.
- grok (intake_server): a propose_batch tool that POSTs a "batch" relay
event via the shared _post_event helper (post_draft/post_batch).
A batch carries N drafts, each the propose_draft shape PLUS its own
project_id (a MegaTask spans unrelated repos) and collision surface so the
analyzer sequences the waves. The prompter prompt documents the MegaTask
scope + when to call propose_batch. Adds Claude-normalize and grok-relay
tests for the batch path.
* feat(batch): MegaTask intake panel — third scope, batch review, waves
The panel now drives a MegaTask end to end. The intake modal gains a
third scope, 'MegaTask', beside Single cell and Board-led: a multi-project
checklist (a MegaTask spans several possibly-unrelated repos), validated
to at least two. start() sends project_ids; use-prompter accumulates the
agent's single propose_batch hand-off as a 'batch' SSE event into a
BatchProposal and lands in a new batch_preview state.
A new BatchReviewCard lists every proposed task with its target project +
collision-surface badges (migration / shared) and offers one start path
for the whole batch — Board review & Start or Approve & Start — wired to
confirmBatch → POST /confirm-batch. The success card shows the sequenced
result: N tasks in M waves (+ any advisory notes). prompter.ts gains the
DraftScale 'megatask' + the BatchConfirm payload/result types; the SSE
client allows the 'batch' kind. Panel typecheck + lint + 113 tests green.
* docs(batch): MegaTask across changelog, CLAUDE.md, site, and RAG
The four documentation obligations for the MegaTask feature:
- CHANGELOG: an Unreleased entry covering the umbrella model, sequencing,
multi-project intake, propose_batch, and the create/approval path.
- CLAUDE.md: a MegaTask section (identity predicate, umbrella/root-subtask
hierarchy, sequencing rules, intake + create path, board activation).
- Published site: a user-facing company/megatask.md (scopes, waves, the
umbrella, the two start buttons) + nav entry; a pointer added to the
intake chapter of the Tour.
- RAG corpus: workflows/megatask.md so the Main PM (and any agent) can
retrieve the umbrella's branchless / no-PR / completion rules at runtime.
The runtime concurrent-migration guard is intentionally NOT added: the
analyzer already chains migration-adders into dependencies and the
dependency-gate serializes them, so a separate guard would be dead code.
* feat(batch): batch_id guardrail + wave preview + batch_id on TaskResponse
Guardrail (CEO): a batch_id is denied on any task that is not a well-formed
MegaTask member. is_valid_batch_shape permits batch_id only on an umbrella
(no parent → must target neither project nor product) or a root-subtask
(has a parent → exactly one target); TaskService.create enforces it AND
verifies a root-subtask's parent is the batch umbrella (same batch_id,
top-level). This closes a latent hole: is_batch_umbrella is true for a
batch_id + no-parent task even with a project, so a stray batch_id could
have spoofed the branchless branch-gate / no-PR exemption. (The public
task API never exposed batch_id for write; this guards the service layer.)
Wave preview: PrompterService.preview_batch + POST .../preview-batch
compute a MegaTask's waves from the proposed drafts WITHOUT creating
anything, so the panel can show the sequencing before confirm. Extracted
_sequence_drafts as the single source shared by preview and confirm, so
the previewed waves are exactly the ones wired.
TaskResponse now carries batch_id so the panel can badge the umbrella.
* feat(batch): MegaTask review — project editor, wave preview, persistence, badge
Closes the panel gaps in the MegaTask review experience:
- Per-task project editor: each proposed task gets an inline project
Select (updateBatchDraftProject), so a task the agent put in the wrong
or no repo can be fixed before launch — not only by re-chatting. Launch
stays blocked until every task has a project.
- Wave preview: on a batch proposal the panel fetches POST .../preview-batch
(no task created) and shows the conflict-free wave plan, so the human
reviews the sequencing before confirming.
- Refresh durability: the MegaTask review (batch + waves + projectIds) is
persisted, so a browser reload mid-review restores it like a single draft.
- MegaTask badge: TaskResponse exposes batch_id, the panel Task type
carries it, and the task table badges the umbrella row 'MegaTask'.
Panel typecheck + lint + 113 tests green.
* test(batch): stub task carries batch_id for task_to_response
task_to_response now serializes batch_id (TaskResponse field), so the
_stub_task SimpleNamespace fixture must provide it — without it the reader
hit AttributeError, failing the 8 task-schema serialization/enrichment
tests. Test-only; the real TaskTable carries the column (migration 046).
* fix(batch): close MegaTask audit gaps — completion crash, analyzer cycle, guardrails
An adversarial multi-agent audit of the feature surfaced 20 verified gaps;
this closes the backend ones.
HIGH:
- Umbrella completion crashed. escalate_to_ceo hard-required a pr_number,
which a branchless umbrella never has, so main_pm_complete dereferenced
None. Both pr_number gates now waive a MegaTask umbrella (escalate_to_ceo
+ the awaiting_pm_review->awaiting_ceo_approval lifecycle gate via a new
GitContext.is_umbrella), and main_pm_complete guards a None return. The
completion test had mocked escalate_to_ceo, hiding it — now a real
service test covers the waiver.
- The collision analyzer could fabricate a cycle (a touches_shared +
adds_migration draft overlapping another migration draft) and raise
SequencingError — a bare ValueError that escaped as an opaque 500. The
migration chain is now shared-last-aware (never contradicts rule 3), and
_sequence_drafts translates SequencingError to a clean 400.
MEDIUM:
- Collisions are now project-scoped: two repos can't collide on a
coincidental path or serialize independent migrations (DraftSurface
carries project_id; rules 1/2/3 respect it).
- The batch_id guardrail ran only at create. update() + the PATCH
null-clear path now re-assert is_valid_batch_shape, so a mutation can't
break a member's shape and spoof the branchless exemption.
- A draft missing title/acceptance_criteria now raises ValidationError
(was a bare KeyError -> 500).
- confirm_live_batch re-asserts every draft targets a scoped project and
the batch spans >=2 distinct projects (project_ids added to the request).
- Route-level tests for confirm-batch / preview-batch.
LOW: strict multi-repo clone (fail loud on any unresolvable project);
malformed/empty propose_batch surfaces an error chunk (Claude) / refuses
to POST (grok) instead of silently acking; dropped malformed drafts are
counted and surfaced; stale grok intake docstrings updated.
* fix(batch): MegaTask panel + doc audit gaps
Frontend half of the audit fixes:
- The confirm payload now carries project_ids (the schema requires it), and
the panel re-checks every task targets one of the scoped repos before
launching, naming the offending task.
- The Review-MegaTask project picker is filtered to the scoped repos and
the per-task validity (border + launch gate) keys off scoped membership,
so a task can only be (re)pointed at an in-scope project — also fixing the
case where the agent emitted a non-UUID / unknown project.
- Dropped malformed drafts are surfaced as a chat error so the human knows
the batch shrank instead of silently confirming fewer tasks.
- Doc wording: a wave releases on the previous wave's terminal state
(normally a merge; a cancellation releases it too), not strictly 'merged'.
* test(batch): lock the CEO's EXACT 4-wave hand-sequencing as the golden bar
The golden test asserted the constraints (S6 last, the migration chain, the
shared-threats serialization, S1/S2/S7 parallel) but not the full wave
partition. The bar for MegaTask is 'reproduce my exact waves or it's not
done', so assert the exact 4-wave partition the analyzer produces for the
guard-core-app batch:
wave 1: R1 R2 S1 S2 S3 S5 S7 · wave 2: R3 · wave 3: R4 S8 · wave 4: S6
Confirmed unchanged by the audit's analyzer fixes (no migration is shared;
single project).
* fix(batch): tolerate a stub task in assert_batch_shape_intact
The batch-shape re-validation read task.batch_id directly, but update()'s
partial-caller contract is exercised with a SimpleNamespace stub that has no
batch_id column → AttributeError. Use getattr(..., None) for batch_id and the
shape fields so the guard no-ops on any task lacking the column (a stub, or a
non-batch task) while still enforcing on a real batch member.
* fix(orchestrator): authenticate internal API self-calls with the system identity
The dispatcher httpx clients were built without an agent identity, so the
orchestrator's self-PATCHes to /api/tasks/{id} (auto-block, auto-resume,
auto-recover, SLA annotation) were rejected 401 "Missing X-Agent-ID" and
silently no-op'd. The auto-resume that lifts a PM's paused parent could never
write, so paused/blocked parents stayed wedged and stranded their dependents
(the fe-pm/be-pm respawn churn seen in prod).
Header propagation was inconsistent across the separate AsyncClient call-sites:
only the main dispatch client carried the system identity; the readiness and
sweep clients did not. Hoist the identity into a shared _SYSTEM_API_HEADERS
constant and apply it to every API-facing dispatcher client. The system role
holds TaskAction.ASSIGN, so it is authorized for the audited admin_set_status
path those write routes use. The external provider-recovery probe client is
intentionally left untouched.
---------
Co-authored-by: Renn F <rennf93@users.noreply.github.com>
891 lines
31 KiB
Python
891 lines
31 KiB
Python
"""Tests for PM Choreographer methods.
|
|
|
|
Covers: triage, triage_all, unblock, complete, escalate_up.
|
|
"""
|
|
|
|
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.gateway.choreographer import Choreographer, ChoreographerDeps
|
|
|
|
|
|
def _make_deps(**overrides: Any) -> ChoreographerDeps:
|
|
base = {
|
|
"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)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cell_pm_triage_returns_blocked_first() -> None:
|
|
pm_id = uuid4()
|
|
blocked_task = MagicMock(id=uuid4(), status="blocked", title="b", team="backend")
|
|
pending_task = MagicMock(
|
|
id=uuid4(), status="awaiting_pm_review", title="p", team="backend"
|
|
)
|
|
task_svc = AsyncMock()
|
|
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
|
|
task_svc.list_blocked_for_team.return_value = [blocked_task]
|
|
task_svc.list_awaiting_pm_review_for_team.return_value = [pending_task]
|
|
deps = _make_deps(task=task_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.triage(pm_id)
|
|
body = env.as_dict()
|
|
assert body["task_id"] == str(blocked_task.id)
|
|
assert "unblock" in body["next"].lower()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cell_pm_triage_returns_awaiting_review_when_no_blocked() -> None:
|
|
pm_id = uuid4()
|
|
pending_task = MagicMock(id=uuid4(), status="awaiting_pm_review", team="backend")
|
|
task_svc = AsyncMock()
|
|
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
|
|
task_svc.list_blocked_for_team.return_value = []
|
|
task_svc.list_awaiting_pm_review_for_team.return_value = [pending_task]
|
|
deps = _make_deps(task=task_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.triage(pm_id)
|
|
body = env.as_dict()
|
|
assert body["task_id"] == str(pending_task.id)
|
|
assert "complete" in body["next"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cell_pm_triage_returns_idle_when_no_work() -> None:
|
|
pm_id = uuid4()
|
|
task_svc = AsyncMock()
|
|
task_svc.agent_for.return_value = MagicMock(role="cell_pm", team="backend")
|
|
task_svc.list_blocked_for_team.return_value = []
|
|
task_svc.list_awaiting_pm_review_for_team.return_value = []
|
|
deps = _make_deps(task=task_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.triage(pm_id)
|
|
body = env.as_dict()
|
|
assert body["status"] == "idle"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_pm_triage_all_includes_cross_team() -> None:
|
|
pm_id = uuid4()
|
|
blocked = MagicMock(id=uuid4(), status="blocked", team="backend", title="x")
|
|
task_svc = AsyncMock()
|
|
task_svc.list_blocked_all_teams.return_value = [blocked]
|
|
task_svc.list_awaiting_main_pm_all.return_value = []
|
|
deps = _make_deps(task=task_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.triage_all(pm_id)
|
|
body = env.as_dict()
|
|
assert body["error"] is None
|
|
assert body["task_id"] == str(blocked.id)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_pm_triage_all_returns_idle() -> None:
|
|
pm_id = uuid4()
|
|
task_svc = AsyncMock()
|
|
task_svc.list_blocked_all_teams.return_value = []
|
|
task_svc.list_awaiting_main_pm_all.return_value = []
|
|
deps = _make_deps(task=task_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.triage_all(pm_id)
|
|
assert env.status == "idle"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unblock_restores_pre_block_state() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(
|
|
id=task_id,
|
|
status="blocked",
|
|
pre_block_state="awaiting_documentation",
|
|
pre_block_assignee=uuid4(),
|
|
pre_block_metadata={"some_field": "x"},
|
|
)
|
|
after = MagicMock(
|
|
**{
|
|
**t.__dict__,
|
|
"status": "awaiting_documentation",
|
|
"assigned_to": t.pre_block_assignee,
|
|
},
|
|
)
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.unblock_with_restore.return_value = after
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.unblock(pm_id, task_id, restore=True)
|
|
assert env.error is None
|
|
assert env.status == "awaiting_documentation"
|
|
task_svc.unblock_with_restore.assert_awaited_once_with(pm_id, task_id, restore=True)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unblock_default_restores() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(
|
|
id=task_id,
|
|
status="blocked",
|
|
pre_block_state="awaiting_qa",
|
|
pre_block_assignee=uuid4(),
|
|
pre_block_metadata={},
|
|
)
|
|
after = MagicMock(**{**t.__dict__, "status": "awaiting_qa"})
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.unblock_with_restore.return_value = after
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
# restore omitted -> defaults to True
|
|
env = await c.unblock(pm_id, task_id)
|
|
assert env.status == "awaiting_qa"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unblock_blocks_without_journal_decision() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(id=task_id, status="blocked")
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = False
|
|
journal_svc.latest_decision_at.return_value = None
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.unblock(pm_id, task_id)
|
|
body = env.as_dict()
|
|
assert body["error"] == "tracing_gap"
|
|
assert "journal:decision" in body["missing"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unblock_wrong_state_returns_invalid_state() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(id=task_id, status="in_progress")
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
deps = _make_deps(task=task_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.unblock(pm_id, task_id)
|
|
body = env.as_dict()
|
|
assert body["error"] == "invalid_state"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unblock_restore_false_returns_legacy_message() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(
|
|
id=task_id,
|
|
status="blocked",
|
|
pre_block_state="awaiting_qa",
|
|
pre_block_assignee=uuid4(),
|
|
pre_block_metadata={},
|
|
)
|
|
after = MagicMock(**{**t.__dict__, "status": "in_progress"})
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.unblock_with_restore.return_value = after
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.unblock(pm_id, task_id, restore=False)
|
|
body = env.as_dict()
|
|
assert body["status"] == "in_progress"
|
|
assert "re-engage" in body["next"].lower()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unblock_refused_while_a_dependency_is_unfinished() -> None:
|
|
"""A dependency block can't be force-cleared by a PM.
|
|
|
|
It auto-clears via _unblock_dependents once the upstream completes; manual
|
|
unblock would let the dependent proceed without the upstream's work.
|
|
"""
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
dep_id = uuid4()
|
|
t = MagicMock(id=task_id, status="blocked", dependency_ids=[dep_id])
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.unmet_dependency_ids.return_value = [dep_id]
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.unblock(pm_id, task_id)
|
|
body = env.as_dict()
|
|
|
|
assert body["error"] == "invalid_state"
|
|
assert "depends on" in body["message"]
|
|
# The task must not have been advanced out of blocked.
|
|
task_svc.unblock_with_restore.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cell_pm_complete_merges_then_completes() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
parent_id = uuid4()
|
|
t = MagicMock(
|
|
id=task_id,
|
|
status="awaiting_pm_review",
|
|
assigned_to=pm_id,
|
|
pr_number=8,
|
|
branch_name="feature/backend/abc--def",
|
|
parent_task_id=parent_id,
|
|
team="backend",
|
|
)
|
|
after = MagicMock(**{**t.__dict__, "status": "completed"})
|
|
# #181/#182: the merge target is the PARENT task's real branch_name —
|
|
# here under a DIFFERENT team prefix, which the old parent_branch_for
|
|
# would have mis-derived as feature/backend/abc.
|
|
parent = MagicMock(
|
|
id=parent_id, branch_name="feature/main_pm/abc", parent_task_id=None
|
|
)
|
|
task_svc = AsyncMock()
|
|
task_svc.get.side_effect = lambda tid: parent if tid == parent_id else t
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
task_svc.cell_pm_complete.return_value = after
|
|
git_svc = AsyncMock()
|
|
git_svc.pr_merge.return_value = {"merged": True, "merge_commit_sha": "merge-abc"}
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, git=git_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.cell_pm_complete(pm_id, task_id, notes="reviewed and approved")
|
|
assert env.error is None
|
|
assert env.status == "completed"
|
|
git_svc.pr_merge.assert_awaited_once_with(
|
|
8, target="feature/main_pm/abc", actor_agent_id=pm_id
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cell_pm_complete_blocks_if_subtasks_unfinished() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(
|
|
id=task_id,
|
|
status="awaiting_pm_review",
|
|
assigned_to=pm_id,
|
|
parent_task_id=uuid4(),
|
|
)
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.all_subtasks_terminal.return_value = False
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.cell_pm_complete(
|
|
pm_id, task_id, notes="reviewed cell scope and approved merge"
|
|
)
|
|
body = env.as_dict()
|
|
assert body["error"] == "tracing_gap"
|
|
assert "subtasks" in str(body["missing"]).lower()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cell_pm_complete_requires_journal_decision() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(
|
|
id=task_id,
|
|
status="awaiting_pm_review",
|
|
assigned_to=pm_id,
|
|
parent_task_id=uuid4(),
|
|
)
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = False
|
|
journal_svc.latest_decision_at.return_value = None
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.cell_pm_complete(pm_id, task_id, notes="x")
|
|
body = env.as_dict()
|
|
assert body["error"] == "tracing_gap"
|
|
assert "journal:decision" in body["missing"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cell_pm_complete_no_pr_returns_invalid_state() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(
|
|
id=task_id,
|
|
status="awaiting_pm_review",
|
|
assigned_to=pm_id,
|
|
pr_number=None,
|
|
branch_name="feature/backend/abc--def",
|
|
parent_task_id=uuid4(),
|
|
)
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.cell_pm_complete(
|
|
pm_id, task_id, notes="reviewed cell scope and approved merge"
|
|
)
|
|
assert env.as_dict()["error"] == "invalid_state"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cell_pm_complete_not_assigned_returns_not_authorized() -> None:
|
|
pm_id = uuid4()
|
|
other = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(id=task_id, status="awaiting_pm_review", assigned_to=other)
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
deps = _make_deps(task=task_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.cell_pm_complete(pm_id, task_id, notes="x")
|
|
assert env.as_dict()["error"] == "not_authorized"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cell_pm_complete_in_progress_steers_to_submit_up() -> None:
|
|
"""Mirror of the main-PM submit_root steer: a cell task still in_progress
|
|
must enter the gate via submit_up first. The rejection must NAME submit_up
|
|
so the cell PM isn't left guessing the verb (the gap that deadlocked the
|
|
main PM on submit_root)."""
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(
|
|
id=task_id,
|
|
status="in_progress",
|
|
assigned_to=pm_id,
|
|
parent_task_id=uuid4(),
|
|
branch_name="feature/backend/parent123",
|
|
)
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.cell_pm_complete(
|
|
pm_id, task_id, notes="cell scope assembled; ready to bubble up"
|
|
)
|
|
assert env.error is not None
|
|
assert "submit_up" in (env.remediate or "")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_pm_complete_escalates_code_root_without_reopening_pr() -> None:
|
|
"""A code root reaches main_pm_complete already in awaiting_pm_review —
|
|
submit_root opened the root→master PR and the main reviewer pr_passed it —
|
|
so complete just escalates to the CEO and does NOT reopen the PR."""
|
|
main_pm_id = uuid4()
|
|
root_task_id = uuid4()
|
|
t = MagicMock(
|
|
id=root_task_id,
|
|
status="awaiting_pm_review",
|
|
assigned_to=main_pm_id,
|
|
pr_number=99,
|
|
branch_name="feature/backend/root123",
|
|
parent_task_id=None,
|
|
team="backend",
|
|
)
|
|
after = MagicMock(**{**t.__dict__, "status": "awaiting_ceo_approval"})
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.escalate_to_ceo.return_value = after
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
git_svc = AsyncMock()
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, git=git_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.main_pm_complete(
|
|
main_pm_id, root_task_id, notes="root scope reviewed and ready for production"
|
|
)
|
|
assert env.error is None
|
|
assert env.status == "awaiting_ceo_approval"
|
|
git_svc.create_pr.assert_not_awaited()
|
|
task_svc.escalate_to_ceo.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_pm_complete_rejects_in_progress_code_root_toward_submit_root() -> (
|
|
None
|
|
):
|
|
"""A code root must pass the in-path gate first. main_pm_complete rejects it
|
|
while still in_progress and points the Main PM at submit_root."""
|
|
main_pm_id = uuid4()
|
|
root_task_id = uuid4()
|
|
t = MagicMock(
|
|
id=root_task_id,
|
|
status="in_progress",
|
|
assigned_to=main_pm_id,
|
|
pr_number=None,
|
|
branch_name="feature/main_pm/root123",
|
|
parent_task_id=None,
|
|
team="main_pm",
|
|
)
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
git_svc = AsyncMock()
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, git=git_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.main_pm_complete(
|
|
main_pm_id, root_task_id, notes="root scope reviewed; ready for CEO sign-off"
|
|
)
|
|
assert env.error is not None
|
|
assert "submit_root" in (env.remediate or "")
|
|
task_svc.escalate_to_ceo.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_root_accepts_main_pm_and_enters_the_gate() -> None:
|
|
"""submit_root is the Main PM's entry to the in-path gate. It reuses the
|
|
cell PM's _submit_up_guard for ownership/state, so the ownership guard must
|
|
NOT hardcode-reject main_pm — otherwise submit_root and complete point at
|
|
each other and a code root can never close (the circular-rejection bug)."""
|
|
main_pm_id = uuid4()
|
|
root_task_id = uuid4()
|
|
in_prog = MagicMock(
|
|
id=root_task_id,
|
|
status="in_progress",
|
|
assigned_to=main_pm_id,
|
|
pr_number=None,
|
|
branch_name="feature/main_pm/root123",
|
|
parent_task_id=None,
|
|
batch_id=None, # a normal root carries no batch_id (not a MegaTask umbrella)
|
|
team="main_pm",
|
|
)
|
|
gated = MagicMock(**{**in_prog.__dict__, "status": "awaiting_pr_review"})
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = in_prog
|
|
task_svc.submit_for_review.return_value = gated
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
task_svc.uncovered_parent_acceptance_criteria.return_value = []
|
|
task_svc.agent_for.return_value = MagicMock(role="main_pm", team="main_pm")
|
|
task_svc.session.begin_nested = MagicMock(
|
|
return_value=MagicMock(__aenter__=AsyncMock(), __aexit__=AsyncMock())
|
|
)
|
|
git_svc = AsyncMock()
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, git=git_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.submit_root(
|
|
main_pm_id, root_task_id, notes="root scope assembled; opening root→master PR"
|
|
)
|
|
assert env.error is None, env.as_dict()
|
|
assert env.status == "awaiting_pr_review"
|
|
task_svc.submit_for_review.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_pm_complete_walks_branchless_coordination_root_to_ceo() -> None:
|
|
"""A branchless coordination root (product fan-out, no repo/PR) skips the
|
|
in-path gate: main_pm_complete walks it in_progress→awaiting_pm_review and
|
|
escalates to the CEO. No root→master PR is created (it has no branch)."""
|
|
main_pm_id = uuid4()
|
|
root_task_id = uuid4()
|
|
in_prog = MagicMock(
|
|
id=root_task_id,
|
|
status="in_progress",
|
|
assigned_to=main_pm_id,
|
|
pr_number=None,
|
|
branch_name=None,
|
|
parent_task_id=None,
|
|
team="main_pm",
|
|
)
|
|
awaiting = MagicMock(**{**in_prog.__dict__, "status": "awaiting_pm_review"})
|
|
after = MagicMock(**{**in_prog.__dict__, "status": "awaiting_ceo_approval"})
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = in_prog
|
|
task_svc.submit_pm_review.return_value = awaiting
|
|
task_svc.escalate_to_ceo.return_value = after
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
git_svc = AsyncMock()
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, git=git_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.main_pm_complete(
|
|
main_pm_id, root_task_id, notes="coordination root reviewed; ready for CEO"
|
|
)
|
|
assert env.error is None
|
|
assert env.status == "awaiting_ceo_approval"
|
|
git_svc.create_pr.assert_not_awaited()
|
|
task_svc.submit_pm_review.assert_awaited_once()
|
|
task_svc.escalate_to_ceo.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_pm_complete_skips_pr_creation_if_already_master_targeted() -> None:
|
|
main_pm_id = uuid4()
|
|
root_task_id = uuid4()
|
|
t = MagicMock(
|
|
id=root_task_id,
|
|
status="awaiting_pm_review",
|
|
assigned_to=main_pm_id,
|
|
pr_number=42,
|
|
branch_name="feature/backend/root123",
|
|
parent_task_id=None,
|
|
team="backend",
|
|
)
|
|
after = MagicMock(**{**t.__dict__, "status": "awaiting_ceo_approval"})
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.escalate_to_ceo.return_value = after
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
git_svc = AsyncMock()
|
|
git_svc.pr_target.return_value = "master"
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, git=git_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
await c.main_pm_complete(
|
|
main_pm_id, root_task_id, notes="root scope reviewed and ready"
|
|
)
|
|
git_svc.create_pr.assert_not_awaited()
|
|
task_svc.escalate_to_ceo.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_pm_complete_rejects_non_root_task() -> None:
|
|
main_pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(
|
|
id=task_id,
|
|
status="awaiting_pm_review",
|
|
assigned_to=main_pm_id,
|
|
parent_task_id=uuid4(), # has parent -> not a root task
|
|
)
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
deps = _make_deps(task=task_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.main_pm_complete(main_pm_id, task_id, notes="x")
|
|
body = env.as_dict()
|
|
assert body["error"] == "invalid_state"
|
|
assert "root tasks" in body["message"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_main_pm_complete_blocks_unfinished_subtasks() -> None:
|
|
main_pm_id = uuid4()
|
|
root_task_id = uuid4()
|
|
t = MagicMock(
|
|
id=root_task_id,
|
|
status="awaiting_pm_review",
|
|
assigned_to=main_pm_id,
|
|
parent_task_id=None,
|
|
team="backend",
|
|
)
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.all_subtasks_terminal.return_value = False
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.main_pm_complete(main_pm_id, root_task_id, notes="x")
|
|
body = env.as_dict()
|
|
assert body["error"] == "tracing_gap"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_complete_dispatches_cell_pm() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(
|
|
id=task_id,
|
|
status="awaiting_pm_review",
|
|
assigned_to=pm_id,
|
|
parent_task_id=uuid4(),
|
|
pr_number=8,
|
|
branch_name="feature/backend/abc--def",
|
|
team="backend",
|
|
)
|
|
after = MagicMock(**{**t.__dict__, "status": "completed"})
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.agent_for.return_value = MagicMock(role="cell_pm")
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
task_svc.cell_pm_complete.return_value = after
|
|
git_svc = AsyncMock()
|
|
git_svc.pr_merge.return_value = {"merged": True, "merge_commit_sha": "x"}
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, git=git_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.complete(
|
|
pm_id, task_id, notes="cell scope reviewed and approved for merge"
|
|
)
|
|
assert env.status == "completed"
|
|
task_svc.cell_pm_complete.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_complete_dispatches_main_pm() -> None:
|
|
main_pm_id = uuid4()
|
|
root_task_id = uuid4()
|
|
t = MagicMock(
|
|
id=root_task_id,
|
|
status="awaiting_pm_review",
|
|
assigned_to=main_pm_id,
|
|
pr_number=None,
|
|
branch_name="feature/backend/root123",
|
|
parent_task_id=None,
|
|
team="backend",
|
|
)
|
|
after = MagicMock(**{**t.__dict__, "status": "awaiting_ceo_approval"})
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.agent_for.return_value = MagicMock(role="main_pm")
|
|
task_svc.all_subtasks_terminal.return_value = True
|
|
task_svc.escalate_to_ceo.return_value = after
|
|
git_svc = AsyncMock()
|
|
git_svc.create_pr.return_value = {"pr_number": 99, "pr_url": "x"}
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
journal_svc.has_reflect_for_task.return_value = True
|
|
deps = _make_deps(task=task_svc, git=git_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.complete(
|
|
main_pm_id, root_task_id, notes="root scope reviewed and ready"
|
|
)
|
|
assert env.status == "awaiting_ceo_approval"
|
|
task_svc.escalate_to_ceo.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_complete_rejects_non_pm_role() -> None:
|
|
dev_id = uuid4()
|
|
task_id = uuid4()
|
|
task_svc = AsyncMock()
|
|
task_svc.agent_for.return_value = MagicMock(role="developer")
|
|
deps = _make_deps(task=task_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.complete(dev_id, task_id, notes="reviewed and approved")
|
|
body = env.as_dict()
|
|
assert body["error"] == "not_authorized"
|
|
assert "cell_pm" in body["remediate"] and "main_pm" in body["remediate"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_up_routes_by_escalation_target() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(id=task_id, status="blocked", assigned_to=pm_id, team="backend")
|
|
after = MagicMock(**{**t.__dict__, "assigned_to": uuid4()})
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.agent_for.return_value = MagicMock(
|
|
role="cell_pm",
|
|
escalation_target="main-pm",
|
|
)
|
|
task_svc.escalate.return_value = after
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.escalate_up(pm_id, task_id, reason="cross-cell coordination needed")
|
|
assert env.error is None
|
|
task_svc.escalate.assert_awaited_once_with(
|
|
pm_id,
|
|
task_id,
|
|
"cross-cell coordination needed",
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_up_returns_invalid_state_when_target_lookup_fails() -> None:
|
|
"""Regression: escalate_up_to_role returning None used to crash on t.status."""
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(id=task_id, status="blocked", assigned_to=pm_id, team="backend")
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.agent_for.return_value = MagicMock(
|
|
role="cell_pm",
|
|
escalation_target="main-pm",
|
|
)
|
|
task_svc.escalate.return_value = None # target slug not found in DB
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.escalate_up(pm_id, task_id, reason="needs cross-cell coordination")
|
|
body = env.as_dict()
|
|
assert body["error"] == "invalid_state"
|
|
assert "main-pm" in body["message"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_up_blocks_without_journal_decision() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(id=task_id, status="blocked")
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
# Spec gate runs before the journal:decision preflight; provide a
|
|
# valid PM role so the gate passes and the preflight is the
|
|
# load-bearing rejector.
|
|
task_svc.agent_for.return_value = MagicMock(
|
|
role="cell_pm", escalation_target="main-pm"
|
|
)
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = False
|
|
journal_svc.latest_decision_at.return_value = None
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.escalate_up(pm_id, task_id, reason="needs cross-cell coordination")
|
|
body = env.as_dict()
|
|
assert body["error"] == "tracing_gap"
|
|
assert "journal:decision" in body["missing"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_up_no_target_returns_invalid_state() -> None:
|
|
"""Verb-specific preflight: PM whose escalation_target is unconfigured.
|
|
|
|
The spec allows cell_pm/main_pm to call escalate_up regardless of
|
|
target slug presence (target metadata lives on the agent record, not
|
|
the lifecycle). The verb body's preflight is what surfaces the
|
|
invalid_state when no target is configured.
|
|
"""
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
t = MagicMock(id=task_id, status="blocked")
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = t
|
|
task_svc.agent_for.return_value = MagicMock(
|
|
role="cell_pm",
|
|
escalation_target=None,
|
|
)
|
|
journal_svc = AsyncMock()
|
|
journal_svc.has_decision_for_task.return_value = True
|
|
journal_svc.latest_decision_at.return_value = datetime.now(UTC)
|
|
deps = _make_deps(task=task_svc, journal=journal_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.escalate_up(pm_id, task_id, reason="needs cross-cell coordination")
|
|
body = env.as_dict()
|
|
assert body["error"] == "invalid_state"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_up_task_not_found() -> None:
|
|
pm_id = uuid4()
|
|
task_id = uuid4()
|
|
task_svc = AsyncMock()
|
|
task_svc.get.return_value = None
|
|
deps = _make_deps(task=task_svc)
|
|
c = Choreographer(deps)
|
|
|
|
env = await c.escalate_up(pm_id, task_id, reason="needs cross-cell coordination")
|
|
assert env.as_dict()["error"] == "not_found"
|