mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
* feat(batch): batch_id + collision descriptor columns
Sequenced batch intake ("Mega task") foundation: tasks.batch_id (indexed)
groups a batch of top-level tasks created together; intends_to_touch (text[]),
adds_migration and touches_shared (bool, NOT NULL default false) are the
per-task collision surface the SequencingService will read to wire dependency
waves. Mirrored on the Task model + TaskCreateRequest and wired through
TaskService.create. Migration 046 (real upgrade->downgrade->upgrade verified
vs a throwaway pgvector PG); a non-batch task declares no surface (defaults).
Task 1 of the 0.11.0 sequenced-batch-intake plan.
* feat(batch): flag + draft collision descriptors
Default-off ROBOCO_BATCH_INTAKE_ENABLED (config + FEATURE_FLAGS + panel card);
the propose_draft tool doc + the TS DraftProposal gain the per-task collision
surface intends_to_touch / adds_migration / touches_shared. The draft is a loose
dict so the descriptors ride it through the relay intact (test asserts the
forwarded payload); the analyzer (Task 3) reads them to wire dependency waves.
Task 2 of the 0.11.0 sequenced-batch-intake plan.
* feat(batch): deterministic collision-sequencing analyzer
SequencingService.analyze turns a batch's per-task collision surfaces into a
dependency DAG + execution waves — correctness in CODE, not agent judgment.
Rules in order: file overlap serializes (more-important first), migrations form
a serial chain (no concurrent Alembic heads), touches_shared runs last, cell
contention warns (never serializes); then dedupe, existence + cycle check, and
Kahn topological layering. Pure (no DB/services); SequencingError on a cycle or
out-of-range edge.
Golden test reproduces the CEO's hand-sequenced 4 waves of the 11-item
guard-core-app batch (the effort that deadlocked the Main PM): S6 alone last,
the R1/R3/R4 migration chain, R2/R3/S8 serialized on the shared threat service,
S1/S2/S7 in one parallel wave.
Task 3 of the 0.11.0 sequenced-batch-intake plan.
* chore(batch): brand the user-facing surfaces "MegaTask"
The user-facing name is MegaTask: the feature-flag label is "MegaTask intake",
the panel flag-card and the config description lead with MegaTask. Internal
names stay technical (batch_intake_enabled, batch_id, SequencingService).
* chore(batch): drop the feature flag — MegaTask is a core intake scope
MegaTask is additive and opt-in by its own nature (the Prompter proposes a
batch only when the CEO asks for several tasks; single-task intake is
unchanged), so there is no risk surface a flag protects — 'don't create a
MegaTask' is the off switch. Remove batch_intake_enabled from config, the
FEATURE_FLAGS registry, the panel flag card, and its tests. MegaTask will be
a third scope option in the Intake modal (single-cell / multi-project /
MegaTask), not a toggle.
* feat(batch): MegaTask identity predicate + orchestrator branchless recognition
The single source of truth for the umbrella's exemptions: pure
is_batch_umbrella / is_batch_root_subtask / is_branchless_coordination
(foundation/policy/batch.py) — an umbrella has a batch_id and is top-level; a
root-subtask shares the batch_id but is parented. The orchestrator's
_is_coordination_task now consults is_branchless_coordination, so a MegaTask
umbrella is recognized as doing no git of its own (git-exempt at spawn-readiness
/ stuck-detection) exactly like a product fan-out root. Non-batch behavior is
identical (the predicate reduces to the old no-project+product check; the
orchestrator coordination suite stays green), and the umbrella branch is inert
until the create path exists.
First slice of the MegaTask umbrella enforcement (branchless guard).
* feat(batch): branchless umbrella guard across the git-exemption sites
A MegaTask umbrella does no git of its own — every git-exemption site in
TaskService now consults the shared is_branchless_coordination predicate
instead of an inline product-only check, so the umbrella's exemptions
cannot drift between sites:
- the claimed->in_progress branch gate (GitContext.is_coordination) lets
an unbranched umbrella reach in_progress and delegate;
- _ensure_branch_for_task short-circuits an umbrella to "" instead of the
misconfigured raise (the claim path ignores the return, treating it as
branchless);
- CEO-reject routing sends a rejected umbrella to the Main PM in PENDING
(needs_revision is developer-claim-only and would deadlock it).
Covers both shapes via the predicate (product fan-out root OR umbrella);
a batch root-subtask keeps its own branch/PR. Adds orchestrator
recognition tests for the umbrella plus claim/branch/reject integration
tests.
* feat(batch): umbrella assembles no PR; completes branchless
submit_root now hard-rejects a MegaTask umbrella up front (a preflight
that also folds in the unknown-role refusal to stay within the
return-count budget): the umbrella spans many projects with no single
master, so each root-subtask opens and is reviewed on its own PR — the
umbrella never enters the in-path review gate. The Main PM completes it
directly once every root-subtask is terminal.
Umbrella completion needs no new code: it is branchless (no branch_name),
so _main_pm_complete_guard already accepts it from in_progress, checks
all_subtasks_terminal, and main_pm_complete walks it to awaiting_pm_review
and escalates to the CEO with no PR creation — exactly the product
fan-out root path. Adds the submit_root-reject and umbrella-completion
gateway tests; pins batch_id=None on the normal-root submit_root test
(a MagicMock auto-attr would otherwise read as an umbrella).
* feat(batch): MegaTask create path — umbrella + sequenced root-subtasks
PrompterService.confirm_live_batch turns N confirmed drafts into a real
MegaTask: it builds each draft's collision surface, runs the pure
SequencingService to get conflict-free waves, creates the branchless
umbrella (batch_id, no project/product), then one root-subtask per draft
(own project, parent=umbrella, sequence=wave index, descriptors), and
wires the analyzer's edges through add_dependency so the existing
dependency-gate runs the waves in order. The route picks the start path
like a single confirm: 'board' holds the root-subtasks in BACKLOG for the
batch review; 'main_pm' creates them PENDING so wave 0 dispatches at once.
create_task_from_draft gains a BatchPlacement (parent/batch/sequence/
team_override) and forwards the collision descriptors; the exactly-one-
target rule (here and the TaskService.create invariant) is relaxed for an
umbrella, which legitimately targets neither. New route
POST /live/{session}/confirm-batch + BatchConfirmRequest mirror the single
confirm. Adds the structural-invariant + board-hold + empty-batch tests.
* feat(batch): release MegaTask root-subtasks on CEO approval; board awareness
The board route holds a MegaTask's root-subtasks in BACKLOG so the work
waits for the batch review. approve_and_start (CEO gate #1, board->Main PM)
now releases them via _activate_batch_root_subtasks: each held child flips
BACKLOG -> PENDING + team=main_pm so the dependency-gate dispatches wave 0.
No-op for a non-umbrella; idempotent (children past BACKLOG untouched).
The Product Owner and Head of Marketing identity prompts gain a MegaTask
section so they review the whole batch + wave plan and adjust scope before
sign-off (they review drafts; the umbrella is their unit). Also extracts
the create() target invariant into _require_target_or_umbrella to keep the
method under the complexity gate after the umbrella exemption. Adds the
umbrella-approval activation test.
* feat(batch): multi-project intake scope for MegaTask
A MegaTask spans several possibly-unrelated repos, so the intake chat can
now be scoped to an explicit project list (not just one project or one
product). StartLiveRequest gains project_ids; /live/start threads it
through start/spawn_intake_session -> _spawn_intake_container ->
_clone_intake_scope. The multi-repo clone machinery already existed for
products; _intake_scope_slugs now also resolves an explicit project_ids
set (split into _slugs_for_project_ids / _slugs_for_product), cloning each
repo with the first as the primary cwd and the siblings readable. Scope
validation is now 'exactly one of project_slug / product_id / project_ids'
via the shared _require_one_intake_scope. Adds scope-resolution, spawn,
and route tests for the MegaTask path.
* feat(batch): propose_batch intake tool (MegaTask multi-draft hand-off)
The intake agent can now hand the panel a whole MegaTask in one tool call.
Both intake paths gain propose_batch alongside propose_draft:
- Claude (intake_driver): a propose_batch tool registered on the in-SDK
MCP server + allowlisted; the driver intercepts the ToolUseBlock and
emits ONE StreamChunk(kind="batch") carrying {drafts:[...], title}.
- grok (intake_server): a propose_batch tool that POSTs a "batch" relay
event via the shared _post_event helper (post_draft/post_batch).
A batch carries N drafts, each the propose_draft shape PLUS its own
project_id (a MegaTask spans unrelated repos) and collision surface so the
analyzer sequences the waves. The prompter prompt documents the MegaTask
scope + when to call propose_batch. Adds Claude-normalize and grok-relay
tests for the batch path.
* feat(batch): MegaTask intake panel — third scope, batch review, waves
The panel now drives a MegaTask end to end. The intake modal gains a
third scope, 'MegaTask', beside Single cell and Board-led: a multi-project
checklist (a MegaTask spans several possibly-unrelated repos), validated
to at least two. start() sends project_ids; use-prompter accumulates the
agent's single propose_batch hand-off as a 'batch' SSE event into a
BatchProposal and lands in a new batch_preview state.
A new BatchReviewCard lists every proposed task with its target project +
collision-surface badges (migration / shared) and offers one start path
for the whole batch — Board review & Start or Approve & Start — wired to
confirmBatch → POST /confirm-batch. The success card shows the sequenced
result: N tasks in M waves (+ any advisory notes). prompter.ts gains the
DraftScale 'megatask' + the BatchConfirm payload/result types; the SSE
client allows the 'batch' kind. Panel typecheck + lint + 113 tests green.
* docs(batch): MegaTask across changelog, CLAUDE.md, site, and RAG
The four documentation obligations for the MegaTask feature:
- CHANGELOG: an Unreleased entry covering the umbrella model, sequencing,
multi-project intake, propose_batch, and the create/approval path.
- CLAUDE.md: a MegaTask section (identity predicate, umbrella/root-subtask
hierarchy, sequencing rules, intake + create path, board activation).
- Published site: a user-facing company/megatask.md (scopes, waves, the
umbrella, the two start buttons) + nav entry; a pointer added to the
intake chapter of the Tour.
- RAG corpus: workflows/megatask.md so the Main PM (and any agent) can
retrieve the umbrella's branchless / no-PR / completion rules at runtime.
The runtime concurrent-migration guard is intentionally NOT added: the
analyzer already chains migration-adders into dependencies and the
dependency-gate serializes them, so a separate guard would be dead code.
* feat(batch): batch_id guardrail + wave preview + batch_id on TaskResponse
Guardrail (CEO): a batch_id is denied on any task that is not a well-formed
MegaTask member. is_valid_batch_shape permits batch_id only on an umbrella
(no parent → must target neither project nor product) or a root-subtask
(has a parent → exactly one target); TaskService.create enforces it AND
verifies a root-subtask's parent is the batch umbrella (same batch_id,
top-level). This closes a latent hole: is_batch_umbrella is true for a
batch_id + no-parent task even with a project, so a stray batch_id could
have spoofed the branchless branch-gate / no-PR exemption. (The public
task API never exposed batch_id for write; this guards the service layer.)
Wave preview: PrompterService.preview_batch + POST .../preview-batch
compute a MegaTask's waves from the proposed drafts WITHOUT creating
anything, so the panel can show the sequencing before confirm. Extracted
_sequence_drafts as the single source shared by preview and confirm, so
the previewed waves are exactly the ones wired.
TaskResponse now carries batch_id so the panel can badge the umbrella.
* feat(batch): MegaTask review — project editor, wave preview, persistence, badge
Closes the panel gaps in the MegaTask review experience:
- Per-task project editor: each proposed task gets an inline project
Select (updateBatchDraftProject), so a task the agent put in the wrong
or no repo can be fixed before launch — not only by re-chatting. Launch
stays blocked until every task has a project.
- Wave preview: on a batch proposal the panel fetches POST .../preview-batch
(no task created) and shows the conflict-free wave plan, so the human
reviews the sequencing before confirming.
- Refresh durability: the MegaTask review (batch + waves + projectIds) is
persisted, so a browser reload mid-review restores it like a single draft.
- MegaTask badge: TaskResponse exposes batch_id, the panel Task type
carries it, and the task table badges the umbrella row 'MegaTask'.
Panel typecheck + lint + 113 tests green.
* test(batch): stub task carries batch_id for task_to_response
task_to_response now serializes batch_id (TaskResponse field), so the
_stub_task SimpleNamespace fixture must provide it — without it the reader
hit AttributeError, failing the 8 task-schema serialization/enrichment
tests. Test-only; the real TaskTable carries the column (migration 046).
* fix(batch): close MegaTask audit gaps — completion crash, analyzer cycle, guardrails
An adversarial multi-agent audit of the feature surfaced 20 verified gaps;
this closes the backend ones.
HIGH:
- Umbrella completion crashed. escalate_to_ceo hard-required a pr_number,
which a branchless umbrella never has, so main_pm_complete dereferenced
None. Both pr_number gates now waive a MegaTask umbrella (escalate_to_ceo
+ the awaiting_pm_review->awaiting_ceo_approval lifecycle gate via a new
GitContext.is_umbrella), and main_pm_complete guards a None return. The
completion test had mocked escalate_to_ceo, hiding it — now a real
service test covers the waiver.
- The collision analyzer could fabricate a cycle (a touches_shared +
adds_migration draft overlapping another migration draft) and raise
SequencingError — a bare ValueError that escaped as an opaque 500. The
migration chain is now shared-last-aware (never contradicts rule 3), and
_sequence_drafts translates SequencingError to a clean 400.
MEDIUM:
- Collisions are now project-scoped: two repos can't collide on a
coincidental path or serialize independent migrations (DraftSurface
carries project_id; rules 1/2/3 respect it).
- The batch_id guardrail ran only at create. update() + the PATCH
null-clear path now re-assert is_valid_batch_shape, so a mutation can't
break a member's shape and spoof the branchless exemption.
- A draft missing title/acceptance_criteria now raises ValidationError
(was a bare KeyError -> 500).
- confirm_live_batch re-asserts every draft targets a scoped project and
the batch spans >=2 distinct projects (project_ids added to the request).
- Route-level tests for confirm-batch / preview-batch.
LOW: strict multi-repo clone (fail loud on any unresolvable project);
malformed/empty propose_batch surfaces an error chunk (Claude) / refuses
to POST (grok) instead of silently acking; dropped malformed drafts are
counted and surfaced; stale grok intake docstrings updated.
* fix(batch): MegaTask panel + doc audit gaps
Frontend half of the audit fixes:
- The confirm payload now carries project_ids (the schema requires it), and
the panel re-checks every task targets one of the scoped repos before
launching, naming the offending task.
- The Review-MegaTask project picker is filtered to the scoped repos and
the per-task validity (border + launch gate) keys off scoped membership,
so a task can only be (re)pointed at an in-scope project — also fixing the
case where the agent emitted a non-UUID / unknown project.
- Dropped malformed drafts are surfaced as a chat error so the human knows
the batch shrank instead of silently confirming fewer tasks.
- Doc wording: a wave releases on the previous wave's terminal state
(normally a merge; a cancellation releases it too), not strictly 'merged'.
* test(batch): lock the CEO's EXACT 4-wave hand-sequencing as the golden bar
The golden test asserted the constraints (S6 last, the migration chain, the
shared-threats serialization, S1/S2/S7 parallel) but not the full wave
partition. The bar for MegaTask is 'reproduce my exact waves or it's not
done', so assert the exact 4-wave partition the analyzer produces for the
guard-core-app batch:
wave 1: R1 R2 S1 S2 S3 S5 S7 · wave 2: R3 · wave 3: R4 S8 · wave 4: S6
Confirmed unchanged by the audit's analyzer fixes (no migration is shared;
single project).
* fix(batch): tolerate a stub task in assert_batch_shape_intact
The batch-shape re-validation read task.batch_id directly, but update()'s
partial-caller contract is exercised with a SimpleNamespace stub that has no
batch_id column → AttributeError. Use getattr(..., None) for batch_id and the
shape fields so the guard no-ops on any task lacking the column (a stub, or a
non-batch task) while still enforcing on a real batch member.
* fix(orchestrator): authenticate internal API self-calls with the system identity
The dispatcher httpx clients were built without an agent identity, so the
orchestrator's self-PATCHes to /api/tasks/{id} (auto-block, auto-resume,
auto-recover, SLA annotation) were rejected 401 "Missing X-Agent-ID" and
silently no-op'd. The auto-resume that lifts a PM's paused parent could never
write, so paused/blocked parents stayed wedged and stranded their dependents
(the fe-pm/be-pm respawn churn seen in prod).
Header propagation was inconsistent across the separate AsyncClient call-sites:
only the main dispatch client carried the system identity; the readiness and
sweep clients did not. Hoist the identity into a shared _SYSTEM_API_HEADERS
constant and apply it to every API-facing dispatcher client. The system role
holds TaskAction.ASSIGN, so it is authorized for the audited admin_set_status
path those write routes use. The external provider-recovery probe client is
intentionally left untouched.
---------
Co-authored-by: Renn F <rennf93@users.noreply.github.com>
494 lines
16 KiB
Python
494 lines
16 KiB
Python
"""roboco.api.schemas.tasks coverage — pure-Python conversion helpers.
|
|
|
|
The route layer is owned by another agent; here we cover the pure
|
|
data-mapping helpers: convert_plan, convert_checkpoints,
|
|
convert_progress_updates, convert_commits, parse_uuid_or_none,
|
|
_parse_uuid_list, transform_update_data, and task_to_response/
|
|
task_list_to_response (with a stub TaskTable to avoid DB).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from datetime import UTC, datetime
|
|
from types import SimpleNamespace
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock, MagicMock, patch
|
|
from uuid import UUID, uuid4
|
|
|
|
import pytest
|
|
from roboco.api.schemas.tasks import (
|
|
TaskUpdate,
|
|
_parse_uuid_list,
|
|
convert_checkpoints,
|
|
convert_commits,
|
|
convert_plan,
|
|
convert_progress_updates,
|
|
enrich_task_with_context,
|
|
parse_uuid_or_none,
|
|
task_list_to_response,
|
|
task_to_response,
|
|
transform_update_data,
|
|
)
|
|
from roboco.models.base import Complexity, TaskNature, TaskStatus, TaskType, Team
|
|
|
|
_ORDER_DEFAULT = 0
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# convert_plan
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_convert_plan_returns_none_for_empty() -> None:
|
|
assert convert_plan(None) is None
|
|
assert convert_plan({}) is None
|
|
|
|
|
|
def test_convert_plan_with_full_data() -> None:
|
|
sub_id = uuid4()
|
|
data = {
|
|
"approach": "Implement X using Y",
|
|
"sub_tasks": [
|
|
{
|
|
"id": str(sub_id),
|
|
"title": "Sub 1",
|
|
"description": "do thing",
|
|
"completed": True,
|
|
"order": 1,
|
|
"estimated_hours": 2.5,
|
|
"notes": "n",
|
|
},
|
|
],
|
|
"technical_considerations": ["c1"],
|
|
"risks": [{"name": "r1"}],
|
|
"open_questions": [{"q": "?"}],
|
|
}
|
|
plan = convert_plan(data)
|
|
assert plan is not None
|
|
assert plan.approach == "Implement X using Y"
|
|
assert plan.sub_tasks[0].id == sub_id
|
|
assert plan.sub_tasks[0].completed is True
|
|
|
|
|
|
def test_convert_plan_coerces_invalid_uuid_to_fresh() -> None:
|
|
"""Non-UUID id strings are silently replaced with a new UUID."""
|
|
data: dict[str, Any] = {
|
|
"approach": "x",
|
|
"sub_tasks": [{"id": "not-a-uuid", "title": "t", "order": 0}],
|
|
}
|
|
plan = convert_plan(data)
|
|
assert plan is not None
|
|
assert isinstance(plan.sub_tasks[0].id, UUID)
|
|
|
|
|
|
def test_convert_plan_passes_through_uuid_id() -> None:
|
|
"""When id is already a UUID instance, it's preserved."""
|
|
sub_id = uuid4()
|
|
data: dict[str, Any] = {
|
|
"approach": "x",
|
|
"sub_tasks": [{"id": sub_id, "title": "t", "order": 0}],
|
|
}
|
|
plan = convert_plan(data)
|
|
assert plan is not None
|
|
assert plan.sub_tasks[0].id == sub_id
|
|
|
|
|
|
def test_convert_plan_with_non_uuid_non_string_id() -> None:
|
|
"""Numeric ids are also coerced to a fresh UUID."""
|
|
data: dict[str, Any] = {
|
|
"approach": "x",
|
|
"sub_tasks": [{"id": 12345, "title": "t", "order": 0}],
|
|
}
|
|
plan = convert_plan(data)
|
|
assert plan is not None
|
|
assert isinstance(plan.sub_tasks[0].id, UUID)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# convert_checkpoints
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_convert_checkpoints_empty() -> None:
|
|
assert convert_checkpoints(None) == []
|
|
assert convert_checkpoints([]) == []
|
|
|
|
|
|
def test_convert_checkpoints_with_data() -> None:
|
|
cp_id = uuid4()
|
|
agent_id = uuid4()
|
|
data = [
|
|
{
|
|
"id": cp_id,
|
|
"timestamp": datetime.now(UTC),
|
|
"agent_id": agent_id,
|
|
"state_summary": "halfway",
|
|
"remaining_work": ["x"],
|
|
"notes": "fine",
|
|
}
|
|
]
|
|
result = convert_checkpoints(data)
|
|
assert len(result) == 1
|
|
assert result[0].id == cp_id
|
|
assert result[0].state_summary == "halfway"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# convert_progress_updates
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_convert_progress_updates_empty() -> None:
|
|
assert convert_progress_updates(None) == []
|
|
assert convert_progress_updates([]) == []
|
|
|
|
|
|
def test_convert_progress_updates_with_data() -> None:
|
|
agent_id = uuid4()
|
|
data = [
|
|
{
|
|
"timestamp": datetime.now(UTC),
|
|
"agent_id": agent_id,
|
|
"message": "step done",
|
|
"percentage": 50,
|
|
}
|
|
]
|
|
result = convert_progress_updates(data)
|
|
assert len(result) == 1
|
|
assert result[0].message == "step done"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# convert_commits
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_convert_commits_empty() -> None:
|
|
assert convert_commits(None) == []
|
|
assert convert_commits([]) == []
|
|
|
|
|
|
def test_convert_commits_with_data() -> None:
|
|
agent_id = uuid4()
|
|
data = [
|
|
{
|
|
"hash": "abc123",
|
|
"message": "fix",
|
|
"timestamp": datetime.now(UTC),
|
|
"author_agent_id": agent_id,
|
|
}
|
|
]
|
|
result = convert_commits(data)
|
|
assert len(result) == 1
|
|
assert result[0].hash == "abc123"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# parse_uuid_or_none / _parse_uuid_list
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_parse_uuid_or_none_with_valid_uuid() -> None:
|
|
raw = uuid4()
|
|
assert parse_uuid_or_none(str(raw)) == raw
|
|
|
|
|
|
def test_parse_uuid_or_none_with_empty() -> None:
|
|
assert parse_uuid_or_none("") is None
|
|
assert parse_uuid_or_none(None) is None
|
|
|
|
|
|
def test_parse_uuid_or_none_with_invalid_returns_none() -> None:
|
|
assert parse_uuid_or_none("not-a-uuid") is None
|
|
|
|
|
|
def test_parse_uuid_list_with_valid() -> None:
|
|
a, b = uuid4(), uuid4()
|
|
out = _parse_uuid_list([str(a), str(b)])
|
|
assert a in out
|
|
assert b in out
|
|
|
|
|
|
def test_parse_uuid_list_skips_empty_strings() -> None:
|
|
raw = uuid4()
|
|
out = _parse_uuid_list([str(raw), "", None]) # type: ignore[list-item]
|
|
assert raw in out
|
|
assert len(out) == 1
|
|
|
|
|
|
def test_parse_uuid_list_with_none() -> None:
|
|
assert _parse_uuid_list(None) == []
|
|
assert _parse_uuid_list([]) == []
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# transform_update_data
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def test_transform_update_data_converts_assigned_to() -> None:
|
|
raw = uuid4()
|
|
update = TaskUpdate(assigned_to=str(raw))
|
|
out = transform_update_data(update)
|
|
assert out["assigned_to"] == raw
|
|
|
|
|
|
def test_transform_update_data_converts_dependency_ids() -> None:
|
|
a, b = uuid4(), uuid4()
|
|
update = TaskUpdate(dependency_ids=[str(a), str(b)])
|
|
out = transform_update_data(update)
|
|
assert a in out["dependency_ids"]
|
|
assert b in out["dependency_ids"]
|
|
|
|
|
|
def test_transform_update_data_skips_unset_fields() -> None:
|
|
"""Empty TaskUpdate produces an empty dict (model_dump exclude_unset)."""
|
|
update = TaskUpdate()
|
|
out = transform_update_data(update)
|
|
assert out == {}
|
|
|
|
|
|
def test_transform_update_data_handles_null_unassign() -> None:
|
|
"""Empty string assigned_to → None (parse_uuid_or_none)."""
|
|
update = TaskUpdate(assigned_to="")
|
|
out = transform_update_data(update)
|
|
assert out["assigned_to"] is None
|
|
|
|
|
|
def test_transform_update_data_passes_sequence() -> None:
|
|
"""sequence is editable via PATCH (panel task-details sequence editor)."""
|
|
new_order = 3
|
|
update = TaskUpdate(sequence=new_order)
|
|
out = transform_update_data(update)
|
|
assert out["sequence"] == new_order
|
|
# Unset sequence is omitted (exclude_unset), so a partial PATCH never
|
|
# clobbers the existing order.
|
|
assert "sequence" not in transform_update_data(TaskUpdate(priority=1))
|
|
|
|
|
|
def test_task_update_sequence_rejects_negative() -> None:
|
|
"""sequence has ge=0 — a negative order is a validation error, not stored."""
|
|
with pytest.raises(ValueError, match="sequence"):
|
|
TaskUpdate(sequence=-1)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# task_to_response / task_list_to_response
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _stub_task(*, with_project: bool = False) -> SimpleNamespace:
|
|
"""Build a TaskTable stand-in that matches task_to_response's reads."""
|
|
return SimpleNamespace(
|
|
id=uuid4(),
|
|
title="t",
|
|
description="d",
|
|
acceptance_criteria=["a"],
|
|
status=TaskStatus.PENDING,
|
|
priority=1,
|
|
sequence=0,
|
|
nature=TaskNature.TECHNICAL,
|
|
task_type=TaskType.CODE,
|
|
project_id=uuid4(),
|
|
product_id=None,
|
|
project=(SimpleNamespace(slug="proj-1") if with_project else None),
|
|
docs_complete=False,
|
|
pr_created=False,
|
|
board_review_complete=False,
|
|
team=Team.BACKEND,
|
|
created_by=uuid4(),
|
|
assigned_to=None,
|
|
parent_task_id=None,
|
|
batch_id=None,
|
|
dependency_ids=[],
|
|
blocker_ids=[],
|
|
created_at=datetime.now(UTC),
|
|
updated_at=None,
|
|
claimed_at=None,
|
|
claimed_by=None,
|
|
started_at=None,
|
|
completed_at=None,
|
|
target_date=None,
|
|
last_heartbeat_at=None,
|
|
estimated_complexity=Complexity.LOW,
|
|
plan=None,
|
|
checkpoints=[],
|
|
progress_updates=[],
|
|
commits=[],
|
|
dev_notes=None,
|
|
qa_notes=None,
|
|
auditor_notes=None,
|
|
pr_reviewer_notes=None,
|
|
doc_notes=None,
|
|
quick_context=None,
|
|
notes_structured=None,
|
|
self_verified=False,
|
|
qa_verified=None,
|
|
branch_name=None,
|
|
pr_number=None,
|
|
pr_url=None,
|
|
)
|
|
|
|
|
|
def test_task_to_response_omits_slug_when_project_not_loaded() -> None:
|
|
stub = _stub_task(with_project=False)
|
|
fake_inspector = MagicMock()
|
|
fake_inspector.unloaded = {"project"}
|
|
with patch("roboco.api.schemas.tasks.sa_inspect", return_value=fake_inspector):
|
|
resp = task_to_response(stub) # type: ignore[arg-type]
|
|
assert resp.project_slug is None
|
|
|
|
|
|
def test_task_to_response_includes_slug_when_project_loaded() -> None:
|
|
stub = _stub_task(with_project=True)
|
|
fake_inspector = MagicMock()
|
|
fake_inspector.unloaded = set() # project IS loaded
|
|
with patch("roboco.api.schemas.tasks.sa_inspect", return_value=fake_inspector):
|
|
resp = task_to_response(stub) # type: ignore[arg-type]
|
|
assert resp.project_slug == "proj-1"
|
|
|
|
|
|
def test_task_to_response_serializes_all_note_sections() -> None:
|
|
"""Regression: pr_reviewer_notes / doc_notes / notes_structured MUST be in the
|
|
response. The builder previously omitted them, so the panel showed them blank
|
|
even when the DB had them (the recurring "notes invisible" bug)."""
|
|
stub = _stub_task()
|
|
stub.pr_reviewer_notes = "## Findings\n- looks good"
|
|
stub.doc_notes = "Updated the README"
|
|
stub.notes_structured = {"pr_review": {"verdict": "passed"}}
|
|
fake_inspector = MagicMock()
|
|
fake_inspector.unloaded = {"project"}
|
|
with patch("roboco.api.schemas.tasks.sa_inspect", return_value=fake_inspector):
|
|
resp = task_to_response(stub) # type: ignore[arg-type]
|
|
assert resp.pr_reviewer_notes == "## Findings\n- looks good"
|
|
assert resp.doc_notes == "Updated the README"
|
|
assert resp.notes_structured == {"pr_review": {"verdict": "passed"}}
|
|
|
|
|
|
def test_task_list_to_response_returns_list() -> None:
|
|
stubs = [_stub_task(), _stub_task()]
|
|
fake_inspector = MagicMock()
|
|
fake_inspector.unloaded = {"project"}
|
|
with patch("roboco.api.schemas.tasks.sa_inspect", return_value=fake_inspector):
|
|
out = task_list_to_response(stubs) # type: ignore[arg-type]
|
|
assert len(out) == len(stubs)
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# enrich_task_with_context — covers the work_session + project lookup branches.
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _stub_response() -> Any:
|
|
"""Build a TaskResponse-like object that supports model_dump."""
|
|
fake_inspector = MagicMock()
|
|
fake_inspector.unloaded = {"project"}
|
|
with patch("roboco.api.schemas.tasks.sa_inspect", return_value=fake_inspector):
|
|
resp = task_to_response(_stub_task()) # type: ignore[arg-type]
|
|
return resp
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_enrich_task_with_context_attaches_workssession_and_project() -> None:
|
|
"""Both work_session and project rows present → both keys attached."""
|
|
resp = _stub_response()
|
|
|
|
work_session = MagicMock()
|
|
work_session.id = uuid4()
|
|
work_session.branch_name = "feature/backend/x"
|
|
work_session.status = MagicMock()
|
|
work_session.status.value = "active"
|
|
work_session.commits = ["abc123"]
|
|
work_session.files_modified = ["foo.py"]
|
|
work_session.pr_number = 42
|
|
work_session.pr_url = "https://github.com/x/y/pull/42"
|
|
work_session.pr_status = "open"
|
|
work_session.project_id = uuid4()
|
|
|
|
project = MagicMock()
|
|
project.id = work_session.project_id
|
|
project.name = "Proj"
|
|
project.slug = "proj"
|
|
project.git_url = "https://github.com/example/repo.git"
|
|
project.default_branch = "main"
|
|
|
|
db = MagicMock()
|
|
db.execute = AsyncMock()
|
|
# First execute returns work_session; second returns project.
|
|
ws_result = MagicMock()
|
|
ws_result.scalar_one_or_none.return_value = work_session
|
|
proj_result = MagicMock()
|
|
proj_result.scalar_one_or_none.return_value = project
|
|
db.execute.side_effect = [ws_result, proj_result]
|
|
|
|
enriched = await enrich_task_with_context(resp, db)
|
|
assert enriched.work_session is not None
|
|
assert enriched.project is not None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_enrich_task_with_context_no_work_session() -> None:
|
|
"""No work_session row → enrichment passes through with no work_session set."""
|
|
resp = _stub_response()
|
|
db = MagicMock()
|
|
db.execute = AsyncMock()
|
|
ws_result = MagicMock()
|
|
ws_result.scalar_one_or_none.return_value = None
|
|
db.execute.return_value = ws_result
|
|
enriched = await enrich_task_with_context(resp, db)
|
|
# Returned object — work_session stays as default (None) since pull was empty.
|
|
assert enriched.work_session is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_enrich_task_with_context_status_unknown_when_status_falsy() -> None:
|
|
"""work_session.status is None → 'unknown' fallback string (line 656)."""
|
|
resp = _stub_response()
|
|
|
|
work_session = MagicMock()
|
|
work_session.id = uuid4()
|
|
work_session.branch_name = "feature/x"
|
|
work_session.status = None
|
|
work_session.commits = []
|
|
work_session.files_modified = []
|
|
work_session.pr_number = None
|
|
work_session.pr_url = None
|
|
work_session.pr_status = None
|
|
work_session.project_id = None
|
|
|
|
db = MagicMock()
|
|
db.execute = AsyncMock()
|
|
ws_result = MagicMock()
|
|
ws_result.scalar_one_or_none.return_value = work_session
|
|
db.execute.return_value = ws_result
|
|
enriched = await enrich_task_with_context(resp, db)
|
|
assert enriched.work_session is not None
|
|
assert enriched.work_session.status == "unknown"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_enrich_task_with_context_skips_project_when_not_requested() -> None:
|
|
"""include_project=False bypasses project enrichment."""
|
|
resp = _stub_response()
|
|
|
|
work_session = MagicMock()
|
|
work_session.id = uuid4()
|
|
work_session.branch_name = "feature/x"
|
|
work_session.status = MagicMock()
|
|
work_session.status.value = "active"
|
|
work_session.commits = []
|
|
work_session.files_modified = []
|
|
work_session.pr_number = None
|
|
work_session.pr_url = None
|
|
work_session.pr_status = None
|
|
work_session.project_id = uuid4()
|
|
|
|
db = MagicMock()
|
|
db.execute = AsyncMock()
|
|
ws_result = MagicMock()
|
|
ws_result.scalar_one_or_none.return_value = work_session
|
|
db.execute.return_value = ws_result
|
|
enriched = await enrich_task_with_context(resp, db, include_project=False)
|
|
assert enriched.work_session is not None
|
|
assert enriched.project is None
|