W6: Telegram notifications bridge (V1) (#524)

* feat(gateway): reviewer/PM collision map (W5)

The collision surface (intends_to_touch / adds_migration / touches_shared)
is authored at delegate time, consumed once by SequencingService to wire
dependency edges, then never shown to a reviewer again. This surfaces it:

- Pure builder (services/gateway/choreographer/collision.py): for a task
  under review, the surfaced siblings (same parent) that would collide —
  file-overlap globs or a shared migration chain (both adds_migration) —
  with the overlapping globs and a declared-vs-actual drift check. No
  DB/IO; callers fetch siblings (one indexed get_subtasks query, mig 069)
  + actual files (git). Caps: 10 siblings, 5 globs.

- Evidence envelopes: collision_context block injected into QA
  claim_review, PR-gate claim_gate_review (both carry real touched files
  so drift is populated), and the PM i_will_plan briefing (no actual
  files at plan time, drift omitted). Best-effort — a failure omits the
  block, never breaks the verb/briefing. Empty block omitted (zero token
  cost via _EVIDENCE_OMIT_WHEN_EMPTY).

- Panel: GET /api/tasks/{id}/collision-map (declared surface + sibling
  overlap; no drift — the panel route resolves no workspace) + a Collision
  tab on the task detail (8th tab). Mock-mode returns an empty map.

- docs/map added to the RAG auto-index dirs so the collision-map concept
  is fleet-retrievable; skipped gracefully if the dir is absent.

19 new tests (15 unit on the pure builder + 4 integration on the route).
Gate green: ruff/mypy/xenon (module rank A)/pytest 13000/coverage 94.81%,
panel typecheck/lint/516 tests.

* [w6-telegram] Add Telegram notifications bridge (V1)

CEO-facing Telegram DM bridge, flag-gated off by default
(ROBOCO_TELEGRAM_ENABLED). Mirrors the X-credentials / X-client pattern:

- TelegramCredentialsTable (migration 073) — singleton Fernet-encrypted
  bot_token + chat_id, all-or-nothing set/clear; API never returns plaintext.
- TelegramClient ABC / NullTelegramClient (no-op, configured->False, never
  raises) / LiveTelegramClient (httpx POST sendMessage) / build_telegram_client
  factory (Null when creds unset).
- /telegram/credentials CEO-only routes (write-only, guard-decorated).
- Best-effort _notify_telegram fan-out from the two CEO-notify producers
  (notify_ceo_of_escalation, notify_ceo_of_completion) — guarded by the flag,
  never raises into the producer, carries a panel deep-link when
  panel_base_url is set.
- panel credentials card (2 fields) nested in the Telegram feature-flag row.
- panel_base_url + telegram_timeout_seconds config fields.

V1 scope only: credentials + flag + panel card + client + one-line fan-out.
Out of scope (V2): inbound commands, a TelegramEngine background loop, a
dedup ledger, a bus subscription.

* [w6-telegram] fix: slave mypy/xenon regression (product tests + helper extract)

Pre-existing on slave from prior session's merges — no PR's CI caught them
(squash merges don't re-CI the result; each branch was based on older slave).

- test_product: _product helper returned MagicMock -> list invariant error;
  cast to ProductTable, move import under TYPE_CHECKING.
- test_usage: svc.session.execute (AsyncSession) has no call_args_list;
  cast to MagicMock at the two call sites.
- product.progress_for_products: xenon rank C -> extract module-level
  _project_to_products_map helper (repo pattern: helper-extract).

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
This commit is contained in:
Renzo F
2026-07-15 05:45:57 +02:00
committed by GitHub
co-authored by Renn F
parent d80dfb8bbe
commit bb3b4b0c6d
35 changed files with 2100 additions and 20 deletions
@@ -0,0 +1,180 @@
"""GET /api/tasks/{id}/collision-map — the reviewer/PM collision map route.
Read-only feed for the panel's Collision tab: the task's own declared
surface plus the surfaced siblings (same parent) that would collide with
it. Mirrors test_task_findings_route.py's fixture shape.
"""
from __future__ import annotations
from http import HTTPStatus
from typing import TYPE_CHECKING, Any, cast
from uuid import UUID, uuid4
import pytest
import pytest_asyncio
from fastapi import FastAPI
from httpx import ASGITransport, AsyncClient
from roboco.api.deps import get_agent_context, get_db
from roboco.api.routes.tasks import router as tasks_router
from roboco.db.tables import AgentTable, ProjectTable, TaskTable
from roboco.models import AgentRole, AgentStatus, Team
from roboco.models.base import TaskNature, TaskStatus, TaskType
from roboco.models.permissions import AgentContext
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import AsyncSession
@pytest_asyncio.fixture
async def collision_client(db_session: AsyncSession) -> AsyncIterator[dict]:
pm = AgentTable(
id=uuid4(),
name="PM",
slug=f"pm-{uuid4().hex[:8]}",
role=AgentRole.MAIN_PM,
team=None,
status=AgentStatus.ACTIVE,
model_config={},
system_prompt="pm",
capabilities=[],
permissions={},
metrics={},
)
db_session.add(pm)
await db_session.flush()
project = ProjectTable(
id=uuid4(),
name="CM-Proj",
slug=f"cm-proj-{uuid4().hex[:6]}",
git_url="https://example.com/cm.git",
assigned_cell=Team.BACKEND,
created_by=pm.id,
)
db_session.add(project)
await db_session.flush()
app = FastAPI()
app.include_router(tasks_router, prefix="/api/tasks")
async def _override_db() -> AsyncIterator[AsyncSession]:
yield db_session
async def _override_agent() -> AgentContext:
return AgentContext(
agent_id=cast("UUID", pm.id), role=AgentRole.MAIN_PM, team=None
)
app.dependency_overrides[get_db] = _override_db
app.dependency_overrides[get_agent_context] = _override_agent
transport = ASGITransport(app=app)
async with AsyncClient(transport=transport, base_url="http://test") as client:
yield {"client": client, "agent": pm, "project": project, "db": db_session}
app.dependency_overrides.clear()
def _task(setup: dict, **kw: Any) -> TaskTable:
task = TaskTable(
id=uuid4(),
title=kw.pop("title", "t"),
description=kw.pop("description", "d"),
acceptance_criteria=["ac"],
status=kw.pop("status", TaskStatus.IN_PROGRESS),
priority=kw.pop("priority", 2),
sequence=kw.pop("sequence", 0),
task_type=TaskType.CODE,
nature=TaskNature.TECHNICAL,
project_id=setup["project"].id,
created_by=setup["agent"].id,
team=Team.BACKEND,
**kw,
)
setup["db"].add(task)
return task
_HDR = {"X-Agent-ID": "ignored", "X-Agent-Role": "main_pm"}
@pytest.mark.asyncio
async def test_collision_map_404_for_missing_task(collision_client: dict) -> None:
client = collision_client["client"]
response = await client.get(f"/api/tasks/{uuid4()}/collision-map", headers=_HDR)
assert response.status_code == HTTPStatus.NOT_FOUND
@pytest.mark.asyncio
async def test_collision_map_empty_for_rootless_task(collision_client: dict) -> None:
client = collision_client["client"]
task = _task(collision_client, intends_to_touch=["roboco/services/git.py"])
await collision_client["db"].flush()
response = await client.get(f"/api/tasks/{task.id}/collision-map", headers=_HDR)
assert response.status_code == HTTPStatus.OK
body = response.json()
assert body["parent_task_id"] is None
assert body["intends_to_touch"] == ["roboco/services/git.py"]
assert body["siblings"] == []
@pytest.mark.asyncio
async def test_collision_map_shows_overlapping_sibling(collision_client: dict) -> None:
client = collision_client["client"]
parent = _task(collision_client, title="parent", status=TaskStatus.PENDING)
await collision_client["db"].flush()
under = _task(
collision_client,
parent_task_id=parent.id,
title="under review",
intends_to_touch=["roboco/services/git.py"],
sequence=0,
)
_task(
collision_client,
parent_task_id=parent.id,
title="colliding sibling",
intends_to_touch=["roboco/services/git.py", "roboco/services/x.py"],
sequence=1,
)
await collision_client["db"].flush()
response = await client.get(f"/api/tasks/{under.id}/collision-map", headers=_HDR)
assert response.status_code == HTTPStatus.OK
body = response.json()
assert body["parent_task_id"] == str(parent.id)
assert len(body["siblings"]) == 1
sib_entry = body["siblings"][0]
assert sib_entry["title"] == "colliding sibling"
assert "roboco/services/git.py" in sib_entry["overlap"]
# panel path carries no actual files → drift is empty (the QA/gate
# evidence envelopes populate it; the panel schema defaults to []).
assert sib_entry["undeclared"] == []
@pytest.mark.asyncio
async def test_collision_map_omits_non_overlapping_sibling(
collision_client: dict,
) -> None:
client = collision_client["client"]
parent = _task(collision_client, title="parent", status=TaskStatus.PENDING)
await collision_client["db"].flush()
under = _task(
collision_client,
parent_task_id=parent.id,
title="under review",
intends_to_touch=["roboco/services/git.py"],
)
_task(
collision_client,
parent_task_id=parent.id,
title="parallel sibling",
intends_to_touch=["roboco/services/other.py"],
)
await collision_client["db"].flush()
response = await client.get(f"/api/tasks/{under.id}/collision-map", headers=_HDR)
assert response.status_code == HTTPStatus.OK
body = response.json()
assert body["siblings"] == [] # no overlap, no shared migration
@@ -0,0 +1,93 @@
"""TelegramCredentialsService coverage — encrypt/roundtrip, all-or-nothing set/clear.
Drives a real ``db_session`` via the project's Postgres-backed conftest. The
service never returns plaintext to a caller other than ``get_decrypted`` (the
server-side-only reader) — the API layer only ever sees ``has_credentials``.
"""
from __future__ import annotations
from typing import TYPE_CHECKING
import pytest
import pytest_asyncio
from roboco.db.tables import TelegramCredentialsTable
from roboco.services.telegram_credentials import (
TelegramCredentialsService,
TelegramCredentialsValidationError,
get_telegram_credentials_service,
)
from sqlalchemy import select
if TYPE_CHECKING:
from collections.abc import AsyncIterator
from sqlalchemy.ext.asyncio import AsyncSession
_CREDS = {"bot_token": "123456:ABC-bot-token", "chat_id": "987654321"}
@pytest_asyncio.fixture
async def svc(
db_session: AsyncSession,
) -> AsyncIterator[TelegramCredentialsService]:
yield get_telegram_credentials_service(db_session)
@pytest.mark.asyncio
async def test_unset_has_no_credentials(svc: TelegramCredentialsService) -> None:
assert await svc.has_credentials() is False
assert await svc.get_decrypted() is None
@pytest.mark.asyncio
async def test_set_both_encrypts_and_roundtrips(
svc: TelegramCredentialsService,
) -> None:
has_creds = await svc.set_credentials(**_CREDS)
assert has_creds is True
assert await svc.has_credentials() is True
decrypted = await svc.get_decrypted()
assert decrypted is not None
assert decrypted.bot_token == _CREDS["bot_token"]
assert decrypted.chat_id == _CREDS["chat_id"]
@pytest.mark.asyncio
async def test_stored_row_never_holds_plaintext(
svc: TelegramCredentialsService, db_session: AsyncSession
) -> None:
await svc.set_credentials(**_CREDS)
result = await db_session.execute(select(TelegramCredentialsTable).limit(1))
row = result.scalar_one_or_none()
assert row is not None
assert row.bot_token_encrypted != _CREDS["bot_token"]
assert row.chat_id_encrypted != _CREDS["chat_id"]
@pytest.mark.asyncio
async def test_clearing_both_removes_row(svc: TelegramCredentialsService) -> None:
await svc.set_credentials(**_CREDS)
has_creds = await svc.set_credentials(bot_token="", chat_id="")
assert has_creds is False
assert await svc.has_credentials() is False
assert await svc.get_decrypted() is None
@pytest.mark.asyncio
async def test_partial_set_is_rejected(svc: TelegramCredentialsService) -> None:
with pytest.raises(TelegramCredentialsValidationError):
await svc.set_credentials(bot_token="only-one", chat_id="")
@pytest.mark.asyncio
async def test_rotate_overwrites_previous_values(
svc: TelegramCredentialsService,
) -> None:
await svc.set_credentials(**_CREDS)
rotated = {k: f"{v}-rotated" for k, v in _CREDS.items()}
await svc.set_credentials(**rotated)
decrypted = await svc.get_decrypted()
assert decrypted is not None
assert decrypted.bot_token == rotated["bot_token"]