mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
* [sweep] lifecycle: 6 confirmed gaps fixed (cancel-ceo-gate, claim_pr_review gate, needs_team_match, valid_next_verbs narrowing, pr_reviewer unclaim, complete side_effect ordering)
* [chore] logical-gaps: route-layer force gate + privileged-field gate + pre-task audit attribution
tasks.py (5 gaps):
- _HATCH_OVERRIDE_STATES expanded to 7: a privileged PATCH INTO a gate
state (completed/cancelled/awaiting_{qa,documentation,pr_review,
pm_review,ceo_approval}) now requires explicit force — the panel hatch
is no longer a quiet click that drops a task into/out of a human gate.
- _RESURRECT_SOURCE_STATES: a privileged PATCH OUT of a terminal status
(completed/cancelled) resurrects finished work and likewise requires
force, audited as an override.
- _PRIVILEGED_UPDATE_FIELDS gate: a bare task owner (UPDATE_OWN, no
ASSIGN) cannot self-reassign / re-team / re-parent / re-depend /
re-block / rewrite-plan / re-project its task — those structural fields
are PM-gated; the REST surface must not bypass the verb-layer's
reassign/delegate/triage gate. A 403 names the touched fields + the
verb to use instead.
- pre-task create denial: a role that cannot create tasks is now logged
via log_task_creation_denial (distinct task_creation target_type +
attempted payload) instead of a 'N/A' task_id that coerced to NULL and
left the role-escalation attempt unattributable.
audit.py:
- split log_task_action_denial (5-param, under PLR0913) from
log_task_creation_denial (4-param) — the create path has no task_id;
the non-UUID sentinel (N/A) is preserved in details[target_id_raw]
rather than dropped to a NULL target_id indistinguishable from any
other NULL-target denial.
tests:
- test_tasks_routes.py: parametrized admin-override gate (force
required for gate + terminal states, force succeeds).
- test_tasks_route_privileged_fields.py: dev owner 403 on
assigned_to/team/parent_task_id, 200 on dev-facing description.
- test_audit.py: pre-task attribution via log_task_creation_denial +
non-UUID sentinel preservation.
* [chore] logical-gaps: kanban board column coverage + status-class fixes (6 gaps)
models/kanban.py:
- DEV_COLUMNS: cover all 15 lifecycle statuses (was 7; dropped BACKLOG,
PAUSED, VERIFYING, NEEDS_REVISION, AWAITING_PR_REVIEW, AWAITING_PM_REVIEW,
AWAITING_CEO_APPROVAL, CANCELLED). A dev whose task bounced to
needs_revision or sits in a gate used to see their own task vanish.
- PM_COLUMNS: add the gate/revision/paused/cancelled/backlog columns so the
cell PM sees the QA->docs->PR-review->PM-review->CEO chain on its board.
- QA_COLUMNS: drop the 'In Review'->VERIFYING mapping. VERIFYING is the dev's
self-verification (task still with the dev, not with QA); it misrepresented
dev mid-verification as active QA work.
services/kanban.py:
- _build_flat_board: add an 'Other' fallback column for any task whose status
matches no configured column, so total_cards == sum(card_count) and no card
is built-then-silently-dropped (the vanished-card leak).
- get_qa_board: drop VERIFYING from qa_statuses (consistent with the column
change).
- get_documenter_board: scope to task_type=documentation so a dev IN_PROGRESS
code task sharing the cell team no longer appears under 'Gathering'.
- get_main_pm_board_flat: widen the status filter to include PENDING/CLAIMED/
COMPLETED and route those to the incoming/distributed/done columns, which
were structurally always empty under the in-flight-only filter.
tests/integration/test_kanban_service.py: parametrized coverage of every
dropped dev status, PM gate/revision states, QA excludes VERIFYING,
documenter excludes dev code tasks, flat Main PM incoming/distributed/done
populated, and the 'Other' fallback invariant.
* [chore] logical-gaps: lifecycle-enforcement validators + status-class fixes (5 gaps)
enforcement/task_lifecycle.py:
- drop the spurious VERIFYING->awaiting_documentation legacy edge. The
canonical exit is submit_qa -> awaiting_qa -> (qa_pass) ->
awaiting_documentation; the direct edge bypassed the entire QA review hop
(ungated — no role gate existed for it).
- is_waiting_state: add awaiting_pr_review. The PR-review gate parks the PM on
the reviewer; it is a waiting state. The hard-coded set was never updated
when AWAITING_PR_REVIEW was added to the enum, so the gate status was
miscategorized as active.
foundation/_validate_lifecycle.py:
- _check_status_enum_coverage: replace the tautology (STATUS_GRAPH keys every
Status by construction) with a real bidirectional check — every non-terminal
Status is the source of a transition (catches orphan states), and every
source/target referenced is a real Status member (catches stray-string
targets).
- _check_terminal_exits: split the {COMPLETED, CANCELLED} reachability into a
COMPLETED-path requirement + a cancel-exit requirement. The cancel fan-out
made the old check structurally trivial — a status whose sole exit was cancel
passed with no real forward completion path.
- _check_status_enum_parity (new, registered): cross-check spec.Status against
models.base.TaskStatus at import so the ORM column type and the lifecycle
map cannot drift (TaskType had this guard; Status did not).
tests: verifying->awaiting_documentation rejected, self-fail preserved,
awaiting_pr_review is waiting, mutually-disjoint classification invariant,
status enum parity, stray-string-target / orphan-source / cancel-only-exit
validator rejections.
* [chore] logical-gaps: stream-bus poison-pill ACK + dead-letter, periodic reclaim, cancelled-handler marker cleanup (3 gaps)
stream_bus.py:
- _handle_message isolates Event.from_json in its own try/except; an
undecodable payload (unknown EventType, bad UUID/timestamp, malformed
JSON) is dead-lettered then ACKed instead of falling through to the
broad except that only logged — a poison pill stayed pending forever
and re-failed on every reclaim. (gap: stream-bus-malformed-event-poison-pill)
- _reclaim_loop spawned alongside _listen_loop in start_listening (cancelled
in disconnect). XREADGROUP '>' delivers only NEW messages, so a runtime
handler failure left its message pending and unretried until a restart;
the loop re-runs recover_pending every 60s so the idempotency-guarded
replay actually fires. (gap: stream-bus-no-runtime-reclaim-loop)
- _run_handler_guarded marker cleanup catches BaseException so a handler
cancelled mid-flight (asyncio.CancelledError is BaseException-derived
since 3.8) clears its SET-NX marker; otherwise the guard suppressed the
very redelivery that would complete the work. (gap: stream-bus-cancelled-
handler-keeps-idempotency-marker)
TDD: 4 red->green tests in tests/unit/events/test_bus.py.
* [chore] logical-gaps: verb_runner trailing-None side-effect guard + actor_agent_id threading (3 gaps)
_verb_runner.py:
- run_intent skips the side_effects loop when a TRAILING composed action
returned None (its source-status check failed under a concurrent
transition). Previously the loop ran unconditionally on the None task
and _do_push_branch(None)/_do_pr_merge(None) crashed with a
NoneType AttributeError, turning the clean INVALID_STATE the
entry/intermediate guards give into a 500/respawn loop. The trailing
None now flows to the caller's `if task is None` handler. Latent today
(no shipped intent has both a None-capable compose and trailing
side_effects) but the runner is generic. (gap: runner-side-effects-fire-
on-trailing-none-task)
- _do_push_branch / _do_create_pr / _do_create_root_pr forward
actor_agent_id=agent.id into git_service (push_branch / create_pr),
matching _do_pr_merge. Without it, a verb on a task whose assigned_to
was cleared before the side effect falls through to created_by and
pushes from / opens a PR against the wrong workspace.
(gap: side-effect-handlers-drop-actor-agent-id)
- _do_escalate_to_ceo forwards actor_agent_id=agent.id so the
awaiting_ceo_approval audit row attributes to the specific PM/Board
agent. (gap: do-escalate-to-ceo-drops-actor-agent-id)
task.py: escalate_to_ceo gains actor_agent_id param, passed as
audit_agent_id to _validate_and_set_status and recorded as
escalated_by_agent_id in the event payload + log. escalate_to_ceo_for_agent
forwards agent.agent_id.
_impl.py: the main_pm complete->escalate path forwards
actor_agent_id=main_pm_agent_id.
TDD: 5 red->green tests (synthetic trailing-None intent, actor forwarding
for push_branch/create_pr/create_root_pr/escalate_to_ceo) + real-DB audit
test asserting the awaiting_ceo_approval row carries the actor UUID.
Updated 3 board escalate_to_ceo tests to assert the forwarded actor.
* [B-REL] release executor: idempotent half-landed retry + commit-scoped CI + decoupled workflow
Three confirmed gaps in the release fail-closed pipeline (#87/#318/#402):
#87 publish_failed retry duplicates changelog: execute() only short-circuits
on an existing tag. A publish_failed outcome (commit pushed + CI green, no
tag) left no tag, so a retry re-ran apply_version_bumps + write_changelog_entry
(re-inserting the entry above the already-present heading -> duplicate) and
commit_and_push (a second chore(release) commit). Add ReleaseOps
.release_commit_sha(version) detecting a prior release commit on the branch
(clone already at the target version); when present, skip the bump/changelog/
gate/commit pipeline and rejoin the shared CI -> publish tail on the existing
commit. No second commit, no duplicate entry.
#318 wait_for_ci polls branch-latest, not the release commit: a later push to
master during the ~40min wait made the latest run's head_sha != the release
sha forever, exhausting _CI_MAX_POLLS -> false ci_failed on a release whose
own CI was green. Thread head_sha through get_latest_ci_conclusion /
_fetch_latest_ci_run (GitHub actions/runs?head_sha=) so the gate polls the
release commit's own run; a concurrent push can no longer mask it.
#402 release CI gate reuses self_heal_ci_workflow: that setting documents an
empty-string mode for single-workflow repos which, inherited here, degraded
the fail-closed gate to the all-workflows mode git.py itself flags as
unreliable. Add release_ci_workflow (default ci.yml) and _resolve_release_
ci_workflow(); the release gate always resolves a NAMED workflow, never None.
Refactor: bundle the CI-fetch per-project inputs into a _CiRunQuery dataclass
so _fetch_latest_ci_run stays under the arg-count gate; unify the half-landed
path into execute's shared tail (drops a separate _publish_existing, one
return path). TDD red->green; ruff/mypy clean.
* [chore] logical-gaps: a2a service hierarchy gate (typed, unconditional) + persist skill on message row (3 gaps)
create_a2a_notification gated A2A hierarchy only when both ends resolved
(`if from_agent and target_agent:`), so an unattributed (from_agent falsy)
or unresolvable-target request slipped past the hierarchy matrix and
dispatched with from_agent='unknown' / to_agent='' — and a denial came back
as a bare ValueError indistinguishable from the missing-task_id ValueError.
Require both ends present, then validate via the shared typed
validate_a2a_access path (A2AAccessDeniedError + route_hint) so the legacy
notification surface enforces the same who-may-talk-to-whom invariant as the
conversation path.
send() accepts skill= and the gateway callers (qa/doc/pr_gate) pass it
expecting the receiver to learn which capability the message is about, but
send_chat_message never read it from options — silently dropped. Persist a
nullable skill column (migration 054) on a2a_messages, wire it through
send_chat_message + _msg_to_model + the A2AChatMessage model, and fix the
send() docstring (it claimed 'recorded in message metadata').
TDD: 4 red→green (skill recorded on message + surfaces in inbox; permission
denied raises typed A2AAccessDeniedError with route_hint; self-A2A raises
typed; missing from_agent raises instead of silent dispatch). 103 a2a
integration tests green; ruff/mypy clean; migration 054 verified
upgrade/downgrade on throwaway PG.
* [chore] logical-gaps: release-proposal already_published closes proposal + heartbeat-lock-loss cancels execute (2 gaps)
approve() closed the proposal only on status=='published'. A retry that finds
the tag already shipped returns 'already_published' (is_already_published),
so if a prior publish's route commit failed / HTTP 504'd, the proposal stayed
non-terminal forever — every retry returned already_published and never
closed it; only a manual cancel unstuck it. Close on both published and
already_published: the release shipped either way.
_heartbeat_loop returned silently when the lock was no longer owned (a >TTL
Redis outage let the mutex expire mid-execute), leaving executor.execute
running UNGUARDED — a concurrent approve (once Redis returns) could then
acquire the lock and _prepare_release_clone rm -rf the in-flight shared
release clone while the first execute was still mid-run_gate, re-opening the
very rm -rf-clone race the mutex+heartbeat exist to prevent. Run execute as a
task; on lock-loss the heartbeat sets a flag and cancels it, and approve()
turns the CancelledError into a structured 'lock_lost' result (an external
cancellation of approve itself still propagates — distinguished by the flag).
TDD: 2 red→green (already_published → COMPLETED not wedged; heartbeat lock-loss
→ lock_lost + execute cancelled, proposal not completed). 8 concurrency tests
green; ruff/mypy clean.
* [chore] logical-gaps: release approve async dispatch (202) — kill the 40min synchronous HTTP 504
The approve route ran the whole fail-closed execute inline: clone(600s) +
gate(1800s) + CI poll(2400s) + publish(300s) ≈ up to 85min worst case. nginx
(the single :3000 entry point, ~60s read timeout) 504'd long before it
finished, so the CEO's approve always appeared to fail even when the release
succeeded server-side — the structured ReleaseResult was unreachable over the
wire. dispatch_approve spawns the execute in a background task with a fresh
session (built from the request session's engine) and the route returns 202
'accepted' immediately; _INFLIGHT_APPROVES tracks the dispatched task for
observability (self-cleans via done-callback; the Redis mutex still refuses a
double-execute on a second click). The panel already polls GET /proposal every
30s, so it observes the final status (COMPLETED on published/already_published,
else the proposal stays open for retry); the card's approve toast now treats
'accepted' as an info 'dispatched, running in the background' instead of the
old 'Release halted' warning.
TDD: 2 route tests red→green (approve returns 202 'accepted' + the proposal
transitions to COMPLETED / stays PENDING once the background faked execute
completes; the dispatched task is awaited while the executor patch is live).
83 release tests green; ruff/mypy clean; panel typecheck+lint+format+test
green.
* [chore] mcp-servers: normalize exception bodies to Envelope + lift task_id/correlation_id on circuit_open (#232 #359 #57)
flow_server/do_server: the non-404 JSON path returned exception-handler bodies
raw (dict `error` from roboco/generic/http exception handlers, or a 422
`detail` list) — neither is the Envelope wire format the agent is prompted to
trust (string error kind + message + remediate + missing), so on any
service/validation failure the agent got no remediate and flailed until the
breaker tripped. _normalize_exception_envelope lifts the body into a real
Envelope (code -> counted string kind via _classify_dict_error_code, NOT_FOUND
-> not_found, message lifted, remediate synthesized, missing=[]; 422 -> incomplete_input with the validation detail preserved). The synthesized
envelope still flows through the breaker so a 500/422 storm trips it.
_record_and_check_circuit: the circuit_open substitution dropped task_id /
correlation_id from the top level (the SDK's envelope omits them); lift them
from the original rejection so the agent's envelope contract and ops audit-join
of the trip event still work, not just nested in inner.
intake_server._post_event: capture the relay response body under `detail` on
non-success so the grok intake agent gets the real reason (e.g. 'session not in
MegaTask scope' on a 422) instead of an opaque http_422 token with no
remediation.
TDD red->green; ruff + mypy clean; 157 mcp/SDK-breaker tests pass.
* [chore] a2a-routes: authenticate send_message responder + gate cancel task (PM-only) (#116 #423)
send_message took the responder identity from a client-supplied
metadata.from_agent, so any caller could spoof anyone (e.g.
from_agent='ceo') in the task's notes and in the spawn/notification
routed back to the original requester. Stamp the authenticated caller's
slug as the responder instead (CurrentAgentContext).
cancel_task was ungated: no auth dependency and no role check, so any
agent (or any caller) could cancel a task the lifecycle rule reserves to
PM roles (Any -> cancelled: PM roles only) — and the cascade-cancel of
all non-terminal descendants ran with a hardcoded cell_pm role and no
recorded actor. Add require_any_authenticated_agent + a PM-or-above gate,
and thread the authenticated role (into the cascade role gate) and slug
(into the cancellation note) into A2AService.cancel_task.
Tests: send_message ignores a spoofed from_agent and records the
authenticated slug; cancel rejects a developer (403) and a missing auth
header; a PM cancel threads role + slug into the service; the pre-existing
cancel success/already-terminal/not-found tests now run under a PM context
(the success test's body was missing the A2A 'name' field and false-passed
on a 422 — now genuine).
* [chore] work-session-routes: ownership check on mutating routes + stamp merge_pr merged_by from auth (#158 #271)
Every mutating work-session route keyed off session_id alone after the
role gate, so any developer could commit into / abandon / complete a
peer's active session (breaking the single-active-WorkSession invariant
and stranding that task) and any PM could merge any cell's PR — the REST
surface bypassed the verb layer's active-claimant gate entirely. Add a
shared _assert_ownership guard: dev ops require session.agent_id to be
the caller; PM merge_pr requires a cell PM to own the session's task cell
(main PM / CEO / board coordinate every cell), 404 for a missing session.
merge_pr took merged_by from the request body, so any PM could record a
PR merge under another agent's id, corrupting the merge audit trail the
completion/CEO-approval chain and metrics rely on. Drop the body param
and stamp the authenticated caller's agent_id as merged_by (the
MergePRRequest schema is gone with it).
Tests: a second dev's token hitting a peer's /commits and /abandon -> 403
(session left active); a foreign-cell PM -> 403, same-cell PM -> 200; a
spoofed body merged_by is ignored and the persisted row records the PM.
* [chore] ci-watch/dep-update dedupe: normalize git_url + treat empty-string workflow as default (#148 #1267)
The per-repo open-task dedupe filtered ProjectTable.git_url == git_url
(exact), while the orchestrator collapses its poll set by repo_key
(lower / strip trailing '/' / drop '.git'). Two projects whose git_url
differs only by those accidentals (a monorepo's cell-projects, or a
re-registered canonical project) defeated the one-open-task-per-repo
invariant and opened duplicate fix / dep-update tasks. Extract
roboco.utils.converters.repo_key as the single source and match the
dedupe query on its SQL mirror (regexp_replace(rtrim(lower(...)))).
The ci_watch (git_url, workflow) dedupe used func.coalesce(ci_watch_workflow,
default), but SQL COALESCE only substitutes for NULL — a project saved with
ci_watch_workflow='' (reachable via panel/API) yielded coalesce('', default)
= '' != default, so the DB diverged from the engine/orchestrator (which
collapse '' to the default via Python truthiness) and opened a duplicate
fix task every red cycle. Wrap with func.nullif(..., '') so an empty string
collapses to the default too.
Tests: a ''-workflow + NULL-workflow project on one repo dedupe to one task;
git_url accidentals (.git suffix / trailing slash) dedupe across both
ci_watch and dep_update. The orchestrator _repo_key now delegates to repo_key.
* [chore] admin_set_status: attribute the blocked-restore to the admin actor + emit override row (#2176)
admin_set_status taking a BLOCKED task to pending/in_progress with a
pre-block snapshot returned early via _apply_pre_block_restore, which
emitted its audit row with agent_role=None and audit_agent_id=restored_owner
(the pre-block dev) — the admin actor_id/actor_role were dropped entirely.
Because this branch runs with force=false (pending/in_progress aren't hatch
destinations), the distinguishing task.admin_override row (written only on
the non-restore path, gated by force) was never written, so an operator
could silently re-own a blocked task with no trace of who triggered it.
Thread actor_id/actor_role into _apply_pre_block_restore (admin_set_status
passes them with admin_override=True) so the transition audit row attributes
the re-owning to the admin, and emit a task.admin_override row (forced=False,
restore=True) on this branch independent of the force flag. The in-band
unblock(restore=True) path passes no actor and keeps the legacy attribution
(restored owner) with no override row.
Test: admin PATCH status=pending on a BLOCKED task with a snapshot attributes
every audit row to the admin (not the restored dev) and emits the override
row.
* [chore] converters: typed InvalidIdentifierError from require_uuid + log the orchestrator drop (#25)
require_uuid raised a bare ValueError('UUID value cannot be None'), so a
malformed/None identifier propagated as an opaque error callers either let
500 or broad-catch-and-silently-swallow — the orchestrator reaper call site
wrapped it in a bare except-Exception return with NO log, dropping a bad
task_id_str invisibly. Introduce InvalidIdentifierError(ValueError) and
raise it from require_uuid for both None and unparseable input; it stays a
ValueError subclass so existing except-ValueError / except-Exception callers
are unaffected, but typed so a caller can handle a bad identifier distinctly.
The reaper now catches the typed error, logs at warning, and no-ops — the
drop is visible instead of swallowed.
Tests: None and an unparseable string both raise InvalidIdentifierError; it
subclasses ValueError (back-comat).
* [sweep] notification_delivery: list_system_notifications over-fetch-then-slice for pending_ack_only
The SQL limit was applied before the post-fetch 'not fully acked' Python
filter. A window of newer fully-acked ack-required rows filled the limit
and masked older unacked notifications the operator still needs to act on
(the pending-ACK queue silently under-reported; a CEO-approval notification
could be hidden by newer already-acked noise). pending_ack_only now drops
the SQL limit, filters in Python, then slices to limit; the non-pending
branch keeps the SQL limit unchanged.
* [sweep] proactive: drop vestigial code-patterns surface from context package
Code indexing was removed, so _find_code_patterns always returned [] yet
build_context_package still called it, ContextPackage.code_patterns stayed
a live field, _build_summary advertised 'Found N code patterns', and
_count_items counted it — a permanently-empty slot the system claimed to
populate. The dead method, its call, the summary line, and the count
reference are removed. The code_patterns field itself is retained
(always-empty, serialized in to_dict and the optimal route response) for
API/schema back-compat, marked deprecated in its docstring.
* [sweep] migration 052: integration-test the task_cell_projects unique constraint
The UNIQUE(task_id, team) 'one project per cell per task' invariant was
only exercised through SimpleNamespace stubs that never touch a DB
session, so the real Postgres constraint was unverified. If it were
mis-declared or dropped, two same-team rows could coexist and
_resolve_subtask_project would non-deterministically return one, cutting
a subtask's branch/PR against the wrong repo. Adds an integration test
that inserts two same-(task_id, team) rows and asserts IntegrityError on
uq_task_cell_projects_task_team, plus a positive different-teams case.
* [sweep] pr_gate: classify MegaTask root-subtask as root so its root->master PR gets COMMENT (#608)
_post_gate_review_to_pr identified a root->master PR by absence of a
parent_task_id. A MegaTask root-subtask opens its own root->master PR into
the project's master (submit_root, parent='master') but carries
parent_task_id=umbrella, so is_root was False and the gate posted APPROVE
(pr_pass) / REQUEST_CHANGES (pr_fail) instead of COMMENT. The APPROVE could
satisfy a single-approval master branch-protection rule and let a non-CEO
merge via the GitHub UI before the CEO, against the documented invariant
that only the CEO acts on master. is_root now also covers
is_batch_root_subtask (batch_id set + parented); a non-batch cell-PM
coordination root keeps batch_id=None so it stays a cell->root PR
(APPROVE/REQUEST_CHANGES). Extends the _task test helper with a batch_id
kwarg.
* [sweep] enforcement: complete the status-class partition + coverage invariant (#247)
is_waiting_state already covered awaiting_pr_review (the primary fix), but
the doc's coverage invariant was missing: backlog and pending fell through
ALL three predicates (terminal/active/waiting), so a future enum addition
could silently land in no category. is_waiting_state now also covers
pending (waiting for a claim) and backlog (waiting on PM activation), so
is_terminal_state / is_active_state / is_waiting_state partition the whole
Status enum. Adds test_status_classification_covers_every_enum_member
asserting every Status member is classified by exactly one predicate, so
an enum addition that drifts the partition fails the build.
* [chore] test-suite: unblock the quality gate (mypy + 2 behavior fixes)
12 mypy errors across 5 test files: drop banned type:ignore comments
(lifecycle_spec monkeypatch uses cast(Any, ...); the ignores were unused),
wrap SQLAlchemy-typed ids with cast(UUID, ...) for AgentContext / WorkSession
args (AgentTable.id is Mapped[sqla UUID], not uuid.UUID), annotate **kw: Any,
and cast(Any, svc) for a method-assignment mock.
test_cancel_descendants_cascades_for_authorized_pm: the child was parked in
awaiting_ceo_approval, which the spec gates to CEO-only cancel
(lifecycle.py:378-389) — a cell_pm cascade correctly refuses it (the #103
refuse path). Use a PM-cancelable in_progress child so the positive-cascade
assertion holds; the refuse case is already covered by its sibling test.
test_a2a_message_auth: /message/send now resolves the authenticated
responder slug via get_agent_context (a DB lookup, #116). This is a DB-free
unit test of the token gate + route body, so stub get_agent_context in the
fixture — the gate (require_any_authenticated_agent) still runs real and
401s on a missing/forged token before that dependency resolves.
* [chore] complexity: split 5 C-rank blocks to <=B for the xenon gate
No behavior change; each C-rank function factored into a helper so the
complexity gate (xenon --max-absolute B) holds.
- lifecycle.can_invoke_action: extract the team-match check into
_check_team_match.
- a2a.cancel_task: extract _status_value_of + _apply_cancel_note.
- task._apply_pre_block_restore: extract _restore_block_ownership (status/
owner restore + snapshot clear) and _emit_admin_override_audit (#2176).
- release_proposal.approve: extract _finalize_release_lock (heartbeat/
execute cancel + mutex release) out of the finally.
- kanban.get_main_pm_board_flat: dict-dispatch the column routing instead
of a 7-branch if/elif ladder (status wins over team; in-flight + no cell
team falls through to Coordination, #196).
* [chore] lifecycle artifacts: regenerate to match the spec (foundation-check)
The rendered artifacts (docs/rag/lifecycle, panel/lib/lifecycle.json, the
_generated role-prompt fragments) had drifted from the spec — the prior
sweep commits (cancel-CEO gate, claim_pr_review preconditions, pr_reviewer
unclaim, complete merge-first ordering) changed spec data without
regenerating, and the foundation-check render+diff stage never ran because
mypy failed earlier in the gate. make foundation-check now passes.
* [fix] chat: wire live message delivery end-to-end (MESSAGE_SENT)
send_message persisted messages but never broadcast them, there was no
MESSAGE_SENT event type or bridge forwarder, and the panel session view
had no websocket subscription — the live chat path was dead end-to-end.
- add EventType.MESSAGE_SENT and publish it best-effort on every persisted
send (a bus outage logs, never rolls back the durable row)
- bridge _handle_message_event forwards to /ws/sessions/{id} and
/ws/channels/{id}; subscribe it in register_websocket_bridge_handlers
- panel useSessionStream subscribes the session view; the page invalidates
the transcript + session-detail queries on each message.new so the held
(staleTime Infinity) views refresh live without the manual Refresh
* [fix] chat: return session task_links in one read; drop panel N+1
GET /sessions/{id} ran a bare select and session_to_response omitted
task_links, so it always returned them empty — the panel worked around it
with a triple-fetch (get session, get-tasks-for-session which re-fetched
the same endpoint, then a task GET per link), and the links never showed.
- add get_session_with_links(_or_raise) that eager-loads task_links -> task
- add session_to_response_with_links; GET /sessions/{id} uses both
- panel useSession now relies on the single populated response; remove the
dead getTasksForSession + per-task fetch and the unused tasksApi import
* [fix] chat: validate reply_to against the effective session; guard closed-session composer
Posting to a closed session transparently redirects the message to the
group's active session (intended for agents holding stale refs), but
reply_to was validated against the requested session, not the one the
message lands in — letting a cross-session reply slip through — and the
panel silently posted there too, so the message vanished from the view.
- validate reply_to against session.id (the effective, possibly-redirected
session), not req.session_id
- panel: render a "session is closed" notice instead of the composer for a
non-active session; if a send still lands elsewhere (stale status), toast
that it went to the active session rather than letting it appear to vanish
* [fix] chat: close session/group/message read IDOR; fix doubled 404s
get_session and the messages-list took an agent id but never used it, and
get_group took none at all — any authenticated agent could read any private
channel's group, session, and message transcripts. Three NotFoundError sites
also passed a full sentence as resource_type, yielding "... not found not found".
- add require_group_read_access / require_session_read_access (channel
member / silent observer / privileged, mirroring list_group_sessions_for_agent)
and get_session_with_links_for_agent; enforce on GET /sessions/{id},
GET /sessions/{id}/tasks, GET /messages, GET /groups/{id} (-> 403 on deny)
- fix the three doubled-404 sites to the NotFoundError(resource_type, resource_id) form
Also folds two gate fixes for the prior chat commits: cast session.id to UUID
for the reply_to validation, and ruff import/format touch-ups.
Note: POST /messages intentionally still skips the channel write-ACL on the
HTTP (human-CEO/panel) path — the CEO is not in writers for 8/11 channels, so
enforcing it there would block the panel; the gateway/agent path enforces it.
* [fix] secretary: harden live chat — stuck spinner, mid-reply clobber, reload
The Secretary live chat had three live-behaviour bugs: a dropped SSE
connection left a permanent "thinking…" spinner (openStream set no
transport-error handler, so the no-data error Event was swallowed by the
JSON-parse guard and streaming never reset); sending mid-reply wiped the
accumulation buffer and pushed a user message without guarding the in-flight
turn, abandoning/duplicating the reply; and the chat lived only in React
state, so a reload wiped it.
- route the dual-purpose `error` listener: server-sent JSON → handleEvent,
transport error (no data) → reset streaming, surface a notice, close stream
- guard send while streaming (streamingRef); disable the composer Send/Enter
while a reply is in flight
- persist sessionId + messages to localStorage (TTL'd) and, on mount, restore
+ re-attach the stream once the backend confirms the session is still alive
(mirrors the intake/prompter durability)
* [chore] groups: extract group-read helper to keep module rank A
The get_group IDOR access-check added try/except branches that tipped the
module to xenon rank B. Extract the service-error→HTTP mapping into a small
helper so get_group stays lean and the module is rank A again (behaviour
unchanged; covered by the groups route tests).
* [fix] chat: correct panel session-task mutation endpoints
linkTask/unlinkTask posted to /add-task and /remove-task (with a body), but
the backend exposes POST /sessions/{id}/tasks and DELETE
/sessions/{id}/tasks/{task_id} (path param) — so every call 404'd. updateTaskLink
targeted /update-task, a route that does not exist at all. Point linkTask and
unlinkTask at the real routes and drop the phantom updateTaskLink. All three were
unused, so no behaviour changes today — this removes a latent 404 trap.
* [docs] chat: document live message delivery (MESSAGE_SENT / message.new)
Document the live transcript-update path the chat-subsystem fixes wired:
- docs/api/websockets.md: add the message.new event-types row (carried on
/ws/sessions + /ws/channels from EventType.MESSAGE_SENT) and note the
forwarder sets type:"message.new"
- docs/panel/communications-and-journals.md: the session transcript updates
live; a closed session is read-only (composer disabled)
- CLAUDE.md: name message.new on the per-resource streams and make
MESSAGE_SENT the worked example of the add-a-live-event recipe
The internal roboco_map slices (gitignored) were updated in place to match.
* [docs] reconcile published docs with code since v0.13.0
Drift caught by the doc-reconciliation pass (all verified against HEAD):
- CLAUDE.md + rag: pr_reviewer gained the unclaim verb (16b71be8)
- rag permissions/task-states/task-tools: awaiting_ceo_approval -> cancelled is
CEO-only, not PM+CEO (16b71be8 cancel-ceo-gate; lifecycle.py:373-382)
- deploy/env-reference: ROBOCO_APP_VERSION default 0.9.0 -> 0.14.0 (config.py:31);
add ROBOCO_RELEASE_CI_WORKFLOW row (2759edf7, config.py:454)
- deploy/data-and-migrations: 44->54 revisions, head 054_a2a_message_skill
- optional/autonomous-maintenance: CI-watch dedupe is per (repo, workflow) (d34bc1a7)
---------
Co-authored-by: Renn F <rennf93@users.noreply.github.com>
3558 lines
123 KiB
Python
3558 lines
123 KiB
Python
"""Tasks API route coverage — list/get/lifecycle endpoints."""
|
|
|
|
from __future__ import annotations
|
|
|
|
from http import HTTPStatus
|
|
from pathlib import Path
|
|
from types import SimpleNamespace
|
|
from typing import TYPE_CHECKING, Any, cast
|
|
from unittest.mock import AsyncMock, patch
|
|
from uuid import UUID, uuid4
|
|
|
|
import pytest
|
|
import pytest_asyncio
|
|
from fastapi import FastAPI, HTTPException
|
|
from httpx import ASGITransport, AsyncClient
|
|
from roboco.api.deps import get_agent_context, get_db
|
|
from roboco.api.routes.tasks import (
|
|
_translate_error,
|
|
get_awaiting_ceo_approval_tasks,
|
|
get_awaiting_pm_review_tasks,
|
|
)
|
|
from roboco.api.routes.tasks import (
|
|
router as tasks_router,
|
|
)
|
|
from roboco.db.tables import AgentTable, ProjectTable, TaskTable
|
|
from roboco.exceptions import GitError, TaskLifecycleError
|
|
from roboco.foundation.policy.lifecycle import STATUS_GRAPH
|
|
from roboco.foundation.policy.lifecycle import Status as LifecycleStatus
|
|
from roboco.models import AgentRole, AgentStatus, Team
|
|
from roboco.models.base import (
|
|
TaskNature,
|
|
TaskStatus,
|
|
TaskType,
|
|
)
|
|
from roboco.models.permissions import AgentContext
|
|
from roboco.services.base import (
|
|
NotFoundError,
|
|
ServiceError,
|
|
UnauthorizedError,
|
|
ValidationError,
|
|
)
|
|
from roboco.services.base import ServiceError as SvcError
|
|
from roboco.services.git import GitService
|
|
from roboco.services.notification_delivery import EscalationError
|
|
from roboco.services.permissions import PermissionService
|
|
from roboco.services.task import TaskService
|
|
|
|
if TYPE_CHECKING:
|
|
from collections.abc import AsyncIterator
|
|
|
|
from sqlalchemy.ext.asyncio import AsyncSession
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def task_client(
|
|
db_session: AsyncSession,
|
|
) -> AsyncIterator[dict]:
|
|
main_pm = AgentTable(
|
|
id=uuid4(),
|
|
name="MainPM",
|
|
slug=f"main-pm-{uuid4().hex[:8]}",
|
|
role=AgentRole.MAIN_PM,
|
|
team=None,
|
|
status=AgentStatus.ACTIVE,
|
|
model_config={},
|
|
system_prompt="pm",
|
|
capabilities=[],
|
|
permissions={},
|
|
metrics={},
|
|
)
|
|
db_session.add(main_pm)
|
|
await db_session.flush()
|
|
project = ProjectTable(
|
|
id=uuid4(),
|
|
name="TR-Proj",
|
|
slug=f"tr-proj-{uuid4().hex[:6]}",
|
|
git_url="https://example.com/r.git",
|
|
assigned_cell=Team.BACKEND,
|
|
created_by=main_pm.id,
|
|
)
|
|
db_session.add(project)
|
|
await db_session.flush()
|
|
|
|
app = FastAPI()
|
|
app.include_router(tasks_router, prefix="/api/tasks")
|
|
|
|
async def _override_db() -> AsyncIterator[AsyncSession]:
|
|
yield db_session
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=cast("UUID", main_pm.id), role=AgentRole.MAIN_PM, team=None
|
|
)
|
|
|
|
app.dependency_overrides[get_db] = _override_db
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
yield {
|
|
"client": client,
|
|
"agent": main_pm,
|
|
"project": project,
|
|
"db": db_session,
|
|
}
|
|
app.dependency_overrides.clear()
|
|
|
|
|
|
_HDR = {"X-Agent-ID": str(uuid4()), "X-Agent-Role": "main_pm"}
|
|
|
|
|
|
def _seed_task(
|
|
setup: dict, *, status: TaskStatus = TaskStatus.PENDING, **kw: Any
|
|
) -> TaskTable:
|
|
task = TaskTable(
|
|
id=uuid4(),
|
|
title=kw.pop("title", "t"),
|
|
description=kw.pop("description", "d"),
|
|
acceptance_criteria=["ac"],
|
|
status=status,
|
|
priority=kw.pop("priority", 2),
|
|
task_type=kw.pop("task_type", TaskType.CODE),
|
|
nature=kw.pop("nature", TaskNature.TECHNICAL),
|
|
project_id=kw.pop("project_id", setup["project"].id),
|
|
created_by=kw.pop("created_by", setup["agent"].id),
|
|
team=kw.pop("team", Team.BACKEND),
|
|
**kw,
|
|
)
|
|
setup["db"].add(task)
|
|
return task
|
|
|
|
|
|
async def _seed_agent(
|
|
setup: dict, *, role: AgentRole = AgentRole.DEVELOPER
|
|
) -> AgentTable:
|
|
"""Seed a real agent so FK constraints don't break."""
|
|
other = AgentTable(
|
|
id=uuid4(),
|
|
name="Other",
|
|
slug=f"other-{uuid4().hex[:8]}",
|
|
role=role,
|
|
team=Team.BACKEND,
|
|
status=AgentStatus.ACTIVE,
|
|
model_config={},
|
|
system_prompt="x",
|
|
capabilities=[],
|
|
permissions={},
|
|
metrics={},
|
|
)
|
|
setup["db"].add(other)
|
|
await setup["db"].flush()
|
|
return other
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_task(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
"/api/tasks",
|
|
json={
|
|
"title": "Test Task",
|
|
"description": "Some description that is long enough for the schema",
|
|
"acceptance_criteria": ["criteria"],
|
|
"team": "backend",
|
|
"project_id": str(task_client["project"].id),
|
|
"task_type": "code",
|
|
"nature": "technical",
|
|
"estimated_complexity": "medium",
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.CREATED
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_task_missing_project_id(task_client: dict) -> None:
|
|
"""Create with no project_id should fail validation."""
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
"/api/tasks",
|
|
json={
|
|
"title": "Test",
|
|
"description": "x",
|
|
"acceptance_criteria": ["a"],
|
|
"team": "backend",
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tasks(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
_seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
response = await client.get("/api/tasks", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tasks_filter_by_team(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks?team=backend", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tasks_filter_by_status(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks?status=pending", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_my_tasks(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks/my", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_pending_tasks(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks/pending", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_blocked_tasks(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks/blocked", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_awaiting_qa(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks/awaiting-qa", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_task_not_found(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get(f"/api/tasks/{uuid4()}", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_task_by_id(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
response = await client.get(f"/api/tasks/{task.id}", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_task(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
response = await client.patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"title": "Renamed"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (HTTPStatus.OK, HTTPStatus.UNPROCESSABLE_ENTITY)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_task_status_override_recovers_blocked(task_client: dict) -> None:
|
|
"""A privileged PATCH with ``status`` + ``force`` is applied as an audited
|
|
override, so an operator can recover a task wedged in ``blocked`` (which
|
|
``/complete`` refuses) instead of the status being silently dropped. The
|
|
``force`` flag acknowledges the bypass past the lifecycle gate (#13)."""
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client, status=TaskStatus.BLOCKED)
|
|
await task_client["db"].flush()
|
|
response = await client.patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"status": "completed", "force": True},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json()["status"] == "completed"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_task_status_override_refused_without_force(
|
|
task_client: dict,
|
|
) -> None:
|
|
"""#13: pasting over the lifecycle gate into a terminal/final hatch state
|
|
(completed / awaiting_qa / awaiting_pm_review) without ``force`` is refused
|
|
with 400 — the bypass must be an explicit, acknowledged forced override."""
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client, status=TaskStatus.IN_PROGRESS)
|
|
await task_client["db"].flush()
|
|
for hatch in ("completed", "awaiting_qa", "awaiting_pm_review"):
|
|
response = await client.patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"status": hatch},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST, hatch
|
|
assert "force" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_task_status_override_non_hatch_needs_no_force(
|
|
task_client: dict,
|
|
) -> None:
|
|
"""#13: a non-terminal recovery override (blocked -> pending) does NOT require
|
|
``force`` — only the terminal/final hatch states do."""
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client, status=TaskStatus.BLOCKED)
|
|
await task_client["db"].flush()
|
|
response = await client.patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"status": "pending"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json()["status"] == "pending"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("hatch", ["awaiting_ceo_approval", "cancelled"])
|
|
async def test_update_task_override_gate_states_require_force(
|
|
task_client: dict, hatch: str
|
|
) -> None:
|
|
"""The hatch set covers the CEO gate and the terminal cancel too (not just
|
|
completed/awaiting_qa/awaiting_pm_review): a privileged PATCH into either
|
|
without ``force`` is refused 400."""
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client, status=TaskStatus.IN_PROGRESS)
|
|
await task_client["db"].flush()
|
|
response = await client.patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"status": hatch},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST, hatch
|
|
assert "force" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
@pytest.mark.parametrize("hatch", ["awaiting_ceo_approval", "cancelled"])
|
|
async def test_update_task_override_gate_states_with_force_succeeds(
|
|
task_client: dict, hatch: str
|
|
) -> None:
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client, status=TaskStatus.IN_PROGRESS)
|
|
await task_client["db"].flush()
|
|
response = await client.patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"status": hatch, "force": True},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK, hatch
|
|
assert response.json()["status"] == hatch
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_task_resurrect_terminal_requires_force(task_client: dict) -> None:
|
|
"""Resurrecting a COMPLETED task back to in_progress is a bypass of the merge
|
|
decision; the target (in_progress) is not itself a hatch state, so the
|
|
target-only gate would miss it — the source-terminal check requires force."""
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client, status=TaskStatus.COMPLETED)
|
|
await task_client["db"].flush()
|
|
no_force = await client.patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"status": "in_progress"},
|
|
headers=_HDR,
|
|
)
|
|
assert no_force.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "force" in no_force.json()["detail"]
|
|
with_force = await client.patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"status": "in_progress", "force": True},
|
|
headers=_HDR,
|
|
)
|
|
assert with_force.status_code == HTTPStatus.OK
|
|
assert with_force.json()["status"] == "in_progress"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_delete_task(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
response = await client.delete(f"/api/tasks/{task.id}", headers=_HDR)
|
|
assert response.status_code in (
|
|
HTTPStatus.OK,
|
|
HTTPStatus.NO_CONTENT,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_delete_task_not_found(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.delete(f"/api/tasks/{uuid4()}", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_subtasks_of_unknown_task(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get(f"/api/tasks/{uuid4()}/subtasks", headers=_HDR)
|
|
# Either 404 or empty list depending on implementation.
|
|
assert response.status_code in (HTTPStatus.OK, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_count_endpoint_returns_response(task_client: dict) -> None:
|
|
"""Count route may take query params we don't supply; just ensure it's reached."""
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks/count", headers=_HDR)
|
|
assert response.status_code in (HTTPStatus.OK, HTTPStatus.UNPROCESSABLE_ENTITY)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Additional list endpoints
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_awaiting_docs(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks/awaiting-docs", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_team_tasks(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks/team/backend", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_task_stats(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks/stats", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_task_stats_by_team(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks/stats/by-team", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_lifecycle_transitions_parity(task_client: dict) -> None:
|
|
"""GET /lifecycle-transitions returns the exact STATUS_GRAPH as strings.
|
|
|
|
Parity check: response keys and values must match
|
|
roboco.foundation.policy.lifecycle.STATUS_GRAPH.
|
|
"""
|
|
client = task_client["client"]
|
|
response = await client.get("/api/tasks/lifecycle-transitions", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
body = response.json()
|
|
|
|
# Keys must be exactly the set of status string values
|
|
expected_keys = {s.value for s in STATUS_GRAPH}
|
|
assert set(body.keys()) == expected_keys, (
|
|
f"Key mismatch: extra={set(body.keys()) - expected_keys}, "
|
|
f"missing={expected_keys - set(body.keys())}"
|
|
)
|
|
|
|
# Values must match STATUS_GRAPH (as sorted lists of strings)
|
|
for status_str, next_statuses in body.items():
|
|
src = LifecycleStatus(status_str)
|
|
expected_targets = sorted(t.value for t in STATUS_GRAPH[src])
|
|
assert sorted(next_statuses) == expected_targets, (
|
|
f"Targets for {status_str!r} mismatch: "
|
|
f"got {sorted(next_statuses)!r}, want {expected_targets!r}"
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Lifecycle: claim/unclaim (404 paths)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_claim_unknown_task_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/claim",
|
|
json={"role": "developer"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.FORBIDDEN,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unclaim_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(f"/api/tasks/{uuid4()}/unclaim", headers=_HDR)
|
|
assert response.status_code in (HTTPStatus.BAD_REQUEST, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_for_qa_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/submit-qa",
|
|
json={},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pass_qa_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/pass-qa",
|
|
json={"notes": "looks good and is sufficiently detailed"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.FORBIDDEN,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_fail_qa_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/fail-qa",
|
|
json={"notes": "broken in many ways"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.FORBIDDEN,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_complete_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/complete",
|
|
json={},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.FORBIDDEN,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_block_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/block",
|
|
json={"reason": "blocker", "blocker_type": "external", "what_needed": "x"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.FORBIDDEN,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unblock_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(f"/api/tasks/{uuid4()}/unblock", headers=_HDR)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.FORBIDDEN,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pause_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(f"/api/tasks/{uuid4()}/pause", headers=_HDR)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.FORBIDDEN,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_resume_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(f"/api/tasks/{uuid4()}/resume", headers=_HDR)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.FORBIDDEN,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancel_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/cancel",
|
|
json={"reason": "no longer needed"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.FORBIDDEN,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_progress_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/progress",
|
|
json={"message": "doing things", "percentage": 25},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (HTTPStatus.BAD_REQUEST, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_checkpoint_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/checkpoints",
|
|
json={
|
|
"state_summary": "halfway",
|
|
"remaining_work": ["finish API"],
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (HTTPStatus.BAD_REQUEST, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_commit_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/commits",
|
|
json={"hash": "abc123", "message": "fix"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (HTTPStatus.BAD_REQUEST, HTTPStatus.NOT_FOUND)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/escalate",
|
|
json={"reason": "needs PM input"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.FORBIDDEN,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_sessions_for_task(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
response = await client.get(f"/api/tasks/{task.id}/sessions", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Additional create_task validation paths
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_task_no_acceptance_criteria(task_client: dict) -> None:
|
|
"""Task without acceptance criteria — 4xx."""
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
"/api/tasks",
|
|
json={
|
|
"title": "T",
|
|
"description": "d",
|
|
"acceptance_criteria": [],
|
|
"team": "backend",
|
|
"project_id": str(task_client["project"].id),
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_task_blank_acceptance_criteria(task_client: dict) -> None:
|
|
"""Task with blank acceptance criteria — 400."""
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
"/api/tasks",
|
|
json={
|
|
"title": "T",
|
|
"description": "d",
|
|
"acceptance_criteria": [" ", ""],
|
|
"team": "backend",
|
|
"project_id": str(task_client["project"].id),
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_task_assigned_to_uuid(task_client: dict) -> None:
|
|
"""Task with assigned_to as UUID string — should work."""
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
"/api/tasks",
|
|
json={
|
|
"title": "T",
|
|
"description": "Twenty character description here ok",
|
|
"acceptance_criteria": ["a"],
|
|
"team": "backend",
|
|
"project_id": str(task_client["project"].id),
|
|
"assigned_to": str(task_client["agent"].id),
|
|
"task_type": "code",
|
|
"nature": "technical",
|
|
"estimated_complexity": "medium",
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.CREATED
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_task_assigned_to_slug(task_client: dict) -> None:
|
|
"""Task with assigned_to as slug — should resolve."""
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
"/api/tasks",
|
|
json={
|
|
"title": "T",
|
|
"description": "Twenty character description here ok",
|
|
"acceptance_criteria": ["a"],
|
|
"team": "backend",
|
|
"project_id": str(task_client["project"].id),
|
|
"assigned_to": task_client["agent"].slug,
|
|
"task_type": "code",
|
|
"nature": "technical",
|
|
"estimated_complexity": "medium",
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.CREATED
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_task_assigned_to_unknown_slug(task_client: dict) -> None:
|
|
"""Task with unknown assigned_to slug — 422."""
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
"/api/tasks",
|
|
json={
|
|
"title": "T",
|
|
"description": "d",
|
|
"acceptance_criteria": ["a"],
|
|
"team": "backend",
|
|
"project_id": str(task_client["project"].id),
|
|
"assigned_to": "ghost-agent-1",
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Get descendants
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_descendants(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.get(f"/api/tasks/{uuid4()}/descendants", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Update task — privileges
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_task_not_found(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.patch(
|
|
f"/api/tasks/{uuid4()}",
|
|
json={"title": "Renamed"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_task_via_put(task_client: dict) -> None:
|
|
"""PUT alias works the same as PATCH."""
|
|
client = task_client["client"]
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
response = await client.put(
|
|
f"/api/tasks/{task.id}",
|
|
json={"title": "PutRenamed"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (HTTPStatus.OK, HTTPStatus.UNPROCESSABLE_ENTITY)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Lifecycle: start
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_start_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(f"/api/tasks/{uuid4()}/start", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_start_task_not_assigned_returns_403(task_client: dict) -> None:
|
|
"""Main PM is not the assignee, so start should fail with 403."""
|
|
client = task_client["client"]
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, status=TaskStatus.CLAIMED, assigned_to=other.id)
|
|
await task_client["db"].flush()
|
|
response = await client.post(f"/api/tasks/{task.id}/start", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_start_task_no_branch_returns_400(task_client: dict) -> None:
|
|
"""Task without branch — 400."""
|
|
client = task_client["client"]
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.CLAIMED,
|
|
assigned_to=task_client["agent"].id,
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await client.post(f"/api/tasks/{task.id}/start", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "NO_BRANCH" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_start_claimed_task_no_plan_returns_400(task_client: dict) -> None:
|
|
"""Claimed task without plan — 400."""
|
|
client = task_client["client"]
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.CLAIMED,
|
|
assigned_to=task_client["agent"].id,
|
|
branch_name="feature/backend/X",
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await client.post(f"/api/tasks/{task.id}/start", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "NO_PLAN" in response.json()["detail"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Block
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_block_task_not_found(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
blocker = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/block?blocker_id={blocker.id}",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_block_task_forbidden(task_client: dict) -> None:
|
|
"""Non-assignee, non-PM cannot block."""
|
|
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, assigned_to=other.id)
|
|
blocker = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
|
|
# Override agent to a developer not assigned
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=uuid4(), role=AgentRole.DEVELOPER, team=Team.BACKEND
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/block?blocker_id={blocker.id}",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Soft-block
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_soft_block_unknown_returns_404(task_client: dict) -> None:
|
|
client = task_client["client"]
|
|
response = await client.post(
|
|
f"/api/tasks/{uuid4()}/soft-block",
|
|
json={
|
|
"reason": "stuck",
|
|
"blocker_type": "external",
|
|
"what_needed": "some external system",
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.FORBIDDEN,
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Unblock — happy path with progress notification
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unblock_task_not_blocked_returns_400(task_client: dict) -> None:
|
|
"""Unblock a task that is not blocked - 400."""
|
|
client = task_client["client"]
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.PENDING,
|
|
assigned_to=task_client["agent"].id,
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await client.post(f"/api/tasks/{task.id}/unblock", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unblock_task_forbidden(task_client: dict) -> None:
|
|
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, status=TaskStatus.BLOCKED, assigned_to=other.id)
|
|
await task_client["db"].flush()
|
|
|
|
# Override agent role to be non-PM, non-assignee
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=uuid4(), role=AgentRole.DEVELOPER, team=Team.BACKEND
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/unblock", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Pause/resume forbidden + invalid-status branches
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pause_task_forbidden(task_client: dict) -> None:
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, status=TaskStatus.IN_PROGRESS, assigned_to=other.id)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/pause", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pause_task_invalid_status_returns_400(task_client: dict) -> None:
|
|
"""Pause when not in_progress — 400."""
|
|
task = _seed_task(
|
|
task_client, status=TaskStatus.PENDING, assigned_to=task_client["agent"].id
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/pause", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_resume_task_forbidden(task_client: dict) -> None:
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, status=TaskStatus.PAUSED, assigned_to=other.id)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/resume", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_resume_task_invalid_status(task_client: dict) -> None:
|
|
task = _seed_task(
|
|
task_client, status=TaskStatus.PENDING, assigned_to=task_client["agent"].id
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/resume", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# verify
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_verify_task_not_found(task_client: dict) -> None:
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/verify", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_verify_task_forbidden(task_client: dict) -> None:
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, status=TaskStatus.IN_PROGRESS, assigned_to=other.id)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/verify", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_verify_task_invalid_status(task_client: dict) -> None:
|
|
task = _seed_task(
|
|
task_client, status=TaskStatus.PENDING, assigned_to=task_client["agent"].id
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/verify", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# submit-qa gates
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_qa_not_self_verified_returns_400(task_client: dict) -> None:
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.VERIFYING,
|
|
assigned_to=task_client["agent"].id,
|
|
self_verified=False,
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/submit-qa", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "NOT_SELF_VERIFIED" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_qa_no_commits_returns_400(task_client: dict) -> None:
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.VERIFYING,
|
|
assigned_to=task_client["agent"].id,
|
|
self_verified=True,
|
|
commits=[],
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/submit-qa", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "NO_COMMITS" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_qa_no_pr_returns_400(task_client: dict) -> None:
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.VERIFYING,
|
|
assigned_to=task_client["agent"].id,
|
|
self_verified=True,
|
|
commits=[{"hash": "abc", "message": "fix"}],
|
|
pr_number=None,
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/submit-qa", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "NO_PR" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_qa_no_progress_updates_returns_400(task_client: dict) -> None:
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.VERIFYING,
|
|
assigned_to=task_client["agent"].id,
|
|
self_verified=True,
|
|
commits=[{"hash": "abc", "message": "fix"}],
|
|
pr_number=42,
|
|
progress_updates=[],
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/submit-qa", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "NO_PROGRESS" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_qa_forbidden_non_assignee(task_client: dict) -> None:
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.VERIFYING,
|
|
assigned_to=other.id,
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/submit-qa", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# pass-qa gates
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pass_qa_non_qa_role_forbidden(task_client: dict) -> None:
|
|
task = _seed_task(task_client, status=TaskStatus.AWAITING_QA, pr_number=42)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/pass-qa",
|
|
json={"notes": "looks good and is sufficiently substantive notes"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_fail_qa_non_qa_role_forbidden(task_client: dict) -> None:
|
|
task = _seed_task(task_client, status=TaskStatus.AWAITING_QA, pr_number=42)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/fail-qa",
|
|
json={"notes": "broken in some ways"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# docs-complete
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_docs_complete_unknown_returns_4xx(task_client: dict) -> None:
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/docs-complete",
|
|
json={"notes": "completed docs"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.FORBIDDEN,
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# submit-pm-review
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_pm_review_not_found(task_client: dict) -> None:
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/submit-pm-review",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_pm_review_forbidden(task_client: dict) -> None:
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, status=TaskStatus.IN_PROGRESS, assigned_to=other.id)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/submit-pm-review",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# CEO endpoints
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_awaiting_pm_review(task_client: dict) -> None:
|
|
"""Path collides with /{task_id} — invalid UUID gives 422."""
|
|
response = await task_client["client"].get(
|
|
"/api/tasks/awaiting-pm-review", headers=_HDR
|
|
)
|
|
# Route ordering quirk: /{task_id} matches first.
|
|
assert response.status_code in (HTTPStatus.OK, HTTPStatus.UNPROCESSABLE_ENTITY)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_awaiting_ceo_approval(task_client: dict) -> None:
|
|
response = await task_client["client"].get(
|
|
"/api/tasks/awaiting-ceo-approval", headers=_HDR
|
|
)
|
|
# Same /{task_id} ordering quirk.
|
|
assert response.status_code in (HTTPStatus.OK, HTTPStatus.UNPROCESSABLE_ENTITY)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_approve_unknown_returns_4xx(task_client: dict) -> None:
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/ceo-approve",
|
|
json={"notes": "approved"},
|
|
headers=_HDR,
|
|
)
|
|
# Main PM is not CEO — 403
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_reject_non_ceo_forbidden(task_client: dict) -> None:
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/ceo-reject",
|
|
json={"notes": "rejected"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_to_ceo_unknown_returns_4xx(task_client: dict) -> None:
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/escalate-to-ceo",
|
|
json={"notes": "needs CEO"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.FORBIDDEN,
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Substitute
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_substitute_unknown_returns_4xx(task_client: dict) -> None:
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/substitute",
|
|
json={"reason": "low_context", "details": "Need more context"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.FORBIDDEN,
|
|
)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# progress / checkpoint / commit forbidden + not-found
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_progress_forbidden(task_client: dict) -> None:
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, assigned_to=other.id)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/progress",
|
|
json={"message": "doing things now", "percentage": 25},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_checkpoint_forbidden(task_client: dict) -> None:
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, assigned_to=other.id)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/checkpoint",
|
|
json={"state_summary": "halfway", "remaining_work": ["finish"]},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_checkpoint_unknown_returns_404(task_client: dict) -> None:
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/checkpoint",
|
|
json={"state_summary": "halfway", "remaining_work": ["finish"]},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_commit_unknown_returns_404(task_client: dict) -> None:
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/commit",
|
|
json={"hash": "abc1234", "message": "fix"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_commit_forbidden(task_client: dict) -> None:
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, assigned_to=other.id)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/commit",
|
|
json={"hash": "abc1234", "message": "fix"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Activate (PM)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_activate_unknown_returns_4xx(task_client: dict) -> None:
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/activate", headers=_HDR
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.NOT_FOUND,
|
|
HTTPStatus.FORBIDDEN,
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_activate_developer_forbidden(task_client: dict) -> None:
|
|
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=task_client["agent"].id,
|
|
role=AgentRole.DEVELOPER,
|
|
team=Team.BACKEND,
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/activate", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Listing variants — different team filters
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tasks_by_team_filter(task_client: dict) -> None:
|
|
"""Both team and status filters set."""
|
|
response = await task_client["client"].get(
|
|
"/api/tasks?team=backend&status=pending", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_team_tasks_unauthorized(task_client: dict) -> None:
|
|
"""Developer trying to view a team's tasks they aren't on."""
|
|
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=task_client["agent"].id,
|
|
role=AgentRole.DEVELOPER,
|
|
team=Team.BACKEND,
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].get("/api/tasks/team/frontend", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_task_stats_by_team_developer_forbidden(
|
|
task_client: dict,
|
|
) -> None:
|
|
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=task_client["agent"].id,
|
|
role=AgentRole.DEVELOPER,
|
|
team=Team.BACKEND,
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].get("/api/tasks/stats/by-team", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# List as developer with no team — empty list
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tasks_no_team_no_view_all(task_client: dict) -> None:
|
|
"""Agent with no team and no VIEW_ALL — empty list."""
|
|
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=task_client["agent"].id,
|
|
role=AgentRole.DEVELOPER,
|
|
team=None,
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].get("/api/tasks", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json() == []
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_list_tasks_developer_with_team_filters_to_own(
|
|
task_client: dict,
|
|
) -> None:
|
|
"""Developer (no VIEW_ALL) with a team — effective_team = agent.team."""
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=task_client["agent"].id,
|
|
role=AgentRole.DEVELOPER,
|
|
team=Team.BACKEND,
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].get("/api/tasks", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert isinstance(response.json(), list)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_task_missing_project_id_returns_422(task_client: dict) -> None:
|
|
"""`TaskCreate.project_id` is `UUID` (required); pydantic rejects missing
|
|
value with 422 before the route runs. (The previously-dead inline runtime
|
|
`if not data.project_id` branch was removed.)"""
|
|
response = await task_client["client"].post(
|
|
"/api/tasks",
|
|
json={
|
|
"title": "T",
|
|
"description": "d",
|
|
"acceptance_criteria": ["a"],
|
|
"team": "backend",
|
|
# project_id intentionally missing
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Delete forbidden
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_delete_task_forbidden_non_creator(task_client: dict) -> None:
|
|
"""Developer not the creator — 403."""
|
|
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, created_by=other.id)
|
|
await task_client["db"].flush()
|
|
|
|
# Override to be a developer different from creator
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=uuid4(), role=AgentRole.DEVELOPER, team=Team.BACKEND
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].delete(f"/api/tasks/{task.id}", headers=_HDR)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# Cancel forbidden + happy path
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancel_developer_forbidden(task_client: dict) -> None:
|
|
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=task_client["agent"].id,
|
|
role=AgentRole.DEVELOPER,
|
|
team=Team.BACKEND,
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/cancel",
|
|
json={"reason": "no longer needed at all"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancel_task_pm_succeeds(task_client: dict) -> None:
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/cancel",
|
|
json={"reason": "no longer needed at all"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _translate_error: direct unit coverage for service-error → HTTP mapping
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_translate_error_not_found() -> None:
|
|
"""NotFoundError → 404."""
|
|
err = NotFoundError(resource_type="task", resource_id="123")
|
|
http_exc = _translate_error(err)
|
|
assert isinstance(http_exc, HTTPException)
|
|
assert http_exc.status_code == HTTPStatus.NOT_FOUND
|
|
assert "task not found" in http_exc.detail.lower()
|
|
|
|
|
|
def test_translate_error_unauthorized() -> None:
|
|
"""UnauthorizedError → 403."""
|
|
err = UnauthorizedError(action="delete", reason="not your task")
|
|
http_exc = _translate_error(err)
|
|
assert http_exc.status_code == HTTPStatus.FORBIDDEN
|
|
assert "delete" in http_exc.detail
|
|
|
|
|
|
def test_translate_error_validation() -> None:
|
|
"""ValidationError → 400."""
|
|
err = ValidationError("bad field value")
|
|
http_exc = _translate_error(err)
|
|
assert http_exc.status_code == HTTPStatus.BAD_REQUEST
|
|
assert http_exc.detail == "bad field value"
|
|
|
|
|
|
def test_translate_error_generic_service_error() -> None:
|
|
"""Plain ServiceError → 500."""
|
|
err = ServiceError("service exploded")
|
|
http_exc = _translate_error(err)
|
|
assert http_exc.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
|
|
assert http_exc.detail == "service exploded"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# create_task: role denial + audit logging
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_create_task_role_not_authorized(task_client: dict) -> None:
|
|
"""Override agent to a role that cannot CREATE; audit denial path runs."""
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=task_client["agent"].id,
|
|
role=AgentRole.QA,
|
|
team=Team.BACKEND,
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].post(
|
|
"/api/tasks",
|
|
json={
|
|
"title": "T",
|
|
"description": "Twenty character description here ok",
|
|
"acceptance_criteria": ["a"],
|
|
"team": "backend",
|
|
"project_id": str(task_client["project"].id),
|
|
"task_type": "code",
|
|
"nature": "technical",
|
|
"estimated_complexity": "medium",
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
assert "Not authorized" in response.json()["detail"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# update_task: forbidden (non-owner non-PM) + 500 fallback
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_task_forbidden_non_owner(task_client: dict) -> None:
|
|
"""Developer who is neither owner nor creator gets 403."""
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, assigned_to=other.id, created_by=other.id)
|
|
await task_client["db"].flush()
|
|
|
|
app = task_client["client"]._transport.app
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=uuid4(), role=AgentRole.DEVELOPER, team=Team.BACKEND
|
|
)
|
|
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
response = await task_client["client"].patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"title": "X"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
assert "Not authorized" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_update_task_service_returns_none_yields_500(
|
|
task_client: dict,
|
|
) -> None:
|
|
"""Force service.update() to return None → route raises 500."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.update = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"title": "Renamed"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
|
|
assert "update failed" in response.json()["detail"].lower()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# claim_task: ServiceError -> _translate_error
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_claim_task_service_error_translated(task_client: dict) -> None:
|
|
"""A ServiceError raised by claim_task_for_agent surfaces via _translate_error."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.claim_task_for_agent = AsyncMock(
|
|
side_effect=ValidationError("Cannot claim — already claimed")
|
|
)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/claim",
|
|
json={"agent_id": "main-pm"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_claim_task_success(task_client: dict) -> None:
|
|
"""Happy path: claim returns task, route serializes it."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.claim_task_for_agent = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
# No body — claim with the caller's own context.
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/claim",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json()["id"] == str(task.id)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# start_task: success path
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_start_task_success(task_client: dict) -> None:
|
|
"""Claimed task with branch + plan starts cleanly → in_progress."""
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.CLAIMED,
|
|
assigned_to=task_client["agent"].id,
|
|
branch_name="feature/backend/X",
|
|
plan={"steps": ["a"]},
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/start", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json()["status"] == "in_progress"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_start_task_service_returns_none_returns_400(
|
|
task_client: dict,
|
|
) -> None:
|
|
"""If service.start returns None on a non-claimed/paused task, route 400s."""
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.IN_PROGRESS,
|
|
assigned_to=task_client["agent"].id,
|
|
branch_name="feature/backend/X",
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/start", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "invalid status" in response.json()["detail"].lower()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# block_task: success + 500 fallback
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_block_task_success(task_client: dict) -> None:
|
|
"""PM blocks a task with a real blocker_id → 200."""
|
|
blocker = _seed_task(task_client)
|
|
target = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.IN_PROGRESS,
|
|
assigned_to=task_client["agent"].id,
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{target.id}/block?blocker_id={blocker.id}",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json()["status"] == "blocked"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_block_task_service_returns_none_500(task_client: dict) -> None:
|
|
"""If service.block returns None → 500."""
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.IN_PROGRESS,
|
|
assigned_to=task_client["agent"].id,
|
|
)
|
|
blocker = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.block = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/block?blocker_id={blocker.id}",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
|
|
assert "block failed" in response.json()["detail"].lower()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# soft_block: success
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_soft_block_task_success(task_client: dict) -> None:
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.IN_PROGRESS,
|
|
assigned_to=task_client["agent"].id,
|
|
)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.soft_block_task_for_agent = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/soft-block",
|
|
json={
|
|
"reason": "external system unavailable",
|
|
"blocker_type": "external",
|
|
"what_needed": "Stripe API",
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# unblock: success notifies assignee + commits
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unblock_task_success_notifies_assignee(
|
|
task_client: dict,
|
|
) -> None:
|
|
"""Unblock a blocked task assigned to a different agent → notification path."""
|
|
other = await _seed_agent(task_client)
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.BLOCKED,
|
|
assigned_to=other.id,
|
|
)
|
|
await task_client["db"].flush()
|
|
|
|
with patch(
|
|
"roboco.api.routes.tasks.get_notification_delivery_service"
|
|
) as mock_delivery:
|
|
delivery_instance = AsyncMock()
|
|
delivery_instance.notify_assignee_of_unblock = AsyncMock(return_value=None)
|
|
mock_delivery.return_value = delivery_instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/unblock", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json()["status"] != "blocked"
|
|
delivery_instance.notify_assignee_of_unblock.assert_awaited_once()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# pause / resume / verify success
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pause_task_success(task_client: dict) -> None:
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.IN_PROGRESS,
|
|
assigned_to=task_client["agent"].id,
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/pause", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json()["status"] == "paused"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_resume_task_success(task_client: dict) -> None:
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.PAUSED,
|
|
assigned_to=task_client["agent"].id,
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/resume", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_verify_task_success(task_client: dict) -> None:
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.IN_PROGRESS,
|
|
assigned_to=task_client["agent"].id,
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/verify", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# submit_for_qa: success
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_qa_success(task_client: dict) -> None:
|
|
"""All gates satisfied + status=verifying → submit succeeds."""
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.VERIFYING,
|
|
assigned_to=task_client["agent"].id,
|
|
self_verified=True,
|
|
commits=[
|
|
{
|
|
"hash": "abc1234",
|
|
"message": "wip",
|
|
"timestamp": "2026-01-01T00:00:00+00:00",
|
|
}
|
|
],
|
|
pr_number=42,
|
|
progress_updates=[
|
|
{
|
|
"timestamp": "2026-01-01T00:00:00+00:00",
|
|
"agent_id": str(task_client["agent"].id),
|
|
"message": "started",
|
|
}
|
|
],
|
|
)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/submit-qa", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json()["status"] == "awaiting_qa"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_qa_service_returns_none_returns_400(
|
|
task_client: dict,
|
|
) -> None:
|
|
"""Force service.submit_for_qa to return None → route 400s with cannot submit."""
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.VERIFYING,
|
|
assigned_to=task_client["agent"].id,
|
|
self_verified=True,
|
|
commits=[{"hash": "abc", "message": "fix"}],
|
|
pr_number=42,
|
|
progress_updates=[
|
|
{
|
|
"timestamp": "2026-01-01T00:00:00+00:00",
|
|
"agent_id": str(task_client["agent"].id),
|
|
"message": "started",
|
|
}
|
|
],
|
|
)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.submit_for_qa = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/submit-qa", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "not verifying" in response.json()["detail"].lower()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# pass_qa: full body coverage
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def qa_client(db_session: AsyncSession) -> AsyncIterator[dict]:
|
|
"""Client where the agent context role is QA."""
|
|
qa = AgentTable(
|
|
id=uuid4(),
|
|
name="QA",
|
|
slug=f"be-qa-{uuid4().hex[:8]}",
|
|
role=AgentRole.QA,
|
|
team=Team.BACKEND,
|
|
status=AgentStatus.ACTIVE,
|
|
model_config={},
|
|
system_prompt="qa",
|
|
capabilities=[],
|
|
permissions={},
|
|
metrics={},
|
|
)
|
|
db_session.add(qa)
|
|
await db_session.flush()
|
|
project = ProjectTable(
|
|
id=uuid4(),
|
|
name="QA-Proj",
|
|
slug=f"qa-proj-{uuid4().hex[:6]}",
|
|
git_url="https://example.com/r.git",
|
|
assigned_cell=Team.BACKEND,
|
|
created_by=qa.id,
|
|
)
|
|
db_session.add(project)
|
|
await db_session.flush()
|
|
|
|
app = FastAPI()
|
|
app.include_router(tasks_router, prefix="/api/tasks")
|
|
|
|
async def _override_db() -> AsyncIterator[AsyncSession]:
|
|
yield db_session
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=cast("UUID", qa.id), role=AgentRole.QA, team=Team.BACKEND
|
|
)
|
|
|
|
app.dependency_overrides[get_db] = _override_db
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
yield {
|
|
"client": client,
|
|
"agent": qa,
|
|
"project": project,
|
|
"db": db_session,
|
|
}
|
|
app.dependency_overrides.clear()
|
|
|
|
|
|
def _seed_task_qa(setup: dict, **kw: Any) -> TaskTable:
|
|
task = TaskTable(
|
|
id=uuid4(),
|
|
title="t",
|
|
description="d",
|
|
acceptance_criteria=["ac"],
|
|
status=kw.pop("status", TaskStatus.AWAITING_QA),
|
|
priority=2,
|
|
task_type=TaskType.CODE,
|
|
nature=TaskNature.TECHNICAL,
|
|
project_id=setup["project"].id,
|
|
created_by=setup["agent"].id,
|
|
team=Team.BACKEND,
|
|
**kw,
|
|
)
|
|
setup["db"].add(task)
|
|
return task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pass_qa_self_review_forbidden(qa_client: dict) -> None:
|
|
"""QA agent cannot pass-QA on a task where they were the original developer."""
|
|
task = _seed_task_qa(
|
|
qa_client,
|
|
pr_number=42,
|
|
orchestration_markers={"original_developer": str(qa_client["agent"].id)},
|
|
)
|
|
await qa_client["db"].flush()
|
|
response = await qa_client["client"].post(
|
|
f"/api/tasks/{task.id}/pass-qa",
|
|
json={"notes": "looks good and covers all criteria"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
assert "your own task" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pass_qa_no_pr_attached(qa_client: dict) -> None:
|
|
"""pass-qa without a PR returns NO_PR_ATTACHED 400."""
|
|
task = _seed_task_qa(qa_client, pr_number=None)
|
|
await qa_client["db"].flush()
|
|
response = await qa_client["client"].post(
|
|
f"/api/tasks/{task.id}/pass-qa",
|
|
json={"notes": "ok and was thorough enough for review"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "NO_PR_ATTACHED" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pass_qa_notes_too_short(qa_client: dict) -> None:
|
|
"""pass-qa with notes < 20 chars → QA_NOTES_REQUIRED 400."""
|
|
task = _seed_task_qa(qa_client, pr_number=42)
|
|
await qa_client["db"].flush()
|
|
response = await qa_client["client"].post(
|
|
f"/api/tasks/{task.id}/pass-qa",
|
|
json={"notes": "ok"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "QA_NOTES_REQUIRED" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pass_qa_no_notes_at_all(qa_client: dict) -> None:
|
|
"""pass-qa with NO body at all → QA_NOTES_REQUIRED 400."""
|
|
task = _seed_task_qa(qa_client, pr_number=42)
|
|
await qa_client["db"].flush()
|
|
response = await qa_client["client"].post(
|
|
f"/api/tasks/{task.id}/pass-qa",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "QA_NOTES_REQUIRED" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pass_qa_success(qa_client: dict) -> None:
|
|
"""Happy path — QA passes a task, transitions to awaiting_documentation."""
|
|
task = _seed_task_qa(qa_client, pr_number=42)
|
|
await qa_client["db"].flush()
|
|
response = await qa_client["client"].post(
|
|
f"/api/tasks/{task.id}/pass-qa",
|
|
json={
|
|
"notes": (
|
|
"Verified all acceptance criteria match the PR diff. "
|
|
"No security issues."
|
|
)
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json()["status"] == "awaiting_documentation"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pass_qa_service_returns_none(qa_client: dict) -> None:
|
|
"""If service.pass_qa returns None → route 400s."""
|
|
task = _seed_task_qa(qa_client, pr_number=42)
|
|
await qa_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.pass_qa = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await qa_client["client"].post(
|
|
f"/api/tasks/{task.id}/pass-qa",
|
|
json={"notes": "verified all acceptance criteria are met."},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "invalid status" in response.json()["detail"].lower()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# fail_qa: full body coverage
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_fail_qa_self_review_forbidden(qa_client: dict) -> None:
|
|
"""QA cannot fail-QA on a task where they were the dev."""
|
|
task = _seed_task_qa(
|
|
qa_client,
|
|
orchestration_markers={"original_developer": str(qa_client["agent"].id)},
|
|
)
|
|
await qa_client["db"].flush()
|
|
response = await qa_client["client"].post(
|
|
f"/api/tasks/{task.id}/fail-qa",
|
|
json={"notes": "broken in many ways"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
assert "your own task" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_fail_qa_success(qa_client: dict) -> None:
|
|
"""fail-qa happy path → needs_revision."""
|
|
task = _seed_task_qa(qa_client)
|
|
await qa_client["db"].flush()
|
|
response = await qa_client["client"].post(
|
|
f"/api/tasks/{task.id}/fail-qa",
|
|
json={"notes": "broken in some ways"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
assert response.json()["status"] == "needs_revision"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_fail_qa_service_returns_none(qa_client: dict) -> None:
|
|
"""If service.fail_qa returns None → 400."""
|
|
task = _seed_task_qa(qa_client)
|
|
await qa_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.fail_qa = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await qa_client["client"].post(
|
|
f"/api/tasks/{task.id}/fail-qa",
|
|
json={"notes": "broken"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# docs_complete: success
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_docs_complete_success(task_client: dict) -> None:
|
|
"""Mock service.docs_complete_for_task to return a task, route serializes it."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.docs_complete_for_task = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/docs-complete",
|
|
json={"notes": "documented thoroughly enough"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# submit_pm_review: success + None branch
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_pm_review_success(task_client: dict) -> None:
|
|
"""Assigned in_progress task — assignee submits for PM review."""
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.IN_PROGRESS,
|
|
assigned_to=task_client["agent"].id,
|
|
branch_name="feature/backend/X",
|
|
pr_created=True,
|
|
pr_number=42,
|
|
)
|
|
await task_client["db"].flush()
|
|
with patch(
|
|
"roboco.api.routes.tasks.get_notification_delivery_service"
|
|
) as mock_delivery:
|
|
delivery_instance = AsyncMock()
|
|
delivery_instance.notify_pm_of_review_submission = AsyncMock(return_value=None)
|
|
mock_delivery.return_value = delivery_instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/submit-pm-review",
|
|
json={"notes": "Submitted for PM review please."},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
delivery_instance.notify_pm_of_review_submission.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_submit_pm_review_service_returns_none(task_client: dict) -> None:
|
|
"""If service.submit_for_pm_review returns None → 400."""
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.IN_PROGRESS,
|
|
assigned_to=task_client["agent"].id,
|
|
)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.submit_for_pm_review = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/submit-pm-review",
|
|
json={"notes": "Ready for PM review — all criteria met."},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "not in progress" in response.json()["detail"].lower()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# complete_task: success path through service mock
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_complete_task_success(task_client: dict) -> None:
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.complete_task_for_agent = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/complete",
|
|
json={
|
|
"force_with_cancelled": False,
|
|
"justification": "All acceptance criteria met; merging.",
|
|
},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_complete_without_justification_rejected(task_client: dict) -> None:
|
|
"""Audit: completing a task must carry its rationale (>= 20 chars)."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/complete",
|
|
json={"force_with_cancelled": False},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "JUSTIFICATION_REQUIRED" in response.json()["detail"]
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# cancel: service returns None branch (1162-1167)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cancel_task_service_returns_none(task_client: dict) -> None:
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.cancel = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/cancel",
|
|
json={"reason": "no longer needed at all"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# CEO endpoints with separate ceo_client fixture
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest_asyncio.fixture
|
|
async def ceo_client(db_session: AsyncSession) -> AsyncIterator[dict]:
|
|
"""Client where agent role is CEO."""
|
|
ceo = AgentTable(
|
|
id=uuid4(),
|
|
name="CEO",
|
|
slug=f"ceo-{uuid4().hex[:8]}",
|
|
role=AgentRole.CEO,
|
|
team=None,
|
|
status=AgentStatus.ACTIVE,
|
|
model_config={},
|
|
system_prompt="ceo",
|
|
capabilities=[],
|
|
permissions={},
|
|
metrics={},
|
|
)
|
|
db_session.add(ceo)
|
|
await db_session.flush()
|
|
project = ProjectTable(
|
|
id=uuid4(),
|
|
name="CEO-Proj",
|
|
slug=f"ceo-proj-{uuid4().hex[:6]}",
|
|
git_url="https://example.com/r.git",
|
|
assigned_cell=Team.BACKEND,
|
|
created_by=ceo.id,
|
|
)
|
|
db_session.add(project)
|
|
await db_session.flush()
|
|
|
|
app = FastAPI()
|
|
app.include_router(tasks_router, prefix="/api/tasks")
|
|
|
|
async def _override_db() -> AsyncIterator[AsyncSession]:
|
|
yield db_session
|
|
|
|
async def _override_agent() -> AgentContext:
|
|
return AgentContext(
|
|
agent_id=cast("UUID", ceo.id), role=AgentRole.CEO, team=None
|
|
)
|
|
|
|
app.dependency_overrides[get_db] = _override_db
|
|
app.dependency_overrides[get_agent_context] = _override_agent
|
|
|
|
transport = ASGITransport(app=app)
|
|
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
|
yield {
|
|
"client": client,
|
|
"agent": ceo,
|
|
"project": project,
|
|
"db": db_session,
|
|
}
|
|
app.dependency_overrides.clear()
|
|
|
|
|
|
def _seed_task_ceo(setup: dict, **kw: Any) -> TaskTable:
|
|
task = TaskTable(
|
|
id=uuid4(),
|
|
title="t",
|
|
description="d",
|
|
acceptance_criteria=["ac"],
|
|
status=kw.pop("status", TaskStatus.AWAITING_CEO_APPROVAL),
|
|
priority=2,
|
|
task_type=TaskType.CODE,
|
|
nature=TaskNature.TECHNICAL,
|
|
project_id=setup["project"].id,
|
|
created_by=setup["agent"].id,
|
|
team=Team.BACKEND,
|
|
**kw,
|
|
)
|
|
setup["db"].add(task)
|
|
return task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_awaiting_pm_review_via_query(task_client: dict) -> None:
|
|
"""Hit get_awaiting_pm_review_tasks helper directly (route ordering quirk)."""
|
|
db = task_client["db"]
|
|
agent_ctx = AgentContext(
|
|
agent_id=task_client["agent"].id, role=AgentRole.MAIN_PM, team=None
|
|
)
|
|
permissions = PermissionService()
|
|
result = await get_awaiting_pm_review_tasks(
|
|
db=db,
|
|
agent=agent_ctx,
|
|
permissions=permissions,
|
|
team=Team.BACKEND,
|
|
)
|
|
assert isinstance(result, list)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_awaiting_pm_review_no_view_all(task_client: dict) -> None:
|
|
"""Developer (no VIEW_ALL) — falls back to agent.team."""
|
|
db = task_client["db"]
|
|
agent_ctx = AgentContext(
|
|
agent_id=task_client["agent"].id,
|
|
role=AgentRole.DEVELOPER,
|
|
team=Team.BACKEND,
|
|
)
|
|
permissions = PermissionService()
|
|
result = await get_awaiting_pm_review_tasks(
|
|
db=db, agent=agent_ctx, permissions=permissions, team=None
|
|
)
|
|
assert isinstance(result, list)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_awaiting_ceo_approval_pm_role(task_client: dict) -> None:
|
|
"""Main PM can view CEO approval queue — direct invocation."""
|
|
db = task_client["db"]
|
|
agent_ctx = AgentContext(
|
|
agent_id=task_client["agent"].id, role=AgentRole.MAIN_PM, team=None
|
|
)
|
|
permissions = PermissionService()
|
|
result = await get_awaiting_ceo_approval_tasks(
|
|
db=db, agent=agent_ctx, permissions=permissions
|
|
)
|
|
assert isinstance(result, list)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_awaiting_ceo_approval_developer_forbidden(
|
|
task_client: dict,
|
|
) -> None:
|
|
"""Developer (no VIEW_ALL, not PM/CEO) → 403 from helper."""
|
|
db = task_client["db"]
|
|
agent_ctx = AgentContext(
|
|
agent_id=task_client["agent"].id,
|
|
role=AgentRole.DEVELOPER,
|
|
team=Team.BACKEND,
|
|
)
|
|
permissions = PermissionService()
|
|
with pytest.raises(HTTPException) as exc_info:
|
|
await get_awaiting_ceo_approval_tasks(
|
|
db=db, agent=agent_ctx, permissions=permissions
|
|
)
|
|
assert exc_info.value.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_to_ceo_returns_task(task_client: dict) -> None:
|
|
"""Mock service.escalate_to_ceo_for_agent → route returns serialized task."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.escalate_to_ceo_for_agent = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/escalate-to-ceo",
|
|
json={"notes": "Need CEO sign-off please"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_approve_task_not_found(ceo_client: dict) -> None:
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/ceo-approve",
|
|
json={"notes": "approved"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_approve_service_returns_none(ceo_client: dict) -> None:
|
|
"""If service.ceo_approve returns None — 400."""
|
|
task = _seed_task_ceo(ceo_client, status=TaskStatus.PENDING)
|
|
await ceo_client["db"].flush()
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/ceo-approve",
|
|
json={"notes": "Reviewed and approved for production release."},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "not awaiting CEO" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_approve_success(ceo_client: dict) -> None:
|
|
task = _seed_task_ceo(ceo_client)
|
|
await ceo_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.ceo_approve = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/ceo-approve",
|
|
json={"notes": "Verified against all acceptance criteria; approved."},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_approve_without_notes_rejected(ceo_client: dict) -> None:
|
|
"""Audit: a CEO approval with no/thin notes leaves no record of WHY the
|
|
work shipped, so the endpoint must reject it (>= 20 chars required). The
|
|
panel collects the note before POSTing."""
|
|
task = _seed_task_ceo(ceo_client)
|
|
await ceo_client["db"].flush()
|
|
for body in ({}, {"notes": ""}, {"notes": "lgtm"}):
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/ceo-approve",
|
|
json=body,
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code in (
|
|
HTTPStatus.BAD_REQUEST,
|
|
HTTPStatus.UNPROCESSABLE_ENTITY,
|
|
), (body, response.status_code)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_and_start_success(ceo_client: dict) -> None:
|
|
task = _seed_task_ceo(ceo_client, status=TaskStatus.PENDING)
|
|
await ceo_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.approve_and_start = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
resp = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/approve-and-start",
|
|
json={"notes": "Board review complete; clear requirements; build it now."},
|
|
headers=_HDR,
|
|
)
|
|
assert resp.status_code == HTTPStatus.OK
|
|
instance.approve_and_start.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_and_start_requires_ceo(task_client: dict) -> None:
|
|
# task_client is MAIN_PM-role; the inline CEO guard must 403.
|
|
resp = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/approve-and-start",
|
|
json={"notes": "x" * 30},
|
|
headers=_HDR,
|
|
)
|
|
assert resp.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_and_start_short_notes(ceo_client: dict) -> None:
|
|
task = _seed_task_ceo(ceo_client, status=TaskStatus.PENDING)
|
|
await ceo_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
resp = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/approve-and-start",
|
|
json={"notes": "too short"},
|
|
headers=_HDR,
|
|
)
|
|
assert resp.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_and_start_missing_task_404_before_notes_gate(
|
|
ceo_client: dict,
|
|
) -> None:
|
|
# Missing task -> 404 even with valid notes: the not-found guard runs
|
|
# before the notes gate, so service.approve_and_start is never reached.
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
resp = await ceo_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/approve-and-start",
|
|
json={"notes": "Board review complete; clear requirements; build it now."},
|
|
headers=_HDR,
|
|
)
|
|
assert resp.status_code == HTTPStatus.NOT_FOUND
|
|
instance.approve_and_start.assert_not_awaited()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_reject_task_not_found(ceo_client: dict) -> None:
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/ceo-reject",
|
|
json={"notes": "rejected"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_reject_service_returns_none(ceo_client: dict) -> None:
|
|
"""ceo_reject on a task not in awaiting_ceo_approval — service None → 400."""
|
|
task = _seed_task_ceo(ceo_client, status=TaskStatus.PENDING)
|
|
await ceo_client["db"].flush()
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/ceo-reject",
|
|
json={"notes": "rejected"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_reject_success_notifies_assignee(ceo_client: dict) -> None:
|
|
"""ceo_reject success path with assignee triggers notification."""
|
|
other = AgentTable(
|
|
id=uuid4(),
|
|
name="Dev",
|
|
slug=f"dev-{uuid4().hex[:8]}",
|
|
role=AgentRole.DEVELOPER,
|
|
team=Team.BACKEND,
|
|
status=AgentStatus.ACTIVE,
|
|
model_config={},
|
|
system_prompt="x",
|
|
capabilities=[],
|
|
permissions={},
|
|
metrics={},
|
|
)
|
|
ceo_client["db"].add(other)
|
|
await ceo_client["db"].flush()
|
|
|
|
task = _seed_task_ceo(ceo_client, assigned_to=other.id)
|
|
await ceo_client["db"].flush()
|
|
|
|
with (
|
|
patch("roboco.api.routes.tasks.get_task_service") as mock_factory,
|
|
patch(
|
|
"roboco.api.routes.tasks.get_notification_delivery_service"
|
|
) as mock_delivery,
|
|
):
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.ceo_reject = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
delivery_instance = AsyncMock()
|
|
delivery_instance.notify_assignee_of_ceo_rejection = AsyncMock(
|
|
return_value=None
|
|
)
|
|
mock_delivery.return_value = delivery_instance
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/ceo-reject",
|
|
json={"notes": "rejected with detailed notes"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
delivery_instance.notify_assignee_of_ceo_rejection.assert_awaited_once()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# escalate (general): success + EscalationError 403/400
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_task_success(task_client: dict) -> None:
|
|
"""escalate_and_notify returns outcome → service.apply_escalation runs."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
outcome = SimpleNamespace(
|
|
target_agent_id=uuid4(),
|
|
escalator_slug="be-dev-1",
|
|
target_slug="be-pm",
|
|
)
|
|
with (
|
|
patch(
|
|
"roboco.api.routes.tasks.get_notification_delivery_service"
|
|
) as mock_delivery,
|
|
patch("roboco.api.routes.tasks.get_task_service") as mock_factory,
|
|
):
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.apply_escalation = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
delivery_instance = AsyncMock()
|
|
delivery_instance.escalate_and_notify = AsyncMock(return_value=outcome)
|
|
mock_delivery.return_value = delivery_instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/escalate",
|
|
json={"reason": "Need help — out of scope"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
body = response.json()
|
|
assert body["status"] == "escalated"
|
|
assert body["escalated_to"] == "be-pm"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_task_escalation_error_404(task_client: dict) -> None:
|
|
"""EscalationError starting with 'escalator agent' → 404."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
with patch(
|
|
"roboco.api.routes.tasks.get_notification_delivery_service"
|
|
) as mock_delivery:
|
|
delivery_instance = AsyncMock()
|
|
delivery_instance.escalate_and_notify = AsyncMock(
|
|
side_effect=EscalationError("escalator agent missing")
|
|
)
|
|
mock_delivery.return_value = delivery_instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/escalate",
|
|
json={"reason": "stuck"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_task_escalation_error_403(task_client: dict) -> None:
|
|
"""EscalationError 'Cannot escalate to ...' → 403."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
with patch(
|
|
"roboco.api.routes.tasks.get_notification_delivery_service"
|
|
) as mock_delivery:
|
|
delivery_instance = AsyncMock()
|
|
delivery_instance.escalate_and_notify = AsyncMock(
|
|
side_effect=EscalationError("Cannot escalate to qa")
|
|
)
|
|
mock_delivery.return_value = delivery_instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/escalate",
|
|
json={"reason": "stuck"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_escalate_task_escalation_error_400(task_client: dict) -> None:
|
|
"""Other EscalationError → 400."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
with patch(
|
|
"roboco.api.routes.tasks.get_notification_delivery_service"
|
|
) as mock_delivery:
|
|
delivery_instance = AsyncMock()
|
|
delivery_instance.escalate_and_notify = AsyncMock(
|
|
side_effect=EscalationError("no chain configured")
|
|
)
|
|
mock_delivery.return_value = delivery_instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/escalate",
|
|
json={"reason": "stuck"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# substitute: success
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_substitute_task_success(task_client: dict) -> None:
|
|
task = _seed_task(task_client, assigned_to=task_client["agent"].id)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.substitute_task_for_agent = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/substitute",
|
|
json={"reason": "low_context", "details": "Need more context"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# progress / checkpoint / commit: success and 500-fallback
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_progress_success(task_client: dict) -> None:
|
|
task = _seed_task(task_client, assigned_to=task_client["agent"].id)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/progress",
|
|
json={"message": "Halfway done now", "percentage": 50},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_progress_service_returns_none_500(task_client: dict) -> None:
|
|
task = _seed_task(task_client, assigned_to=task_client["agent"].id)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.add_progress = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/progress",
|
|
json={"message": "halfway done now", "percentage": 50},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_checkpoint_success(task_client: dict) -> None:
|
|
task = _seed_task(task_client, assigned_to=task_client["agent"].id)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/checkpoint",
|
|
json={"state_summary": "halfway", "remaining_work": ["finish API"]},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_checkpoint_service_returns_none_500(task_client: dict) -> None:
|
|
task = _seed_task(task_client, assigned_to=task_client["agent"].id)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.add_checkpoint = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/checkpoint",
|
|
json={"state_summary": "halfway", "remaining_work": ["finish"]},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_commit_success(task_client: dict) -> None:
|
|
task = _seed_task(task_client, assigned_to=task_client["agent"].id)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/commit",
|
|
json={"hash": "abc1234", "message": "fix"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_add_commit_service_returns_none_500(task_client: dict) -> None:
|
|
task = _seed_task(task_client, assigned_to=task_client["agent"].id)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=task)
|
|
instance.add_commit = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/commit",
|
|
json={"hash": "abc1234", "message": "fix"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.INTERNAL_SERVER_ERROR
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# activate: success + ValueError + TaskLifecycleError
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_activate_success(task_client: dict) -> None:
|
|
task = _seed_task(task_client, status=TaskStatus.BACKLOG)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.activate = AsyncMock(return_value=task)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/activate", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_activate_value_error_returns_400(task_client: dict) -> None:
|
|
task = _seed_task(task_client, status=TaskStatus.BACKLOG)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.activate = AsyncMock(side_effect=ValueError("no session linked"))
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/activate", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "no session" in response.json()["detail"].lower()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_activate_task_lifecycle_error_returns_403(task_client: dict) -> None:
|
|
task = _seed_task(task_client, status=TaskStatus.BACKLOG)
|
|
await task_client["db"].flush()
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.activate = AsyncMock(
|
|
side_effect=TaskLifecycleError(
|
|
current_status="backlog",
|
|
target_status="pending",
|
|
message="Wrong role",
|
|
)
|
|
)
|
|
mock_factory.return_value = instance
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/activate", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# get_sessions_for_task: 404 path for unknown task
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_get_sessions_for_task_not_found(task_client: dict) -> None:
|
|
response = await task_client["client"].get(
|
|
f"/api/tasks/{uuid4()}/sessions", headers=_HDR
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# TaskUpdate schema: nature / task_type / project_id (AC: schema fix)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_patch_nature_persists(task_client: dict) -> None:
|
|
"""PATCH with nature=non_technical persists; GET returns updated value."""
|
|
task = _seed_task(task_client, nature=TaskNature.TECHNICAL)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"nature": "non_technical"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
body = response.json()
|
|
assert body["nature"] == "non_technical"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_patch_task_type_persists(task_client: dict) -> None:
|
|
"""PATCH with task_type=research persists; GET returns updated value."""
|
|
task = _seed_task(task_client, task_type=TaskType.CODE)
|
|
await task_client["db"].flush()
|
|
response = await task_client["client"].patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"task_type": "research"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
body = response.json()
|
|
assert body["task_type"] == "research"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_patch_project_id_persists(task_client: dict) -> None:
|
|
"""PATCH with project_id=<valid-uuid> persists; GET returns updated value."""
|
|
task = _seed_task(task_client)
|
|
# Create a second project to switch to
|
|
second_project = ProjectTable(
|
|
id=uuid4(),
|
|
name="Proj2",
|
|
slug=f"proj2-{uuid4().hex[:6]}",
|
|
git_url="https://example.com/proj2.git",
|
|
assigned_cell=Team.BACKEND,
|
|
created_by=task_client["agent"].id,
|
|
)
|
|
task_client["db"].add(second_project)
|
|
await task_client["db"].flush()
|
|
|
|
response = await task_client["client"].patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"project_id": str(second_project.id)},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
body = response.json()
|
|
assert body["project_id"] == str(second_project.id)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_patch_title_only_changes_title(task_client: dict) -> None:
|
|
"""PATCH with only title does not mutate nature/task_type/status/team."""
|
|
task = _seed_task(
|
|
task_client,
|
|
title="original title",
|
|
nature=TaskNature.TECHNICAL,
|
|
task_type=TaskType.CODE,
|
|
team=Team.BACKEND,
|
|
)
|
|
await task_client["db"].flush()
|
|
|
|
response = await task_client["client"].patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"title": "updated title"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
body = response.json()
|
|
assert body["title"] == "updated title"
|
|
# Other fields unchanged
|
|
assert body["nature"] == "technical"
|
|
assert body["task_type"] == "code"
|
|
assert body["team"] == "backend"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# assigned_to: slug resolution and null guard (AC: slug-resolution fix)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_patch_assigned_to_slug_resolves_to_uuid(task_client: dict) -> None:
|
|
"""PATCH assigned_to with agent slug resolves to agent UUID."""
|
|
dev = await _seed_agent(task_client)
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
|
|
response = await task_client["client"].patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"assigned_to": dev.slug},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
body = response.json()
|
|
assert body["assigned_to"] == str(dev.id)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_patch_assigned_to_null_unassigns(task_client: dict) -> None:
|
|
"""PATCH assigned_to: null sets assigned_to to null (unassign)."""
|
|
dev = await _seed_agent(task_client)
|
|
task = _seed_task(task_client, assigned_to=dev.id)
|
|
await task_client["db"].flush()
|
|
|
|
response = await task_client["client"].patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"assigned_to": None},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
body = response.json()
|
|
assert body["assigned_to"] is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_patch_assigned_to_unknown_slug_returns_422(task_client: dict) -> None:
|
|
"""PATCH assigned_to with unknown slug returns 422 ASSIGNEE_NOT_FOUND."""
|
|
task = _seed_task(task_client)
|
|
await task_client["db"].flush()
|
|
|
|
response = await task_client["client"].patch(
|
|
f"/api/tasks/{task.id}",
|
|
json={"assigned_to": "totally-nonexistent-slug"},
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.UNPROCESSABLE_ENTITY
|
|
detail = response.json()["detail"]
|
|
assert isinstance(detail, dict)
|
|
assert detail["error"]["code"] == "ASSIGNEE_NOT_FOUND"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# GET /tasks/{id}/ceo-approve — eligibility check (AC: ceo-approve fix)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_approve_get_no_pr_returns_400(ceo_client: dict) -> None:
|
|
"""GET /ceo-approve with no pr_number on the task → 400 NO_PR."""
|
|
task = _seed_task_ceo(ceo_client, pr_number=None)
|
|
await ceo_client["db"].flush()
|
|
response = await ceo_client["client"].get(
|
|
f"/api/tasks/{task.id}/ceo-approve",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "NO_PR" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_approve_get_with_pr_returns_200(ceo_client: dict) -> None:
|
|
"""GET /ceo-approve with pr_number set → 200 with task."""
|
|
task = _seed_task_ceo(ceo_client, pr_number=42)
|
|
await ceo_client["db"].flush()
|
|
response = await ceo_client["client"].get(
|
|
f"/api/tasks/{task.id}/ceo-approve",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.OK
|
|
body = response.json()
|
|
_expected_pr = 42
|
|
assert body["pr_number"] == _expected_pr
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_approve_get_not_ceo_returns_403(task_client: dict) -> None:
|
|
"""GET /ceo-approve by non-CEO → 403 Forbidden."""
|
|
response = await task_client["client"].get(
|
|
f"/api/tasks/{uuid4()}/ceo-approve",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_ceo_approve_get_task_not_found(ceo_client: dict) -> None:
|
|
"""GET /ceo-approve for unknown task → 404."""
|
|
response = await ceo_client["client"].get(
|
|
f"/api/tasks/{uuid4()}/ceo-approve",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# POST /tasks/{id}/approve-and-merge (AC: approve-and-merge fix)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_and_merge_no_pr_returns_400(ceo_client: dict) -> None:
|
|
"""POST /approve-and-merge with no pr_number → 400 NO_PR."""
|
|
task = _seed_task_ceo(ceo_client, pr_number=None)
|
|
await ceo_client["db"].flush()
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/approve-and-merge",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.BAD_REQUEST
|
|
assert "NO_PR" in response.json()["detail"]
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_and_merge_not_ceo_returns_403(task_client: dict) -> None:
|
|
"""POST /approve-and-merge by non-CEO → 403 Forbidden."""
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/approve-and-merge",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.FORBIDDEN
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_and_merge_task_not_found(ceo_client: dict) -> None:
|
|
"""POST /approve-and-merge for unknown task → 404."""
|
|
with patch("roboco.api.routes.tasks.get_task_service") as mock_factory:
|
|
instance = AsyncMock()
|
|
instance.get = AsyncMock(return_value=None)
|
|
mock_factory.return_value = instance
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{uuid4()}/approve-and-merge",
|
|
headers=_HDR,
|
|
)
|
|
assert response.status_code == HTTPStatus.NOT_FOUND
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_and_merge_success(ceo_client: dict) -> None:
|
|
"""POST /approve-and-merge with PR + fully mocked services → 200 task."""
|
|
task = _seed_task_ceo(ceo_client, pr_number=99)
|
|
await ceo_client["db"].flush()
|
|
|
|
# The handler does lazy imports of get_project_service and get_git_service.
|
|
# Patch them at their source modules so the lazy import picks up the mock.
|
|
with (
|
|
patch("roboco.api.routes.tasks.get_task_service") as mock_task_factory,
|
|
patch("roboco.services.project.get_project_service") as mock_proj_factory,
|
|
patch("roboco.services.git.get_git_service") as mock_git_factory,
|
|
):
|
|
task_instance = AsyncMock()
|
|
# service.get is called twice: once for the initial check, once to re-fetch.
|
|
task_instance.get = AsyncMock(side_effect=[task, task])
|
|
mock_task_factory.return_value = task_instance
|
|
|
|
proj_instance = AsyncMock()
|
|
proj_instance.get = AsyncMock(return_value=ceo_client["project"])
|
|
mock_proj_factory.return_value = proj_instance
|
|
|
|
git_instance = AsyncMock()
|
|
git_instance.merge_pr_for_task = AsyncMock(return_value=("main", "abc1234"))
|
|
mock_git_factory.return_value = git_instance
|
|
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/approve-and-merge",
|
|
headers=_HDR,
|
|
)
|
|
|
|
assert response.status_code == HTTPStatus.OK
|
|
body = response.json()
|
|
_expected_pr = 99
|
|
assert body["pr_number"] == _expected_pr
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_and_merge_merge_failure_returns_structured_error(
|
|
ceo_client: dict,
|
|
) -> None:
|
|
"""POST /approve-and-merge where git merge fails → 400 with descriptive message.
|
|
|
|
The error must NOT be an unhandled exception (500 with traceback); it must
|
|
be a structured HTTP error (400 or 500) with a human-readable message.
|
|
"""
|
|
task = _seed_task_ceo(ceo_client, pr_number=55)
|
|
await ceo_client["db"].flush()
|
|
|
|
with (
|
|
patch("roboco.api.routes.tasks.get_task_service") as mock_task_factory,
|
|
patch("roboco.services.project.get_project_service") as mock_proj_factory,
|
|
patch("roboco.services.git.get_git_service") as mock_git_factory,
|
|
):
|
|
task_instance = AsyncMock()
|
|
task_instance.get = AsyncMock(return_value=task)
|
|
mock_task_factory.return_value = task_instance
|
|
|
|
proj_instance = AsyncMock()
|
|
proj_instance.get = AsyncMock(return_value=ceo_client["project"])
|
|
mock_proj_factory.return_value = proj_instance
|
|
|
|
git_instance = AsyncMock()
|
|
git_instance.merge_pr_for_task = AsyncMock(
|
|
side_effect=SvcError("GitHub refused the merge: 409 Conflict")
|
|
)
|
|
mock_git_factory.return_value = git_instance
|
|
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/approve-and-merge",
|
|
headers=_HDR,
|
|
)
|
|
|
|
# Must be a structured error, not an unhandled 500
|
|
_ok_statuses = (HTTPStatus.BAD_REQUEST, HTTPStatus.INTERNAL_SERVER_ERROR)
|
|
assert response.status_code in _ok_statuses
|
|
body = response.json()
|
|
# The detail must be a string (not a raw traceback or empty)
|
|
assert isinstance(body.get("detail"), str)
|
|
assert len(body["detail"]) > 0
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_approve_and_merge_git_error_returns_structured_error(
|
|
ceo_client: dict,
|
|
) -> None:
|
|
"""POST /approve-and-merge: GitError → 400 with descriptive message."""
|
|
task = _seed_task_ceo(ceo_client, pr_number=66)
|
|
await ceo_client["db"].flush()
|
|
|
|
with (
|
|
patch("roboco.api.routes.tasks.get_task_service") as mock_task_factory,
|
|
patch("roboco.services.project.get_project_service") as mock_proj_factory,
|
|
patch("roboco.services.git.get_git_service") as mock_git_factory,
|
|
):
|
|
task_instance = AsyncMock()
|
|
task_instance.get = AsyncMock(return_value=task)
|
|
mock_task_factory.return_value = task_instance
|
|
|
|
proj_instance = AsyncMock()
|
|
proj_instance.get = AsyncMock(return_value=ceo_client["project"])
|
|
mock_proj_factory.return_value = proj_instance
|
|
|
|
git_instance = AsyncMock()
|
|
git_instance.merge_pr_for_task = AsyncMock(
|
|
side_effect=GitError(
|
|
"GitHub API refused PR merge (422): branch protected",
|
|
{"pr": 66},
|
|
)
|
|
)
|
|
mock_git_factory.return_value = git_instance
|
|
|
|
response = await ceo_client["client"].post(
|
|
f"/api/tasks/{task.id}/approve-and-merge",
|
|
headers=_HDR,
|
|
)
|
|
|
|
# Must be a structured error — NOT an unhandled traceback
|
|
_ok_statuses = (HTTPStatus.BAD_REQUEST, HTTPStatus.INTERNAL_SERVER_ERROR)
|
|
assert response.status_code in _ok_statuses
|
|
body = response.json()
|
|
assert isinstance(body.get("detail"), str)
|
|
assert len(body["detail"]) > 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# POST /tasks/{id}/complete — PM merge path (AC: pm-merge-path fix)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_cell_pm_complete_merges_then_completes(task_client: dict) -> None:
|
|
"""POST /complete on an awaiting_pm_review task with a pr_number triggers
|
|
merge_pr_for_task before the task is marked completed.
|
|
|
|
The git service and project service are mocked so no real GitHub call is
|
|
made; the test verifies the call ordering and the final 200 response.
|
|
"""
|
|
task = _seed_task(task_client, status=TaskStatus.AWAITING_PM_REVIEW, pr_number=77)
|
|
await task_client["db"].flush()
|
|
|
|
with (
|
|
patch("roboco.api.routes.tasks.get_task_service") as mock_task_factory,
|
|
patch("roboco.services.project.get_project_service") as mock_proj_factory,
|
|
patch("roboco.services.git.get_git_service") as mock_git_factory,
|
|
):
|
|
# Task service: get() returns the seeded task; complete_task_for_agent
|
|
# simulates the service marking it completed and returning it.
|
|
task_instance = AsyncMock()
|
|
task_instance.get = AsyncMock(return_value=task)
|
|
completed_task = task # same object; status already set on the mock
|
|
task_instance.complete_task_for_agent = AsyncMock(return_value=completed_task)
|
|
mock_task_factory.return_value = task_instance
|
|
|
|
proj_instance = AsyncMock()
|
|
proj_instance.get = AsyncMock(return_value=task_client["project"])
|
|
mock_proj_factory.return_value = proj_instance
|
|
|
|
git_instance = AsyncMock()
|
|
git_instance.merge_pr_for_task = AsyncMock(return_value=("main", "abc1234"))
|
|
mock_git_factory.return_value = git_instance
|
|
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/complete",
|
|
json={"justification": "All criteria met; QA and docs signed off."},
|
|
headers=_HDR,
|
|
)
|
|
|
|
assert response.status_code == HTTPStatus.OK
|
|
# merge_pr_for_task must have been called exactly once
|
|
git_instance.merge_pr_for_task.assert_called_once()
|
|
call_args = git_instance.merge_pr_for_task.call_args
|
|
# The GitMergePRRequest passed to merge_pr_for_task must carry the right pr_number
|
|
merge_request = call_args.args[2] # positional: agent_id, agent_role, request
|
|
_expected_pr = 77
|
|
assert merge_request.pr_number == _expected_pr
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# POST /tasks/{id}/complete — PM merge path end-to-end (AC: double-completion fix)
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_pm_merge_auto_completes_without_double_completion(
|
|
task_client: dict,
|
|
) -> None:
|
|
"""POST /complete on awaiting_pm_review calls real merge_pr_for_task and
|
|
real complete_task_for_agent is NOT called — the task is auto-completed
|
|
by _auto_complete_on_merge inside the git service, and the route detects
|
|
the completed state from the re-fetch and returns 200 directly.
|
|
|
|
Only the git-workspace / GitHub-API layer is mocked (GitService.get_workspace
|
|
and GitService.merge_pull_request). merge_pr_for_task and complete_task_for_agent
|
|
run for real so this exercises the fix for the double-completion 500.
|
|
"""
|
|
# Seed a task in awaiting_pm_review with a PR. No work_session_id so that
|
|
# _assert_pr_merged_for_complete returns True without querying WorkSession.
|
|
task = _seed_task(
|
|
task_client,
|
|
status=TaskStatus.AWAITING_PM_REVIEW,
|
|
pr_number=99,
|
|
# work_session_id intentionally omitted (defaults to None)
|
|
)
|
|
await task_client["db"].flush()
|
|
|
|
# Spy: we want to assert complete_task_for_agent is never reached.
|
|
# If it were called on an already-completed task it would raise ValidationError
|
|
# and the route would return a non-200 — but we assert explicitly to be clear.
|
|
complete_for_agent_spy = AsyncMock(
|
|
wraps=TaskService.complete_task_for_agent,
|
|
name="complete_task_for_agent_spy",
|
|
)
|
|
|
|
_mock_workspace = Path("/tmp/mock_workspace")
|
|
|
|
with (
|
|
patch.object(
|
|
GitService,
|
|
"get_workspace",
|
|
new=AsyncMock(return_value=_mock_workspace),
|
|
),
|
|
patch.object(
|
|
GitService,
|
|
"merge_pull_request",
|
|
new=AsyncMock(return_value=("main", "dead1234")),
|
|
),
|
|
patch.object(
|
|
TaskService,
|
|
"complete_task_for_agent",
|
|
new=complete_for_agent_spy,
|
|
),
|
|
):
|
|
response = await task_client["client"].post(
|
|
f"/api/tasks/{task.id}/complete",
|
|
json={"justification": "All criteria met and QA signed off."},
|
|
headers=_HDR,
|
|
)
|
|
|
|
# The route must return 200; if the double-completion bug were present the
|
|
# second call to complete() would fail (task already completed) → 422/400.
|
|
assert response.status_code == HTTPStatus.OK, response.text
|
|
|
|
body = response.json()
|
|
assert body["status"] == "completed", f"expected completed, got {body['status']}"
|
|
|
|
# complete_task_for_agent must NOT have been called: the task was already
|
|
# auto-completed by _auto_complete_on_merge inside merge_pr_for_task.
|
|
complete_for_agent_spy.assert_not_called()
|