mirror of
https://github.com/rennf93/roboco.git
synced 2026-08-03 07:23:24 +02:00
* 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>
1022 lines
33 KiB
Python
1022 lines
33 KiB
Python
"""TelegramInboundEngine coverage: chat-id rejection, offset advancement, and
|
|
one test per approve/reject-kind dispatching to a mocked service (asserting
|
|
CEO identity + reason threading). Every service factory the engine calls is
|
|
monkeypatched module-level — no DB, no network."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from types import SimpleNamespace
|
|
from typing import TYPE_CHECKING, Any, cast
|
|
from unittest.mock import AsyncMock, MagicMock
|
|
from uuid import UUID, uuid4
|
|
|
|
import pytest
|
|
from roboco.models.base import TaskStatus
|
|
from roboco.services import telegram_inbound as ti
|
|
from roboco.services.pest_control_service import PestHuntItemResult
|
|
from roboco.services.roadmap_service import RoadmapItemResult
|
|
from roboco.services.telegram_credentials import TelegramCredentialsData
|
|
from roboco.services.video_post_service import VideoPostExecuteResult
|
|
from roboco.services.x_post_service import XPostExecuteResult
|
|
|
|
if TYPE_CHECKING:
|
|
from roboco.db.tables import TaskTable
|
|
|
|
CEO_UUID = ti._CEO_UUID
|
|
|
|
|
|
def _uuid_with_prefix(prefix: str) -> UUID:
|
|
"""A real UUID whose ``str(uuid)[:8] == prefix`` — the id8 convention."""
|
|
return UUID(hex=prefix + uuid4().hex[len(prefix) :])
|
|
|
|
|
|
def _fake_task(id8: str = "a1b2c3d4", title: str = "Test task") -> SimpleNamespace:
|
|
return SimpleNamespace(
|
|
id=_uuid_with_prefix(id8),
|
|
title=title,
|
|
description="",
|
|
pr_url=None,
|
|
status=SimpleNamespace(value="pending"),
|
|
team=None,
|
|
)
|
|
|
|
|
|
def _fake_session() -> MagicMock:
|
|
"""``session.add`` is sync in real SQLAlchemy (a plain MagicMock call, no
|
|
"never awaited" warning); only the awaited methods this engine actually
|
|
uses get an AsyncMock."""
|
|
session = MagicMock()
|
|
session.commit = AsyncMock()
|
|
session.execute = AsyncMock()
|
|
return session
|
|
|
|
|
|
def _engine() -> ti.TelegramInboundEngine:
|
|
"""A bare engine over a mocked session — nothing in these tests touches
|
|
real DB rows, only the monkeypatched service factories."""
|
|
return ti.TelegramInboundEngine(_fake_session())
|
|
|
|
|
|
CREDS = TelegramCredentialsData(bot_token="123:ABC", chat_id="777")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# chat-id rejection
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unauthorized_chat_message_is_dropped(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
dispatch = AsyncMock()
|
|
monkeypatch.setattr(engine, "_dispatch_command", dispatch)
|
|
client = AsyncMock()
|
|
|
|
await engine._handle_message(
|
|
{"chat": {"id": 999}, "text": "/status"}, CREDS, client
|
|
)
|
|
|
|
dispatch.assert_not_called()
|
|
client.send_message.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_authorized_chat_message_dispatches_command(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
dispatch = AsyncMock()
|
|
monkeypatch.setattr(engine, "_dispatch_command", dispatch)
|
|
client = AsyncMock()
|
|
|
|
await engine._handle_message(
|
|
{"chat": {"id": 777}, "text": "/status"}, CREDS, client
|
|
)
|
|
|
|
dispatch.assert_awaited_once_with("status", "", client, chat_id="777", creds=CREDS)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_unauthorized_chat_callback_answers_not_authorized() -> None:
|
|
engine = _engine()
|
|
client = AsyncMock()
|
|
|
|
await engine._handle_callback(
|
|
{
|
|
"id": "cq1",
|
|
"data": "apv:xpost:a1b2c3d4",
|
|
"message": {"chat": {"id": 999}, "message_id": 5},
|
|
},
|
|
CREDS,
|
|
client,
|
|
)
|
|
|
|
client.answer_callback_query.assert_awaited_once_with("cq1", "Not authorized")
|
|
client.send_message.assert_not_called()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# sender identity — defense-in-depth on top of chat-id authorization
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_message_with_mismatched_sender_is_dropped(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""The right chat, but a `from.id` that disagrees with it (would only
|
|
happen if the "private" chat somehow carried a second poster) — dropped
|
|
silently, same as an unauthorized chat."""
|
|
engine = _engine()
|
|
dispatch = AsyncMock()
|
|
monkeypatch.setattr(engine, "_dispatch_command", dispatch)
|
|
client = AsyncMock()
|
|
|
|
await engine._handle_message(
|
|
{"chat": {"id": 777}, "from": {"id": 999}, "text": "/status"}, CREDS, client
|
|
)
|
|
|
|
dispatch.assert_not_called()
|
|
client.send_message.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_message_with_matching_sender_dispatches(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
dispatch = AsyncMock()
|
|
monkeypatch.setattr(engine, "_dispatch_command", dispatch)
|
|
client = AsyncMock()
|
|
|
|
await engine._handle_message(
|
|
{"chat": {"id": 777}, "from": {"id": 777}, "text": "/status"}, CREDS, client
|
|
)
|
|
|
|
dispatch.assert_awaited_once_with("status", "", client, chat_id="777", creds=CREDS)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_message_without_from_keeps_prior_behavior(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""No `from` on the update at all — the pre-Fix-2 behavior (chat-id-only)
|
|
is unchanged."""
|
|
engine = _engine()
|
|
dispatch = AsyncMock()
|
|
monkeypatch.setattr(engine, "_dispatch_command", dispatch)
|
|
client = AsyncMock()
|
|
|
|
await engine._handle_message(
|
|
{"chat": {"id": 777}, "text": "/status"}, CREDS, client
|
|
)
|
|
|
|
dispatch.assert_awaited_once_with("status", "", client, chat_id="777", creds=CREDS)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_callback_with_mismatched_sender_answers_not_authorized() -> None:
|
|
engine = _engine()
|
|
client = AsyncMock()
|
|
|
|
await engine._handle_callback(
|
|
{
|
|
"id": "cq1",
|
|
"data": "apv:xpost:a1b2c3d4",
|
|
"from": {"id": 999},
|
|
"message": {"chat": {"id": 777}, "message_id": 5},
|
|
},
|
|
CREDS,
|
|
client,
|
|
)
|
|
|
|
client.answer_callback_query.assert_awaited_once_with("cq1", "Not authorized")
|
|
client.send_message.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_callback_with_matching_sender_proceeds(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
client = AsyncMock()
|
|
dispatch = AsyncMock(return_value=(True, "ok"))
|
|
monkeypatch.setattr(engine, "_dispatch_approve", dispatch)
|
|
|
|
await engine._handle_callback(
|
|
{
|
|
"id": "cq1",
|
|
"data": "apv:xpost:a1b2c3d4",
|
|
"from": {"id": 777},
|
|
"message": {"chat": {"id": 777}, "message_id": 5},
|
|
},
|
|
CREDS,
|
|
client,
|
|
)
|
|
|
|
dispatch.assert_awaited_once()
|
|
client.answer_callback_query.assert_any_await("cq1", "Working...")
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# expired force-reply prompt
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_expired_reply_prompt_sends_notice(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""A popped-but-expired pending prompt must tell the CEO instead of
|
|
silently doing nothing (the CEO otherwise has no idea why their reply had
|
|
no effect)."""
|
|
engine = _engine()
|
|
client = AsyncMock()
|
|
dispatch = AsyncMock()
|
|
monkeypatch.setattr(engine, "_dispatch_command", dispatch)
|
|
ti._PENDING_REPLIES[("777", 42)] = ti._PendingAction(
|
|
kind="xpost",
|
|
id8="a1b2c3d4",
|
|
extra="",
|
|
action="reject",
|
|
origin_message_id=10,
|
|
expires_at=time.monotonic() - 1, # already expired
|
|
)
|
|
|
|
await engine._handle_message(
|
|
{
|
|
"chat": {"id": 777},
|
|
"text": "some reason",
|
|
"reply_to_message": {"message_id": 42},
|
|
},
|
|
CREDS,
|
|
client,
|
|
)
|
|
|
|
client.send_message.assert_awaited_once_with(
|
|
"That prompt expired — tap the button again.", parse_mode="HTML"
|
|
)
|
|
dispatch.assert_not_called()
|
|
assert ("777", 42) not in ti._PENDING_REPLIES
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# offset advancement
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_cycle_noop_when_flags_off(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
monkeypatch.setattr(ti.settings, "telegram_enabled", False)
|
|
monkeypatch.setattr(ti.settings, "telegram_inbound_enabled", True)
|
|
engine = _engine()
|
|
creds_svc = AsyncMock()
|
|
monkeypatch.setattr(
|
|
ti, "get_telegram_credentials_service", lambda _session: creds_svc
|
|
)
|
|
|
|
await engine.run_cycle()
|
|
|
|
creds_svc.get_decrypted.assert_not_called()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_cycle_noop_without_credentials(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr(ti.settings, "telegram_enabled", True)
|
|
monkeypatch.setattr(ti.settings, "telegram_inbound_enabled", True)
|
|
engine = _engine()
|
|
creds_svc = AsyncMock()
|
|
creds_svc.get_decrypted = AsyncMock(return_value=None)
|
|
monkeypatch.setattr(
|
|
ti, "get_telegram_credentials_service", lambda _session: creds_svc
|
|
)
|
|
|
|
await engine.run_cycle()
|
|
|
|
creds_svc.get_decrypted.assert_awaited_once()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_cycle_advances_offset_past_highest_update_id(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr(ti.settings, "telegram_enabled", True)
|
|
monkeypatch.setattr(ti.settings, "telegram_inbound_enabled", True)
|
|
engine = _engine()
|
|
|
|
creds_svc = AsyncMock()
|
|
creds_svc.get_decrypted = AsyncMock(return_value=CREDS)
|
|
monkeypatch.setattr(
|
|
ti, "get_telegram_credentials_service", lambda _session: creds_svc
|
|
)
|
|
|
|
client = AsyncMock()
|
|
client.configured = True
|
|
# Two updates the engine ignores (no message/callback_query key) — only
|
|
# the offset bookkeeping is under test here.
|
|
client.get_updates = AsyncMock(
|
|
return_value=[{"update_id": 100}, {"update_id": 105}]
|
|
)
|
|
monkeypatch.setattr(engine, "_client", AsyncMock(return_value=client))
|
|
|
|
settings_svc = AsyncMock()
|
|
settings_svc.get_int = AsyncMock(return_value=0)
|
|
monkeypatch.setattr(ti, "get_settings_service", lambda _session: settings_svc)
|
|
|
|
await engine.run_cycle()
|
|
|
|
client.get_updates.assert_awaited_once_with(offset=None, timeout=25, limit=50)
|
|
settings_svc.set.assert_awaited_once_with("telegram_last_update_id", "106")
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_run_cycle_requests_stored_offset(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
monkeypatch.setattr(ti.settings, "telegram_enabled", True)
|
|
monkeypatch.setattr(ti.settings, "telegram_inbound_enabled", True)
|
|
engine = _engine()
|
|
|
|
creds_svc = AsyncMock()
|
|
creds_svc.get_decrypted = AsyncMock(return_value=CREDS)
|
|
monkeypatch.setattr(
|
|
ti, "get_telegram_credentials_service", lambda _session: creds_svc
|
|
)
|
|
|
|
client = AsyncMock()
|
|
client.configured = True
|
|
client.get_updates = AsyncMock(return_value=[])
|
|
monkeypatch.setattr(engine, "_client", AsyncMock(return_value=client))
|
|
|
|
settings_svc = AsyncMock()
|
|
settings_svc.get_int = AsyncMock(return_value=42)
|
|
monkeypatch.setattr(ti, "get_settings_service", lambda _session: settings_svc)
|
|
|
|
await engine.run_cycle()
|
|
|
|
client.get_updates.assert_awaited_once_with(offset=42, timeout=25, limit=50)
|
|
# No updates seen -> offset must not regress/rewrite.
|
|
settings_svc.set.assert_not_called()
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# _resolve_task — exact id-prefix match, ambiguity handling
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_resolve_task_exact_prefix_match(monkeypatch: pytest.MonkeyPatch) -> None:
|
|
engine = _engine()
|
|
task = _fake_task("a1b2c3d4")
|
|
task_svc = AsyncMock()
|
|
task_svc.search_tasks = AsyncMock(return_value=[task])
|
|
monkeypatch.setattr(ti, "get_task_service", lambda _session: task_svc)
|
|
|
|
resolved = await engine._resolve_task("a1b2c3d4")
|
|
|
|
# Widened from 10 -> 50: a real id-prefix hit can otherwise be pushed out
|
|
# of a small window by title/description ILIKE hits on newer rows.
|
|
task_svc.search_tasks.assert_awaited_once_with("a1b2c3d4", limit=50)
|
|
assert resolved is task
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_resolve_task_ambiguous_returns_none(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
# Both genuinely start with the same prefix -> ambiguous.
|
|
t1 = _fake_task("a1b2c3d4")
|
|
t2 = SimpleNamespace(id=UUID(hex="a1b2c3d4" + "0" * 24), title="dup")
|
|
task_svc = AsyncMock()
|
|
task_svc.search_tasks = AsyncMock(return_value=[t1, t2])
|
|
monkeypatch.setattr(ti, "get_task_service", lambda _session: task_svc)
|
|
|
|
assert await engine._resolve_task("a1b2c3d4") is None
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_resolve_task_filters_out_title_only_matches(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""search_tasks also OR-matches title/description substrings; a hit whose
|
|
id does NOT start with the query must be filtered back out."""
|
|
engine = _engine()
|
|
real = _fake_task("a1b2c3d4")
|
|
title_hit = _fake_task("ffffffff", title="mentions a1b2c3d4 in the title")
|
|
task_svc = AsyncMock()
|
|
task_svc.search_tasks = AsyncMock(return_value=[real, title_hit])
|
|
monkeypatch.setattr(ti, "get_task_service", lambda _session: task_svc)
|
|
|
|
assert await engine._resolve_task("a1b2c3d4") is real
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# dispatch: one per approve-kind
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
def _stub_resolve(
|
|
monkeypatch: pytest.MonkeyPatch, engine: ti.TelegramInboundEngine, task: Any
|
|
) -> None:
|
|
monkeypatch.setattr(engine, "_resolve_task", AsyncMock(return_value=task))
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_approve_task_calls_ceo_approve_with_notes(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
task_svc = AsyncMock()
|
|
task_svc.ceo_approve = AsyncMock(return_value=task)
|
|
monkeypatch.setattr(ti, "get_task_service", lambda _session: task_svc)
|
|
|
|
notes = "Looks solid, shipping it now."
|
|
ok, _text = await engine._dispatch_approve("task", "a1b2c3d4", "", notes=notes)
|
|
|
|
task_svc.ceo_approve.assert_awaited_once_with(task.id, notes)
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_approve_task_refuses_short_notes(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
task_svc = AsyncMock()
|
|
monkeypatch.setattr(ti, "get_task_service", lambda _session: task_svc)
|
|
|
|
ok, text = await engine._dispatch_approve("task", "a1b2c3d4", "", notes="too short")
|
|
|
|
task_svc.ceo_approve.assert_not_called()
|
|
assert ok is False
|
|
assert "20" in text
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_reject_task_calls_ceo_reject_with_reason(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
task_svc = AsyncMock()
|
|
task_svc.ceo_reject = AsyncMock(return_value=task)
|
|
monkeypatch.setattr(ti, "get_task_service", lambda _session: task_svc)
|
|
|
|
ok, _text = await engine._dispatch_reject("task", "a1b2c3d4", "", "not good enough")
|
|
|
|
task_svc.ceo_reject.assert_awaited_once_with(task.id, "not good enough")
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_approve_release_dispatches_background(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
dispatch_mock = MagicMock()
|
|
monkeypatch.setattr(ti, "dispatch_approve", dispatch_mock)
|
|
factory = object()
|
|
monkeypatch.setattr(ti, "get_session_factory", lambda: factory)
|
|
|
|
ok, text = await engine._dispatch_approve("release", "a1b2c3d4", "", notes=None)
|
|
|
|
dispatch_mock.assert_called_once_with(task.id, factory)
|
|
assert ok is True
|
|
assert "background" in text
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_approve_release_refuses_when_cancelled(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""dispatch_approve fires the release execute in the background with no
|
|
result to inspect, so a stale Approve on an already-rejected (CANCELLED)
|
|
proposal must be caught HERE, before dispatch — else the CEO sees a false
|
|
"dispatched" success while the service-level guard silently no-ops."""
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
task.status = TaskStatus.CANCELLED
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
dispatch_mock = MagicMock()
|
|
monkeypatch.setattr(ti, "dispatch_approve", dispatch_mock)
|
|
|
|
ok, text = await engine._dispatch_approve("release", "a1b2c3d4", "", notes=None)
|
|
|
|
dispatch_mock.assert_not_called()
|
|
assert ok is False
|
|
assert "already rejected" in text.lower()
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_reject_release_surfaces_already_completed(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""The reject-after-approve mirror guard: the service raises when the
|
|
proposal already published; the handler must map that to (False, ...)
|
|
instead of an uncaught exception (which `run_cycle`'s broad except would
|
|
swallow, leaving the CEO with no response at all)."""
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
release_svc = AsyncMock()
|
|
release_svc.reject = AsyncMock(
|
|
side_effect=ti._ReleaseDone(
|
|
"release proposal already published (COMPLETED); cannot be rejected"
|
|
)
|
|
)
|
|
monkeypatch.setattr(
|
|
ti, "get_release_proposal_service", lambda _session: release_svc
|
|
)
|
|
|
|
ok, text = await engine._dispatch_reject(
|
|
"release", "a1b2c3d4", "", "needs another migration check"
|
|
)
|
|
|
|
assert ok is False
|
|
assert "already published" in text
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_reject_release_calls_service_with_reason(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
release_svc = AsyncMock()
|
|
release_svc.reject = AsyncMock(return_value=task)
|
|
monkeypatch.setattr(
|
|
ti, "get_release_proposal_service", lambda _session: release_svc
|
|
)
|
|
|
|
ok, _text = await engine._dispatch_reject(
|
|
"release", "a1b2c3d4", "", "needs another migration check"
|
|
)
|
|
|
|
release_svc.reject.assert_awaited_once_with(
|
|
task.id, "needs another migration check"
|
|
)
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_reject_release_enforces_ten_char_floor(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
release_svc = AsyncMock()
|
|
monkeypatch.setattr(
|
|
ti, "get_release_proposal_service", lambda _session: release_svc
|
|
)
|
|
|
|
ok, text = await engine._dispatch_reject("release", "a1b2c3d4", "", "short")
|
|
|
|
release_svc.reject.assert_not_called()
|
|
assert ok is False
|
|
assert "not recorded" in text
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_approve_xpost_calls_service(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
x_svc = AsyncMock()
|
|
x_svc.approve = AsyncMock(
|
|
return_value=XPostExecuteResult(status="posted", tweet_id="1", detail="ok")
|
|
)
|
|
monkeypatch.setattr(ti, "get_x_post_service", lambda _session: x_svc)
|
|
|
|
ok, _text = await engine._dispatch_approve("xpost", "a1b2c3d4", "", notes=None)
|
|
|
|
x_svc.approve.assert_awaited_once_with(task.id)
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_reject_xpost_calls_service_with_reason(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
x_svc = AsyncMock()
|
|
x_svc.reject = AsyncMock(return_value=task)
|
|
monkeypatch.setattr(ti, "get_x_post_service", lambda _session: x_svc)
|
|
|
|
ok, _text = await engine._dispatch_reject("xpost", "a1b2c3d4", "", "off-brand tone")
|
|
|
|
x_svc.reject.assert_awaited_once_with(task.id, "off-brand tone")
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_approve_video_calls_real_video_service(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
video_svc = AsyncMock()
|
|
video_svc.approve = AsyncMock(
|
|
return_value=VideoPostExecuteResult(
|
|
status="posted", posted={"x": "1"}, detail="ok"
|
|
)
|
|
)
|
|
monkeypatch.setattr(
|
|
engine, "_real_video_post_service", AsyncMock(return_value=video_svc)
|
|
)
|
|
|
|
ok, _text = await engine._dispatch_approve("video", "a1b2c3d4", "", notes=None)
|
|
|
|
video_svc.approve.assert_awaited_once_with(task.id)
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_reject_video_calls_service_with_reason(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
video_svc = AsyncMock()
|
|
video_svc.reject = AsyncMock(return_value=task)
|
|
monkeypatch.setattr(ti, "get_video_post_service", lambda _session: video_svc)
|
|
|
|
ok, _text = await engine._dispatch_reject("video", "a1b2c3d4", "", "wrong caption")
|
|
|
|
video_svc.reject.assert_awaited_once_with(task.id, "wrong caption")
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_approve_roadmap_calls_service_with_ceo_identity(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
roadmap_svc = AsyncMock()
|
|
roadmap_svc.approve_item = AsyncMock(
|
|
return_value=RoadmapItemResult(
|
|
status="approved", item_id="item-2", materialized_task_id="x", detail="ok"
|
|
)
|
|
)
|
|
monkeypatch.setattr(ti, "get_roadmap_service", lambda _session: roadmap_svc)
|
|
|
|
ok, _text = await engine._dispatch_approve(
|
|
"roadmap", "a1b2c3d4", "item-2", notes=None
|
|
)
|
|
|
|
roadmap_svc.approve_item.assert_awaited_once_with(
|
|
task.id, "item-2", created_by=CEO_UUID
|
|
)
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_reject_roadmap_calls_service_with_reason(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
roadmap_svc = AsyncMock()
|
|
roadmap_svc.reject_item = AsyncMock(
|
|
return_value=RoadmapItemResult(
|
|
status="rejected", item_id="item-2", materialized_task_id=None, detail="ok"
|
|
)
|
|
)
|
|
monkeypatch.setattr(ti, "get_roadmap_service", lambda _session: roadmap_svc)
|
|
|
|
ok, _text = await engine._dispatch_reject(
|
|
"roadmap", "a1b2c3d4", "item-2", "not aligned with strategy"
|
|
)
|
|
|
|
roadmap_svc.reject_item.assert_awaited_once_with(
|
|
task.id, "item-2", "not aligned with strategy"
|
|
)
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_approve_pest_control_calls_service_with_ceo_identity(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
pest_svc = AsyncMock()
|
|
pest_svc.approve_item = AsyncMock(
|
|
return_value=PestHuntItemResult(
|
|
status="approved", item_id="item-1", materialized_task_id="x", detail="ok"
|
|
)
|
|
)
|
|
monkeypatch.setattr(ti, "get_pest_control_service", lambda _session: pest_svc)
|
|
|
|
ok, _text = await engine._dispatch_approve(
|
|
"pest_control", "a1b2c3d4", "item-1", notes=None
|
|
)
|
|
|
|
pest_svc.approve_item.assert_awaited_once_with(
|
|
task.id, "item-1", created_by=CEO_UUID
|
|
)
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_reject_pest_control_calls_service_with_reason(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
pest_svc = AsyncMock()
|
|
pest_svc.reject_item = AsyncMock(
|
|
return_value=PestHuntItemResult(
|
|
status="rejected", item_id="item-1", materialized_task_id=None, detail="ok"
|
|
)
|
|
)
|
|
monkeypatch.setattr(ti, "get_pest_control_service", lambda _session: pest_svc)
|
|
|
|
ok, _text = await engine._dispatch_reject(
|
|
"pest_control", "a1b2c3d4", "item-1", "not a real bug, already fixed"
|
|
)
|
|
|
|
pest_svc.reject_item.assert_awaited_once_with(
|
|
task.id, "item-1", "not a real bug, already fixed"
|
|
)
|
|
assert ok is True
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_approve_unresolved_task_short_circuits(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
_stub_resolve(monkeypatch, engine, None)
|
|
|
|
ok, text = await engine._dispatch_approve("xpost", "ffffffff", "", notes=None)
|
|
|
|
assert ok is False
|
|
assert "No such" in text
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_approve_unknown_kind_is_graceful(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""A genuinely unrecognized kind (not one of the wired handlers, unlike
|
|
pest_control above) degrades to a reported failure, never an exception —
|
|
the handler-dict lookup's own fallback, unrelated to pest_control's
|
|
wiring."""
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
_stub_resolve(monkeypatch, engine, task)
|
|
|
|
ok, text = await engine._dispatch_approve("bogus", "a1b2c3d4", "", notes=None)
|
|
|
|
assert ok is False
|
|
assert "Unknown kind" in text
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# audit marker
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_mark_audit_adds_via_telegram_row() -> None:
|
|
engine = _engine()
|
|
task_id = uuid4()
|
|
|
|
engine._mark_audit("xpost", task_id, "approve", item_id="")
|
|
|
|
added = cast("MagicMock", engine.session.add).call_args.args[0]
|
|
assert added.event_type == "telegram.xpost.approve"
|
|
assert added.agent_id == CEO_UUID
|
|
assert added.target_id == task_id
|
|
assert added.details["via"] == "telegram"
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# /queue rendering — pluralization + HTML formatting
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_queue_empty_says_nothing_awaiting(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
monkeypatch.setattr(engine, "_collect_queue_items", AsyncMock(return_value=[]))
|
|
client = AsyncMock()
|
|
|
|
await engine._send_queue(client)
|
|
|
|
client.send_message.assert_awaited_once_with(
|
|
"✅ Nothing awaiting your approval.", parse_mode="HTML"
|
|
)
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_queue_singular_item_pluralization(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
monkeypatch.setattr(
|
|
engine,
|
|
"_collect_queue_items",
|
|
AsyncMock(return_value=[("task", "a1b2c3d4", "", "Ship it")]),
|
|
)
|
|
client = AsyncMock()
|
|
|
|
await engine._send_queue(client)
|
|
|
|
header = client.send_message.await_args_list[0].args[0]
|
|
assert header == "<b>🔔 Awaiting your approval</b> — 1 item"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_queue_plural_items_pluralization(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
monkeypatch.setattr(
|
|
engine,
|
|
"_collect_queue_items",
|
|
AsyncMock(
|
|
return_value=[
|
|
("task", "a1b2c3d4", "", "Ship it"),
|
|
("release", "deadbeef", "", "v1.0.0 ready"),
|
|
]
|
|
),
|
|
)
|
|
client = AsyncMock()
|
|
|
|
await engine._send_queue(client)
|
|
|
|
header = client.send_message.await_args_list[0].args[0]
|
|
assert header == "<b>🔔 Awaiting your approval</b> — 2 items"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_send_queue_item_line_escapes_title_and_carries_keyboard(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""Injection regression: a malicious task title must arrive HTML-escaped
|
|
— never as live markup — in the /queue item line's sent payload."""
|
|
engine = _engine()
|
|
monkeypatch.setattr(
|
|
engine,
|
|
"_collect_queue_items",
|
|
AsyncMock(return_value=[("task", "a1b2c3d4", "", "<b>bold&joke</b>")]),
|
|
)
|
|
client = AsyncMock()
|
|
|
|
await engine._send_queue(client)
|
|
|
|
item_call = client.send_message.await_args_list[1]
|
|
text = item_call.args[0]
|
|
assert "<b>bold&joke</b>" in text
|
|
assert "<b>bold&joke</b>" not in text
|
|
assert text.startswith("📋 <b>Task</b> — ")
|
|
assert item_call.kwargs["parse_mode"] == "HTML"
|
|
assert "reply_markup" in item_call.kwargs
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# /task — link preview disabled, title/status/team escaping
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_dispatch_command_task_disables_link_preview(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
engine = _engine()
|
|
monkeypatch.setattr(engine, "_render_task", AsyncMock(return_value="detail"))
|
|
client = AsyncMock()
|
|
|
|
await engine._dispatch_command("task", "a1b2c3d4", client)
|
|
|
|
client.send_message.assert_awaited_once_with(
|
|
"detail", parse_mode="HTML", disable_link_preview=True
|
|
)
|
|
|
|
|
|
def test_format_task_detail_escapes_html_in_title() -> None:
|
|
"""Injection regression: a task titled ``<b>bold&joke</b>`` must render
|
|
HTML-escaped, not as live markup, in /task's detail view."""
|
|
engine = _engine()
|
|
task = _fake_task(title="<b>bold&joke</b>")
|
|
|
|
rendered = engine._format_task_detail(cast("TaskTable", task))
|
|
|
|
assert "<b>bold&joke</b>" in rendered
|
|
assert "<b>bold&joke</b>" not in rendered
|
|
|
|
|
|
def test_format_task_detail_pr_url_is_a_named_link() -> None:
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
task.pr_url = "https://github.com/example/repo/pull/1"
|
|
|
|
rendered = engine._format_task_detail(cast("TaskTable", task))
|
|
|
|
assert '<a href="https://github.com/example/repo/pull/1">View PR</a>' in rendered
|
|
|
|
|
|
def test_format_task_detail_pr_url_quote_cannot_break_out_of_href() -> None:
|
|
"""Injection regression: a pr_url containing a literal '"' must not be
|
|
able to close the href attribute early and inject a bogus attribute —
|
|
_esc_attr (quote=True) turns it into '"', keeping the whole value
|
|
inside the attribute."""
|
|
engine = _engine()
|
|
task = _fake_task()
|
|
task.pr_url = 'https://evil.example/x" onmouseover="alert(1)'
|
|
|
|
rendered = engine._format_task_detail(cast("TaskTable", task))
|
|
|
|
assert (
|
|
'<a href="https://evil.example/x" onmouseover="alert(1)">'
|
|
"View PR</a>" in rendered
|
|
)
|
|
assert 'onmouseover="alert(1)"' not in rendered
|
|
|
|
|
|
# ---------------------------------------------------------------------------
|
|
# outcome confirmations (_finish_action / _consume_reply) — escaping
|
|
# ---------------------------------------------------------------------------
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_finish_action_escapes_text_and_edits_origin() -> None:
|
|
engine = _engine()
|
|
client = AsyncMock()
|
|
|
|
await engine._finish_action(client, 42, True, "Rejected: <script>xss</script>")
|
|
|
|
client.edit_message_reply_markup.assert_awaited_once_with(42, None)
|
|
call = client.edit_message_text.await_args
|
|
assert call.args == (42, "✅ Rejected: <script>xss</script>")
|
|
assert call.kwargs["parse_mode"] == "HTML"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_finish_action_escapes_text_without_origin() -> None:
|
|
engine = _engine()
|
|
client = AsyncMock()
|
|
|
|
await engine._finish_action(client, None, False, "<script>alert(1)</script>")
|
|
|
|
call = client.send_message.await_args
|
|
assert call.args == ("❌ <script>alert(1)</script>",)
|
|
assert call.kwargs["parse_mode"] == "HTML"
|
|
|
|
|
|
@pytest.mark.asyncio
|
|
async def test_consume_reply_reject_outcome_arrives_escaped(
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
) -> None:
|
|
"""End-to-end regression: a reject reason that reaches the CEO through
|
|
whatever text a dispatch handler returns must never arrive as live HTML —
|
|
the funnel (_finish_action) escapes it regardless of the handler."""
|
|
engine = _engine()
|
|
client = AsyncMock()
|
|
dispatch = AsyncMock(return_value=(True, "Rejected: <script>xss</script>"))
|
|
monkeypatch.setattr(engine, "_dispatch_reject", dispatch)
|
|
pending = ti._PendingAction(
|
|
kind="xpost",
|
|
id8="a1b2c3d4",
|
|
extra="",
|
|
action="reject",
|
|
origin_message_id=None,
|
|
expires_at=time.monotonic() + 60,
|
|
)
|
|
|
|
await engine._consume_reply(pending, "<script>xss</script>", client)
|
|
|
|
dispatch.assert_awaited_once_with("xpost", "a1b2c3d4", "", "<script>xss</script>")
|
|
sent_text = client.send_message.await_args.args[0]
|
|
assert "<script>xss</script>" in sent_text
|
|
assert "<script>xss</script>" not in sent_text
|