mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
feat(board): Board Programs — the complete twelve-program catalog (Phases 1-3) (#699)
* feat(board): Pest Control — the first project-scoped Board Program The Product Owner hunts latent defects (what the org records but nobody reads): a weekly cycle — accelerated off-schedule when the trailing-7-day rework rate crosses pest_rework_threshold, with the cheap dedup/scope gates evaluated before the metrics queries — opens one held exploration task against the least-recently-explored opted-in project (deterministic round-robin; opted_in_projects gains a stable ORDER BY), with server- assembled evidence in the spawn prompt (rework hotspots, recurring-findings and waived-minor ledger aggregates, all capped) plus prior-cycle LEARN context. The PO calls the new PO-only propose_bug_hunt verb once: ≤5 items, evidence required per item, targets validated against pest_control participation. CEO decides per item — approve materializes a BACKLOG task (source pest_control, never auto-starts), reject records the reason; both feed the LEARN ledger by exploration task id; all-terminal completes the cycle. Telegram queue pushes carry working Approve/Reject handlers mirroring the roadmap kind. Doctrine: board.md Pest Control section + product-owner verb entry + regenerated verb tables. * feat(panel): Pest Control review queue Command Center gains the pest review queue (per-item approve/reject with reason, mirroring the roadmap queue); the Programs card and the project settings participates-in checkboxes pick the new program up registry-driven — the settings section renders for the first time now that a project-scoped program exists. * feat(board): Periscope — HoM market-research brief program Weekly org-scoped cycle: a solo HoM spawn researches the market (web research with mandatory source URLs — uncited findings are rejected) and files one structured brief via the new HoM-only propose_market_brief verb: headline, cited findings, threats/opportunities, positioning note, all soup-checked and screened through the injection guard at persist time (web-derived text later reaches prompts; flags recorded, content never dropped). A brief is a report, not a proposal: the verb completes the exploration in the same call (the x_feature asymmetry), the cycle ledger auto-closes, and the CEO gets a best-effort notification with no approve/reject surface (periscope deliberately never joins Telegram's action kinds). The latest brief is injected into the roadmap exploration prompt — Periscope feeds Printer, the first cross-role program input. * feat(panel): Market Briefs tab (read-only) Business page gains a Market Briefs tab listing Periscope briefs — headline, cited findings, threats/opportunities — read-only by design; a report has nothing to approve. * feat(board): Coroner — event-triggered Auditor postmortems The first EVENT program: no cron — three best-effort hooks open an autopsy when a task bounces to its 3rd revision (the audit chokepoint), is cancelled after work started, or is budget-blocked; all gated on arming + one-open-autopsy dedup, none can fail the underlying transition. A solo Auditor spawn reads the incident (server-assembled findings + transition context) and files one propose_postmortem: incident summary, root cause, failed stage (validated against the real status vocabulary), and ONE process change — a playbook-kind change drafts via PlaybookService directly into the normal pending-curation queue; the briefed draft_playbook manifest grant was deliberately NOT added, preserving the existing 'auditor curates but never drafts' invariant test. Complete-at-propose (report asymmetry), cycle ledger auto-closes, CEO notified link-only. Integrated as a union with Periscope across the shared program surfaces. * feat(panel): Coroner postmortems card Read-only postmortems list under Business → Programs — incident, root cause, failed stage, process change; nothing to approve, the process-change artifact (a draft playbook) rides the existing curation queue. * feat(board): Sentinel — Auditor drift-watch quality reports Weekly org-scoped cycle: a solo Auditor spawn receives a server-assembled drift context (waived-findings trend, open findings by severity, conventions-violation hotspots, top spend — all capped, pure ORM) and files one propose_quality_report: headline, 1-7 area-validated items with evidence and suggested actions, overall assessment. Report semantics — complete-at-propose, cycle auto-closes, CEO notified display-only (never on Telegram's approve/reject surface); items are structured so a later convert-to-task control is cheap. Integration adopts Sentinel's module- level dict-dispatch for board-program routing (xenon-driven), folding all prior programs in; app router mounting extracted to a helper for the same budget. * feat(panel): Quality Reports tab (read-only) Business page gains the Sentinel quality-reports tab — headline, per-area observations with evidence and suggested actions; read-only, a report has nothing to approve. * feat(board): Spackle — gap-fill audit program Biweekly project-scoped PO cycle over the half-shipped surface area: API routes without panel surfaces (and vice versa), armed flags without docs, docs promises the code doesn't keep, dead-end tabs — the inventory diffing is the PO's own read-tool work, ordered by the spawn prompt with file:line citations required; the server injects only prior-cycle LEARN and the rotation target. Rotation is now a shared module-level helper (pick_rotation_target, parameterized by source) both project-scoped engines use — pest_control delegates to it, behavior-identical, with a cross-pollution test proving the two programs' rotations stay independent. propose_gap_fill mirrors the bug-hunt verb (≤5 items, two-sided evidence required, participation gate); per-item CEO decide materializes BACKLOG source=spackle tasks; full Telegram kind incl. approve/reject handlers. All seven program routers now mount from one helper. * feat(panel): Spackle gap-fill review queue Command Center gains the gap-fill queue mirroring the pest-control one — per-item approve/reject with the two-sided gap evidence rendered. * feat(board): Scales — monthly portfolio rebalance Org-scoped PO cycle over the stale backlog: the spawn receives a capped stale-task snapshot (BACKLOG/PENDING unclaimed >30 days) plus the charter and prior-cycle LEARN, and files one propose_rebalance — 1-7 items, each a resolvable task_ref with action reprioritize (validated new priority) or cancel, rationale required. Per-item CEO decide: approve EXECUTES the action (audited priority update, or the normal cancel path) — the first program whose materializer mutates existing tasks instead of creating them; reject records the reason; LEARN by exploration task id; all-terminal completes the cycle. Full Telegram decide-kind wiring. Integrated as the eight-program union (registry, dict dispatch, routers helper, teardown enumerations). * feat(panel): Scales rebalance review queue Command Center gains the rebalance queue — per-item approve/reject with the action, target task, and rationale rendered. * feat(board): Mirror — quarterly positioning audit Project-scoped HoM cycle over messaging surfaces: README claims vs shipped reality, docs-site promises vs code, charter alignment — the audit is the HoM's own read-tool work with citations required; the server injects the charter, prior-cycle LEARN, and the shared rotation target. propose_ messaging_fixes mirrors the gap-fill verb (≤5 items, drift evidence naming claim + contradicting reality, participation gate); per-item CEO decide materializes BACKLOG source=mirror documentation tasks; full Telegram decide-kind wiring. Nine-program union across the shared surfaces. * feat(panel): Mirror messaging-fixes review queue * feat(board): Megaphone — HoM standing editorial calendar Cron cycle (3 days, org-scoped, gated on X credentials — drafting content nobody can post is pointless): the HoM receives a shipped-this-week digest plus Unreleased changelog bullets and files one propose_editorial_post (angle-validated, ≤280, brand voice) that materializes a held x_editorial draft through the SAME X-queue origination chokepoint release posts use — zero new approval surface, notifications and CEO decide for free. Complete-at-propose; cycle auto-closes. Ten-program union. * feat(panel): x_editorial source labels in the X queue surfaces * feat(board): Librarian — proactive playbook mining Biweekly org-scoped Auditor cycle: mines recurring non-private learning journals (≥2-count grouping with a recency fallback) against the existing playbook-title inventory and files one propose_playbook_drafts — 1-3 drafts, each with the repeated-pattern evidence that justifies it, duplicate titles rejected in-batch and against the live store. Drafts are created via PlaybookService directly (the Coroner precedent — the 'auditor curates but never drafts' do-verb invariant stays intact and tested) and land in the normal pending-curation queue the Auditor's own triage already surfaces; no new panel surface. Complete-at-propose; display-only CEO notification. Eleven-program union. * feat(board): War Room — release campaign planning EVENT program with a REAL originator (unlike coroner's stub): a release publish hooks a campaign brief beside the release-post seam, and the CEO's run-now originates on demand — the cron loop never fires it. The HoM designs a 2-6 post arc (teaser → launch → follow-up → spotlight; 280-cap, future strictly-ascending publish_after, stage vocabulary) and one propose_campaign call materializes each post as a held x_campaign draft through the X-queue chokepoint. V1 is manual-cadence by design: publish_ after renders as queue guidance and the CEO approves each post at its moment — nothing auto-posts, ever; the auto-schedule upgrade is a documented ceiling. Twelve-program union: full registry complete. * feat(panel): x_campaign labels + publish-after guidance in the X queue * feat(board): Barfly — adjacent-conversation replies Cron cycle (2 days, org-scoped, X-credentials gated): the engine searches X for conversations where RoboCo is relevant but unmentioned (new OAuth- signed search_recent on the client; queries + candidate cap configurable), screens every fetched tweet through the injection guard (stored unclamped — a clamp was truncating the candidate under the envelope, caught by the dev's own tests), dedupes via the existing x_seen_mentions ledger (no migration; also prevents double-drafting against the mentions poll), and opens one held HoM exploration carrying the screened candidates. propose_ conversation_replies enforces candidate-id-only replies (≤5, 280-cap); each materializes a held x_barfly draft through the X-queue chokepoint, threaded via a new in_reply_to seam on post_tweet that only x_barfly drafts use. The X redraft machinery is now dict-dispatch over per-source extractors with reply-ref carry for x_barfly. Thirteen-program registry. War Room's test fakes gained the new abstract search_recent stub. * feat(board): Dogfood — the PO walks the product The fourteenth and final registry entry, completing the catalog. EVENT program (release-publish hook beside the war-room hook + CEO run-now, both through the same real originator; the cron loop never fires it), project- scoped with shared rotation. The permission surface is the careful part: the PO's dogfood spawn — and ONLY that spawn — gets the Playwright MCP mounted, via a task-scoped fail-closed probe mirroring the video-authoring precedent (a PO spawned for roadmap/pest/scales never sees browser tools; tested both ways); the PM agent image bakes chromium unconditionally like the ux image, the mount stays task-gated in code. The walk targets the rotation target's live surfaces (panel_base_url only when the target is the org's own project, honest degradation otherwise); propose_friction_ fixes files ≤5 walked-path-evidenced items; per-item CEO decide materializes BACKLOG source=dogfood tasks; full Telegram decide kind. Also: megaphone/librarian/war_room arming keys restored to the settings validator — their panel toggles would have been rejected (dropped in earlier unions; the same silent-arming class the drill killed once already). * feat(panel): Dogfood friction review queue * chore(board): final whole-branch sweep fixes The night's closing adversarial pass over the integrated fourteen-program registry found ONE functional defect — the war-room test fakes' post_tweet predated Barfly's in_reply_to_tweet_id kwarg (LSP violation, the only red in an otherwise fully green gate) — plus doc/test drift, all fixed: the source-parity test completes to fourteen (spackle/mirror were silently absent while its neighboring comment claimed full coverage), the PO identity doc gains its missing Dogfood verb, the auditor quick-list gains propose_postmortem, three stale comments corrected (rotation docstring, panel registry header, X source enumerations), the dogfood release-hook gains the exception-swallow test its four sibling hooks already had, and the CHANGELOG's Unreleased section documents the whole Board Programs train. Full make quality: exit 0, all gates green. * docs: full documentation sweep for the Board Programs train CLAUDE.md's roadmap-engine entry superseded by the Board Program registry entry (all fourteen programs, arming, scoping, LEARN, guardrails) with the role verb tables and playwright row refreshed; docs/rag gains the agent- facing architecture doc plus full propose_* call-shape sections in the three board role docs, and corrects the strategy-engine section to shipped reality (only idle→roadmap is wired); docs/map covers the registry + all twelve engines with flags, gotchas, and drift notes. The 0.27.0 reference inventory confirmed only the release-executor's canonical set carries the version — left for the 0.28.0 cut. * feat(board): human titles + descriptions on every program surface Raw registry keys rendered as bare panel labels — an operator reading x_feature had no idea what enabling or running it does. The registry dataclass gains title/description (test-enforced non-empty for every entry, unique titles), the API passes them through, and every surface renders title-with-description-tooltip instead of the key: the Programs card (label, toggle hint, run-now toast), and the project settings participates-in/excluded-from checkboxes. --------- Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
@@ -23,12 +23,29 @@ from roboco.db.tables import (
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.models import AgentRole, AgentStatus, TaskStatus, Team
|
||||
from roboco.models.permissions import AgentContext
|
||||
from roboco.services.task import ROADMAP_SOURCE
|
||||
from roboco.services.task import (
|
||||
BARFLY_SOURCE,
|
||||
CORONER_SOURCE,
|
||||
DOGFOOD_SOURCE,
|
||||
LIBRARIAN_SOURCE,
|
||||
MEGAPHONE_SOURCE,
|
||||
MIRROR_SOURCE,
|
||||
PERISCOPE_SOURCE,
|
||||
PEST_CONTROL_SOURCE,
|
||||
ROADMAP_SOURCE,
|
||||
SCALES_SOURCE,
|
||||
SENTINEL_SOURCE,
|
||||
SPACKLE_SOURCE,
|
||||
WAR_ROOM_SOURCE,
|
||||
X_FEATURE_EXPLORATION_SOURCE,
|
||||
)
|
||||
from roboco.services.x_credentials import get_x_credentials_service
|
||||
from sqlalchemy import delete, update
|
||||
|
||||
CEO_UUID = _foundation.AGENTS["ceo"].uuid
|
||||
SYSTEM_UUID = _foundation.AGENTS["system"].uuid
|
||||
PO_UUID = _foundation.AGENTS["product-owner"].uuid
|
||||
HOM_UUID = _foundation.AGENTS["head-marketing"].uuid
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
@@ -41,6 +58,7 @@ async def _seed_agents(session: AsyncSession) -> None:
|
||||
(CEO_UUID, "ceo", AgentRole.CEO),
|
||||
(SYSTEM_UUID, "system", AgentRole.SYSTEM),
|
||||
(PO_UUID, "product-owner", AgentRole.PRODUCT_OWNER),
|
||||
(HOM_UUID, "head-marketing", AgentRole.HEAD_MARKETING),
|
||||
):
|
||||
if await session.get(AgentTable, uuid) is not None:
|
||||
continue
|
||||
@@ -98,6 +116,43 @@ async def _arm_roadmap(session: AsyncSession, monkeypatch: pytest.MonkeyPatch) -
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def _arm_war_room(session: AsyncSession, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
"""Arms war_room via its settings-store key (no legacy flag exists for
|
||||
it — ``program_armed``'s ``_legacy_enabled`` returns False for an
|
||||
unregistered legacy alias), seeds the project ``WarRoomEngine.
|
||||
_roboco_project`` resolves against (mirrors ``_arm_roadmap``'s unique-
|
||||
slug-per-call rationale), and seeds X credentials — ``WarRoomEngine``'s
|
||||
own creds gate would otherwise no-op every call, mirroring XEngine's
|
||||
release/spotlight guard."""
|
||||
key = "board_program.war_room.enabled"
|
||||
existing = await session.get(SystemSettingTable, key)
|
||||
if existing is None:
|
||||
session.add(SystemSettingTable(key=key, value="true"))
|
||||
else:
|
||||
existing.value = "true"
|
||||
|
||||
slug = f"roboco-api-{uuid4().hex[:8]}"
|
||||
monkeypatch.setattr(cfg, "self_heal_project_slug", slug)
|
||||
session.add(
|
||||
ProjectTable(
|
||||
id=uuid4(),
|
||||
name="RoboCo",
|
||||
slug=slug,
|
||||
git_url="https://example.com/roboco.git",
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=SYSTEM_UUID,
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
await get_x_credentials_service(session).set_credentials(
|
||||
api_key="ak-test",
|
||||
api_secret="as-test",
|
||||
access_token="at-test",
|
||||
access_token_secret="ats-test",
|
||||
)
|
||||
|
||||
|
||||
def _build_app(db_session: AsyncSession, role: AgentRole, agent_id: UUID) -> FastAPI:
|
||||
app = FastAPI()
|
||||
app.include_router(board_programs_router, prefix="/api/board-programs")
|
||||
@@ -123,11 +178,14 @@ async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
app.dependency_overrides.clear()
|
||||
# run-now's route handler commits explicitly (write-route convention), so
|
||||
# anything a test wrote through it (settings-store overrides, an opened
|
||||
# ledger row, the board_roadmap task it originates) would otherwise
|
||||
# outlive this test in the shared, cross-test-persistent DB and poison
|
||||
# every later real-DB roadmap/board-program unit test (dedup checks,
|
||||
# settings-store PK collisions, ledger scalar_one() lookups). Purge
|
||||
# unconditionally — a no-op for the tests here that never wrote anything.
|
||||
# ledger row, the board_roadmap/x_feature_exploration/board_pest_control
|
||||
# task it originates) would otherwise outlive this test in the shared,
|
||||
# cross-test-persistent DB and poison every later real-DB board-program
|
||||
# unit test (dedup checks, settings-store PK collisions, ledger
|
||||
# scalar_one() lookups) — not just roadmap's, so every registered
|
||||
# program's exploration source is swept here, not only the one this
|
||||
# module's own tests happen to exercise today. Purge unconditionally — a
|
||||
# no-op for the tests here that never wrote anything.
|
||||
await db_session.execute(
|
||||
delete(SystemSettingTable).where(SystemSettingTable.key.like("board_program.%"))
|
||||
)
|
||||
@@ -135,7 +193,24 @@ async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
await db_session.execute(
|
||||
update(TaskTable)
|
||||
.where(
|
||||
TaskTable.source == ROADMAP_SOURCE,
|
||||
TaskTable.source.in_(
|
||||
[
|
||||
ROADMAP_SOURCE,
|
||||
X_FEATURE_EXPLORATION_SOURCE,
|
||||
PEST_CONTROL_SOURCE,
|
||||
PERISCOPE_SOURCE,
|
||||
CORONER_SOURCE,
|
||||
SENTINEL_SOURCE,
|
||||
SPACKLE_SOURCE,
|
||||
SCALES_SOURCE,
|
||||
MIRROR_SOURCE,
|
||||
MEGAPHONE_SOURCE,
|
||||
LIBRARIAN_SOURCE,
|
||||
WAR_ROOM_SOURCE,
|
||||
BARFLY_SOURCE,
|
||||
DOGFOOD_SOURCE,
|
||||
]
|
||||
),
|
||||
TaskTable.status.notin_([TaskStatus.COMPLETED, TaskStatus.CANCELLED]),
|
||||
)
|
||||
.values(status=TaskStatus.CANCELLED)
|
||||
@@ -144,15 +219,54 @@ async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_returns_both_migrated_programs(ceo_client: AsyncClient) -> None:
|
||||
async def test_list_returns_every_registered_program(ceo_client: AsyncClient) -> None:
|
||||
resp = await ceo_client.get("/api/board-programs")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert {p["key"] for p in body} == {"roadmap", "x_feature"}
|
||||
assert {p["key"] for p in body} == {
|
||||
"roadmap",
|
||||
"x_feature",
|
||||
"pest_control",
|
||||
"periscope",
|
||||
"coroner",
|
||||
"sentinel",
|
||||
"spackle",
|
||||
"scales",
|
||||
"mirror",
|
||||
"megaphone",
|
||||
"librarian",
|
||||
"war_room",
|
||||
"barfly",
|
||||
"dogfood",
|
||||
}
|
||||
pest_control = next(p for p in body if p["key"] == "pest_control")
|
||||
assert pest_control["role"] == "product_owner"
|
||||
assert pest_control["trigger"] == "cron"
|
||||
assert pest_control["scope"] == "project"
|
||||
spackle = next(p for p in body if p["key"] == "spackle")
|
||||
assert spackle["role"] == "product_owner"
|
||||
assert spackle["trigger"] == "cron"
|
||||
assert spackle["scope"] == "project"
|
||||
mirror = next(p for p in body if p["key"] == "mirror")
|
||||
assert mirror["role"] == "head_marketing"
|
||||
assert mirror["trigger"] == "cron"
|
||||
assert mirror["scope"] == "project"
|
||||
barfly = next(p for p in body if p["key"] == "barfly")
|
||||
assert barfly["role"] == "head_marketing"
|
||||
assert barfly["trigger"] == "cron"
|
||||
assert barfly["scope"] == "org"
|
||||
roadmap = next(p for p in body if p["key"] == "roadmap")
|
||||
assert roadmap["role"] == "product_owner"
|
||||
assert roadmap["trigger"] == "cron"
|
||||
assert roadmap["scope"] == "org"
|
||||
coroner = next(p for p in body if p["key"] == "coroner")
|
||||
assert coroner["role"] == "auditor"
|
||||
assert coroner["trigger"] == "event"
|
||||
assert coroner["scope"] == "org"
|
||||
war_room = next(p for p in body if p["key"] == "war_room")
|
||||
assert war_room["role"] == "head_marketing"
|
||||
assert war_room["trigger"] == "event"
|
||||
assert war_room["scope"] == "org"
|
||||
assert roadmap["open_cycle"] is False
|
||||
assert roadmap["last_opened_at"] is None
|
||||
# Not asserted == [] — org-scoped "eligible" means every active project
|
||||
@@ -185,6 +299,31 @@ async def test_run_now_opens_a_cycle_then_conflicts_on_retry(
|
||||
assert second.status_code == HTTPStatus.CONFLICT
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_now_opens_a_cycle_for_event_program_war_room(
|
||||
db_session: AsyncSession,
|
||||
ceo_client: AsyncClient,
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""War Room is EVENT-triggered same as Coroner (never cron-due — see
|
||||
test_list_returns_every_registered_program's assertion), but UNLIKE
|
||||
Coroner its ``_ORIGINATORS`` entry is a REAL originator
|
||||
(``WarRoomEngine.run_cycle``, not an always-None stub): run-now must
|
||||
actually open a cycle through the route, proving the EVENT contract
|
||||
holds without needing a stub — ``open_program_cycle`` never checks
|
||||
trigger kind, only the cron loop does."""
|
||||
await _arm_war_room(db_session, monkeypatch)
|
||||
|
||||
first = await ceo_client.post("/api/board-programs/war_room/run-now")
|
||||
assert first.status_code == HTTPStatus.OK
|
||||
body = first.json()
|
||||
assert body["open_cycle"] is True
|
||||
assert body["last_opened_at"] is not None
|
||||
|
||||
second = await ceo_client.post("/api/board-programs/war_room/run-now")
|
||||
assert second.status_code == HTTPStatus.CONFLICT
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_now_unknown_key_is_404(ceo_client: AsyncClient) -> None:
|
||||
resp = await ceo_client.post("/api/board-programs/not-a-real-program/run-now")
|
||||
|
||||
@@ -0,0 +1,335 @@
|
||||
"""Coroner (Board Program) event hooks fired through the REAL service
|
||||
transition paths — bounce >=3x (TaskService._emit_status_transition_audit,
|
||||
via a real _validate_and_set_status transition) and cancel-after-work-started
|
||||
(TaskService.cancel). Every hook must be best-effort: a transition succeeds
|
||||
even when the hook itself raises."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import types
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
from unittest.mock import AsyncMock
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from roboco.db.tables import (
|
||||
AgentTable,
|
||||
BoardProgramCycleTable,
|
||||
ProjectTable,
|
||||
SystemSettingTable,
|
||||
TaskTable,
|
||||
)
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.models.base import AgentRole, AgentStatus, Complexity, Team
|
||||
from roboco.models.base import TaskNature as TN
|
||||
from roboco.models.base import TaskStatus as TS
|
||||
from roboco.models.base import TaskType as TT
|
||||
from roboco.services import coroner_engine as coroner_engine_module
|
||||
from roboco.services import task as task_module
|
||||
from roboco.services.task import (
|
||||
CORONER_SOURCE,
|
||||
PEST_CONTROL_SOURCE,
|
||||
ROADMAP_SOURCE,
|
||||
X_FEATURE_EXPLORATION_SOURCE,
|
||||
TaskCreateRequest,
|
||||
TaskService,
|
||||
_fire_coroner_bounce_hook,
|
||||
get_task_service,
|
||||
)
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.orm import selectinload
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
SYSTEM_UUID = _foundation.AGENTS["system"].uuid
|
||||
AUDITOR_UUID = _foundation.AGENTS["auditor"].uuid
|
||||
ONE = 1
|
||||
THIRD_BOUNCE = 3
|
||||
|
||||
|
||||
@pytest_asyncio.fixture(autouse=True)
|
||||
async def _purge_board_program_pollution(db_session: AsyncSession) -> None:
|
||||
await db_session.execute(
|
||||
delete(SystemSettingTable).where(SystemSettingTable.key.like("board_program.%"))
|
||||
)
|
||||
await db_session.execute(delete(BoardProgramCycleTable))
|
||||
await db_session.execute(
|
||||
update(TaskTable)
|
||||
.where(
|
||||
TaskTable.source.in_(
|
||||
[
|
||||
ROADMAP_SOURCE,
|
||||
X_FEATURE_EXPLORATION_SOURCE,
|
||||
PEST_CONTROL_SOURCE,
|
||||
CORONER_SOURCE,
|
||||
]
|
||||
),
|
||||
TaskTable.status.notin_([TS.COMPLETED, TS.CANCELLED]),
|
||||
)
|
||||
.values(status=TS.CANCELLED)
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
|
||||
async def _seed(session: AsyncSession) -> ProjectTable:
|
||||
for uuid, slug, role, team in (
|
||||
(SYSTEM_UUID, "system", AgentRole.SYSTEM, None),
|
||||
(AUDITOR_UUID, "auditor", AgentRole.AUDITOR, Team.BOARD),
|
||||
):
|
||||
if await session.get(AgentTable, uuid) is None:
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=uuid,
|
||||
name=slug,
|
||||
slug=slug,
|
||||
role=role,
|
||||
team=team,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
project = ProjectTable(
|
||||
name="Backend Service",
|
||||
slug=f"backend-svc-{uuid4().hex[:6]}",
|
||||
git_url=f"https://github.com/x/{uuid4().hex[:6]}.git",
|
||||
default_branch="master",
|
||||
protected_branches=["master"],
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=SYSTEM_UUID,
|
||||
is_active=True,
|
||||
)
|
||||
session.add(project)
|
||||
await session.flush()
|
||||
return project
|
||||
|
||||
|
||||
def _arm(session: AsyncSession) -> None:
|
||||
session.add(SystemSettingTable(key="board_program.coroner.enabled", value="true"))
|
||||
|
||||
|
||||
async def _make_task(
|
||||
session: AsyncSession, project: ProjectTable, *, status: TS = TS.PENDING
|
||||
) -> TaskTable:
|
||||
"""A real dev task, with its ``cell_projects`` relationship eagerly
|
||||
(re)loaded before returning: ``_validate_and_set_status`` reads it
|
||||
synchronously (``bool(task.cell_projects)``), and a task fresh off
|
||||
``create()`` can otherwise leave it in a state that needs a lazy DB
|
||||
load outside any active greenlet the next time it's touched — a
|
||||
``MissingGreenlet`` error, not a real business-logic failure."""
|
||||
task = await get_task_service(session).create(
|
||||
TaskCreateRequest(
|
||||
title="A real dev task",
|
||||
description="Something a dev worked on",
|
||||
acceptance_criteria=["it works"],
|
||||
team=Team.BACKEND,
|
||||
created_by=SYSTEM_UUID,
|
||||
task_type=TT.CODE,
|
||||
nature=TN.TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
project_id=cast("UUID", project.id),
|
||||
status=TS.PENDING,
|
||||
)
|
||||
)
|
||||
if status != TS.PENDING:
|
||||
task.status = status
|
||||
await session.flush()
|
||||
return (
|
||||
await session.execute(
|
||||
select(TaskTable)
|
||||
.options(selectinload(TaskTable.cell_projects))
|
||||
.where(TaskTable.id == task.id)
|
||||
)
|
||||
).scalar_one()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bounce_hook_schedules_only_at_the_third_bounce(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""The chokepoint (_emit_status_transition_audit) schedules
|
||||
``_fire_coroner_bounce_hook`` via ``asyncio.create_task`` — mock the
|
||||
module-level hook function itself (a narrow, single-name patch that
|
||||
leaves the real ``asyncio`` module and every other caller of
|
||||
``create_task`` — including session-teardown internals — untouched) and
|
||||
let the REAL ``create_task`` schedule the mock's coroutine normally."""
|
||||
calls: list[Any] = []
|
||||
|
||||
async def _fake_hook(task_id: Any) -> None:
|
||||
calls.append(task_id)
|
||||
|
||||
monkeypatch.setattr(task_module, "_fire_coroner_bounce_hook", _fake_hook)
|
||||
|
||||
project = await _seed(db_session)
|
||||
_arm(db_session)
|
||||
task = await _make_task(db_session, project, status=TS.IN_PROGRESS)
|
||||
await db_session.flush()
|
||||
|
||||
svc = TaskService(db_session)
|
||||
# 1st and 2nd bounce: no autopsy yet.
|
||||
svc._validate_and_set_status(task, TS.NEEDS_REVISION, "qa")
|
||||
task.status = TS.IN_PROGRESS # re-enter from a different status
|
||||
svc._validate_and_set_status(task, TS.NEEDS_REVISION, "qa")
|
||||
task.status = TS.IN_PROGRESS
|
||||
await asyncio.sleep(0)
|
||||
assert calls == []
|
||||
|
||||
# 3rd bounce: schedules the hook.
|
||||
svc._validate_and_set_status(task, TS.NEEDS_REVISION, "qa")
|
||||
await db_session.flush()
|
||||
assert task.revision_count == THIRD_BOUNCE
|
||||
await asyncio.sleep(0) # let the scheduled task actually run
|
||||
|
||||
assert calls == [task.id]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bounce_hook_opens_its_own_session_and_commits(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""``_fire_coroner_bounce_hook``'s own responsibility — open a FRESH
|
||||
session via ``get_db_context()``, delegate to ``CoronerEngine.
|
||||
open_for_incident``, commit. Verified with mocks (never a real
|
||||
``get_db_context`` redirect to the shared ``db_session``): the hook's own
|
||||
``await db.commit()`` would otherwise durably commit whatever this test
|
||||
session had pending — including the OTHER real rows this file's other
|
||||
tests create — permanently polluting the shared, cross-test-persistent
|
||||
test DB for every test that runs after this one in the same session.
|
||||
``CoronerEngine.open_for_incident``'s actual behavior is covered by
|
||||
test_coroner_engine.py's dedicated real-DB tests; this is pure wiring."""
|
||||
fake_session = AsyncMock()
|
||||
|
||||
@contextlib.asynccontextmanager
|
||||
async def _fake_db_context() -> Any:
|
||||
yield fake_session
|
||||
|
||||
monkeypatch.setattr("roboco.db.base.get_db_context", _fake_db_context)
|
||||
|
||||
engine = AsyncMock()
|
||||
engine.open_for_incident = AsyncMock(return_value=None)
|
||||
monkeypatch.setattr(
|
||||
coroner_engine_module, "get_coroner_engine", lambda _session: engine
|
||||
)
|
||||
|
||||
task_id = uuid4()
|
||||
await _fire_coroner_bounce_hook(task_id)
|
||||
|
||||
engine.open_for_incident.assert_awaited_once_with(task_id, kind="bounced")
|
||||
fake_session.commit.assert_awaited_once()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bounce_hook_never_fails_the_transition_even_if_it_raises(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Best-effort: a hook scheduling failure never breaks the real bounce
|
||||
transition that triggered it. Swaps out the ``asyncio`` NAME BINDING
|
||||
``roboco.services.task`` sees (not the shared ``asyncio`` module's own
|
||||
``create_task`` attribute) so this stays scoped to that one module and
|
||||
can't break session-teardown machinery elsewhere in the same process."""
|
||||
|
||||
def _raise_create_task(coro: Any, *_a: object, **_kw: object) -> object:
|
||||
coro.close() # avoid a "coroutine was never awaited" warning
|
||||
raise RuntimeError("event loop trouble")
|
||||
|
||||
fake_asyncio = types.SimpleNamespace(create_task=_raise_create_task)
|
||||
monkeypatch.setattr(task_module, "asyncio", fake_asyncio)
|
||||
|
||||
project = await _seed(db_session)
|
||||
_arm(db_session)
|
||||
task = await _make_task(db_session, project, status=TS.IN_PROGRESS)
|
||||
task.revision_count = 2
|
||||
await db_session.flush()
|
||||
|
||||
svc = TaskService(db_session)
|
||||
# Must NOT raise even though scheduling the hook blows up — the real
|
||||
# transition (status + revision_count bump + audit row) still lands.
|
||||
svc._validate_and_set_status(task, TS.NEEDS_REVISION, "qa")
|
||||
assert task.status == TS.NEEDS_REVISION
|
||||
assert task.revision_count == THIRD_BOUNCE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_after_work_started_opens_autopsy(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
project = await _seed(db_session)
|
||||
_arm(db_session)
|
||||
task = await _make_task(db_session, project, status=TS.IN_PROGRESS)
|
||||
task.commits = [{"sha": "abc123", "message": "did work"}]
|
||||
await db_session.flush()
|
||||
|
||||
svc = TaskService(db_session)
|
||||
await svc.cancel(cast("UUID", task.id), agent_role="cell_pm")
|
||||
await db_session.flush()
|
||||
|
||||
cycles = (
|
||||
(
|
||||
await db_session.execute(
|
||||
select(TaskTable).where(
|
||||
TaskTable.source == CORONER_SOURCE, TaskTable.status == TS.PENDING
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
assert len(cycles) == ONE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_with_no_work_started_opens_no_autopsy(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
project = await _seed(db_session)
|
||||
_arm(db_session)
|
||||
task = await _make_task(db_session, project, status=TS.PENDING)
|
||||
await db_session.flush()
|
||||
|
||||
svc = TaskService(db_session)
|
||||
await svc.cancel(cast("UUID", task.id), agent_role="cell_pm")
|
||||
await db_session.flush()
|
||||
|
||||
cycles = (
|
||||
(
|
||||
await db_session.execute(
|
||||
select(TaskTable).where(
|
||||
TaskTable.source == CORONER_SOURCE, TaskTable.status == TS.PENDING
|
||||
)
|
||||
)
|
||||
)
|
||||
.scalars()
|
||||
.all()
|
||||
)
|
||||
assert cycles == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cancel_hook_never_fails_the_cancel_when_coroner_engine_raises(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
project = await _seed(db_session)
|
||||
_arm(db_session)
|
||||
task = await _make_task(db_session, project, status=TS.IN_PROGRESS)
|
||||
task.commits = [{"sha": "abc123", "message": "did work"}]
|
||||
await db_session.flush()
|
||||
|
||||
def _boom(_session: AsyncSession) -> object:
|
||||
raise RuntimeError("coroner engine trouble")
|
||||
|
||||
monkeypatch.setattr(coroner_engine_module, "get_coroner_engine", _boom)
|
||||
|
||||
svc = TaskService(db_session)
|
||||
result = await svc.cancel(cast("UUID", task.id), agent_role="cell_pm")
|
||||
assert result is not None
|
||||
assert result.status == TS.CANCELLED
|
||||
@@ -0,0 +1,208 @@
|
||||
"""Coroner (Board Program) engine route coverage — CEO-only read-only
|
||||
Postmortems list. Unlike Pest Control/Roadmap there is no approve/reject
|
||||
action: a postmortem completes atomically at propose_postmortem time.
|
||||
Mirrors test_pest_control_routes.py's harness shape."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from roboco.api.deps import get_agent_context, get_db
|
||||
from roboco.api.routes.coroner import router as coroner_router
|
||||
from roboco.db.tables import AgentTable, ProjectTable, TaskTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.foundation.policy.content import markers
|
||||
from roboco.models import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import Complexity, TaskNature, TaskStatus, TaskType
|
||||
from roboco.models.permissions import AgentContext
|
||||
from roboco.services.task import CORONER_SOURCE
|
||||
|
||||
CEO_UUID = _foundation.AGENTS["ceo"].uuid
|
||||
AUDITOR_UUID = _foundation.AGENTS["auditor"].uuid
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def _seed_system_and_auditor(session: AsyncSession) -> None:
|
||||
for uuid, slug, role, team in (
|
||||
(_foundation.AGENTS["system"].uuid, "system", AgentRole.SYSTEM, None),
|
||||
(AUDITOR_UUID, "auditor", AgentRole.AUDITOR, Team.BOARD),
|
||||
):
|
||||
if await session.get(AgentTable, uuid) is not None:
|
||||
continue
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=uuid,
|
||||
name=slug,
|
||||
slug=slug,
|
||||
role=role,
|
||||
team=team,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def _seed_ceo(session: AsyncSession) -> None:
|
||||
if await session.get(AgentTable, CEO_UUID) is not None:
|
||||
return
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=CEO_UUID,
|
||||
name="ceo",
|
||||
slug=f"ceo-{uuid4().hex[:6]}",
|
||||
role=AgentRole.CEO,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def _seed_completed_postmortem(session: AsyncSession) -> TaskTable:
|
||||
await _seed_system_and_auditor(session)
|
||||
await _seed_ceo(session)
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name="Backend Service",
|
||||
slug=f"backend-svc-{uuid4().hex[:6]}",
|
||||
git_url=f"https://github.com/x/{uuid4().hex[:6]}.git",
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=_foundation.AGENTS["system"].uuid,
|
||||
)
|
||||
session.add(project)
|
||||
await session.flush()
|
||||
incident_id = uuid4()
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Coroner postmortem",
|
||||
description="Autopsy the chronic task.",
|
||||
acceptance_criteria=["propose_postmortem() called once"],
|
||||
status=TaskStatus.COMPLETED,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=_foundation.AGENTS["system"].uuid,
|
||||
assigned_to=AUDITOR_UUID,
|
||||
team=Team.BOARD,
|
||||
source=CORONER_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
project_id=project.id,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
markers.set_coroner_incident(
|
||||
task,
|
||||
{
|
||||
"incident_task_id": str(incident_id),
|
||||
"kind": "bounced",
|
||||
"revision_count": 3,
|
||||
"title": "Chronic task",
|
||||
},
|
||||
)
|
||||
markers.set_coroner_postmortem(
|
||||
task,
|
||||
{
|
||||
"incident_summary": "the task bounced 3 times over a stale venv",
|
||||
"root_cause": "the gate never verified the venv's dev extras",
|
||||
"failed_stage": "awaiting_qa",
|
||||
"process_change": {
|
||||
"kind": "conventions_rule",
|
||||
"description": "add a venv-freshness check",
|
||||
},
|
||||
"playbook_id": None,
|
||||
},
|
||||
)
|
||||
await session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _build_app(db_session: AsyncSession, role: AgentRole, agent_id: UUID) -> FastAPI:
|
||||
app = FastAPI()
|
||||
app.include_router(coroner_router, prefix="/api/coroner")
|
||||
|
||||
async def _override_db() -> AsyncIterator[AsyncSession]:
|
||||
yield db_session
|
||||
|
||||
async def _override_agent() -> AgentContext:
|
||||
return AgentContext(agent_id=agent_id, role=role, team=None)
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
app.dependency_overrides[get_agent_context] = _override_agent
|
||||
return app
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
await _seed_ceo(db_session)
|
||||
app = _build_app(db_session, AgentRole.CEO, CEO_UUID)
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def dev_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
dev_id = uuid4()
|
||||
app = _build_app(db_session, AgentRole.DEVELOPER, dev_id)
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_postmortems_empty(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
await _seed_ceo(db_session)
|
||||
resp = await ceo_client.get("/api/coroner/postmortems")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
assert resp.json() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_postmortems_returns_completed_autopsy(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task = await _seed_completed_postmortem(db_session)
|
||||
resp = await ceo_client.get("/api/coroner/postmortems")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert len(body) == 1
|
||||
row = body[0]
|
||||
assert row["task_id"] == str(task.id)
|
||||
assert row["incident_kind"] == "bounced"
|
||||
assert row["incident_title"] == "Chronic task"
|
||||
assert row["root_cause"] == "the gate never verified the venv's dev extras"
|
||||
assert row["process_change_kind"] == "conventions_rule"
|
||||
assert row["failed_stage"] == "awaiting_qa"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_postmortems_forbidden_for_non_ceo(
|
||||
dev_client: AsyncClient,
|
||||
) -> None:
|
||||
resp = await dev_client.get("/api/coroner/postmortems")
|
||||
assert resp.status_code == HTTPStatus.FORBIDDEN
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Dogfood (Board Program) engine route coverage — CEO-only list/approve/
|
||||
reject. Mirrors test_spackle_routes.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from roboco.api.deps import get_agent_context, get_db
|
||||
from roboco.api.routes.dogfood import router as dogfood_router
|
||||
from roboco.db.tables import AgentTable, ProjectTable, TaskTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.foundation.policy.content import markers
|
||||
from roboco.models import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import Complexity, TaskNature, TaskStatus, TaskType
|
||||
from roboco.models.permissions import AgentContext
|
||||
from roboco.services.task import DOGFOOD_SOURCE
|
||||
from sqlalchemy import update
|
||||
|
||||
_SEED_GIT_URL = "https://example.com/roboco-api-dogfood.git"
|
||||
|
||||
CEO_UUID = _foundation.AGENTS["ceo"].uuid
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def _seed_agent(session: AsyncSession, role: AgentRole, slug: str) -> AgentTable:
|
||||
agent = AgentTable(
|
||||
id=uuid4(),
|
||||
name=slug,
|
||||
slug=f"{slug}-{uuid4().hex[:6]}",
|
||||
role=role,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
session.add(agent)
|
||||
await session.flush()
|
||||
return agent
|
||||
|
||||
|
||||
async def _seed_ceo(session: AsyncSession) -> None:
|
||||
"""The CEO row matching ``CEO_UUID`` — approving an item stamps this id as
|
||||
the materialized task's ``created_by``, which has an FK to ``agents``."""
|
||||
if await session.get(AgentTable, CEO_UUID) is not None:
|
||||
return
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=CEO_UUID,
|
||||
name="ceo",
|
||||
slug=f"ceo-{uuid4().hex[:6]}",
|
||||
role=AgentRole.CEO,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def _seed_cycle(session: AsyncSession) -> tuple[TaskTable, ProjectTable]:
|
||||
system = await _seed_agent(session, AgentRole.SYSTEM, "system")
|
||||
po = await _seed_agent(session, AgentRole.PRODUCT_OWNER, "product-owner")
|
||||
await _seed_ceo(session)
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name="RoboCo API",
|
||||
slug=f"roboco-api-{uuid4().hex[:6]}",
|
||||
git_url=_SEED_GIT_URL,
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=system.id,
|
||||
board_programs=["dogfood"],
|
||||
)
|
||||
session.add(project)
|
||||
await session.flush()
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Dogfood walk",
|
||||
description="Walk the product as a user and propose a friction audit.",
|
||||
acceptance_criteria=["propose_friction_fixes() called once"],
|
||||
status=TaskStatus.PENDING,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
assigned_to=po.id,
|
||||
team=Team.BOARD,
|
||||
source=DOGFOOD_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
markers.set_friction_fixes(
|
||||
task,
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "item-0",
|
||||
"title": "Settings save button gives no feedback",
|
||||
"description": "Clicking Save shows nothing — no toast, no spinner",
|
||||
"acceptance_criteria": ["a toast confirms the save"],
|
||||
"project_slug": project.slug,
|
||||
"team": "frontend",
|
||||
"priority": 2,
|
||||
"evidence": (
|
||||
"Walked /settings -> changed panel_base_url -> clicked "
|
||||
"Save -> network tab shows 200 OK but no UI feedback"
|
||||
),
|
||||
"status": "proposed",
|
||||
"reject_reason": None,
|
||||
"materialized_task_id": None,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
await session.flush()
|
||||
return task, project
|
||||
|
||||
|
||||
def _build_app(db_session: AsyncSession, role: AgentRole, agent_id: UUID) -> FastAPI:
|
||||
app = FastAPI()
|
||||
app.include_router(dogfood_router, prefix="/api/dogfood")
|
||||
|
||||
async def _override_db() -> AsyncIterator[AsyncSession]:
|
||||
yield db_session
|
||||
|
||||
async def _override_agent() -> AgentContext:
|
||||
return AgentContext(agent_id=agent_id, role=role, team=None)
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
app.dependency_overrides[get_agent_context] = _override_agent
|
||||
return app
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
"""CEO-authed client. Approving an item materializes a new task stamping
|
||||
``agent.agent_id`` as ``created_by`` (an FK to ``agents``), so this must be
|
||||
a real seeded row — ``CEO_UUID`` — not an arbitrary ``uuid4()``."""
|
||||
await _seed_ceo(db_session)
|
||||
app = _build_app(db_session, AgentRole.CEO, CEO_UUID)
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client
|
||||
app.dependency_overrides.clear()
|
||||
# The approve/reject routes commit explicitly (write-route convention),
|
||||
# so a leftover ``board_programs=["dogfood"]`` opt-in from an
|
||||
# approve/reject test here would otherwise outlive this test in the
|
||||
# shared, cross-test-persistent DB and poison every later real-DB
|
||||
# dogfood unit test that asserts an exact opted-in-project set (e.g.
|
||||
# "no project opted in"). Mirrors test_spackle_routes.py's identical
|
||||
# cleanup. Reset, not delete — a materialized BACKLOG task may still
|
||||
# hold this project's id as an FK. Unconditional — a no-op for the
|
||||
# tests here that never wrote anything.
|
||||
await db_session.execute(
|
||||
update(ProjectTable)
|
||||
.where(ProjectTable.git_url == _SEED_GIT_URL)
|
||||
.values(board_programs=None)
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_cycles_returns_authored_cycle(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.get("/api/dogfood/cycles")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert len(body) == 1
|
||||
assert body[0]["task_id"] == str(task.id)
|
||||
assert len(body[0]["items"]) == 1
|
||||
assert body[0]["items"][0]["evidence"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_item_materializes_backlog_task(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(f"/api/dogfood/cycles/{task.id}/items/item-0/approve")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "approved"
|
||||
assert body["materialized_task_id"] is not None
|
||||
|
||||
materialized = await db_session.get(TaskTable, UUID(body["materialized_task_id"]))
|
||||
assert materialized is not None
|
||||
assert materialized.status == TaskStatus.BACKLOG
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_unknown_item_is_404(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/dogfood/cycles/{task.id}/items/no-such-item/approve"
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_item_records_reason(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/dogfood/cycles/{task.id}/items/item-0/reject",
|
||||
json={"reason": "already tracked elsewhere"},
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "rejected"
|
||||
|
||||
refreshed = await db_session.get(TaskTable, task.id)
|
||||
assert refreshed is not None
|
||||
payload = markers.get_friction_fixes(refreshed)
|
||||
assert payload is not None
|
||||
assert payload["items"][0]["reject_reason"] == "already tracked elsewhere"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_ceo_is_forbidden(db_session: AsyncSession) -> None:
|
||||
await _seed_cycle(db_session)
|
||||
app = _build_app(db_session, AgentRole.DEVELOPER, uuid4())
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
list_resp = await client.get("/api/dogfood/cycles")
|
||||
assert list_resp.status_code == HTTPStatus.FORBIDDEN
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,250 @@
|
||||
"""Mirror (Board Program) engine route coverage — CEO-only list/approve/
|
||||
reject. Mirrors test_spackle_routes.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from roboco.api.deps import get_agent_context, get_db
|
||||
from roboco.api.routes.mirror import router as mirror_router
|
||||
from roboco.db.tables import AgentTable, ProjectTable, TaskTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.foundation.policy.content import markers
|
||||
from roboco.models import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import Complexity, TaskNature, TaskStatus, TaskType
|
||||
from roboco.models.permissions import AgentContext
|
||||
from roboco.services.task import MIRROR_SOURCE
|
||||
from sqlalchemy import update
|
||||
|
||||
_SEED_GIT_URL = "https://example.com/backend-svc-mirror.git"
|
||||
|
||||
CEO_UUID = _foundation.AGENTS["ceo"].uuid
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def _seed_agent(session: AsyncSession, role: AgentRole, slug: str) -> AgentTable:
|
||||
agent = AgentTable(
|
||||
id=uuid4(),
|
||||
name=slug,
|
||||
slug=f"{slug}-{uuid4().hex[:6]}",
|
||||
role=role,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
session.add(agent)
|
||||
await session.flush()
|
||||
return agent
|
||||
|
||||
|
||||
async def _seed_ceo(session: AsyncSession) -> None:
|
||||
"""The CEO row matching ``CEO_UUID`` — approving an item stamps this id as
|
||||
the materialized task's ``created_by``, which has an FK to ``agents``."""
|
||||
if await session.get(AgentTable, CEO_UUID) is not None:
|
||||
return
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=CEO_UUID,
|
||||
name="ceo",
|
||||
slug=f"ceo-{uuid4().hex[:6]}",
|
||||
role=AgentRole.CEO,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def _seed_cycle(session: AsyncSession) -> tuple[TaskTable, ProjectTable]:
|
||||
system = await _seed_agent(session, AgentRole.SYSTEM, "system")
|
||||
hom = await _seed_agent(session, AgentRole.HEAD_MARKETING, "head-marketing")
|
||||
await _seed_ceo(session)
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name="Backend Service",
|
||||
slug=f"backend-svc-{uuid4().hex[:6]}",
|
||||
git_url=_SEED_GIT_URL,
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=system.id,
|
||||
board_programs=["mirror"],
|
||||
)
|
||||
session.add(project)
|
||||
await session.flush()
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Mirror exploration cycle",
|
||||
description="Audit messaging surfaces and propose a messaging-fixes audit.",
|
||||
acceptance_criteria=["propose_messaging_fixes() called once"],
|
||||
status=TaskStatus.PENDING,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
assigned_to=hom.id,
|
||||
team=Team.BOARD,
|
||||
source=MIRROR_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
markers.set_messaging_fixes(
|
||||
task,
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "item-0",
|
||||
"title": "Fix README real-time sync claim",
|
||||
"description": "README says real-time; sync is polled every 30s",
|
||||
"acceptance_criteria": ["README wording matches behavior"],
|
||||
"project_slug": project.slug,
|
||||
"team": "backend",
|
||||
"priority": 2,
|
||||
"evidence": (
|
||||
"README.md:42 says 'real-time sync'; "
|
||||
"roboco/services/sync.py:88 polls every 30s"
|
||||
),
|
||||
"status": "proposed",
|
||||
"reject_reason": None,
|
||||
"materialized_task_id": None,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
await session.flush()
|
||||
return task, project
|
||||
|
||||
|
||||
def _build_app(db_session: AsyncSession, role: AgentRole, agent_id: UUID) -> FastAPI:
|
||||
app = FastAPI()
|
||||
app.include_router(mirror_router, prefix="/api/mirror")
|
||||
|
||||
async def _override_db() -> AsyncIterator[AsyncSession]:
|
||||
yield db_session
|
||||
|
||||
async def _override_agent() -> AgentContext:
|
||||
return AgentContext(agent_id=agent_id, role=role, team=None)
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
app.dependency_overrides[get_agent_context] = _override_agent
|
||||
return app
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
"""CEO-authed client. Approving an item materializes a new task stamping
|
||||
``agent.agent_id`` as ``created_by`` (an FK to ``agents``), so this must be
|
||||
a real seeded row — ``CEO_UUID`` — not an arbitrary ``uuid4()``."""
|
||||
await _seed_ceo(db_session)
|
||||
app = _build_app(db_session, AgentRole.CEO, CEO_UUID)
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client
|
||||
app.dependency_overrides.clear()
|
||||
# The approve/reject routes commit explicitly (write-route convention),
|
||||
# so a leftover ``board_programs=["mirror"]`` opt-in from an
|
||||
# approve/reject test here would otherwise outlive this test in the
|
||||
# shared, cross-test-persistent DB and poison every later real-DB
|
||||
# mirror unit test that asserts an exact opted-in-project set (e.g.
|
||||
# "no project opted in"). Mirrors test_spackle_routes.py's identical
|
||||
# cleanup. Reset, not delete — a materialized BACKLOG task may still
|
||||
# hold this project's id as an FK. Unconditional — a no-op for the
|
||||
# tests here that never wrote anything.
|
||||
await db_session.execute(
|
||||
update(ProjectTable)
|
||||
.where(ProjectTable.git_url == _SEED_GIT_URL)
|
||||
.values(board_programs=None)
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_cycles_returns_authored_cycle(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.get("/api/mirror/cycles")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert len(body) == 1
|
||||
assert body[0]["task_id"] == str(task.id)
|
||||
assert len(body[0]["items"]) == 1
|
||||
assert body[0]["items"][0]["evidence"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_item_materializes_backlog_task(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(f"/api/mirror/cycles/{task.id}/items/item-0/approve")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "approved"
|
||||
assert body["materialized_task_id"] is not None
|
||||
|
||||
materialized = await db_session.get(TaskTable, UUID(body["materialized_task_id"]))
|
||||
assert materialized is not None
|
||||
assert materialized.status == TaskStatus.BACKLOG
|
||||
assert materialized.task_type == TaskType.DOCUMENTATION
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_unknown_item_is_404(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/mirror/cycles/{task.id}/items/no-such-item/approve"
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_item_records_reason(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/mirror/cycles/{task.id}/items/item-0/reject",
|
||||
json={"reason": "already tracked elsewhere"},
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "rejected"
|
||||
|
||||
refreshed = await db_session.get(TaskTable, task.id)
|
||||
assert refreshed is not None
|
||||
payload = markers.get_messaging_fixes(refreshed)
|
||||
assert payload is not None
|
||||
assert payload["items"][0]["reject_reason"] == "already tracked elsewhere"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_ceo_is_forbidden(db_session: AsyncSession) -> None:
|
||||
await _seed_cycle(db_session)
|
||||
app = _build_app(db_session, AgentRole.DEVELOPER, uuid4())
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
list_resp = await client.get("/api/mirror/cycles")
|
||||
assert list_resp.status_code == HTTPStatus.FORBIDDEN
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,218 @@
|
||||
"""Periscope (Board Program) engine route coverage — CEO-only, read-only.
|
||||
Mirrors test_pest_control_routes.py minus the approve/reject routes: a
|
||||
market brief is a report, not a queue item."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from roboco.api.deps import get_agent_context, get_db
|
||||
from roboco.api.routes.periscope import router as periscope_router
|
||||
from roboco.db.tables import AgentTable, TaskTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.foundation.policy.content import markers
|
||||
from roboco.models import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import Complexity, TaskNature, TaskStatus, TaskType
|
||||
from roboco.models.permissions import AgentContext
|
||||
from roboco.services.task import PERISCOPE_SOURCE
|
||||
from sqlalchemy import update
|
||||
|
||||
CEO_UUID = _foundation.AGENTS["ceo"].uuid
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def _seed_agent(session: AsyncSession, role: AgentRole, slug: str) -> AgentTable:
|
||||
agent = AgentTable(
|
||||
id=uuid4(),
|
||||
name=slug,
|
||||
slug=f"{slug}-{uuid4().hex[:6]}",
|
||||
role=role,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
session.add(agent)
|
||||
await session.flush()
|
||||
return agent
|
||||
|
||||
|
||||
async def _seed_ceo(session: AsyncSession) -> None:
|
||||
if await session.get(AgentTable, CEO_UUID) is not None:
|
||||
return
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=CEO_UUID,
|
||||
name="ceo",
|
||||
slug=f"ceo-{uuid4().hex[:6]}",
|
||||
role=AgentRole.CEO,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def _seed_completed_brief(session: AsyncSession) -> TaskTable:
|
||||
system = await _seed_agent(session, AgentRole.SYSTEM, "system")
|
||||
hom = await _seed_agent(session, AgentRole.HEAD_MARKETING, "head-marketing")
|
||||
await _seed_ceo(session)
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Periscope market-research cycle",
|
||||
description="Research the market and file ONE brief.",
|
||||
acceptance_criteria=["propose_market_brief() called once"],
|
||||
status=TaskStatus.COMPLETED,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
assigned_to=hom.id,
|
||||
team=Team.BOARD,
|
||||
source=PERISCOPE_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
markers.set_market_brief(
|
||||
task,
|
||||
{
|
||||
"headline": "A rival tool shipped agentic PR review",
|
||||
"findings": [
|
||||
{
|
||||
"id": "finding-0",
|
||||
"claim": "Competitor X launched an autonomous reviewer",
|
||||
"source_url": "https://example.com/x-launch",
|
||||
"relevance": "Overlaps our pr_reviewer role",
|
||||
}
|
||||
],
|
||||
"threats": ["Feature parity gap"],
|
||||
"opportunities": ["Lean into structured findings"],
|
||||
"positioning_note": "Emphasize the findings ledger",
|
||||
"injection_hits": [],
|
||||
},
|
||||
)
|
||||
await session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _build_app(db_session: AsyncSession, role: AgentRole, agent_id: UUID) -> FastAPI:
|
||||
app = FastAPI()
|
||||
app.include_router(periscope_router, prefix="/api/periscope")
|
||||
|
||||
async def _override_db() -> AsyncIterator[AsyncSession]:
|
||||
yield db_session
|
||||
|
||||
async def _override_agent() -> AgentContext:
|
||||
return AgentContext(agent_id=agent_id, role=role, team=None)
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
app.dependency_overrides[get_agent_context] = _override_agent
|
||||
return app
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
await _seed_ceo(db_session)
|
||||
app = _build_app(db_session, AgentRole.CEO, CEO_UUID)
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client
|
||||
app.dependency_overrides.clear()
|
||||
# This route only reads — nothing here writes/commits — but a sibling
|
||||
# real-DB suite could still leave a stray board_periscope task behind
|
||||
# from an earlier failed run; keep the cleanup unconditional and cheap.
|
||||
await db_session.execute(
|
||||
update(TaskTable)
|
||||
.where(TaskTable.source == PERISCOPE_SOURCE)
|
||||
.values(status=TaskStatus.CANCELLED)
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_briefs_empty_when_none_filed(ceo_client: AsyncClient) -> None:
|
||||
resp = await ceo_client.get("/api/periscope/briefs")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
assert resp.json() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_briefs_returns_filed_brief(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task = await _seed_completed_brief(db_session)
|
||||
resp = await ceo_client.get("/api/periscope/briefs")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert len(body) == 1
|
||||
row = body[0]
|
||||
assert row["task_id"] == str(task.id)
|
||||
assert row["headline"] == "A rival tool shipped agentic PR review"
|
||||
assert len(row["findings"]) == 1
|
||||
assert row["findings"][0]["source_url"] == "https://example.com/x-launch"
|
||||
assert row["threats"] == ["Feature parity gap"]
|
||||
assert row["opportunities"] == ["Lean into structured findings"]
|
||||
assert row["positioning_note"] == "Emphasize the findings ledger"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_briefs_omits_non_terminal_exploration(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
"""A still-open (PENDING) exploration cycle carries no brief yet — it
|
||||
must never render as an empty/blank brief row."""
|
||||
system = await _seed_agent(db_session, AgentRole.SYSTEM, "system")
|
||||
hom = await _seed_agent(db_session, AgentRole.HEAD_MARKETING, "head-marketing")
|
||||
db_session.add(
|
||||
TaskTable(
|
||||
id=uuid4(),
|
||||
title="Periscope market-research cycle",
|
||||
description="x",
|
||||
acceptance_criteria=["x"],
|
||||
status=TaskStatus.PENDING,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
assigned_to=hom.id,
|
||||
team=Team.BOARD,
|
||||
source=PERISCOPE_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
)
|
||||
await db_session.flush()
|
||||
resp = await ceo_client.get("/api/periscope/briefs")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
assert resp.json() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_ceo_is_forbidden(db_session: AsyncSession) -> None:
|
||||
await _seed_completed_brief(db_session)
|
||||
app = _build_app(db_session, AgentRole.DEVELOPER, uuid4())
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
resp = await client.get("/api/periscope/briefs")
|
||||
assert resp.status_code == HTTPStatus.FORBIDDEN
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Pest Control (Board Program) engine route coverage — CEO-only
|
||||
list/approve/reject. Mirrors test_roadmap_routes.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from roboco.api.deps import get_agent_context, get_db
|
||||
from roboco.api.routes.pest_control import router as pest_control_router
|
||||
from roboco.db.tables import AgentTable, ProjectTable, TaskTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.foundation.policy.content import markers
|
||||
from roboco.models import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import Complexity, TaskNature, TaskStatus, TaskType
|
||||
from roboco.models.permissions import AgentContext
|
||||
from roboco.services.task import PEST_CONTROL_SOURCE
|
||||
from sqlalchemy import update
|
||||
|
||||
_SEED_GIT_URL = "https://example.com/backend-svc.git"
|
||||
|
||||
CEO_UUID = _foundation.AGENTS["ceo"].uuid
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def _seed_agent(session: AsyncSession, role: AgentRole, slug: str) -> AgentTable:
|
||||
agent = AgentTable(
|
||||
id=uuid4(),
|
||||
name=slug,
|
||||
slug=f"{slug}-{uuid4().hex[:6]}",
|
||||
role=role,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
session.add(agent)
|
||||
await session.flush()
|
||||
return agent
|
||||
|
||||
|
||||
async def _seed_ceo(session: AsyncSession) -> None:
|
||||
"""The CEO row matching ``CEO_UUID`` — approving an item stamps this id as
|
||||
the materialized task's ``created_by``, which has an FK to ``agents``."""
|
||||
if await session.get(AgentTable, CEO_UUID) is not None:
|
||||
return
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=CEO_UUID,
|
||||
name="ceo",
|
||||
slug=f"ceo-{uuid4().hex[:6]}",
|
||||
role=AgentRole.CEO,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def _seed_cycle(session: AsyncSession) -> tuple[TaskTable, ProjectTable]:
|
||||
system = await _seed_agent(session, AgentRole.SYSTEM, "system")
|
||||
po = await _seed_agent(session, AgentRole.PRODUCT_OWNER, "product-owner")
|
||||
await _seed_ceo(session)
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name="Backend Service",
|
||||
slug=f"backend-svc-{uuid4().hex[:6]}",
|
||||
git_url=_SEED_GIT_URL,
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=system.id,
|
||||
board_programs=["pest_control"],
|
||||
)
|
||||
session.add(project)
|
||||
await session.flush()
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Pest Control exploration cycle",
|
||||
description="Hunt latent defects and propose a bug hunt.",
|
||||
acceptance_criteria=["propose_bug_hunt() called once"],
|
||||
status=TaskStatus.PENDING,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
assigned_to=po.id,
|
||||
team=Team.BOARD,
|
||||
source=PEST_CONTROL_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
markers.set_pest_hunt(
|
||||
task,
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "item-0",
|
||||
"title": "Fix stale worktree venv",
|
||||
"description": "Fresh worktrees silently reuse a rotted venv",
|
||||
"acceptance_criteria": ["fresh worktree passes make quality"],
|
||||
"project_slug": project.slug,
|
||||
"team": "backend",
|
||||
"priority": 2,
|
||||
"evidence": "task_review_findings row F-abc123 waived 4x",
|
||||
"status": "proposed",
|
||||
"reject_reason": None,
|
||||
"materialized_task_id": None,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
await session.flush()
|
||||
return task, project
|
||||
|
||||
|
||||
def _build_app(db_session: AsyncSession, role: AgentRole, agent_id: UUID) -> FastAPI:
|
||||
app = FastAPI()
|
||||
app.include_router(pest_control_router, prefix="/api/pest-control")
|
||||
|
||||
async def _override_db() -> AsyncIterator[AsyncSession]:
|
||||
yield db_session
|
||||
|
||||
async def _override_agent() -> AgentContext:
|
||||
return AgentContext(agent_id=agent_id, role=role, team=None)
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
app.dependency_overrides[get_agent_context] = _override_agent
|
||||
return app
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
"""CEO-authed client. Approving an item materializes a new task stamping
|
||||
``agent.agent_id`` as ``created_by`` (an FK to ``agents``), so this must be
|
||||
a real seeded row — ``CEO_UUID`` — not an arbitrary ``uuid4()``."""
|
||||
await _seed_ceo(db_session)
|
||||
app = _build_app(db_session, AgentRole.CEO, CEO_UUID)
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client
|
||||
app.dependency_overrides.clear()
|
||||
# The approve/reject routes commit explicitly (write-route convention),
|
||||
# so a leftover ``board_programs=["pest_control"]`` opt-in from an
|
||||
# approve/reject test here would otherwise outlive this test in the
|
||||
# shared, cross-test-persistent DB and poison every later real-DB
|
||||
# pest_control unit test that asserts an exact opted-in-project set
|
||||
# (e.g. "no project opted in"). Unlike roadmap (org-scoped, no opt-in
|
||||
# field to leak) this program is project-scoped, so this cleanup has no
|
||||
# roadmap-side counterpart to mirror. Reset, not delete — a materialized
|
||||
# BACKLOG task may still hold this project's id as an FK. Unconditional —
|
||||
# a no-op for the tests here that never wrote anything.
|
||||
await db_session.execute(
|
||||
update(ProjectTable)
|
||||
.where(ProjectTable.git_url == _SEED_GIT_URL)
|
||||
.values(board_programs=None)
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_cycles_returns_authored_cycle(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.get("/api/pest-control/cycles")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert len(body) == 1
|
||||
assert body[0]["task_id"] == str(task.id)
|
||||
assert len(body[0]["items"]) == 1
|
||||
assert body[0]["items"][0]["evidence"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_item_materializes_backlog_task(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/pest-control/cycles/{task.id}/items/item-0/approve"
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "approved"
|
||||
assert body["materialized_task_id"] is not None
|
||||
|
||||
materialized = await db_session.get(TaskTable, UUID(body["materialized_task_id"]))
|
||||
assert materialized is not None
|
||||
assert materialized.status == TaskStatus.BACKLOG
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_unknown_item_is_404(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/pest-control/cycles/{task.id}/items/no-such-item/approve"
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_item_records_reason(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/pest-control/cycles/{task.id}/items/item-0/reject",
|
||||
json={"reason": "already fixed elsewhere"},
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "rejected"
|
||||
|
||||
refreshed = await db_session.get(TaskTable, task.id)
|
||||
assert refreshed is not None
|
||||
payload = markers.get_pest_hunt(refreshed)
|
||||
assert payload is not None
|
||||
assert payload["items"][0]["reject_reason"] == "already fixed elsewhere"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_ceo_is_forbidden(db_session: AsyncSession) -> None:
|
||||
await _seed_cycle(db_session)
|
||||
app = _build_app(db_session, AgentRole.DEVELOPER, uuid4())
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
list_resp = await client.get("/api/pest-control/cycles")
|
||||
assert list_resp.status_code == HTTPStatus.FORBIDDEN
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,334 @@
|
||||
"""Scales (Board Program) engine route coverage — CEO-only list/approve/
|
||||
reject. Approving EXECUTES the item against the live target task. Mirrors
|
||||
test_pest_control_routes.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from roboco.api.deps import get_agent_context, get_db
|
||||
from roboco.api.routes.scales import router as scales_router
|
||||
from roboco.db.tables import AgentTable, ProjectTable, TaskTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.foundation.policy.content import markers
|
||||
from roboco.models import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import Complexity, TaskNature, TaskStatus, TaskType
|
||||
from roboco.models.permissions import AgentContext
|
||||
from roboco.services.task import SCALES_SOURCE
|
||||
|
||||
CEO_UUID = _foundation.AGENTS["ceo"].uuid
|
||||
_UNTOUCHED_PRIORITY = 2
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def _seed_agent(session: AsyncSession, role: AgentRole, slug: str) -> AgentTable:
|
||||
agent = AgentTable(
|
||||
id=uuid4(),
|
||||
name=slug,
|
||||
slug=f"{slug}-{uuid4().hex[:6]}",
|
||||
role=role,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
session.add(agent)
|
||||
await session.flush()
|
||||
return agent
|
||||
|
||||
|
||||
async def _seed_ceo(session: AsyncSession) -> None:
|
||||
"""The CEO row matching ``CEO_UUID`` — approving an item stamps this id
|
||||
as the actor on the audit row."""
|
||||
if await session.get(AgentTable, CEO_UUID) is not None:
|
||||
return
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=CEO_UUID,
|
||||
name="ceo",
|
||||
slug=f"ceo-{uuid4().hex[:6]}",
|
||||
role=AgentRole.CEO,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def _seed_cycle(session: AsyncSession) -> tuple[TaskTable, TaskTable]:
|
||||
"""Returns (exploration cycle task, live target task the item mutates)."""
|
||||
system = await _seed_agent(session, AgentRole.SYSTEM, "system")
|
||||
po = await _seed_agent(session, AgentRole.PRODUCT_OWNER, "product-owner")
|
||||
await _seed_ceo(session)
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name="Backend Service",
|
||||
slug=f"backend-svc-{uuid4().hex[:6]}",
|
||||
git_url="https://example.com/backend-svc.git",
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=system.id,
|
||||
)
|
||||
session.add(project)
|
||||
await session.flush()
|
||||
target = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Stale onboarding polish",
|
||||
description="A live backlog task the rebalance plan targets",
|
||||
acceptance_criteria=["done"],
|
||||
status=TaskStatus.BACKLOG,
|
||||
priority=2,
|
||||
task_type=TaskType.CODE,
|
||||
nature=TaskNature.TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
project_id=project.id,
|
||||
team=Team.BACKEND,
|
||||
)
|
||||
session.add(target)
|
||||
await session.flush()
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Scales portfolio-rebalance cycle",
|
||||
description="Review the live backlog and propose a rebalance.",
|
||||
acceptance_criteria=["propose_rebalance() called once"],
|
||||
status=TaskStatus.PENDING,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
assigned_to=po.id,
|
||||
team=Team.BOARD,
|
||||
source=SCALES_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
markers.set_rebalance_plan(
|
||||
task,
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "item-0",
|
||||
"task_ref": str(target.id)[:8],
|
||||
"target_task_id": str(target.id),
|
||||
"target_task_title": target.title,
|
||||
"action": "reprioritize",
|
||||
"new_priority": 0,
|
||||
"rationale": (
|
||||
"Onboarding friction is this quarter's top charter goal"
|
||||
),
|
||||
"status": "proposed",
|
||||
"reject_reason": None,
|
||||
"executed_detail": None,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
await session.flush()
|
||||
return task, target
|
||||
|
||||
|
||||
def _build_app(db_session: AsyncSession, role: AgentRole, agent_id: UUID) -> FastAPI:
|
||||
app = FastAPI()
|
||||
app.include_router(scales_router, prefix="/api/scales")
|
||||
|
||||
async def _override_db() -> AsyncIterator[AsyncSession]:
|
||||
yield db_session
|
||||
|
||||
async def _override_agent() -> AgentContext:
|
||||
return AgentContext(agent_id=agent_id, role=role, team=None)
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
app.dependency_overrides[get_agent_context] = _override_agent
|
||||
return app
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
await _seed_ceo(db_session)
|
||||
app = _build_app(db_session, AgentRole.CEO, CEO_UUID)
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client
|
||||
app.dependency_overrides.clear()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_cycles_returns_authored_cycle(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _target = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.get("/api/scales/cycles")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert len(body) == 1
|
||||
assert body[0]["task_id"] == str(task.id)
|
||||
assert len(body[0]["items"]) == 1
|
||||
assert body[0]["items"][0]["rationale"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_reprioritize_item_changes_target_priority(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, target = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(f"/api/scales/cycles/{task.id}/items/item-0/approve")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "approved"
|
||||
assert body["executed_detail"] == "priority changed to P0"
|
||||
|
||||
refreshed_target = await db_session.get(TaskTable, target.id)
|
||||
assert refreshed_target is not None
|
||||
assert refreshed_target.priority == 0
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_cancel_item_cancels_target(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
system = await _seed_agent(db_session, AgentRole.SYSTEM, "system2")
|
||||
po = await _seed_agent(db_session, AgentRole.PRODUCT_OWNER, "po2")
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name="Frontend App",
|
||||
slug=f"frontend-app-{uuid4().hex[:6]}",
|
||||
git_url="https://example.com/frontend-app.git",
|
||||
assigned_cell=Team.FRONTEND,
|
||||
created_by=system.id,
|
||||
)
|
||||
db_session.add(project)
|
||||
await db_session.flush()
|
||||
target = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Dead weight experiment",
|
||||
description="A live backlog task the rebalance plan targets",
|
||||
acceptance_criteria=["done"],
|
||||
status=TaskStatus.BACKLOG,
|
||||
priority=2,
|
||||
task_type=TaskType.CODE,
|
||||
nature=TaskNature.TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
project_id=project.id,
|
||||
team=Team.FRONTEND,
|
||||
)
|
||||
db_session.add(target)
|
||||
await db_session.flush()
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Scales portfolio-rebalance cycle",
|
||||
description="Review the live backlog and propose a rebalance.",
|
||||
acceptance_criteria=["propose_rebalance() called once"],
|
||||
status=TaskStatus.PENDING,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
assigned_to=po.id,
|
||||
team=Team.BOARD,
|
||||
source=SCALES_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
db_session.add(task)
|
||||
await db_session.flush()
|
||||
markers.set_rebalance_plan(
|
||||
task,
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "item-0",
|
||||
"task_ref": str(target.id)[:8],
|
||||
"target_task_id": str(target.id),
|
||||
"target_task_title": target.title,
|
||||
"action": "cancel",
|
||||
"new_priority": None,
|
||||
"rationale": (
|
||||
"Superseded by the new dashboard; no longer on the roadmap"
|
||||
),
|
||||
"status": "proposed",
|
||||
"reject_reason": None,
|
||||
"executed_detail": None,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
await db_session.flush()
|
||||
|
||||
resp = await ceo_client.post(f"/api/scales/cycles/{task.id}/items/item-0/approve")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "approved"
|
||||
assert body["executed_detail"] == "cancelled"
|
||||
|
||||
refreshed_target = await db_session.get(TaskTable, target.id)
|
||||
assert refreshed_target is not None
|
||||
assert refreshed_target.status == TaskStatus.CANCELLED
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_unknown_item_is_404(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _target = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/scales/cycles/{task.id}/items/no-such-item/approve"
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_item_records_reason(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, target = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/scales/cycles/{task.id}/items/item-0/reject",
|
||||
json={"reason": "still worth doing at current priority"},
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "rejected"
|
||||
|
||||
refreshed = await db_session.get(TaskTable, task.id)
|
||||
assert refreshed is not None
|
||||
payload = markers.get_rebalance_plan(refreshed)
|
||||
assert payload is not None
|
||||
assert (
|
||||
payload["items"][0]["reject_reason"] == "still worth doing at current priority"
|
||||
)
|
||||
|
||||
refreshed_target = await db_session.get(TaskTable, target.id)
|
||||
assert refreshed_target is not None
|
||||
assert refreshed_target.priority == _UNTOUCHED_PRIORITY # untouched
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_ceo_is_forbidden(db_session: AsyncSession) -> None:
|
||||
await _seed_cycle(db_session)
|
||||
app = _build_app(db_session, AgentRole.DEVELOPER, uuid4())
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
list_resp = await client.get("/api/scales/cycles")
|
||||
assert list_resp.status_code == HTTPStatus.FORBIDDEN
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,215 @@
|
||||
"""Sentinel (Board Program) engine route coverage — CEO-only, read-only.
|
||||
Mirrors test_periscope_routes.py minus the market-brief-specific findings
|
||||
shape: a quality report is a report, not a queue item."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from roboco.api.deps import get_agent_context, get_db
|
||||
from roboco.api.routes.sentinel import router as sentinel_router
|
||||
from roboco.db.tables import AgentTable, TaskTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.foundation.policy.content import markers
|
||||
from roboco.models import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import Complexity, TaskNature, TaskStatus, TaskType
|
||||
from roboco.models.permissions import AgentContext
|
||||
from roboco.services.task import SENTINEL_SOURCE
|
||||
from sqlalchemy import update
|
||||
|
||||
CEO_UUID = _foundation.AGENTS["ceo"].uuid
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def _seed_agent(session: AsyncSession, role: AgentRole, slug: str) -> AgentTable:
|
||||
agent = AgentTable(
|
||||
id=uuid4(),
|
||||
name=slug,
|
||||
slug=f"{slug}-{uuid4().hex[:6]}",
|
||||
role=role,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
session.add(agent)
|
||||
await session.flush()
|
||||
return agent
|
||||
|
||||
|
||||
async def _seed_ceo(session: AsyncSession) -> None:
|
||||
if await session.get(AgentTable, CEO_UUID) is not None:
|
||||
return
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=CEO_UUID,
|
||||
name="ceo",
|
||||
slug=f"ceo-{uuid4().hex[:6]}",
|
||||
role=AgentRole.CEO,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def _seed_completed_report(session: AsyncSession) -> TaskTable:
|
||||
system = await _seed_agent(session, AgentRole.SYSTEM, "system")
|
||||
auditor = await _seed_agent(session, AgentRole.AUDITOR, "auditor")
|
||||
await _seed_ceo(session)
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Sentinel drift-watch cycle",
|
||||
description="Assess org-wide quality drift and file ONE report.",
|
||||
acceptance_criteria=["propose_quality_report() called once"],
|
||||
status=TaskStatus.COMPLETED,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
assigned_to=auditor.id,
|
||||
team=Team.BOARD,
|
||||
source=SENTINEL_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
markers.set_quality_report(
|
||||
task,
|
||||
{
|
||||
"headline": "Waived findings climbed sharply this week",
|
||||
"items": [
|
||||
{
|
||||
"id": "item-0",
|
||||
"area": "waivers",
|
||||
"observation": "Minor findings keep getting waived in one file",
|
||||
"evidence": "5 waived-minor findings this week (prior: 1)",
|
||||
"suggested_action": "Convert to a Pest Control bug task",
|
||||
}
|
||||
],
|
||||
"overall_assessment": "Drift is concentrated, not systemic",
|
||||
},
|
||||
)
|
||||
await session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _build_app(db_session: AsyncSession, role: AgentRole, agent_id: UUID) -> FastAPI:
|
||||
app = FastAPI()
|
||||
app.include_router(sentinel_router, prefix="/api/sentinel")
|
||||
|
||||
async def _override_db() -> AsyncIterator[AsyncSession]:
|
||||
yield db_session
|
||||
|
||||
async def _override_agent() -> AgentContext:
|
||||
return AgentContext(agent_id=agent_id, role=role, team=None)
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
app.dependency_overrides[get_agent_context] = _override_agent
|
||||
return app
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
await _seed_ceo(db_session)
|
||||
app = _build_app(db_session, AgentRole.CEO, CEO_UUID)
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client
|
||||
app.dependency_overrides.clear()
|
||||
# This route only reads — nothing here writes/commits — but a sibling
|
||||
# real-DB suite could still leave a stray board_sentinel task behind
|
||||
# from an earlier failed run; keep the cleanup unconditional and cheap.
|
||||
await db_session.execute(
|
||||
update(TaskTable)
|
||||
.where(TaskTable.source == SENTINEL_SOURCE)
|
||||
.values(status=TaskStatus.CANCELLED)
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_reports_empty_when_none_filed(ceo_client: AsyncClient) -> None:
|
||||
resp = await ceo_client.get("/api/sentinel/reports")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
assert resp.json() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_reports_returns_filed_report(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task = await _seed_completed_report(db_session)
|
||||
resp = await ceo_client.get("/api/sentinel/reports")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert len(body) == 1
|
||||
row = body[0]
|
||||
assert row["task_id"] == str(task.id)
|
||||
assert row["headline"] == "Waived findings climbed sharply this week"
|
||||
assert len(row["items"]) == 1
|
||||
assert row["items"][0]["area"] == "waivers"
|
||||
assert row["items"][0]["suggested_action"] == "Convert to a Pest Control bug task"
|
||||
assert row["overall_assessment"] == "Drift is concentrated, not systemic"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_reports_omits_non_terminal_exploration(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
"""A still-open (PENDING) exploration cycle carries no report yet — it
|
||||
must never render as an empty/blank report row."""
|
||||
system = await _seed_agent(db_session, AgentRole.SYSTEM, "system")
|
||||
auditor = await _seed_agent(db_session, AgentRole.AUDITOR, "auditor")
|
||||
db_session.add(
|
||||
TaskTable(
|
||||
id=uuid4(),
|
||||
title="Sentinel drift-watch cycle",
|
||||
description="x",
|
||||
acceptance_criteria=["x"],
|
||||
status=TaskStatus.PENDING,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
assigned_to=auditor.id,
|
||||
team=Team.BOARD,
|
||||
source=SENTINEL_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
)
|
||||
await db_session.flush()
|
||||
resp = await ceo_client.get("/api/sentinel/reports")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
assert resp.json() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_ceo_is_forbidden(db_session: AsyncSession) -> None:
|
||||
await _seed_completed_report(db_session)
|
||||
app = _build_app(db_session, AgentRole.DEVELOPER, uuid4())
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
resp = await client.get("/api/sentinel/reports")
|
||||
assert resp.status_code == HTTPStatus.FORBIDDEN
|
||||
app.dependency_overrides.clear()
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Spackle (Board Program) engine route coverage — CEO-only list/approve/
|
||||
reject. Mirrors test_pest_control_routes.py."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from http import HTTPStatus
|
||||
from typing import TYPE_CHECKING
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi import FastAPI
|
||||
from httpx import ASGITransport, AsyncClient
|
||||
from roboco.api.deps import get_agent_context, get_db
|
||||
from roboco.api.routes.spackle import router as spackle_router
|
||||
from roboco.db.tables import AgentTable, ProjectTable, TaskTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.foundation.policy.content import markers
|
||||
from roboco.models import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import Complexity, TaskNature, TaskStatus, TaskType
|
||||
from roboco.models.permissions import AgentContext
|
||||
from roboco.services.task import SPACKLE_SOURCE
|
||||
from sqlalchemy import update
|
||||
|
||||
_SEED_GIT_URL = "https://example.com/backend-svc-spackle.git"
|
||||
|
||||
CEO_UUID = _foundation.AGENTS["ceo"].uuid
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from collections.abc import AsyncIterator
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
|
||||
async def _seed_agent(session: AsyncSession, role: AgentRole, slug: str) -> AgentTable:
|
||||
agent = AgentTable(
|
||||
id=uuid4(),
|
||||
name=slug,
|
||||
slug=f"{slug}-{uuid4().hex[:6]}",
|
||||
role=role,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
session.add(agent)
|
||||
await session.flush()
|
||||
return agent
|
||||
|
||||
|
||||
async def _seed_ceo(session: AsyncSession) -> None:
|
||||
"""The CEO row matching ``CEO_UUID`` — approving an item stamps this id as
|
||||
the materialized task's ``created_by``, which has an FK to ``agents``."""
|
||||
if await session.get(AgentTable, CEO_UUID) is not None:
|
||||
return
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=CEO_UUID,
|
||||
name="ceo",
|
||||
slug=f"ceo-{uuid4().hex[:6]}",
|
||||
role=AgentRole.CEO,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
async def _seed_cycle(session: AsyncSession) -> tuple[TaskTable, ProjectTable]:
|
||||
system = await _seed_agent(session, AgentRole.SYSTEM, "system")
|
||||
po = await _seed_agent(session, AgentRole.PRODUCT_OWNER, "product-owner")
|
||||
await _seed_ceo(session)
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name="Backend Service",
|
||||
slug=f"backend-svc-{uuid4().hex[:6]}",
|
||||
git_url=_SEED_GIT_URL,
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=system.id,
|
||||
board_programs=["spackle"],
|
||||
)
|
||||
session.add(project)
|
||||
await session.flush()
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Spackle exploration cycle",
|
||||
description="Audit half-shipped surface area and propose a gap-fill audit.",
|
||||
acceptance_criteria=["propose_gap_fill() called once"],
|
||||
status=TaskStatus.PENDING,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=system.id,
|
||||
assigned_to=po.id,
|
||||
team=Team.BOARD,
|
||||
source=SPACKLE_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
markers.set_gap_fill(
|
||||
task,
|
||||
{
|
||||
"items": [
|
||||
{
|
||||
"id": "item-0",
|
||||
"title": "Add panel surface for /api/widgets",
|
||||
"description": "The route exists but no panel page calls it",
|
||||
"acceptance_criteria": ["panel page lists widgets"],
|
||||
"project_slug": project.slug,
|
||||
"team": "backend",
|
||||
"priority": 2,
|
||||
"evidence": (
|
||||
"roboco/api/routes/widgets.py:12 defines GET /widgets; "
|
||||
"no panel/src page calls it"
|
||||
),
|
||||
"status": "proposed",
|
||||
"reject_reason": None,
|
||||
"materialized_task_id": None,
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
await session.flush()
|
||||
return task, project
|
||||
|
||||
|
||||
def _build_app(db_session: AsyncSession, role: AgentRole, agent_id: UUID) -> FastAPI:
|
||||
app = FastAPI()
|
||||
app.include_router(spackle_router, prefix="/api/spackle")
|
||||
|
||||
async def _override_db() -> AsyncIterator[AsyncSession]:
|
||||
yield db_session
|
||||
|
||||
async def _override_agent() -> AgentContext:
|
||||
return AgentContext(agent_id=agent_id, role=role, team=None)
|
||||
|
||||
app.dependency_overrides[get_db] = _override_db
|
||||
app.dependency_overrides[get_agent_context] = _override_agent
|
||||
return app
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def ceo_client(db_session: AsyncSession) -> AsyncIterator[AsyncClient]:
|
||||
"""CEO-authed client. Approving an item materializes a new task stamping
|
||||
``agent.agent_id`` as ``created_by`` (an FK to ``agents``), so this must be
|
||||
a real seeded row — ``CEO_UUID`` — not an arbitrary ``uuid4()``."""
|
||||
await _seed_ceo(db_session)
|
||||
app = _build_app(db_session, AgentRole.CEO, CEO_UUID)
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
yield client
|
||||
app.dependency_overrides.clear()
|
||||
# The approve/reject routes commit explicitly (write-route convention),
|
||||
# so a leftover ``board_programs=["spackle"]`` opt-in from an
|
||||
# approve/reject test here would otherwise outlive this test in the
|
||||
# shared, cross-test-persistent DB and poison every later real-DB
|
||||
# spackle unit test that asserts an exact opted-in-project set (e.g.
|
||||
# "no project opted in"). Mirrors test_pest_control_routes.py's
|
||||
# identical cleanup. Reset, not delete — a materialized BACKLOG task
|
||||
# may still hold this project's id as an FK. Unconditional — a no-op
|
||||
# for the tests here that never wrote anything.
|
||||
await db_session.execute(
|
||||
update(ProjectTable)
|
||||
.where(ProjectTable.git_url == _SEED_GIT_URL)
|
||||
.values(board_programs=None)
|
||||
)
|
||||
await db_session.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_cycles_returns_authored_cycle(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.get("/api/spackle/cycles")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert len(body) == 1
|
||||
assert body[0]["task_id"] == str(task.id)
|
||||
assert len(body[0]["items"]) == 1
|
||||
assert body[0]["items"][0]["evidence"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_item_materializes_backlog_task(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(f"/api/spackle/cycles/{task.id}/items/item-0/approve")
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "approved"
|
||||
assert body["materialized_task_id"] is not None
|
||||
|
||||
materialized = await db_session.get(TaskTable, UUID(body["materialized_task_id"]))
|
||||
assert materialized is not None
|
||||
assert materialized.status == TaskStatus.BACKLOG
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_unknown_item_is_404(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/spackle/cycles/{task.id}/items/no-such-item/approve"
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.NOT_FOUND
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_item_records_reason(
|
||||
db_session: AsyncSession, ceo_client: AsyncClient
|
||||
) -> None:
|
||||
task, _project = await _seed_cycle(db_session)
|
||||
resp = await ceo_client.post(
|
||||
f"/api/spackle/cycles/{task.id}/items/item-0/reject",
|
||||
json={"reason": "already tracked elsewhere"},
|
||||
)
|
||||
assert resp.status_code == HTTPStatus.OK
|
||||
body = resp.json()
|
||||
assert body["status"] == "rejected"
|
||||
|
||||
refreshed = await db_session.get(TaskTable, task.id)
|
||||
assert refreshed is not None
|
||||
payload = markers.get_gap_fill(refreshed)
|
||||
assert payload is not None
|
||||
assert payload["items"][0]["reject_reason"] == "already tracked elsewhere"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_non_ceo_is_forbidden(db_session: AsyncSession) -> None:
|
||||
await _seed_cycle(db_session)
|
||||
app = _build_app(db_session, AgentRole.DEVELOPER, uuid4())
|
||||
transport = ASGITransport(app=app)
|
||||
async with AsyncClient(transport=transport, base_url="http://test") as client:
|
||||
list_resp = await client.get("/api/spackle/cycles")
|
||||
assert list_resp.status_code == HTTPStatus.FORBIDDEN
|
||||
app.dependency_overrides.clear()
|
||||
@@ -116,8 +116,10 @@ class _StubClient(XClient):
|
||||
def configured(self) -> bool:
|
||||
return True
|
||||
|
||||
async def post_tweet(self, text: str) -> XPostResult:
|
||||
_ = text
|
||||
async def post_tweet(
|
||||
self, text: str, *, in_reply_to_tweet_id: str | None = None
|
||||
) -> XPostResult:
|
||||
_ = (text, in_reply_to_tweet_id)
|
||||
return XPostResult(posted=True, tweet_id="42", detail="posted")
|
||||
|
||||
async def fetch_mentions(
|
||||
@@ -126,6 +128,10 @@ class _StubClient(XClient):
|
||||
_ = (since_id, max_results)
|
||||
return []
|
||||
|
||||
async def search_recent(self, query: str, max_results: int) -> list[XMention]:
|
||||
_ = (query, max_results)
|
||||
return []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_posts_returns_open_draft(
|
||||
|
||||
Reference in New Issue
Block a user