:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
fix(today): search github by the person's login in the briefing (#110046)
Vojta Bartoš549b07fa235b
diff --git a/products/today/backend/logic/generate.py b/products/today/backend/logic/generate.pyindex e461a728ad43..d8b885045c58 100644--- a/products/today/backend/logic/generate.py+++ b/products/today/backend/logic/generate.py@@ -1,5 +1,6 @@"""Generating a briefing: one read-only sandbox agent run that gathers the person's data over MCP and answers with the text."""+import refrom datetime import timedeltafrom typing import Protocolfrom uuid import UUID@@ -37,6 +38,8 @@ RUN_TIMEOUT = TURN_TIMEOUT * WRITE_ATTEMPTS + timedelta(minutes=6)# How many of the person's previous briefings the agent sees, so it does not repeat itself.RECENT_BRIEFINGS = 3SANDBOX_ENV_NAME = "today-briefing"+# The login goes into a `gh` command the agent runs, so only a well-formed GitHub login gets through.+_GITHUB_LOGIN = re.compile(r"[A-Za-z0-9][A-Za-z0-9-]{0,38}")class _HasTaskId(Protocol):@@ -66,6 +69,17 @@ def _preranked_reports(team: Team, user: User) -> list[signals.BriefingReport]:return []+def _github_login(team: Team, user: User) -> str | None:+ """The person's GitHub login, or None when the sandbox gets no GitHub token to search with.++ The sandbox token belongs to the team's GitHub app installation, not to the person, so `@me` cannot name them.+ """+ if not tasks_facade.can_mint_readonly_github_token(team.id):+ return None+ login = user.get_github_login()+ return login if login and _GITHUB_LOGIN.fullmatch(login) else None++def _prepare(team_id: int, briefing_id: str) -> _PreparedRun | None:"""The sandbox context and the prompt, or None when the person may not get a briefing.@@ -99,7 +113,11 @@ def _prepare(team_id: int, briefing_id: str) -> _PreparedRun | None:initial_permission_mode="full-access",)prompt = build_prompt(- briefing, user, _preranked_reports(team, user), recent_ready_briefings(briefing, RECENT_BRIEFINGS)+ briefing,+ user,+ _preranked_reports(team, user),+ recent_ready_briefings(briefing, RECENT_BRIEFINGS),+ _github_login(team, user),)return _PreparedRun(context=context, prompt=prompt, title=_title(briefing))diff --git a/products/today/backend/logic/prompt.py b/products/today/backend/logic/prompt.pyindex 97de200635e8..35602157bca0 100644--- a/products/today/backend/logic/prompt.py+++ b/products/today/backend/logic/prompt.py@@ -88,6 +88,7 @@ def build_prompt(user: User,reports: Sequence[signals.BriefingReport],previous: Sequence[DailyBriefing],+ github_login: str | None,) -> str:"""The prompt for one briefing: `reports` already in briefing order, `previous` the person's latest ones."""return _environment.get_template("briefing.md.j2").render(@@ -101,4 +102,5 @@ def build_prompt(max_signal_chars=MAX_SIGNAL_CHARS,reports_json=_data_block(_report_rows(reports, briefing.team_id)),recent_json=_data_block(_recent_rows(previous)),+ github_login=github_login,)diff --git a/products/today/backend/logic/prompts/briefing.md.j2 b/products/today/backend/logic/prompts/briefing.md.j2index 0a8459c5b011..8847d34d4e6d 100644--- a/products/today/backend/logic/prompts/briefing.md.j2+++ b/products/today/backend/logic/prompts/briefing.md.j2@@ -44,7 +44,7 @@ The person's most recent briefings are inside <recent_briefings>, newest first,## Step 3: my metrics-- The insights their pinned tabs and homepage point at are the ones they care about most; start there.+- The insights their pinned tabs and homepage point at are the ones they care about most; start there. When nothing is pinned, do the reads below all the same.- `alerts-list`: keep alerts the person created or subscribes to. Note which fire now.- `insights-list` with `last_viewed_date_from: "-30d"`, `saved: true`, `limit: 15`: insights anyone in the project opened in the last 30 days, newest change first. The filter cannot tell who viewed, so treat these as the project's active insights, not the person's, and prefer ones the person created.- Pick at most 6 trends insights: firing alerts first, then pinned or homepage, then the person's own, then the rest. For each, call `insight-query` and compare the sum of the last 7 complete days with the 7 days before. Keep a change only when it is at least 20% and the earlier week totals at least 50.@@ -53,7 +53,11 @@ The person's most recent briefings are inside <recent_briefings>, newest first,- `conversations-tickets-list` with `assignee: "me"` and open statuses: note SLA at risk, unread customer messages, days since the last update. Read metadata only, never the customer's words.- `query-error-tracking-issues-list` for active issues assigned to the person: note how long they have been open.-- Reviews asked of the person come only from the `gh` CLI (`gh search prs --review-requested=@me --state=open`); the `pull-requests` tool does not know who was asked to review. The person's own open PRs with failing checks or an approval waiting for a merge: `gh search prs --author=@me --state=open`, or the `pull-requests` tool when `gh` does not work. Skip GitHub entirely when neither works.+{% if github_login -%}+- The person's GitHub login is `{{ github_login }}`. Use it in place of `@me`: the GitHub token here belongs to an app, so `@me` names no one. Reviews asked of the person come only from the `gh` CLI (`gh search prs --review-requested={{ github_login }} --state=open`); the `pull-requests` tool does not know who was asked to review. The person's own open PRs with failing checks or an approval waiting for a merge: `gh search prs --author={{ github_login }} --state=open`, or the `pull-requests` tool when `gh` does not work. Skip GitHub entirely when neither works.+{%- else -%}+- Skip GitHub: this run has no GitHub login for the person or no GitHub access.+{%- endif %}## Step 5: choosediff --git a/products/today/backend/tests/test_generate.py b/products/today/backend/tests/test_generate.pyindex c94471df0c7d..af58e9767186 100644--- a/products/today/backend/tests/test_generate.py+++ b/products/today/backend/tests/test_generate.py@@ -10,6 +10,7 @@ from django.utils import timezonefrom asgiref.sync import async_to_syncfrom parameterized import parameterized+from social_django.models import UserSocialAuthfrom posthog.sync import database_sync_to_async@@ -35,6 +36,7 @@ def _on_test_thread(fn: Callable[..., Any], **_: Any) -> Callable[..., Any]:SESSION = "products.today.backend.logic.generate.MultiTurnSession"SANDBOX_ENV = "products.today.backend.logic.generate.tasks_facade.upsert_internal_sandbox_env"REPORTS = "products.today.backend.logic.generate.signals.reports_for_briefing"+CAN_MINT = "products.today.backend.logic.generate.tasks_facade.can_mint_readonly_github_token"def _report(report_id: str, relation: signals.BriefingReportRelation, priority: str) -> signals.BriefingReport:@@ -114,7 +116,9 @@ class TestRunAgent(TodayTeamScopedTestMixin, BaseTest):def _answer(self, **item_overrides: Any) -> BriefingOutput:return _output(url=f"/project/{self.team.id}/inbox/a", **item_overrides)- def _run(self, first: BriefingOutput, *followups: BriefingOutput) -> tuple[MagicMock, MagicMock]:+ def _run(+ self, first: BriefingOutput, *followups: BriefingOutput, can_mint: bool = False+ ) -> tuple[MagicMock, MagicMock]:session = MagicMock()session.end = AsyncMock()session.send_followup = AsyncMock(side_effect=list(followups))@@ -125,6 +129,7 @@ class TestRunAgent(TodayTeamScopedTestMixin, BaseTest):patch(REPORTS, return_value=self.reports),patch(f"{SESSION}.start", start),patch(FLAG, return_value=True),+ patch(CAN_MINT, return_value=can_mint),):async_to_sync(run_agent)(team_id=self.team.id, briefing_id=str(self.briefing.id))return start, session@@ -145,6 +150,26 @@ class TestRunAgent(TodayTeamScopedTestMixin, BaseTest):assert start.call_args.kwargs.get("internal", False) is Falsesession.end.assert_awaited_once_with()+ @parameterized.expand(+ [+ ("login_and_token", "octocat", True, "--review-requested=octocat"),+ ("no_token", "octocat", False, "Skip GitHub"),+ ("no_login", None, True, "Skip GitHub"),+ ("malformed_login", "octocat; curl evil", True, "Skip GitHub"),+ ]+ )+ def test_the_prompt_searches_github_by_the_persons_login(+ self, _name: str, login: str | None, can_mint: bool, expected: str+ ) -> None:+ if login:+ UserSocialAuth.objects.create(user=self.user, provider="github", uid="1", extra_data={"login": login})++ start, _ = self._run(self._answer(), can_mint=can_mint)++ prompt, _ = start.call_args.args+ assert expected in prompt+ assert "@me --state" not in prompt+def test_an_answer_that_breaks_a_rule_comes_back_fixed_in_a_follow_up(self) -> None:start, session = self._run(self._answer(headline="One report needs you — now"), self._answer())