mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
v0.17.0 — Wave 3: sandbox DB, DB isolation, mobile UI, cloud auth, X account, roadmap engine (#303)
* feat(sandbox): throwaway per-agent Postgres/Redis sandbox containers
Orchestrator-provisioned sibling containers per agent spawn
(SandboxProvisioner, roboco/runtime/sandbox.py). Per-project opt-in via
projects.sandbox_services (migration 057); master switch
ROBOCO_SANDBOX_DB_ENABLED, default-off, armed in the NAS compose only.
When active, ROBOCO_TEST_DB_* / ROBOCO_TEST_REDIS_* point at the sandbox
and the prod-creds gate-env injection is suppressed (sandbox replaces,
never coexists). Sandbox lifetime tracks the agent container: teardown at
every removal path, orphan janitor at startup + each reaper tick with a
grace window for mid-flight spawns. The pre-spawn stale-clear spares the
just-provisioned sandbox; provision pre-clears stale same-named
containers from a crash-missed teardown.
Panel: per-project sandbox-service switches in the edit dialog + feature
flag card entry.
* docs: CLAUDE.md entry for the sandboxed dev DB/Redis subsystem
* feat(security): isolate prod Postgres/Redis from agent containers (roboco_data network)
Second user-defined bridge roboco_data carries postgres+redis only; the
orchestrator is multi-homed (default + data). Spawned agents and their
sandbox sidecars stay on roboco_default and can no longer resolve or
reach roboco-postgres:5432 / roboco-redis:6379 (redis has no auth —
membership is its only containment). Normal bridge, so host-published
ports (15432/16379) keep working. Applied to both build composes and
the registry compose; docker-compose.yml re-synced byte-identical with
docker-compose.yaml (it had drifted by the sandbox flag block).
ROBOCO_DB_NETWORK_ISOLATED (config default false, armed alongside the
topology) suppresses the legacy _append_gate_env prod-creds injection:
under isolation those creds dead-end, and unreachable creds are worse
than none. DB-needing projects opt into sandbox_services instead. The
flag is deliberately not a panel feature flag - it must travel with the
compose networks: stanzas.
Preserved by construction: agent<->agent A2A and orchestrator->agent SDK
polls on :9000, MCP->orchestrator on :8000, ollama reachability, docker
exec/inspect (daemon socket), host port publishing.
* feat(panel): full mobile responsiveness pass
Shared primitives: useIsMobile (useSyncExternalStore, hydration-safe,
memoized matchMedia subscribe), ResponsiveTable table->card switch below
md (single subtree mounted, no duplicated interactive rows), scrollable
snap TabsList in the base primitive (justify-center-safe so the first
tab stays reachable on overflow), persistent md:hidden bottom tab bar
(Overview/Tasks/Kanban/Chat, safe-area padded).
Applied: card lists for tasks/projects/products/work-sessions/sessions
+ the three raw metrics tables; CEO approval queue / release proposal /
playbook review action rows stack on narrow; command-center reorders
approvals above the fold on mobile; task-header metadata wraps;
Communications + A2A become URL-driven single-pane drill-downs below lg
(fixes the unconstrained-height ScrollArea bug) with dvh heights;
recharts label density/radius adapts via useIsMobile; git diff viewer
gets mobile font + wrap toggle; vh->dvh sweep; chat composers get
safe-area-inset padding; dashboard main p-4 md:p-6 + pb-20 for the bar.
Verified at 375px on the built app: bottom bar, drawer, approval-first
overview, swipeable kanban tab strip. All gates green (eslint, tsc,
vitest 249, next build 24/24 routes).
* feat(auth): cloud auth via FastAPI Users (default-off, single-user cookie session)
ROBOCO_CLOUD_AUTH_ENABLED (default off) lets the panel/API be exposed
beyond localhost without changing the CEO's local no-login flow while
off — get_agent_context and the WS gate are byte-for-byte unchanged in
off-mode. On: header-trust dies for humans — any agent-role claim (ceo
or a privileged PM/board role) with no valid HMAC token or session
cookie is 401, closing the header-spoof hole on the host-published
:8000 port for every role. The agent-fleet HMAC path and the system
self-PATCH keep working unmodified in both modes.
Single seeded CEO user (migration 058 users table, UserTable), no
registration router — idempotent env-driven upsert at startup by PK.
Cookie transport (httponly/secure/samesite=lax) + a JWTStrategy bound
to a fingerprint of the current password hash (rotating the password
invalidates every prior session). Sliding 30-day session: every
authenticated request re-mints the cookie, so an active session never
expires — no unexpected logouts.
Panel: (auth)/login page + proxy.ts (Next 16 rename of middleware; probes
/auth/status over the docker-internal URL, fails open to off) gate the
dashboard; client.ts gets withCredentials + 401->/login. nginx unchanged.
Review hardening: broadened the on-mode rejection from ceo-only to every
non-CEO role without a valid token (was only closed when
ROBOCO_AGENT_AUTH_REQUIRED was also armed); Next-16 proxy.ts rename to
clear the middleware deprecation warning.
* feat(x): RoboCo X account engine — HoM drafts, per-post CEO approval (default-off)
ROBOCO_X_ENGINE_ENABLED (default off, inert without creds). Mirrors the
ReleaseManagerEngine held-artifact shape: XEngine drafts a post when a
release publishes (via a draft_release_post seam on ReleaseProposalService
.approve) and drafts replies to meaningful mentions (dedicated poll loop,
x_seen_mentions dedup ledger, per-cycle/open caps). Drafting is
local-model-only, clamped to 280 chars. Nothing auto-posts — every tweet
is a held task (source x_post/x_reply, confirmed_by_human=False,
Secretary-owned, dispatcher-skipped) the CEO edits/approves/rejects in a
panel queue.
The four OAuth 1.0a secrets live Fernet-encrypted in a singleton
x_credentials row (migration 059, all-or-nothing, API returns only
has_credentials); decryption is server-side, agents never hold creds or
egress. Hand-rolled OAuth 1.0a HMAC-SHA1 signer, no new dependency;
NullXClient makes the unconfigured path a graceful no-op.
XPostService.approve (CEO-only) is the sole caller of post_tweet.
Review hardening: closed a double-post race — the approve path now
re-reads committed task state inside the Redis lock and commits COMPLETED
before releasing, so a concurrent approve that acquires the lock after the
winner released can't re-post (SET-NX is non-waiting, and the route-level
commit landed after the lock dropped). Added a regression test.
* feat(roadmap): board roadmap engine — PO proposes themed cycles, CEO approves per-item (default-off)
ROBOCO_ROADMAP_ENGINE_ENABLED (default off). Weekly, RoadmapEngine opens
ONE held exploration task (source=board_roadmap, confirmed_by_human=False,
Product-Owner-assigned), deduped to one open cycle. A dedicated one-shot
_dispatch_roadmap_exploration spawns the PO solo (not the two-reviewer
board path, which would also spawn HoM + fire Approve-&-Start). The PO
explores read-only (git/KB/metrics/releases/charter/web) and makes one
propose_roadmap call (PO-only content verb) authoring a themed cycle —
goal + 3-7 item drafts — persisted as a roadmap_cycle marker (no table,
no migration; head stays 059).
The CEO acts per-item in the panel roadmap queue: approve materializes a
BACKLOG task (source=roadmap, no assignee — never auto-starts), reject
records a reason; all-items-terminal completes the exploration task.
RoadmapService is idempotent per item. Dispatchers skip board_roadmap.
Includes a real SQLAlchemy dirty-check fix (deep-copy the JSON marker
before mutating, or the in-place edit + reassign compares equal to its
own baseline and the UPDATE is skipped).
Review hardening: create_task_from_draft now honors a draft-declared
source only from a {prompter, roadmap} whitelist — drafts are
LLM-authored, so an unbounded source could impersonate a privileged
origin (release_manager would even wedge that engine's dedup).
* chore(release): 0.17.0
Wave 3 — six default-off subsystems: sandboxed dev DB/Redis, prod
Postgres/Redis network isolation, full mobile UI pass, cloud auth
(FastAPI Users), the RoboCo X account engine, and the board roadmap
engine. Plus the waves 1+2 work already on master since 0.16.0.
Version bumped across the canonical set (config.py, __init__.py,
pyproject.toml, panel/package.json, uv.lock); CHANGELOG [Unreleased]
cut to [0.17.0]; docs/map delta added.
Compose: every optional feature armed :-true in the NAS composes, OFF
in the user-facing registry compose. Two opt-in exceptions default off
(CLOUD_AUTH — needs email/password/secret + TLS, would otherwise fail
startup; ROUTING_STRICT — fail-closed spawning). DB_NETWORK_ISOLATED
stays on in both (coupled to the roboco_data topology).
* chore(compose): arm cloud_auth + routing_strict ON in the NAS composes
Every feature defaults ON in the NAS composes per policy — these two
were wrongly left off. Both keep the ${VAR:-true} form so the operator
controls the real runtime via .env: cloud auth needs
ROBOCO_CLOUD_AUTH_EMAIL/_PASSWORD/_SECRET + TLS set there before a boot
(else startup fails loud), and routing_strict is fail-closed. Registry
compose keeps both off.
* fix(ci): reflow board.md prose (quality gate) + document v0.17.0 env creds
The roadmap section added hard-wrapped prose that failed the markdown
prose gate; reflowed (token-invariant). Also brought .env.example
current: cloud auth (now armed — needs SECRET or startup fails), routing
strict, the X engine (panel-entered OAuth), and web research.
* fix(ci): reduce cyclomatic complexity of five wave-3 blocks (xenon gate)
The wave-3 subagents introduced C-rank functions the CI xenon gate
rejects (my per-item reviews ran ruff/mypy/pytest but not xenon):
- sandbox.janitor_sweep -> extract _list_labeled_sandboxes /
_list_live_agent_containers / _prune_grace
- x_client.fetch_mentions -> extract _parse_mention_items
- x_engine.run_cycle -> extract _process_mentions
- orchestrator._dispatch_pm_work -> extract the source-skip into a
MODULE-level _is_held_ceo_source (module, not method, so the
wholesale-mocked dispatcher unit tests exercise the real logic)
- auth/seed.ensure_seed_user -> extract _apply_seed_updates (module avg -> A)
Behavior-preserving; full suite green (11902), xenon clean.
* fix(ci): declare pyjwt + fastapi-users-db-sqlalchemy as direct deps (deptry)
The cloud-auth code imports jwt and fastapi_users_db_sqlalchemy directly
but they were only transitive deps (via fastapi-users), which deptry
(quality gate, DEP003) rejects. Declared explicitly; deptry roboco/ clean.
Missed originally because local make quality stopped at earlier gates
before reaching deptry.
* feat(x): gate mention replies behind ROBOCO_X_REPLIES_ENABLED (default off)
Per CEO decision: the X engine should only post about releases by
default. Reading mentions needs a paid X API tier, so the mention-reply
half is now a deliberate opt-in on top of release posting.
New default-off flag x_replies_enabled gates the mentions poll loop
(_x_mentions_poll_loop) and XEngine.run_cycle; release-post drafting
(the release-proposal approve hook) is unaffected and still runs when
x_engine_enabled + credentials are set. Added to FEATURE_FLAGS + the
panel card. Tests: release posting works with replies off; run_cycle +
the poll loop are no-ops with replies off.
* fix: 401 only redirects to /login when cloud auth is on; panel-token strips .env quotes
Two bugs that together dead-ended login in secure mode:
- client.ts redirected to /login on ANY 401, so a mismatched panel
token (header-trust/secure mode, cloud auth off) bounced the user to a
login page whose backend route isn't mounted -> 404. Now it probes
/auth/status (bare fetch, no interceptor re-entry) and only redirects
when cloud_auth_enabled.
- make panel-token read the .env secret with grep|cut without stripping
surrounding quotes, so a quoted ROBOCO_AGENT_AUTH_SECRET produced a
token signed with the quotes included — which never verifies against
the orchestrator (docker-compose/pydantic unquote the secret). Now
strips surrounding single/double quotes.
* fix: git-log 500 on '|' in commit message; X queue shows an empty state
- GET /api/git/log 500'd (ValueError: Invalid isoformat) when a commit
SUBJECT contained a '|' (e.g. the 'curl|sh' lockdown commit): the
fixed '|' field delimiter let the subject's pipe shift the split so
author+date collapsed into one field. Switched to \x1f (Unit
Separator), which can't appear in commit content. Regression test with
a piped subject.
- The X Post Queue returned null when empty, so there was no visible
place for the X drafts. It now renders a discoverable empty state
pointing at Settings -> X credentials.
* docs: bring docs/rag + docs/map current for v0.17.0 (waves 1-3)
Agent-facing RAG corpus and codebase map updated for every feature in
the 0.17.0 span, code-verified:
- wave 3: sandbox DB, DB network isolation, cloud auth, X engine
(+ x_replies_enabled sub-flag), board roadmap engine — new RAG
architecture pages + role/tool/config-reference updates; new symbols,
migrations 057-059, panel surfaces, and the get_agent_context
dual-path across the map slices.
- waves 1-2: A2A live view + switchboard, prompter memory
(search_past_tasks), Secretary edit access + PM-lighter scope, the
PR-gate auto-submit turn cut (ROBOCO_PR_GATE_AUTO_SUBMIT_ENABLED).
- correctness fix: api-routes-schemas.md no longer claims the A2A admin
routes are reachable by any authenticated agent — they carry a
_require_ceo gate (wave 2c).
docs/internal, _front.md deltas, and the frozen _complete_map.md
snapshot untouched.
* fix(rag): atomic upsert for indexed-doc tracking (kills e2e segfault)
The indexed-document tracking write used check-then-insert in two paths
(IndexedDocumentRepository.upsert_batch and the file-source
_upsert_doc_record). Under concurrent indexing both callers saw no row
and both inserted, so the second violated uq_indexed_doc_source and
poisoned its transaction — surfacing in CI as the intermittent
_checkin_failed SIGSEGV on the failed connection's pool checkin.
Both paths now use INSERT ... ON CONFLICT DO UPDATE against the
constraint: coalesce keeps an existing title/preview when the new value
is empty (matching the old guards) and metadata is jsonb-merged. The
batch dedupes within itself first (ON CONFLICT can't touch a row twice
in one statement). expire_all after the Core upsert keeps same-session
ORM reads consistent with the merged DB row.
---------
Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
@@ -1067,6 +1067,59 @@ async def test_create_task_from_draft_does_not_mutate_caller_draft(
|
||||
assert draft["acceptance_criteria"] == ["done"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_task_from_draft_defaults_source_to_prompter(
|
||||
db_session: Any,
|
||||
) -> None:
|
||||
project_id, ceo_id = await _seed_project_and_ceo(db_session)
|
||||
service = get_prompter_service(db=db_session)
|
||||
draft = {
|
||||
"title": "Default-source draft",
|
||||
"acceptance_criteria": ["done"],
|
||||
"project_id": str(project_id),
|
||||
}
|
||||
task = await service.create_task_from_draft(draft, ceo_id)
|
||||
assert task.source == "prompter"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_task_from_draft_accepts_custom_source(
|
||||
db_session: Any,
|
||||
) -> None:
|
||||
"""A non-intake caller (e.g. an approved roadmap item) stamps its own
|
||||
source tag on the draft instead of the intake default."""
|
||||
project_id, ceo_id = await _seed_project_and_ceo(db_session)
|
||||
service = get_prompter_service(db=db_session)
|
||||
draft = {
|
||||
"title": "Roadmap-sourced draft",
|
||||
"acceptance_criteria": ["done"],
|
||||
"project_id": str(project_id),
|
||||
"source": "roadmap",
|
||||
}
|
||||
task = await service.create_task_from_draft(draft, ceo_id)
|
||||
assert task.source == "roadmap"
|
||||
assert task.confirmed_by_human is True # the CEO approval IS the confirmation
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_create_task_from_draft_rejects_unwhitelisted_source(
|
||||
db_session: Any,
|
||||
) -> None:
|
||||
"""An LLM-authored draft can't impersonate a privileged origin: a source
|
||||
outside the whitelist falls back to 'prompter' (a 'release_manager' spoof
|
||||
would otherwise wedge the release engine's one-open-proposal dedup)."""
|
||||
project_id, ceo_id = await _seed_project_and_ceo(db_session)
|
||||
service = get_prompter_service(db=db_session)
|
||||
draft = {
|
||||
"title": "Spoofed-source draft",
|
||||
"acceptance_criteria": ["done"],
|
||||
"project_id": str(project_id),
|
||||
"source": "release_manager",
|
||||
}
|
||||
task = await service.create_task_from_draft(draft, ceo_id)
|
||||
assert task.source == "prompter"
|
||||
|
||||
|
||||
# =============================================================================
|
||||
# Prompter memory v1 — history digest + compact search rows (pure, no DB)
|
||||
# =============================================================================
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
"""The release-proposal publish hook drafts an X post (best-effort, never
|
||||
raises into approve()). Layering: release_proposal calls only the small typed
|
||||
seam ``XEngine.draft_release_post`` — this test patches at that seam, not the
|
||||
engine's internals."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
from roboco.db.tables import AgentTable, ProjectTable, TaskTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.models.base import AgentRole, AgentStatus, TaskNature, TaskStatus, TaskType
|
||||
from roboco.models.base import Team as T
|
||||
from roboco.services.release_executor import ReleaseResult
|
||||
from roboco.services.release_proposal import ReleaseProposalService
|
||||
from roboco.services.release_readiness import ReleaseReadinessReport, report_to_dict
|
||||
from roboco.services.task import RELEASE_MANAGER_SOURCE
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
_VERSION = "0.18.0"
|
||||
|
||||
|
||||
def _report() -> ReleaseReadinessReport:
|
||||
return ReleaseReadinessReport(
|
||||
proposed_version=_VERSION,
|
||||
bump_kind="minor",
|
||||
change_summary=["feat: a thing", "fix: another thing"],
|
||||
drafted_changelog=f"## [{_VERSION}]\n\n### Added\n- a thing\n",
|
||||
version_bump_plan=["pyproject.toml"],
|
||||
gaps=[],
|
||||
migration_notes=[],
|
||||
gate_state="green",
|
||||
)
|
||||
|
||||
|
||||
async def _seed_proposal(session: AsyncSession) -> TaskTable:
|
||||
system_uuid = _foundation.AGENTS["system"].uuid
|
||||
secretary_uuid = _foundation.AGENTS["secretary-1"].uuid
|
||||
for uuid_, slug, role in (
|
||||
(system_uuid, "system", AgentRole.SYSTEM),
|
||||
(secretary_uuid, "secretary-1", AgentRole.SECRETARY),
|
||||
):
|
||||
if await session.get(AgentTable, uuid_) is None:
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=uuid_,
|
||||
name=slug,
|
||||
slug=slug,
|
||||
role=role,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name="RoboCo",
|
||||
slug=f"roboco-{uuid4().hex[:6]}",
|
||||
git_url="https://example.com/roboco.git",
|
||||
assigned_cell=T.BACKEND,
|
||||
created_by=system_uuid,
|
||||
)
|
||||
session.add(project)
|
||||
await session.flush()
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title=f"Release proposal: v{_VERSION}",
|
||||
description="proposal body",
|
||||
acceptance_criteria=["CEO approves"],
|
||||
status=TaskStatus.PENDING,
|
||||
priority=2,
|
||||
task_type=TaskType.ADMINISTRATIVE,
|
||||
nature=TaskNature.NON_TECHNICAL,
|
||||
project_id=project.id,
|
||||
created_by=system_uuid,
|
||||
assigned_to=secretary_uuid,
|
||||
team=T.MAIN_PM,
|
||||
source=RELEASE_MANAGER_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
orchestration_markers={"release_report": report_to_dict(_report())},
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
return task
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_publish_success_calls_x_engine_draft_seam(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
task = await _seed_proposal(db_session)
|
||||
published = ReleaseResult(
|
||||
status="published",
|
||||
version=_VERSION,
|
||||
files_changed=["pyproject.toml"],
|
||||
commit_sha="abc123",
|
||||
release_url=f"https://github.com/x/roboco/releases/tag/v{_VERSION}",
|
||||
detail="ok",
|
||||
)
|
||||
fake_executor = AsyncMock()
|
||||
fake_executor.execute = AsyncMock(return_value=published)
|
||||
fake_engine = AsyncMock()
|
||||
fake_engine.draft_release_post = AsyncMock(return_value=None)
|
||||
|
||||
with (
|
||||
patch(
|
||||
"roboco.services.release_proposal.get_release_executor",
|
||||
AsyncMock(return_value=fake_executor),
|
||||
),
|
||||
patch("roboco.services.x_engine.get_x_engine", return_value=fake_engine),
|
||||
patch.object(
|
||||
ReleaseProposalService, "_acquire_release_lock", AsyncMock(return_value="t")
|
||||
),
|
||||
patch.object(
|
||||
ReleaseProposalService,
|
||||
"_release_release_lock",
|
||||
AsyncMock(return_value=None),
|
||||
),
|
||||
patch.object(
|
||||
ReleaseProposalService,
|
||||
"_heartbeat_release_lock",
|
||||
AsyncMock(return_value=True),
|
||||
),
|
||||
):
|
||||
result = await ReleaseProposalService(db_session).approve(cast("UUID", task.id))
|
||||
|
||||
assert result is not None
|
||||
assert result.status == "published"
|
||||
fake_engine.draft_release_post.assert_awaited_once_with(
|
||||
version=_VERSION, highlights=["feat: a thing", "fix: another thing"]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_x_draft_failure_never_fails_the_approve(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
"""A drafting exception is swallowed — the release already published."""
|
||||
task = await _seed_proposal(db_session)
|
||||
published = ReleaseResult(
|
||||
status="published",
|
||||
version=_VERSION,
|
||||
files_changed=["pyproject.toml"],
|
||||
commit_sha="abc123",
|
||||
release_url=None,
|
||||
detail="ok",
|
||||
)
|
||||
fake_executor = AsyncMock()
|
||||
fake_executor.execute = AsyncMock(return_value=published)
|
||||
|
||||
with (
|
||||
patch(
|
||||
"roboco.services.release_proposal.get_release_executor",
|
||||
AsyncMock(return_value=fake_executor),
|
||||
),
|
||||
patch(
|
||||
"roboco.services.x_engine.get_x_engine",
|
||||
side_effect=RuntimeError("x-engine boom"),
|
||||
),
|
||||
patch.object(
|
||||
ReleaseProposalService, "_acquire_release_lock", AsyncMock(return_value="t")
|
||||
),
|
||||
patch.object(
|
||||
ReleaseProposalService,
|
||||
"_release_release_lock",
|
||||
AsyncMock(return_value=None),
|
||||
),
|
||||
patch.object(
|
||||
ReleaseProposalService,
|
||||
"_heartbeat_release_lock",
|
||||
AsyncMock(return_value=True),
|
||||
),
|
||||
):
|
||||
result = await ReleaseProposalService(db_session).approve(cast("UUID", task.id))
|
||||
|
||||
assert result is not None
|
||||
assert result.status == "published"
|
||||
await db_session.refresh(task)
|
||||
assert task.status == TaskStatus.COMPLETED # the release itself still completed
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Roadmap engine: originate ONE held exploration cycle, deduped, never authors
|
||||
content itself.
|
||||
|
||||
Mirrors the release-manager engine tests. The engine only opens a HELD
|
||||
exploration task (confirmed_by_human=False, owned by the Product Owner,
|
||||
source=board_roadmap) — it never authors the cycle payload or starts
|
||||
anything; that is entirely the Product Owner's ``propose_roadmap`` plus the
|
||||
CEO's per-item approve.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
import pytest
|
||||
from roboco.config import settings as cfg
|
||||
from roboco.db.tables import AgentTable, ProjectTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.models.base import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import TaskStatus as TS
|
||||
from roboco.services.roadmap_engine import RoadmapEngine
|
||||
from roboco.services.task import ROADMAP_SOURCE, get_task_service
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
SYSTEM_UUID = _foundation.AGENTS["system"].uuid
|
||||
PO_UUID = _foundation.AGENTS["product-owner"].uuid
|
||||
SLUG = "roboco"
|
||||
ONE = 1
|
||||
|
||||
|
||||
async def _seed(session: AsyncSession) -> None:
|
||||
for uuid, slug, role, team in (
|
||||
(SYSTEM_UUID, "system", AgentRole.SYSTEM, None),
|
||||
(PO_UUID, "product-owner", AgentRole.PRODUCT_OWNER, 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()
|
||||
session.add(
|
||||
ProjectTable(
|
||||
name="RoboCo",
|
||||
slug=SLUG,
|
||||
git_url="https://github.com/x/roboco.git",
|
||||
default_branch="master",
|
||||
protected_branches=["master"],
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=SYSTEM_UUID,
|
||||
is_active=True,
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
def _enable(monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
monkeypatch.setattr(cfg, "roadmap_engine_enabled", True)
|
||||
monkeypatch.setattr(cfg, "self_heal_project_slug", SLUG)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disabled_creates_no_cycle(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
monkeypatch.setattr(cfg, "roadmap_engine_enabled", False)
|
||||
engine = RoadmapEngine(db_session)
|
||||
assert await engine.run_cycle() is None
|
||||
assert await get_task_service(db_session).list_open_roadmap_cycles() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_enabled_originates_held_exploration_task(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
engine = RoadmapEngine(db_session)
|
||||
task = await engine.run_cycle()
|
||||
assert task is not None
|
||||
|
||||
open_cycles = await get_task_service(db_session).list_open_roadmap_cycles()
|
||||
assert len(open_cycles) == ONE
|
||||
cycle = open_cycles[0]
|
||||
assert cycle.status == TS.PENDING
|
||||
assert cycle.confirmed_by_human is False # HELD; board-dispatched only
|
||||
assert cycle.assigned_to == PO_UUID
|
||||
assert cycle.team == Team.BOARD
|
||||
assert cycle.source == ROADMAP_SOURCE
|
||||
assert "Roadmap" in cycle.title
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_dedupe_one_open_cycle(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
await RoadmapEngine(db_session).run_cycle()
|
||||
second = await RoadmapEngine(db_session).run_cycle()
|
||||
assert second is None
|
||||
assert len(await get_task_service(db_session).list_open_roadmap_cycles()) == ONE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unresolvable_project_no_cycle(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
monkeypatch.setattr(cfg, "self_heal_project_slug", "no-such-project")
|
||||
engine = RoadmapEngine(db_session)
|
||||
assert await engine.run_cycle() is None
|
||||
assert await get_task_service(db_session).list_open_roadmap_cycles() == []
|
||||
@@ -0,0 +1,292 @@
|
||||
"""RoadmapService coverage: per-item approve materializes a BACKLOG task
|
||||
(idempotent), reject records a reason (idempotent), and the exploration task
|
||||
completes once every item is terminal.
|
||||
|
||||
Mirrors the X-post-service / release-proposal-service tests.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
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.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.roadmap_service import RoadmapService, get_roadmap_service
|
||||
from roboco.services.task import ROADMAP_ITEM_SOURCE, ROADMAP_SOURCE
|
||||
from sqlalchemy import select
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
SYSTEM_UUID = _foundation.AGENTS["system"].uuid
|
||||
PO_UUID = _foundation.AGENTS["product-owner"].uuid
|
||||
CEO_UUID = _foundation.AGENTS["ceo"].uuid
|
||||
ONE = 1
|
||||
TWO = 2
|
||||
|
||||
|
||||
def _item(idx: int, *, status: str = "proposed", project_slug: str) -> dict:
|
||||
return {
|
||||
"id": f"item-{idx}",
|
||||
"title": f"Item {idx}",
|
||||
"description": f"Description for item {idx} that is long enough",
|
||||
"acceptance_criteria": [f"criterion {idx}a", f"criterion {idx}b"],
|
||||
"project_slug": project_slug,
|
||||
"team": "backend",
|
||||
"priority": 2,
|
||||
"rationale": f"Rationale for item {idx}",
|
||||
"status": status,
|
||||
"reject_reason": None,
|
||||
"materialized_task_id": None,
|
||||
}
|
||||
|
||||
|
||||
async def _seed_agents(session: AsyncSession) -> None:
|
||||
for uuid, slug, role, team in (
|
||||
(SYSTEM_UUID, "system", AgentRole.SYSTEM, None),
|
||||
(PO_UUID, "product-owner", AgentRole.PRODUCT_OWNER, Team.BOARD),
|
||||
(CEO_UUID, "ceo", AgentRole.CEO, None),
|
||||
):
|
||||
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()
|
||||
|
||||
|
||||
async def _seed_project(session: AsyncSession, slug: str) -> ProjectTable:
|
||||
await _seed_agents(session)
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name=slug,
|
||||
slug=slug,
|
||||
git_url=f"https://example.com/{slug}.git",
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=SYSTEM_UUID,
|
||||
)
|
||||
session.add(project)
|
||||
await session.flush()
|
||||
return project
|
||||
|
||||
|
||||
async def _seed_cycle(
|
||||
session: AsyncSession, *, items: list[dict] | None = None, project_slug: str
|
||||
) -> TaskTable:
|
||||
await _seed_agents(session)
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="Roadmap exploration cycle",
|
||||
description="Explore and propose a themed cycle of roadmap items.",
|
||||
acceptance_criteria=["propose_roadmap() called once"],
|
||||
status=TS.PENDING,
|
||||
priority=2,
|
||||
task_type=TT.ADMINISTRATIVE,
|
||||
nature=TN.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
created_by=SYSTEM_UUID,
|
||||
assigned_to=PO_UUID,
|
||||
team=Team.BOARD,
|
||||
source=ROADMAP_SOURCE,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
items = items or [
|
||||
_item(0, project_slug=project_slug),
|
||||
_item(1, project_slug=project_slug),
|
||||
]
|
||||
markers.set_roadmap_cycle(
|
||||
task, {"goal": "Close onboarding friction", "items": items}
|
||||
)
|
||||
await session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _svc(session: AsyncSession) -> RoadmapService:
|
||||
return get_roadmap_service(session)
|
||||
|
||||
|
||||
def _id(task: TaskTable) -> UUID:
|
||||
return cast("UUID", task.id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_materializes_backlog_task(db_session: AsyncSession) -> None:
|
||||
await _seed_project(db_session, "backend-svc")
|
||||
task = await _seed_cycle(db_session, project_slug="backend-svc")
|
||||
result = await _svc(db_session).approve_item(
|
||||
_id(task), "item-0", created_by=CEO_UUID
|
||||
)
|
||||
assert result is not None
|
||||
assert result.status == "approved"
|
||||
assert result.materialized_task_id is not None
|
||||
|
||||
materialized = await db_session.get(TaskTable, result.materialized_task_id)
|
||||
assert materialized is not None
|
||||
assert materialized.status == TS.BACKLOG
|
||||
assert materialized.source == ROADMAP_ITEM_SOURCE
|
||||
assert materialized.team == Team.BACKEND
|
||||
|
||||
await db_session.refresh(task)
|
||||
payload = markers.get_roadmap_cycle(task)
|
||||
assert payload is not None
|
||||
item0 = next(i for i in payload["items"] if i["id"] == "item-0")
|
||||
assert item0["status"] == "approved"
|
||||
assert item0["materialized_task_id"] == result.materialized_task_id
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_is_idempotent(db_session: AsyncSession) -> None:
|
||||
await _seed_project(db_session, "backend-svc")
|
||||
task = await _seed_cycle(db_session, project_slug="backend-svc")
|
||||
svc = _svc(db_session)
|
||||
first = await svc.approve_item(_id(task), "item-0", created_by=CEO_UUID)
|
||||
second = await svc.approve_item(_id(task), "item-0", created_by=CEO_UUID)
|
||||
assert first is not None
|
||||
assert second is not None
|
||||
assert second.status == "already_approved"
|
||||
assert second.materialized_task_id == first.materialized_task_id
|
||||
|
||||
# No duplicate BACKLOG task was created for the second approve — scoped to
|
||||
# this item's own (test-unique) title since the source column is shared
|
||||
# across the whole (persistent, cross-test) database.
|
||||
result = await db_session.execute(
|
||||
select(TaskTable).where(
|
||||
TaskTable.source == ROADMAP_ITEM_SOURCE, TaskTable.title == "Item 0"
|
||||
)
|
||||
)
|
||||
assert len(result.scalars().all()) == ONE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_records_reason(db_session: AsyncSession) -> None:
|
||||
await _seed_project(db_session, "backend-svc")
|
||||
task = await _seed_cycle(db_session, project_slug="backend-svc")
|
||||
result = await _svc(db_session).reject_item(
|
||||
_id(task), "item-0", "not a priority this quarter"
|
||||
)
|
||||
assert result is not None
|
||||
assert result.status == "rejected"
|
||||
|
||||
await db_session.refresh(task)
|
||||
payload = markers.get_roadmap_cycle(task)
|
||||
assert payload is not None
|
||||
item0 = next(i for i in payload["items"] if i["id"] == "item-0")
|
||||
assert item0["status"] == "rejected"
|
||||
assert item0["reject_reason"] == "not a priority this quarter"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_is_idempotent(db_session: AsyncSession) -> None:
|
||||
await _seed_project(db_session, "backend-svc")
|
||||
task = await _seed_cycle(db_session, project_slug="backend-svc")
|
||||
svc = _svc(db_session)
|
||||
await svc.reject_item(_id(task), "item-0", "reason one")
|
||||
second = await svc.reject_item(_id(task), "item-0", "reason two")
|
||||
assert second is not None
|
||||
assert second.status == "already_rejected"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cannot_reject_an_approved_item(db_session: AsyncSession) -> None:
|
||||
await _seed_project(db_session, "backend-svc")
|
||||
task = await _seed_cycle(db_session, project_slug="backend-svc")
|
||||
svc = _svc(db_session)
|
||||
await svc.approve_item(_id(task), "item-0", created_by=CEO_UUID)
|
||||
result = await svc.reject_item(_id(task), "item-0", "changed my mind")
|
||||
assert result is not None
|
||||
assert result.status == "invalid_state"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_cannot_approve_a_rejected_item(db_session: AsyncSession) -> None:
|
||||
await _seed_project(db_session, "backend-svc")
|
||||
task = await _seed_cycle(db_session, project_slug="backend-svc")
|
||||
svc = _svc(db_session)
|
||||
await svc.reject_item(_id(task), "item-0", "not now")
|
||||
result = await svc.approve_item(_id(task), "item-0", created_by=CEO_UUID)
|
||||
assert result is not None
|
||||
assert result.status == "invalid_state"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_all_items_terminal_completes_exploration_task(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
await _seed_project(db_session, "backend-svc")
|
||||
task = await _seed_cycle(db_session, project_slug="backend-svc")
|
||||
svc = _svc(db_session)
|
||||
await svc.approve_item(_id(task), "item-0", created_by=CEO_UUID)
|
||||
assert task.status == TS.PENDING # one item still proposed
|
||||
await svc.reject_item(_id(task), "item-1", "not now")
|
||||
assert task.status == TS.COMPLETED # both items terminal
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_unknown_project_slug_is_invalid_state(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
task = await _seed_cycle(db_session, project_slug="no-such-project")
|
||||
result = await _svc(db_session).approve_item(
|
||||
_id(task), "item-0", created_by=CEO_UUID
|
||||
)
|
||||
assert result is not None
|
||||
assert result.status == "invalid_state"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_task_returns_none(db_session: AsyncSession) -> None:
|
||||
result = await _svc(db_session).approve_item(uuid4(), "item-0", created_by=CEO_UUID)
|
||||
assert result is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_unknown_item_id_returns_none(db_session: AsyncSession) -> None:
|
||||
await _seed_project(db_session, "backend-svc")
|
||||
task = await _seed_cycle(db_session, project_slug="backend-svc")
|
||||
result = await _svc(db_session).approve_item(
|
||||
_id(task), "item-999", created_by=CEO_UUID
|
||||
)
|
||||
assert result is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_open_cycles_excludes_completed(db_session: AsyncSession) -> None:
|
||||
await _seed_project(db_session, "backend-svc")
|
||||
task = await _seed_cycle(
|
||||
db_session,
|
||||
items=[_item(0, project_slug="backend-svc")],
|
||||
project_slug="backend-svc",
|
||||
)
|
||||
svc = _svc(db_session)
|
||||
open_before = await svc.list_open_cycles()
|
||||
assert task.id in {t.id for t in open_before}
|
||||
await svc.approve_item(_id(task), "item-0", created_by=CEO_UUID)
|
||||
open_after = await svc.list_open_cycles()
|
||||
assert task.id not in {t.id for t in open_after}
|
||||
@@ -0,0 +1,196 @@
|
||||
"""XClient coverage: OAuth1 signing, NullXClient no-op, LiveXClient calls."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
from roboco.services.x_client import (
|
||||
MAX_TWEET_CHARS,
|
||||
LiveXClient,
|
||||
NullXClient,
|
||||
build_x_client,
|
||||
oauth1_authorization_header,
|
||||
)
|
||||
from roboco.services.x_credentials import XCredentialsData
|
||||
|
||||
_CREDS = XCredentialsData(
|
||||
api_key="xvz1evFS4wEEPTGEFPHBog",
|
||||
api_secret="kAcSOqF21Fu85e7zjz7ZN2U4ZRhfV3WpwPAoE3Z7kBw",
|
||||
access_token="370773112-GmHxMAgYyLbNEtIKZeRNFsMKPR9EyMYzoCgnCU0r",
|
||||
access_token_secret="LswwdoUaIvS8ltyTt5jkRh4J50vUPVVHtR2YPi5kE",
|
||||
)
|
||||
_EXPECTED_LIKE_COUNT = 3
|
||||
|
||||
|
||||
def test_null_client_is_unconfigured_and_never_raises() -> None:
|
||||
client = build_x_client(None, account_user_id="", timeout=5.0)
|
||||
assert isinstance(client, NullXClient)
|
||||
assert client.configured is False
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_null_client_post_tweet_is_a_noop() -> None:
|
||||
client: NullXClient = NullXClient()
|
||||
result = await client.post_tweet("hello")
|
||||
assert result.posted is False
|
||||
assert result.tweet_id is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_null_client_fetch_mentions_returns_empty() -> None:
|
||||
client: NullXClient = NullXClient()
|
||||
mentions = await client.fetch_mentions(since_id=None, max_results=10)
|
||||
assert mentions == []
|
||||
|
||||
|
||||
def test_build_x_client_with_creds_returns_live_client() -> None:
|
||||
client = build_x_client(_CREDS, account_user_id="123", timeout=5.0)
|
||||
assert isinstance(client, LiveXClient)
|
||||
assert client.configured is True
|
||||
|
||||
|
||||
def test_oauth1_header_has_expected_shape() -> None:
|
||||
header = oauth1_authorization_header(
|
||||
"POST", "https://api.twitter.com/2/tweets", _CREDS
|
||||
)
|
||||
assert header.startswith("OAuth ")
|
||||
for key in (
|
||||
"oauth_consumer_key",
|
||||
"oauth_nonce",
|
||||
"oauth_signature_method",
|
||||
"oauth_timestamp",
|
||||
"oauth_token",
|
||||
"oauth_version",
|
||||
"oauth_signature",
|
||||
):
|
||||
assert f'{key}="' in header
|
||||
assert 'oauth_signature_method="HMAC-SHA1"' in header
|
||||
|
||||
|
||||
def test_oauth1_header_signature_is_deterministic_for_fixed_inputs(
|
||||
monkeypatch: pytest.MonkeyPatch,
|
||||
) -> None:
|
||||
"""A known nonce + timestamp must always produce the same signature —
|
||||
proves the HMAC-SHA1 base-string construction is stable/reproducible."""
|
||||
monkeypatch.setattr("secrets.token_hex", lambda _n: "kYjzVBB8Y0ZFabxSWbWovY")
|
||||
monkeypatch.setattr("time.time", lambda: 1318622958.0)
|
||||
header_1 = oauth1_authorization_header(
|
||||
"GET", "https://api.twitter.com/2/users/me", _CREDS
|
||||
)
|
||||
monkeypatch.setattr("secrets.token_hex", lambda _n: "kYjzVBB8Y0ZFabxSWbWovY")
|
||||
monkeypatch.setattr("time.time", lambda: 1318622958.0)
|
||||
header_2 = oauth1_authorization_header(
|
||||
"GET", "https://api.twitter.com/2/users/me", _CREDS
|
||||
)
|
||||
assert header_1 == header_2
|
||||
signature_1 = re.search(r'oauth_signature="([^"]+)"', header_1)
|
||||
assert signature_1 is not None
|
||||
assert len(signature_1.group(1)) > 0
|
||||
|
||||
|
||||
def test_oauth1_header_query_params_affect_signature() -> None:
|
||||
header_a = oauth1_authorization_header(
|
||||
"GET",
|
||||
"https://api.twitter.com/2/users/123/mentions",
|
||||
_CREDS,
|
||||
{"max_results": "5"},
|
||||
)
|
||||
header_b = oauth1_authorization_header(
|
||||
"GET",
|
||||
"https://api.twitter.com/2/users/123/mentions",
|
||||
_CREDS,
|
||||
{"max_results": "10"},
|
||||
)
|
||||
sig_a = re.search(r'oauth_signature="([^"]+)"', header_a)
|
||||
sig_b = re.search(r'oauth_signature="([^"]+)"', header_b)
|
||||
assert sig_a is not None
|
||||
assert sig_b is not None
|
||||
assert sig_a.group(1) != sig_b.group(1) # different signed params -> different sig
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_client_post_tweet_success() -> None:
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
assert request.headers["Authorization"].startswith("OAuth ")
|
||||
return httpx.Response(201, json={"data": {"id": "12345", "text": "hi"}})
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
http_client = httpx.AsyncClient(transport=transport)
|
||||
client = LiveXClient(_CREDS, account_user_id="1", timeout=5.0, client=http_client)
|
||||
result = await client.post_tweet("hi")
|
||||
assert result.posted is True
|
||||
assert result.tweet_id == "12345"
|
||||
await http_client.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_client_post_tweet_http_error_is_graceful() -> None:
|
||||
def handler(_request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(401, text="unauthorized")
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
http_client = httpx.AsyncClient(transport=transport)
|
||||
client = LiveXClient(_CREDS, account_user_id="1", timeout=5.0, client=http_client)
|
||||
result = await client.post_tweet("hi")
|
||||
assert result.posted is False
|
||||
assert "401" in result.detail
|
||||
await http_client.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_client_fetch_mentions_parses_public_metrics() -> None:
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path.endswith("/mentions"):
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={
|
||||
"data": [
|
||||
{
|
||||
"id": "111",
|
||||
"author_id": "222",
|
||||
"text": "great work @roboco",
|
||||
"public_metrics": {
|
||||
"like_count": 3,
|
||||
"reply_count": 1,
|
||||
"retweet_count": 0,
|
||||
},
|
||||
}
|
||||
]
|
||||
},
|
||||
)
|
||||
raise AssertionError(f"unexpected path {request.url.path}")
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
http_client = httpx.AsyncClient(transport=transport)
|
||||
client = LiveXClient(_CREDS, account_user_id="1", timeout=5.0, client=http_client)
|
||||
mentions = await client.fetch_mentions(since_id=None, max_results=10)
|
||||
assert len(mentions) == 1
|
||||
assert mentions[0].id == "111"
|
||||
assert mentions[0].like_count == _EXPECTED_LIKE_COUNT
|
||||
await http_client.aclose()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_live_client_resolves_account_id_via_users_me_when_unset() -> None:
|
||||
calls: list[str] = []
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
calls.append(request.url.path)
|
||||
if request.url.path.endswith("/users/me"):
|
||||
return httpx.Response(200, json={"data": {"id": "999"}})
|
||||
return httpx.Response(200, json={"data": []})
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
http_client = httpx.AsyncClient(transport=transport)
|
||||
client = LiveXClient(_CREDS, account_user_id="", timeout=5.0, client=http_client)
|
||||
await client.fetch_mentions(since_id=None, max_results=10)
|
||||
assert any(p.endswith("/users/me") for p in calls)
|
||||
assert any(p.endswith("/users/999/mentions") for p in calls)
|
||||
await http_client.aclose()
|
||||
|
||||
|
||||
def test_max_tweet_chars_is_280() -> None:
|
||||
expected = 280
|
||||
assert expected == MAX_TWEET_CHARS
|
||||
@@ -0,0 +1,440 @@
|
||||
"""XEngine coverage: release-post drafting + mentions poll, held/deduped/capped.
|
||||
|
||||
Mirrors the release-manager engine tests: flag-gated, no-creds no-ops, drafts
|
||||
via the local model (mocked here), enforces the 280-char limit, dedupes
|
||||
mentions by id, and caps origination per cycle + rolling open count. Never
|
||||
posts — asserted against a real Postgres DB.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import pytest
|
||||
from roboco.config import settings as cfg
|
||||
from roboco.db.tables import AgentTable, ProjectTable
|
||||
from roboco.foundation import identity as _foundation
|
||||
from roboco.foundation.policy.content import markers
|
||||
from roboco.models.base import AgentRole, AgentStatus, Team
|
||||
from roboco.models.base import TaskStatus as TS
|
||||
from roboco.services import x_engine as x_engine_module
|
||||
from roboco.services.task import X_POST_SOURCE, X_REPLY_SOURCE, get_task_service
|
||||
from roboco.services.x_client import MAX_TWEET_CHARS, XClient, XMention, XPostResult
|
||||
from sqlalchemy import select
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
SYSTEM_UUID = _foundation.AGENTS["system"].uuid
|
||||
SECRETARY_UUID = _foundation.AGENTS["secretary-1"].uuid
|
||||
SLUG = "roboco"
|
||||
ONE = 1
|
||||
TWO = 2
|
||||
_VERSION = "0.17.0"
|
||||
|
||||
|
||||
class _FakeClient(XClient):
|
||||
"""A configured stub — never touches the network."""
|
||||
|
||||
def __init__(self, mentions: list[XMention] | None = None) -> None:
|
||||
self._mentions = mentions or []
|
||||
self.posted: list[str] = []
|
||||
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
return True
|
||||
|
||||
async def post_tweet(self, text: str) -> XPostResult:
|
||||
self.posted.append(text)
|
||||
return XPostResult(posted=True, tweet_id="1", detail="ok")
|
||||
|
||||
async def fetch_mentions(
|
||||
self, since_id: str | None, max_results: int
|
||||
) -> list[XMention]:
|
||||
_ = (since_id, max_results)
|
||||
return self._mentions
|
||||
|
||||
|
||||
class _NullClient(XClient):
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
return False
|
||||
|
||||
async def post_tweet(self, text: str) -> XPostResult:
|
||||
_ = text
|
||||
return XPostResult(posted=False, tweet_id=None, detail="no creds")
|
||||
|
||||
async def fetch_mentions(
|
||||
self, since_id: str | None, max_results: int
|
||||
) -> list[XMention]:
|
||||
_ = (since_id, max_results)
|
||||
return []
|
||||
|
||||
|
||||
async def _seed(session: AsyncSession) -> None:
|
||||
for uuid, slug, role in (
|
||||
(SYSTEM_UUID, "system", AgentRole.SYSTEM),
|
||||
(SECRETARY_UUID, "secretary-1", AgentRole.SECRETARY),
|
||||
):
|
||||
if await session.get(AgentTable, uuid) is None:
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=uuid,
|
||||
name=slug,
|
||||
slug=slug,
|
||||
role=role,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
existing = await session.execute(
|
||||
select(ProjectTable).where(ProjectTable.slug == SLUG)
|
||||
)
|
||||
if existing.scalar_one_or_none() is None:
|
||||
session.add(
|
||||
ProjectTable(
|
||||
name="RoboCo",
|
||||
slug=SLUG,
|
||||
git_url="https://github.com/x/roboco.git",
|
||||
default_branch="master",
|
||||
protected_branches=["master"],
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=SYSTEM_UUID,
|
||||
is_active=True,
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
|
||||
|
||||
def _enable(monkeypatch: pytest.MonkeyPatch, **overrides: object) -> None:
|
||||
monkeypatch.setattr(cfg, "x_engine_enabled", True)
|
||||
monkeypatch.setattr(cfg, "x_replies_enabled", True)
|
||||
monkeypatch.setattr(cfg, "self_heal_project_slug", SLUG)
|
||||
monkeypatch.setattr(cfg, "x_max_open_posts", 10)
|
||||
monkeypatch.setattr(cfg, "x_mentions_max_per_cycle", 5)
|
||||
monkeypatch.setattr(cfg, "x_mentions_min_engagement", 0)
|
||||
for key, value in overrides.items():
|
||||
monkeypatch.setattr(cfg, key, value)
|
||||
|
||||
|
||||
def _mock_local_model(monkeypatch: pytest.MonkeyPatch, reply: str | None) -> AsyncMock:
|
||||
mock = AsyncMock(return_value=reply)
|
||||
monkeypatch.setattr(x_engine_module, "_chat", mock)
|
||||
return mock
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Release-post drafting
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disabled_drafts_no_release_post(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
monkeypatch.setattr(cfg, "x_engine_enabled", False)
|
||||
engine = x_engine_module.XEngine(db_session, client=_FakeClient())
|
||||
task = await engine.draft_release_post(version=_VERSION, highlights=["feat: x"])
|
||||
assert task is None
|
||||
assert await get_task_service(db_session).list_open_x_posts() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_credentials_drafts_no_release_post(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
engine = x_engine_module.XEngine(db_session, client=_NullClient())
|
||||
task = await engine.draft_release_post(version=_VERSION, highlights=["feat: x"])
|
||||
assert task is None
|
||||
assert await get_task_service(db_session).list_open_x_posts() == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_draft_release_post_holds_one_proposal(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
_mock_local_model(monkeypatch, "RoboCo just shipped a great new feature!")
|
||||
engine = x_engine_module.XEngine(db_session, client=_FakeClient())
|
||||
task = await engine.draft_release_post(
|
||||
version=_VERSION, highlights=["feat: new thing"]
|
||||
)
|
||||
assert task is not None
|
||||
assert task.status == TS.PENDING
|
||||
assert task.confirmed_by_human is False
|
||||
assert task.assigned_to == SECRETARY_UUID
|
||||
assert task.source == X_POST_SOURCE
|
||||
assert markers.get_x_release_version(task) == _VERSION
|
||||
body = markers.get_x_draft_body(task)
|
||||
assert body is not None
|
||||
assert "RoboCo" in body
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_release_post_body_enforces_280_chars(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
_mock_local_model(monkeypatch, "x" * 500) # a runaway local-model draft
|
||||
engine = x_engine_module.XEngine(db_session, client=_FakeClient())
|
||||
task = await engine.draft_release_post(version=_VERSION, highlights=[])
|
||||
assert task is not None
|
||||
body = markers.get_x_draft_body(task)
|
||||
assert body is not None
|
||||
assert len(body) <= MAX_TWEET_CHARS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_release_post_falls_back_when_local_model_fails(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
mock = AsyncMock(side_effect=RuntimeError("ollama down"))
|
||||
monkeypatch.setattr(x_engine_module, "_chat", mock)
|
||||
engine = x_engine_module.XEngine(db_session, client=_FakeClient())
|
||||
task = await engine.draft_release_post(
|
||||
version=_VERSION, highlights=["feat: still works"]
|
||||
)
|
||||
assert task is not None
|
||||
body = markers.get_x_draft_body(task)
|
||||
assert body is not None
|
||||
assert _VERSION in body
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_draft_release_post_dedupes_same_version(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
_mock_local_model(monkeypatch, "shipped!")
|
||||
engine = x_engine_module.XEngine(db_session, client=_FakeClient())
|
||||
await engine.draft_release_post(version=_VERSION, highlights=[])
|
||||
await engine.draft_release_post(version=_VERSION, highlights=[])
|
||||
open_posts = await get_task_service(db_session).list_open_x_posts()
|
||||
assert len(open_posts) == ONE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_draft_release_post_respects_open_cap(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch, x_max_open_posts=1)
|
||||
_mock_local_model(monkeypatch, "shipped!")
|
||||
engine = x_engine_module.XEngine(db_session, client=_FakeClient())
|
||||
await engine.draft_release_post(version="1.0.0", highlights=[])
|
||||
task = await engine.draft_release_post(version="2.0.0", highlights=[])
|
||||
assert task is None
|
||||
open_posts = await get_task_service(db_session).list_open_x_posts()
|
||||
assert len(open_posts) == ONE
|
||||
|
||||
|
||||
# --------------------------------------------------------------------------- #
|
||||
# Mentions poll
|
||||
# --------------------------------------------------------------------------- #
|
||||
|
||||
|
||||
def _mention(
|
||||
mid: str, text: str = "great work @roboco", engagement: int = 1
|
||||
) -> XMention:
|
||||
return XMention(
|
||||
id=mid,
|
||||
author_id="author-1",
|
||||
text=text,
|
||||
like_count=engagement,
|
||||
reply_count=0,
|
||||
retweet_count=0,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_disabled_run_cycle_originates_nothing(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
monkeypatch.setattr(cfg, "x_engine_enabled", False)
|
||||
engine = x_engine_module.XEngine(
|
||||
db_session, client=_FakeClient(mentions=[_mention("m1")])
|
||||
)
|
||||
result = await engine.run_cycle()
|
||||
assert result == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_run_cycle_noop_when_replies_disabled(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Engine on but the mention-reply sub-switch off: the poll cycle drafts
|
||||
nothing (release posting is a separate, still-enabled path)."""
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch, x_replies_enabled=False)
|
||||
_mock_local_model(monkeypatch, "Thanks!")
|
||||
engine = x_engine_module.XEngine(
|
||||
db_session, client=_FakeClient(mentions=[_mention("m1")])
|
||||
)
|
||||
result = await engine.run_cycle()
|
||||
assert result == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_release_post_holds_even_when_replies_disabled(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Release posting is decoupled from the mention-reply sub-switch: a
|
||||
release draft is still held with replies off."""
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch, x_replies_enabled=False)
|
||||
_mock_local_model(monkeypatch, "RoboCo shipped something great!")
|
||||
engine = x_engine_module.XEngine(db_session, client=_FakeClient())
|
||||
task = await engine.draft_release_post(version=_VERSION, highlights=["feat: x"])
|
||||
assert task is not None
|
||||
assert task.source == X_POST_SOURCE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_no_credentials_run_cycle_originates_nothing(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
engine = x_engine_module.XEngine(db_session, client=_NullClient())
|
||||
result = await engine.run_cycle()
|
||||
assert result == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_meaningful_mention_holds_reply_proposal(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
_mock_local_model(monkeypatch, "Thanks so much for the shoutout!")
|
||||
engine = x_engine_module.XEngine(
|
||||
db_session, client=_FakeClient(mentions=[_mention("m1")])
|
||||
)
|
||||
result = await engine.run_cycle()
|
||||
assert len(result) == ONE
|
||||
task = result[0]
|
||||
assert task.source == X_REPLY_SOURCE
|
||||
assert task.confirmed_by_human is False
|
||||
assert task.assigned_to == SECRETARY_UUID
|
||||
ref = markers.get_x_mention_ref(task)
|
||||
assert ref is not None
|
||||
assert ref["id"] == "m1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_bot_like_mention_is_filtered_out(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
_mock_local_model(monkeypatch, "reply")
|
||||
engine = x_engine_module.XEngine(
|
||||
db_session, client=_FakeClient(mentions=[_mention("m1", text="RT spam")])
|
||||
)
|
||||
result = await engine.run_cycle()
|
||||
assert result == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_below_engagement_floor_is_filtered_out(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch, x_mentions_min_engagement=5)
|
||||
_mock_local_model(monkeypatch, "reply")
|
||||
engine = x_engine_module.XEngine(
|
||||
db_session, client=_FakeClient(mentions=[_mention("m1", engagement=1)])
|
||||
)
|
||||
result = await engine.run_cycle()
|
||||
assert result == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mentions_dedupe_across_cycles(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
_mock_local_model(monkeypatch, "reply")
|
||||
client = _FakeClient(mentions=[_mention("m1")])
|
||||
engine = x_engine_module.XEngine(db_session, client=client)
|
||||
first = await engine.run_cycle()
|
||||
second = await engine.run_cycle()
|
||||
assert len(first) == ONE
|
||||
assert second == [] # same mention id -> already seen, not re-proposed
|
||||
open_posts = await get_task_service(db_session).list_open_x_posts()
|
||||
assert len(open_posts) == ONE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mentions_per_cycle_cap(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch, x_mentions_max_per_cycle=2)
|
||||
_mock_local_model(monkeypatch, "reply")
|
||||
mentions = [_mention(f"m{i}") for i in range(5)]
|
||||
engine = x_engine_module.XEngine(db_session, client=_FakeClient(mentions=mentions))
|
||||
result = await engine.run_cycle()
|
||||
assert len(result) == TWO
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_mentions_respect_open_cap(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch, x_max_open_posts=1, x_mentions_max_per_cycle=5)
|
||||
_mock_local_model(monkeypatch, "reply")
|
||||
mentions = [_mention(f"cap{i}") for i in range(3)]
|
||||
engine = x_engine_module.XEngine(db_session, client=_FakeClient(mentions=mentions))
|
||||
result = await engine.run_cycle()
|
||||
assert len(result) == ONE
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reply_body_enforces_280_chars(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
_mock_local_model(monkeypatch, "y" * 400)
|
||||
engine = x_engine_module.XEngine(
|
||||
db_session, client=_FakeClient(mentions=[_mention("m1")])
|
||||
)
|
||||
result = await engine.run_cycle()
|
||||
assert len(result) == ONE
|
||||
body = markers.get_x_draft_body(result[0])
|
||||
assert body is not None
|
||||
assert len(body) <= MAX_TWEET_CHARS
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_engine_never_calls_post_tweet(
|
||||
db_session: AsyncSession, monkeypatch: pytest.MonkeyPatch
|
||||
) -> None:
|
||||
"""Neither responsibility ever posts — that is XPostService's job only."""
|
||||
await _seed(db_session)
|
||||
_enable(monkeypatch)
|
||||
_mock_local_model(monkeypatch, "reply")
|
||||
client = _FakeClient(mentions=[_mention("m1")])
|
||||
engine = x_engine_module.XEngine(db_session, client=client)
|
||||
await engine.run_cycle()
|
||||
await engine.draft_release_post(version=_VERSION, highlights=[])
|
||||
assert client.posted == []
|
||||
@@ -0,0 +1,317 @@
|
||||
"""XPostService coverage: approve posts (idempotent), reject cancels.
|
||||
|
||||
Mirrors the release-proposal service tests. The Redis lock helpers are
|
||||
patched (no live Redis in tests, matching the project's ``_no_live_redis``
|
||||
fixture) so approve exercises the real post + status-transition path.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, cast
|
||||
from unittest.mock import AsyncMock, patch
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
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.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.task import X_POST_SOURCE, X_REPLY_SOURCE
|
||||
from roboco.services.x_client import XClient, XMention, XPostResult
|
||||
from roboco.services.x_post_service import (
|
||||
XPostBodyTooLongError,
|
||||
XPostService,
|
||||
get_x_post_service,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
SYSTEM_UUID = _foundation.AGENTS["system"].uuid
|
||||
SECRETARY_UUID = _foundation.AGENTS["secretary-1"].uuid
|
||||
ONE = 1
|
||||
|
||||
|
||||
class _StubClient(XClient):
|
||||
def __init__(self, *, posted: bool = True, tweet_id: str = "999") -> None:
|
||||
self._posted = posted
|
||||
self._tweet_id = tweet_id
|
||||
self.calls: list[str] = []
|
||||
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
return True
|
||||
|
||||
async def post_tweet(self, text: str) -> XPostResult:
|
||||
self.calls.append(text)
|
||||
if not self._posted:
|
||||
return XPostResult(posted=False, tweet_id=None, detail="rejected by X")
|
||||
return XPostResult(posted=True, tweet_id=self._tweet_id, detail="posted")
|
||||
|
||||
async def fetch_mentions(
|
||||
self, since_id: str | None, max_results: int
|
||||
) -> list[XMention]:
|
||||
_ = (since_id, max_results)
|
||||
return []
|
||||
|
||||
|
||||
async def _seed_draft(
|
||||
session: AsyncSession, *, source: str = X_POST_SOURCE, body: str = "Draft body"
|
||||
) -> TaskTable:
|
||||
for uuid, slug, role in (
|
||||
(SYSTEM_UUID, "system", AgentRole.SYSTEM),
|
||||
(SECRETARY_UUID, "secretary-1", AgentRole.SECRETARY),
|
||||
):
|
||||
if await session.get(AgentTable, uuid) is None:
|
||||
session.add(
|
||||
AgentTable(
|
||||
id=uuid,
|
||||
name=slug,
|
||||
slug=slug,
|
||||
role=role,
|
||||
team=None,
|
||||
status=AgentStatus.ACTIVE,
|
||||
model_config={},
|
||||
system_prompt="x",
|
||||
capabilities=[],
|
||||
permissions={},
|
||||
metrics={},
|
||||
)
|
||||
)
|
||||
await session.flush()
|
||||
project = ProjectTable(
|
||||
id=uuid4(),
|
||||
name="RoboCo",
|
||||
slug=f"roboco-{uuid4().hex[:6]}",
|
||||
git_url="https://example.com/roboco.git",
|
||||
assigned_cell=Team.BACKEND,
|
||||
created_by=SYSTEM_UUID,
|
||||
)
|
||||
session.add(project)
|
||||
await session.flush()
|
||||
task = TaskTable(
|
||||
id=uuid4(),
|
||||
title="X draft",
|
||||
description=body,
|
||||
acceptance_criteria=["CEO approves or rejects"],
|
||||
status=TS.PENDING,
|
||||
priority=2,
|
||||
task_type=TT.ADMINISTRATIVE,
|
||||
nature=TN.NON_TECHNICAL,
|
||||
estimated_complexity=Complexity.LOW,
|
||||
project_id=project.id,
|
||||
created_by=SYSTEM_UUID,
|
||||
assigned_to=SECRETARY_UUID,
|
||||
team=Team.MAIN_PM,
|
||||
source=source,
|
||||
confirmed_by_human=False,
|
||||
)
|
||||
session.add(task)
|
||||
await session.flush()
|
||||
markers.set_x_draft_body(task, body)
|
||||
await session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _svc(session: AsyncSession) -> XPostService:
|
||||
return get_x_post_service(session)
|
||||
|
||||
|
||||
def _id(task: TaskTable) -> UUID:
|
||||
"""The ORM id typed as stdlib ``uuid.UUID`` for service-call sites."""
|
||||
return cast("UUID", task.id)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_posts_and_completes(db_session: AsyncSession) -> None:
|
||||
task = await _seed_draft(db_session)
|
||||
client = _StubClient()
|
||||
with (
|
||||
patch("roboco.services.x_post_service.build_x_client", return_value=client),
|
||||
patch.object(XPostService, "_acquire_lock", AsyncMock(return_value="tok")),
|
||||
patch.object(XPostService, "_release_lock", AsyncMock(return_value=None)),
|
||||
):
|
||||
result = await _svc(db_session).approve(_id(task))
|
||||
assert result is not None
|
||||
assert result.status == "posted"
|
||||
assert result.tweet_id == "999"
|
||||
assert client.calls == ["Draft body"]
|
||||
await db_session.refresh(task)
|
||||
assert task.status == TS.COMPLETED
|
||||
assert markers.get_x_posted_tweet_id(task) == "999"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_is_idempotent_second_call_is_noop(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
task = await _seed_draft(db_session)
|
||||
client = _StubClient()
|
||||
with (
|
||||
patch("roboco.services.x_post_service.build_x_client", return_value=client),
|
||||
patch.object(XPostService, "_acquire_lock", AsyncMock(return_value="tok")),
|
||||
patch.object(XPostService, "_release_lock", AsyncMock(return_value=None)),
|
||||
):
|
||||
svc = _svc(db_session)
|
||||
first = await svc.approve(_id(task))
|
||||
second = await svc.approve(_id(task))
|
||||
assert first is not None
|
||||
assert first.status == "posted"
|
||||
assert second is not None
|
||||
assert second.status == "already_posted"
|
||||
assert second.tweet_id == "999"
|
||||
# The X client was called exactly once — the second approve never re-posts.
|
||||
assert client.calls == ["Draft body"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_with_edited_body_posts_the_edit(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
task = await _seed_draft(db_session, body="Original")
|
||||
client = _StubClient()
|
||||
with (
|
||||
patch("roboco.services.x_post_service.build_x_client", return_value=client),
|
||||
patch.object(XPostService, "_acquire_lock", AsyncMock(return_value="tok")),
|
||||
patch.object(XPostService, "_release_lock", AsyncMock(return_value=None)),
|
||||
):
|
||||
result = await _svc(db_session).approve(_id(task), "Edited body")
|
||||
assert result is not None
|
||||
assert result.status == "posted"
|
||||
assert client.calls == ["Edited body"]
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_rejects_edited_body_over_280_chars(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
task = await _seed_draft(db_session)
|
||||
with pytest.raises(XPostBodyTooLongError):
|
||||
await _svc(db_session).approve(_id(task), "x" * 281)
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_no_credentials_result(db_session: AsyncSession) -> None:
|
||||
task = await _seed_draft(db_session)
|
||||
no_creds_client = _StubClient()
|
||||
|
||||
class _Null(XClient):
|
||||
@property
|
||||
def configured(self) -> bool:
|
||||
return False
|
||||
|
||||
async def post_tweet(self, text: str) -> XPostResult:
|
||||
_ = text
|
||||
return XPostResult(posted=False, tweet_id=None, detail="no creds")
|
||||
|
||||
async def fetch_mentions(
|
||||
self, since_id: str | None, max_results: int
|
||||
) -> list[XMention]:
|
||||
_ = (since_id, max_results)
|
||||
return []
|
||||
|
||||
_ = no_creds_client
|
||||
with (
|
||||
patch("roboco.services.x_post_service.build_x_client", return_value=_Null()),
|
||||
patch.object(XPostService, "_acquire_lock", AsyncMock(return_value="tok")),
|
||||
patch.object(XPostService, "_release_lock", AsyncMock(return_value=None)),
|
||||
):
|
||||
result = await _svc(db_session).approve(_id(task))
|
||||
assert result is not None
|
||||
assert result.status == "no_credentials"
|
||||
await db_session.refresh(task)
|
||||
assert task.status == TS.PENDING # never advanced without credentials
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_post_failed_keeps_task_open(db_session: AsyncSession) -> None:
|
||||
task = await _seed_draft(db_session)
|
||||
client = _StubClient(posted=False)
|
||||
with (
|
||||
patch("roboco.services.x_post_service.build_x_client", return_value=client),
|
||||
patch.object(XPostService, "_acquire_lock", AsyncMock(return_value="tok")),
|
||||
patch.object(XPostService, "_release_lock", AsyncMock(return_value=None)),
|
||||
):
|
||||
result = await _svc(db_session).approve(_id(task))
|
||||
assert result is not None
|
||||
assert result.status == "post_failed"
|
||||
await db_session.refresh(task)
|
||||
assert task.status == TS.PENDING
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_rechecks_completed_under_lock_and_never_reposts(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
"""The double-post guard: a concurrent approve wins the lock, posts, and
|
||||
commits COMPLETED after our pre-lock read. Once we acquire the lock, the
|
||||
in-lock re-read must see COMPLETED and short-circuit — never re-posting."""
|
||||
task = await _seed_draft(db_session)
|
||||
client = _StubClient()
|
||||
|
||||
async def _win_the_race(_self: XPostService, _key: str) -> str:
|
||||
# Simulate the concurrent winner: the row is COMPLETED (posted) by the
|
||||
# time we hold the lock, exactly as the in-lock expire()+re-fetch sees.
|
||||
markers.set_x_posted_tweet_id(task, "111")
|
||||
task.status = TS.COMPLETED
|
||||
await db_session.flush()
|
||||
return "tok"
|
||||
|
||||
with (
|
||||
patch("roboco.services.x_post_service.build_x_client", return_value=client),
|
||||
patch.object(XPostService, "_acquire_lock", _win_the_race),
|
||||
patch.object(XPostService, "_release_lock", AsyncMock(return_value=None)),
|
||||
):
|
||||
result = await _svc(db_session).approve(_id(task))
|
||||
assert result is not None
|
||||
assert result.status == "already_posted"
|
||||
assert result.tweet_id == "111"
|
||||
# The tweet was never posted a second time.
|
||||
assert client.calls == []
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_concurrent_lock_held_returns_in_progress(
|
||||
db_session: AsyncSession,
|
||||
) -> None:
|
||||
task = await _seed_draft(db_session)
|
||||
with patch.object(XPostService, "_acquire_lock", AsyncMock(return_value=None)):
|
||||
result = await _svc(db_session).approve(_id(task))
|
||||
assert result is not None
|
||||
assert result.status == "already_in_progress"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_approve_unknown_task_returns_none(db_session: AsyncSession) -> None:
|
||||
result = await _svc(db_session).approve(uuid4())
|
||||
assert result is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_reject_records_reason_and_cancels(db_session: AsyncSession) -> None:
|
||||
task = await _seed_draft(db_session, source=X_REPLY_SOURCE)
|
||||
updated = await _svc(db_session).reject(_id(task), "Tone doesn't match our voice")
|
||||
assert updated is not None
|
||||
assert updated.status == TS.CANCELLED
|
||||
assert markers.get_x_reject_reason(updated) == "Tone doesn't match our voice"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_list_open_posts_excludes_terminal(db_session: AsyncSession) -> None:
|
||||
open_task = await _seed_draft(db_session)
|
||||
rejected_task = await _seed_draft(db_session, source=X_REPLY_SOURCE)
|
||||
await _svc(db_session).reject(_id(rejected_task), "not relevant")
|
||||
open_posts = await _svc(db_session).list_open_posts()
|
||||
ids = {t.id for t in open_posts}
|
||||
assert open_task.id in ids
|
||||
assert rejected_task.id not in ids
|
||||
Reference in New Issue
Block a user