Skip to content

: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.

fix(signals): persist a linked repo when repo selection is gated (#87606)

posthog[bot]768d1a58d150
diff --git a/ee/clickhouse/test/test_error.py b/ee/clickhouse/test/test_error.py
index 618c60730462..0d23dde3959d 100644
--- a/ee/clickhouse/test/test_error.py
+++ b/ee/clickhouse/test/test_error.py
@@ -223,6 +223,10 @@ def test_wrap_clickhouse_query_error(error, expected_type, expected_message, exp
assert label == expected_ch_error
+# Marked for the database it queries: `django_db_setup` is what creates the ClickHouse test
+# database, so without this the test only passes when some other test in the package happens to
+# run first and create it, and fails wherever sharding isolates it.
def test_per_query_memory_limit_phrasing_matches_real_clickhouse():
with pytest.raises(ClickHouseQueryMemoryLimitExceeded) as ctx:
sync_execute(
diff --git a/posthog/git.py b/posthog/git.py
index df515438f50e..088c4e5b8d08 100644
--- a/posthog/git.py
+++ b/posthog/git.py
@@ -54,9 +54,10 @@ def get_git_branch() -> Optional[str]:
_TOKEN_PUNCTUATION = "`'\"()[]{}<>,.;:!?"
_GITHUB_HOSTS = frozenset({"github.com", "www.github.com"})
_REPO_TOKEN = re.compile(r"[\w.-]+/[\w.-]+")
-# Slack formats links as <url|label> and either side can carry the repo, so `|` separates
-# candidates the same way whitespace does.
-_CANDIDATE_SEPARATOR = re.compile(r"[\s|]+")
+# A link's URL is rarely space-delimited: Slack writes <url|label> and Markdown writes
+# [label](url), so the brackets and the pipe separate candidates the same way whitespace does.
+# Stripping them as edge punctuation isn't enough — in `[label](url)` they sit mid-token.
+_CANDIDATE_SEPARATOR = re.compile(r"[\s|()\[\]<>]+")
def _repo_from_github_url(token: str) -> str | None:
diff --git a/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py b/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py
index b558548cd636..7551106bd545 100644
--- a/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py
+++ b/posthog/models/usage_report_events_preagg/test/test_usage_report_events_preagg_mv.py
@@ -13,7 +13,7 @@ from uuid import uuid4
from posthog.test.base import ClickhouseTestMixin
from django.conf import settings
-from django.test import SimpleTestCase
+from django.test import TestCase
from kafka import KafkaProducer
@@ -90,7 +90,7 @@ def _wait_for_team_row(
)
-class TestUsageReportEventsPreaggMV(ClickhouseTestMixin, SimpleTestCase):
+class TestUsageReportEventsPreaggMV(ClickhouseTestMixin, TestCase):
@classmethod
def setUpClass(cls) -> None:
super().setUpClass()
diff --git a/posthog/test/test_git.py b/posthog/test/test_git.py
index a057d35ef1dd..6ebf41890a29 100644
--- a/posthog/test/test_git.py
+++ b/posthog/test/test_git.py
@@ -52,6 +52,12 @@ class TestExtractLinkedRepo:
"posthog/posthog-js",
),
("clone_url_suffix", "cloned from [email protected]:posthog/posthog.git", "posthog/posthog"),
+ # Markdown puts the URL inside `](...)`, so edge-punctuation stripping alone never sees it.
+ (
+ "markdown_link_label",
+ "broke in [PR 1](https://github.com/posthog/posthog-js/pull/1)",
+ "posthog/posthog-js",
+ ),
("unconnected_repo_url", "see https://github.com/acme/widgets/pull/1", None),
("lookalike_host", "see https://mygithub.com/posthog/posthog/pull/1", None),
("host_prefix_spoof", "see https://github.com.evil.tld/posthog/posthog", None),
diff --git a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
index 56e4d75f5945..75d277e22f23 100644
--- a/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
+++ b/products/product_analytics/backend/tests/api/__snapshots__/test_insight.ambr
@@ -34,7 +34,7 @@
e.`$window_id` AS `$window_id`,
if(equals(e.event, 'user signed up'), 1, 0) AS step_0,
if(equals(e.event, 'user did things'), 1, 0) AS step_1,
- ([e__person.properties___fish] AS value) AS prop_basic,
+ ([replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', '')] AS value) AS prop_basic,
prop_basic AS prop
FROM events AS e
LEFT OUTER JOIN
@@ -44,16 +44,6 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0)), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -121,17 +111,7 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
+ WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up')), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
GROUP BY breakdown
@@ -188,8 +168,8 @@
e.uuid AS uuid,
e.`$session_id` AS `$session_id`,
e.`$window_id` AS `$window_id`,
- if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_0,
- if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0))), 1, 0) AS step_1
+ if(and(equals(e.event, 'user signed up'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_0,
+ if(and(equals(e.event, 'user did things'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0))), 1, 0) AS step_1
FROM events AS e
LEFT OUTER JOIN
(SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
@@ -198,16 +178,6 @@
WHERE equals(person_distinct_id_overrides.team_id, 99999)
GROUP BY person_distinct_id_overrides.distinct_id
HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
WHERE and(equals(e.team_id, 99999), and(and(greaterOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC')), lessOrEquals(e.timestamp, toDateTime64('explicit_redacted_timestamp', 6, 'UTC'))), in(e.event, tuple('user did things', 'user signed up'))), or(equals(step_0, 1), equals(step_1, 1))))
GROUP BY aggregation_target
HAVING ifNull(greaterOrEquals(step_reached, 0), 0))
@@ -324,24 +294,7 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(greater(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
@@ -373,24 +326,7 @@
(SELECT count() AS total,
toStartOfDay(toTimeZone(e.timestamp, 'UTC')) AS day_start
FROM events AS e
- LEFT OUTER JOIN
- (SELECT argMax(person_distinct_id_overrides.person_id, person_distinct_id_overrides.version) AS person_id,
- person_distinct_id_overrides.distinct_id AS distinct_id
- FROM person_distinct_id_overrides
- WHERE equals(person_distinct_id_overrides.team_id, 99999)
- GROUP BY person_distinct_id_overrides.distinct_id
- HAVING equals(argMax(person_distinct_id_overrides.is_deleted, person_distinct_id_overrides.version), 0) SETTINGS optimize_aggregation_in_order=1) AS e__override ON equals(e.distinct_id, e__override.distinct_id)
- LEFT JOIN
- (SELECT person.id AS id,
- replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(person.properties, 'fish'), ''), 'null'), '^"|"$', '') AS properties___fish
- FROM person
- WHERE and(equals(person.team_id, 99999), in(tuple(person.id, person.version),
- (SELECT person.id AS id, max(person.version) AS version
- FROM person
- WHERE equals(person.team_id, 99999)
- GROUP BY person.id
- HAVING and(equals(argMax(person.is_deleted, person.version), 0), less(argMax(toTimeZone(person.created_at, 'UTC'), person.version), plus(now64(6, 'UTC'), toIntervalDay(1))))))) SETTINGS optimize_aggregation_in_order=1) AS e__person ON equals(if(not(empty(e__override.distinct_id)), e__override.person_id, e.person_id), e__person.id)
- WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(e__person.properties___fish, '%fish%'), 0)))
+ WHERE and(equals(e.team_id, 99999), greaterOrEquals(e.timestamp, toStartOfInterval(assumeNotNull(toDateTime('2012-01-08 00:00:00', 'UTC')), toIntervalDay(1))), lessOrEquals(e.timestamp, assumeNotNull(toDateTime('2012-01-15 23:59:59', 'UTC'))), equals(e.event, '$pageview'), and(ifNull(less(accurateCastOrNull(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.properties, 'int_value'), ''), 'null'), '^"|"$', ''), 'Int64'), 10), 0), ifNull(like(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(e.person_properties, 'fish'), ''), 'null'), '^"|"$', ''), '%fish%'), 0)))
GROUP BY day_start)
GROUP BY day_start
ORDER BY day_start ASC)
diff --git a/products/signals/backend/auto_start.py b/products/signals/backend/auto_start.py
index e622ee64a23d..2c85dff6b571 100644
--- a/products/signals/backend/auto_start.py
+++ b/products/signals/backend/auto_start.py
@@ -573,6 +573,7 @@ async def maybe_autostart_implementation_task(
priority: PriorityAssessment | None,
triggering_user_id: int | None = None,
billing_exempt_reason: str | None = None,
+ repository_autostart_eligible: bool = True,
) -> None:
"""Start an implementation Task for a SignalReport if autonomy + priority allow it.
@@ -604,6 +605,13 @@ async def maybe_autostart_implementation_task(
strictly as the editing user and never falls back, so it can't act under another member's
identity.
+ ``repository_autostart_eligible`` is false when *repository* was inferred from the report's own
+ text rather than chosen for a caller who asked to open a PR (see `RepoSelectionResult`). Such a
+ repo is a target for whoever clicks Create PR, so it may not reach the reviewer-less fallback —
+ that is the one path where nobody named the report's destination *or* its runner. A reviewer who
+ resolves and clears their autonomy threshold, or a user whose own reviewer edit triggered this,
+ is a person authorizing the run, so the inference stops mattering and this no longer applies.
+
Both the agentic signals pipeline (``temporal/agentic/report.py``) and the
custom agent activity (``temporal/custom_agent.py``) call this after persisting
their report and artefacts. Callers should wrap this in try/except so an
@@ -672,7 +680,11 @@ async def maybe_autostart_implementation_task(
task_user = await database_sync_to_async(_resolve_autostart_assignee, thread_sensitive=False)(
team_id, priority.priority, reviewers_content, team_default_priority
)
- if task_user is None and _report_meets_team_autostart_threshold(priority.priority, team_default_priority):
+ if (
+ task_user is None
+ and repository_autostart_eligible
+ and _report_meets_team_autostart_threshold(priority.priority, team_default_priority)
+ ):
# No suggested reviewer resolved to a connected-GitHub member, but the report meets the
# team's default autostart priority, so run it under the member who enabled signals for
# the team rather than dropping the PR.
@@ -804,8 +816,8 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)
repo_selection = await _latest_artefact_as(
report_id, SignalReportArtefact.ArtefactType.REPO_SELECTION, RepoSelectionResult
)
- repository = repo_selection.repository if repo_selection else None
- if not repository:
+ repository = repo_selection.repository if repo_selection is not None else None
+ if repo_selection is None or not repository:
logger.info(
"signals auto-start re-eval skipped",
report_id=report_id,
@@ -834,4 +846,5 @@ async def maybe_autostart_from_report_artefacts(*, team_id: int, report_id: str)
# If a user edited the reviewers, run the task as that user — never as a named colleague,
# which would let one user act under another's PostHog identity (reviewer impersonation).
triggering_user_id=editor_user_id,
+ repository_autostart_eligible=repo_selection.autostart_eligible,
)
diff --git a/products/signals/backend/scout_harness/tools/report.py b/products/signals/backend/scout_harness/tools/report.py
index 84a3c80df092..fd137122e48f 100644
--- a/products/signals/backend/scout_harness/tools/report.py
+++ b/products/signals/backend/scout_harness/tools/report.py
@@ -35,6 +35,7 @@ from pydantic import ValidationError
from posthog.api.capture import capture_internal
from posthog.event_usage import groups
+from posthog.git import extract_linked_repo
from posthog.models import Team
from posthog.sync import database_sync_to_async
@@ -63,6 +64,7 @@ from products.signals.backend.scout_harness.tools.emit import (
remediation_for_skip,
)
from products.signals.backend.scout_report import (
+ INFERRED_REPOSITORY_REASON,
MAX_REPORT_SIGNALS,
InvalidScoutReportError,
ScoutReportSignal,
@@ -74,6 +76,7 @@ from products.signals.backend.scout_report import (
record_scout_run_task_artefact,
set_report_charts,
set_report_suggested_prompts,
+ set_scout_report_inferred_repository,
set_scout_report_reviewers,
update_scout_report,
)
@@ -502,8 +505,73 @@ def _repo_request_section(title: str, summary: str, evidence: list[ReportEvidenc
return "\n".join(lines)
+def _connected_repositories(team_id: int) -> list[str]:
+ """The repos the team's own GitHub installation can reach, or an empty list when it has none.
+
+ Reads the cache as-is and never starts the selection sandbox, which is what keeps the gate-skipped
+ path the cheap one."""
+ from products.tasks.backend.facade.repo_selection import (
+ list_team_connected_repositories, # noqa: PLC0415 — break worker-boot import cycle
+ )
+
+ return list_team_connected_repositories(team_id)
+
+
+def _extract_linked_repository(
+ title: str, summary: str, evidence: list[ReportEvidence], connected_repos: list[str]
+) -> str | None:
+ """Find the single connected GitHub repository linked in the report content, or None.
+
+ Report content quotes ingested project data, so a link in it is untrusted: matching against the
+ team's connected repos is what stops a linked upstream or attacker-placed repo from becoming a
+ target. Ambiguity resolves to nothing too — a report linking two connected repos names no single
+ one, and guessing between them would seed a wrong target for a later Create PR run."""
+ return extract_linked_repo("\n".join([title, summary, *(e.description for e in evidence)]), connected_repos)
+
+
+def _refresh_inferred_repository(*, team_id: int, report_id: str, attribution: ArtefactAttribution) -> None:
+ """Re-derive an inferred `repo_selection` from a report's rewritten title and summary.
+
+ An inferred target is a reading of the report's text, so a rewrite that moves the report onto a
+ different repository leaves it pointing somewhere the report no longer describes. Only a selection
+ this same inference wrote is re-derived; one the scout named or the selection agent chose is a
+ decision, not a reading, and a content edit does not overturn it.
+
+ New content that links nothing keeps the existing target. A repository the reader can override at
+ Create PR time costs less than clearing it, since a cleared selection reads as the scout's
+ deliberate no-repo and suppresses the cascade that would otherwise still find a target.
+ """
+ from products.signals.backend.report_generation.select_repo import (
+ persisted_repo_selection, # noqa: PLC0415 — keeps the sandbox stack off this module's import path
+ )
+
+ selection = persisted_repo_selection(report_id)
+ if selection is None or selection.autostart_eligible or selection.repository is None:
+ return
+ report = SignalReport.objects.filter(team_id=team_id, id=report_id).values("title", "summary").first()
+ if report is None:
+ return
+ linked = extract_linked_repo(
+ "\n".join([report["title"] or "", report["summary"] or ""]), _connected_repositories(team_id)
+ )
+ if linked is None or linked == selection.repository:
+ return
+ set_scout_report_inferred_repository(
+ team_id=team_id,
+ report_id=report_id,
+ repository=linked,
+ attribution=attribution,
+ )
+
+
async def _resolve_report_repository(
- *, team_id: int, repository: str | None, title: str, summary: str, evidence: list[ReportEvidence]
+ *,
+ team_id: int,
+ repository: str | None,
+ title: str,
+ summary: str,
+ evidence: list[ReportEvidence],
+ wants_full_selection: bool,
) -> RepoSelectionResult | None:
"""Resolve the scout's `repository` input into a `repo_selection` artefact (or None to write none).
@@ -512,13 +580,31 @@ async def _resolve_report_repository(
free-form path is the slow one — for a team with many repos it spawns a selection sandbox — so a
scout that knows its repo should pass it explicitly (see the report contract). The cheap
`NO_REPO` / `owner/repo` cases are validated by `_normalize_repository` up front (before the judge),
- so by here an explicit repo is already well-formed; only the free-form path remains."""
+ so by here an explicit repo is already well-formed; only the free-form path remains.
+
+ `wants_full_selection` is the PR-intent gate (`_wants_repo_selection`). When it is false the report
+ surfaced without the inputs the selection sandbox exists to serve, so the free-form branch scans
+ the report content for one linked connected repository instead — a cheap deterministic match that
+ seeds a `repo_selection` artefact so a person clicking Create PR has a target. That inferred
+ selection is `autostart_eligible=False`: the report never signalled PR intent, so it must not open
+ one on its own."""
repository = _normalize_repository(repository)
if repository == NO_REPO:
return RepoSelectionResult(repository=None, reason="Scout passed NO_REPO; report lands without a draft PR.")
if repository is not None:
return RepoSelectionResult(repository=repository, reason="Repository provided by the scout.")
+ if not wants_full_selection:
+ connected_repos = await database_sync_to_async(_connected_repositories, thread_sensitive=False)(team_id)
+ linked = _extract_linked_repository(title, summary, evidence, connected_repos)
+ if linked is None:
+ return None
+ return RepoSelectionResult(
+ repository=linked,
+ reason=INFERRED_REPOSITORY_REASON,
+ autostart_eligible=False,
+ )
+
# Free-form: let the shared selector pick across the team's repos. Imports are deferred to keep the
# temporal/agentic + sandbox stack off this harness-tool module's import path (it loads at worker boot).
from products.signals.backend.report_generation.select_repo import (
@@ -1031,9 +1117,14 @@ async def emit_report(
surfaced = _surfaced(judgement.status)
repo_selection = (
await _resolve_report_repository(
- team_id=team.id, repository=repository, title=title, summary=summary, evidence=evidence
+ team_id=team.id,
+ repository=repository,
+ title=title,
+ summary=summary,
+ evidence=evidence,
+ wants_full_selection=_wants_repo_selection(repository, priority_assessment, reviewers),
)
- if surfaced and _wants_repo_selection(repository, priority_assessment, reviewers)
+ if surfaced
else None
)
persisted = await database_sync_to_async(create_scout_report, thread_sensitive=False)(
@@ -1155,9 +1246,14 @@ def emit_report_sync(
surfaced = _surfaced(judgement.status)
repo_selection = (
async_to_sync(_resolve_report_repository)(
- team_id=team.id, repository=repository, title=title, summary=summary, evidence=evidence
+ team_id=team.id,
+ repository=repository,
+ title=title,
+ summary=summary,
+ evidence=evidence,
+ wants_full_selection=_wants_repo_selection(repository, priority_assessment, reviewers),
)
- if surfaced and _wants_repo_selection(repository, priority_assessment, reviewers)
+ if surfaced
else None
)
persisted = create_scout_report(
@@ -1295,6 +1391,15 @@ def _do_edit_report(
attribution=attribution,
author=run.skill_name,
)
+ # A rewrite can move the report onto a different repository, and an inferred target is only ever a
+ # reading of that text. Outside the transaction above for the same reason autostart is: it reads
+ # the team's GitHub repo cache, which has no business holding the content write open.
+ #
+ # Ordered before autostart, because one edit can both rewrite the content and add a qualifying
+ # reviewer. Autostart reads the selection as it stands and is idempotent, so running it first
+ # would open the task against the repository the rewrite just replaced, with no second chance.
+ if updated_fields:
+ _refresh_inferred_repository(team_id=team.id, report_id=report_id, attribution=attribution)
# Re-run autostart only when reviewers changed: it's idempotent (a report with an implementation
# task already started no-ops), but a report that was missing a qualifying reviewer can now open a
# draft PR. Fired outside any txn since it spawns a Task — mirrors emit's post-commit hand-off.
diff --git a/products/signals/backend/scout_report/__init__.py b/products/signals/backend/scout_report/__init__.py
index 46ecebb47d85..1c73b479b998 100644
--- a/products/signals/backend/scout_report/__init__.py
+++ b/products/signals/backend/scout_report/__init__.py
@@ -9,6 +9,7 @@ code never touches `SignalReport` or the embeddings pipeline directly.
from products.signals.backend.report_charts import MAX_REPORT_CHARTS
from products.signals.backend.report_prompts import MAX_SUGGESTED_PROMPTS
from products.signals.backend.scout_report.persistence import (
+ INFERRED_REPOSITORY_REASON,
MAX_REPORT_SIGNALS,
InvalidScoutReportError,
PersistedScoutReport,
@@ -21,12 +22,14 @@ from products.signals.backend.scout_report.persistence import (
record_scout_run_task_artefact,
set_report_charts,
set_report_suggested_prompts,
+ set_scout_report_inferred_repository,
set_scout_report_reviewers,
soft_delete_scout_signal,
update_scout_report,
)
__all__ = [
+ "INFERRED_REPOSITORY_REASON",
"MAX_REPORT_CHARTS",
"MAX_REPORT_SIGNALS",
"MAX_SUGGESTED_PROMPTS",
@@ -41,6 +44,7 @@ __all__ = [
"record_scout_run_task_artefact",
"set_report_charts",
"set_report_suggested_prompts",
+ "set_scout_report_inferred_repository",
"set_scout_report_reviewers",
"soft_delete_scout_signal",
"update_scout_report",
diff --git a/products/signals/backend/scout_report/persistence.py b/products/signals/backend/scout_report/persistence.py
index 053dbfc7fd8e..8c8d4861e978 100644
--- a/products/signals/backend/scout_report/persistence.py
+++ b/products/signals/backend/scout_report/persistence.py
@@ -60,6 +60,10 @@ from products.signals.backend.scout_harness.tools.emit import SCOUT_SIGNAL_WEIGH
logger = logging.getLogger(__name__)
+# The `reason` on a selection read out of the report's own text. Shared with the emit path so the two
+# writers of an inferred selection stay indistinguishable to anything reading the artefact.
+INFERRED_REPOSITORY_REASON = "Linked GitHub repository found in the report content."
+
# Matches the grouping pipeline's signal rows (`assign_and_emit_signal_activity`): a scout-authored
# report's backing rows live in the same `document_embeddings` space so read-side queries that filter
# by `(product, document_type)` see them identically.
@@ -624,6 +628,43 @@ def set_scout_report_reviewers(
return True
+def set_scout_report_inferred_repository(
+ *,
+ team_id: int,
+ report_id: str,
+ repository: str,
+ attribution: ArtefactAttribution,
+) -> None:
+ """Replace the report's `repo_selection` artefact with a repository read out of its own content.
+
+ Only for the inferred selection `emit_report` writes for a report that never asked for a PR, so
+ the result is stamped `autostart_eligible=False` here rather than trusted from the caller — this
+ entry point must not be able to mint a selection that opens a PR on its own.
+
+ Team-scoped fail-closed: a `report_id` the team doesn't own raises. The append opts out of the
+ model's autostart re-eval hook, since a target the report merely links is not a reason to act.
+ """
+ _validate_report_id(report_id)
+ with transaction.atomic():
+ if not SignalReport.objects.select_for_update().filter(team_id=team_id, id=report_id).exists():
+ raise InvalidScoutReportError(f"report {report_id} not found for team {team_id}")
+ SignalReportArtefact.append_status(
+ team_id=team_id,
+ report_id=report_id,
+ content=RepoSelectionResult(
+ repository=repository,
+ reason=INFERRED_REPOSITORY_REASON,
+ autostart_eligible=False,
+ ),
+ attribution=attribution,
+ reevaluate_autostart=False,
+ )
+ logger.info(
+ "signals_scout.edit_report: inferred repository refreshed",
+ extra={"team_id": team_id, "report_id": report_id, "repository": repository},
+ )
+
+
def soft_delete_scout_signal(
*,
team_id: int,
diff --git a/products/signals/backend/temporal/agentic/report.py b/products/signals/backend/temporal/agentic/report.py
index 238b55b015a4..897d4ec6127e 100644
--- a/products/signals/backend/temporal/agentic/report.py
+++ b/products/signals/backend/temporal/agentic/report.py
@@ -456,6 +456,7 @@ async def _persist_agentic_report_artefacts(
actionability=result.effective_actionability(),
priority=result.effective_priority(),
reviewers_content=reviewers_content,
+ repository_autostart_eligible=repo_selection.autostart_eligible,
)
except Exception as error:
posthoganalytics.capture_exception(error)
diff --git a/products/signals/backend/test/test_agentic_report_activity.py b/products/signals/backend/test/test_agentic_report_activity.py
index 7503f1a61c25..b9c135f30e9a 100644
--- a/products/signals/backend/test/test_agentic_report_activity.py
+++ b/products/signals/backend/test/test_agentic_report_activity.py
@@ -427,6 +427,7 @@ async def test_run_agentic_report_activity_persists_artefacts(monkeypatch, ateam
"repository": "posthog/posthog",
"reason": "Single repository connected: posthog/posthog",
"task_id": None,
+ "autostart_eligible": True,
}
finding_contents = [json.loads(artefact.content) for artefact in artefacts[3:]]
diff --git a/products/signals/backend/test/test_auto_start.py b/products/signals/backend/test/test_auto_start.py
index 14187162d7a3..24b8319402a4 100644
--- a/products/signals/backend/test/test_auto_start.py
+++ b/products/signals/backend/test/test_auto_start.py
@@ -1,4 +1,5 @@
import re
+import json
from types import SimpleNamespace
import pytest
@@ -23,6 +24,7 @@ from products.signals.backend.auto_start import (
_resolve_autostart_assignee,
_resolve_autostart_fallback_user,
_resolve_triggering_user,
+ maybe_autostart_from_report_artefacts,
maybe_autostart_implementation_task,
)
from products.signals.backend.models import (
@@ -699,3 +701,119 @@ async def test_quota_gate_blocks_autostart_only_when_enforced(enforced):
)
assert (mock_create.call_count == 0) is enforced
+
+
[email protected]_db(transaction=True)
[email protected]("autostart_eligible", [True, False])
+async def test_repo_selection_eligibility_reaches_autostart(autostart_eligible):
+ # The re-eval reads the flag off the persisted artefact and hands it to autostart rather than
+ # deciding for itself, so a reviewer edit arriving later still gets the whole gate applied.
+ def _setup() -> tuple[Team, SignalReport]:
+ organization = Organization.objects.create(name="inferred-org")
+ team = Team.objects.create(organization=organization, name="inferred-team")
+ report = SignalReport.objects.create(
+ team=team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=0, total_weight=0.0
+ )
+ for artefact_type, content in (
+ (
+ SignalReportArtefact.ArtefactType.ACTIONABILITY_JUDGMENT,
+ {
+ "explanation": "Clear fix in the affected module.",
+ "actionability": ActionabilityChoice.IMMEDIATELY_ACTIONABLE.value,
+ "already_addressed": False,
+ },
+ ),
+ (
+ SignalReportArtefact.ArtefactType.REPO_SELECTION,
+ {
+ "repository": "owner/repo",
+ "reason": "Linked GitHub repository found in the report content.",
+ "autostart_eligible": autostart_eligible,
+ },
+ ),
+ (
+ SignalReportArtefact.ArtefactType.PRIORITY_JUDGMENT,
+ {"explanation": "Affects many sessions.", "priority": Priority.P2.value},
+ ),
+ ):
+ SignalReportArtefact.objects.create(
+ team=team, report=report, type=artefact_type, content=json.dumps(content)
+ )
+ return team, report
+
+ team, report = await sync_to_async(_setup)()
+
+ with patch("products.signals.backend.auto_start.maybe_autostart_implementation_task") as mock_autostart:
+ await maybe_autostart_from_report_artefacts(team_id=team.id, report_id=str(report.id))
+
+ assert mock_autostart.call_args.kwargs["repository_autostart_eligible"] is autostart_eligible
+
+
[email protected]_db(transaction=True)
+ ("repository_autostart_eligible", "user_triggered", "expect_task"),
+ [
+ (True, False, True),
+ (False, False, False),
+ (False, True, True),
+ ],
+)
+async def test_inferred_repository_only_blocks_the_reviewerless_fallback(
+ repository_autostart_eligible, user_triggered, expect_task
+):
+ # A repo read out of the report's own text is a target for whoever clicks Create PR, so it must not
+ # reach the reviewer-less fallback — the one path where nobody named the destination or the runner.
+ # It must still yield to a person: a later reviewer edit re-runs autostart as the editing user, and
+ # the documented contract is that the report can open a draft PR then.
+ Task = apps.get_model("tasks", "Task")
+ TaskRun = apps.get_model("tasks", "TaskRun")
+
+ def _setup() -> tuple[Team, SignalReport, User]:
+ organization = Organization.objects.create(name="inferred-org")
+ team = Team.objects.create(organization=organization, name="inferred-team")
+ enabler = User.objects.create(email="[email protected]")
+ OrganizationMembership.objects.create(user=enabler, organization=organization)
+ SignalSourceConfig.objects.create(
+ team=team, source_product="error_tracking", source_type="issue_created", created_by=enabler
+ )
+ report = SignalReport.objects.create(
+ team=team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=0, total_weight=0.0
+ )
+ return team, report, enabler
+
+ team, report, enabler = await sync_to_async(_setup)()
+
+ def _fake_create_and_run_task(**kwargs):
+ task = Task.objects.create(
+ team_id=team.id,
+ title=kwargs["title"],
+ description=kwargs["description"],
+ origin_product=Task.OriginProduct.SIGNAL_REPORT,
+ )
+ run = TaskRun.objects.create(task=task, team_id=team.id)
+ return SimpleNamespace(task_id=task.id, team_id=team.id, latest_run=SimpleNamespace(id=run.id))
+
+ with (
+ patch.object(tasks_facade, "create_and_run_task", side_effect=_fake_create_and_run_task) as mock_create,
+ patch("products.signals.backend.auto_start.resolve_agent_runtime", return_value=AgentRuntime()),
+ ):
+ await maybe_autostart_implementation_task(
+ team_id=team.id,
+ report_id=str(report.id),
+ repository="owner/repo",
+ title="t",
+ summary="s",
+ actionability=ActionabilityAssessment(
+ explanation="Clear fix in the affected module.",
+ actionability=ActionabilityChoice.IMMEDIATELY_ACTIONABLE,
+ already_addressed=False,
+ ),
+ reviewers_content=[],
+ priority=PriorityAssessment(explanation="Affects many sessions.", priority=Priority.P2),
+ triggering_user_id=enabler.id if user_triggered else None,
+ repository_autostart_eligible=repository_autostart_eligible,
+ )
+
+ assert (mock_create.call_count == 1) is expect_task
diff --git a/products/signals/backend/test/test_scout_report_api.py b/products/signals/backend/test/test_scout_report_api.py
index c101a0c472f7..a5bcafe5fea2 100644
--- a/products/signals/backend/test/test_scout_report_api.py
+++ b/products/signals/backend/test/test_scout_report_api.py
@@ -8,6 +8,7 @@ from unittest.mock import AsyncMock, patch
from django.apps import apps
from django.test import SimpleTestCase
+from asgiref.sync import async_to_sync, sync_to_async
from parameterized import parameterized
from rest_framework import status
from social_django.models import UserSocialAuth
@@ -24,15 +25,19 @@ from products.signals.backend.scout_harness.tools.report import (
EditReportResult,
InvalidScoutReportError,
ReportChartInput,
+ ReportEvidence,
ReviewerInput,
_build_suggested_reviewers,
_capture_report_edited,
+ _extract_linked_repository,
_report_classification_props,
+ _resolve_report_repository,
_wants_repo_selection,
)
from products.signals.backend.temporal.report_safety_judge import SafetyJudgeResponse
from products.signals.backend.test.test_scout_harness_api import _authenticate_as_scout, _make_run
from products.skills.backend.models.skills import LLMSkill, LLMSkillOwner
+from products.tasks.backend.facade.repo_selection import RepoSelectionResult
JUDGE_PATH = "products.signals.backend.scout_report.judge.judge_report_safety"
EMBED_PATH = "products.signals.backend.scout_report.persistence.emit_embedding_request"
@@ -41,6 +46,8 @@ AUTOSTART_PATH = "products.signals.backend.auto_start.maybe_autostart_from_repor
CAPTURE_PATH = "products.signals.backend.scout_harness.tools.report.posthoganalytics.capture"
# The customer-facing copy lands in the scout's own team project via capture_internal (a network boundary).
CAPTURE_INTERNAL_PATH = "products.signals.backend.scout_harness.tools.report.capture_internal"
+CONNECTED_REPOS_PATH = "products.signals.backend.scout_harness.tools.report._connected_repositories"
+_CONNECTED_REPOS = ["acme/widgets", "acme/gadgets"]
REPORT_TOOLS = ["emit_report", "edit_report"]
@@ -343,6 +350,71 @@ class TestScoutReportAPI(APIBaseTest):
SignalReportArtefact.objects.filter(report_id=report_id, type=artefact_type).order_by("-created_at").first()
)
+ @parameterized.expand(
+ [
+ ("inferred_target_follows_the_rewrite", None, "acme/gadgets"),
+ # A repo the scout named is a decision, not a reading of the prose, so a rewrite never moves it.
+ ("scout_named_target_is_not_overturned", "acme/widgets", "acme/widgets"),
+ ]
+ )
+ def test_content_rewrite_refreshes_only_an_inferred_repository(
+ self, _name: str, repository: str | None, expected: str
+ ) -> None:
+ run = _make_run(self.team)
+ payload = self._payload(summary="Traced to https://github.com/acme/widgets/pull/7")
+ if repository is not None:
+ payload["repository"] = repository
+ with (
+ _safe_judge(),
+ patch(EMBED_PATH),
+ patch(CONNECTED_REPOS_PATH, return_value=_CONNECTED_REPOS),
+ ):
+ created = self.client.post(self._emit_url(str(run.id)), data=payload, format="json").json()
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={"report_id": created["report_id"], "summary": "Actually https://github.com/acme/gadgets/pull/2"},
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ artefact = self._latest_artefact(created["report_id"], SignalReportArtefact.ArtefactType.REPO_SELECTION)
+ assert artefact is not None
+ assert json.loads(artefact.content)["repository"] == expected
+
+ def test_combined_rewrite_and_reviewer_edit_autostarts_on_the_refreshed_repository(self) -> None:
+ # One edit can both move the report onto a new repository and add the reviewer that lets an
+ # inferred target autostart. Autostart reads the selection as it stands and is idempotent, so
+ # refreshing after it would open the implementation task against the repository the same edit
+ # just replaced, with no second chance to correct it.
+ run = _make_run(self.team)
+ payload = self._payload(summary="Traced to https://github.com/acme/widgets/pull/7")
+ with (
+ _safe_judge(),
+ patch(EMBED_PATH),
+ patch(CONNECTED_REPOS_PATH, return_value=_CONNECTED_REPOS),
+ ):
+ created = self.client.post(self._emit_url(str(run.id)), data=payload, format="json").json()
+ repository_at_autostart: list[str | None] = []
+
+ async def _capture(**kwargs) -> None:
+ artefact = await sync_to_async(self._latest_artefact)(
+ created["report_id"], SignalReportArtefact.ArtefactType.REPO_SELECTION
+ )
+ repository_at_autostart.append(json.loads(artefact.content)["repository"] if artefact else None)
+
+ with patch(AUTOSTART_PATH, new=AsyncMock(side_effect=_capture)) as autostart:
+ response = self.client.post(
+ self._edit_url(str(run.id)),
+ data={
+ "report_id": created["report_id"],
+ "summary": "Actually https://github.com/acme/gadgets/pull/2",
+ "suggested_reviewers": [{"github_login": "octocat"}],
+ },
+ format="json",
+ )
+ assert response.status_code == status.HTTP_200_OK, response.json()
+ autostart.assert_awaited_once()
+ assert repository_at_autostart == ["acme/gadgets"]
+
def test_emit_report_writes_autostart_artefacts(self) -> None:
# The autostart inputs the scout supplies become the same artefacts a pipeline report carries,
# which is what `maybe_autostart_from_report_artefacts` reads to open a draft PR. Repo is normalized.
@@ -1116,6 +1188,76 @@ class TestWantsRepoSelection(SimpleTestCase):
assert _wants_repo_selection(repository, priority, reviewers) is expected
+def _evidence(*descriptions: str) -> list[ReportEvidence]:
+ return [ReportEvidence(description=d, source_id=f"s{i}") for i, d in enumerate(descriptions)]
+
+
+class TestExtractLinkedRepository(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("root_url", "", "See https://github.com/acme/widgets for context", (), "acme/widgets"),
+ ("deep_pull_link", "", "Broke in https://github.com/acme/widgets/pull/12", (), "acme/widgets"),
+ ("case_and_git_suffix", "", "https://github.com/Acme/Widgets.git broke", (), "acme/widgets"),
+ ("trailing_period", "", "Fixed in https://github.com/acme/widgets.", (), "acme/widgets"),
+ ("clone_url_ending_a_sentence", "", "Clone https://github.com/acme/widgets.git.", (), "acme/widgets"),
+ ("from_evidence", "", "no link here", ("https://github.com/acme/widgets/blob/main/x.py",), "acme/widgets"),
+ # A report summary is markdown, so its links usually arrive labelled rather than bare.
+ ("markdown_link", "", "Broke in [PR 12](https://github.com/acme/widgets/pull/12)", (), "acme/widgets"),
+ (
+ "same_repo_twice",
+ "https://github.com/acme/widgets",
+ "and https://github.com/acme/widgets/pull/1",
+ (),
+ "acme/widgets",
+ ),
+ (
+ "two_distinct_repos",
+ "https://github.com/acme/widgets",
+ "vs https://github.com/acme/gadgets",
+ (),
+ None,
+ ),
+ ("no_link", "A plain title", "Users hit read/write errors in acme/widgets", (), None),
+ ("unconnected_upstream_repo", "", "Upstream bug: https://github.com/other/sdk/issues/3", (), None),
+ ("feature_path_not_repo", "", "Configured at https://github.com/apps/dependabot", (), None),
+ ]
+ )
+ def test_extract_linked_repository(
+ self, _name: str, title: str, summary: str, evidence_descriptions: tuple[str, ...], expected: str | None
+ ) -> None:
+ assert (
+ _extract_linked_repository(title, summary, _evidence(*evidence_descriptions), _CONNECTED_REPOS) == expected
+ )
+
+ def test_no_connected_repos_resolves_nothing(self) -> None:
+ assert _extract_linked_repository("", "https://github.com/acme/widgets", _evidence(), []) is None
+
+
+class TestResolveReportRepositoryGateSkipped(SimpleTestCase):
+ def _resolve(self, summary: str) -> RepoSelectionResult | None:
+ with patch(
+ "products.signals.backend.scout_harness.tools.report._connected_repositories",
+ return_value=_CONNECTED_REPOS,
+ ):
+ return async_to_sync(_resolve_report_repository)(
+ team_id=1,
+ repository=None,
+ title="Crash on upload",
+ summary=summary,
+ evidence=_evidence(),
+ wants_full_selection=False,
+ )
+
+ def test_linked_repo_seeds_a_manual_only_target(self) -> None:
+ result = self._resolve("Traced to https://github.com/acme/widgets/pull/7")
+ assert result is not None
+ assert result.repository == "acme/widgets"
+ assert result.autostart_eligible is False
+
+ def test_no_linked_repo_writes_nothing(self) -> None:
+ assert self._resolve("No repository named here") is None
+
+
class TestReportClassificationProps(SimpleTestCase):
@parameterized.expand(
[
diff --git a/products/signals/skills/authoring-scouts/references/report-contract.md b/products/signals/skills/authoring-scouts/references/report-contract.md
index 370d70a508d1..9ef9eda15fb1 100644
--- a/products/signals/skills/authoring-scouts/references/report-contract.md
+++ b/products/signals/skills/authoring-scouts/references/report-contract.md
@@ -169,8 +169,11 @@ It's opt-in per report via three more `emit_report` fields; supply them only whe
| `priority_explanation` | string | Required when `priority` is set. |
| `suggested_reviewers` | list of obj | Reviewers to consider, each `{github_login?, user_uuid?}` (at least one per entry; see the section below). A PR opens only if at least one clears their autonomy threshold. |
-Repo selection only runs when you signal PR intent — an explicit `repository`, or both `priority` and `suggested_reviewers`.
-A report that supplies none of these just surfaces in the inbox (no repo sandbox, no PR).
+Full repo selection only runs when you signal PR intent — an explicit `repository`, or both `priority` and `suggested_reviewers`.
+A report that supplies none of these just surfaces in the inbox: no repo sandbox, and no PR.
+It still gets a repo target when its own text links exactly one repository the team has connected on GitHub, so someone reading it can click Create PR.
+That inferred target is for a person to act on — it never opens a PR by itself, and rewriting the report's title or summary to link a different connected repository moves it.
+Adding a qualifying reviewer later is a person asking for the PR, so the report can open a draft one from then on.
Autostart itself still no-ops unless the report is `immediately_actionable`, has a repo + priority, and a reviewer qualifies — so these fields are safe to omit for an informational report.
## Choosing `suggested_reviewers` — how a report gets assigned to a human
diff --git a/products/tasks/backend/facade/repo_selection.py b/products/tasks/backend/facade/repo_selection.py
index 8e8746d1a8a1..c1f26e6243c6 100644
--- a/products/tasks/backend/facade/repo_selection.py
+++ b/products/tasks/backend/facade/repo_selection.py
@@ -11,6 +11,7 @@ from products.tasks.backend.logic.repo_selection import (
RepoSelectionRejectedError,
RepoSelectionResult,
RepoSelectionUnavailableError,
+ list_team_connected_repositories,
resolve_team_github_integration,
select_repository,
)
@@ -20,6 +21,7 @@ __all__ = [
"RepoSelectionRejectedError",
"RepoSelectionResult",
"RepoSelectionUnavailableError",
+ "list_team_connected_repositories",
"resolve_team_github_integration",
"select_repository",
]
diff --git a/products/tasks/backend/logic/repo_selection/__init__.py b/products/tasks/backend/logic/repo_selection/__init__.py
index 30205bd0e641..bbc181ca6a5f 100644
--- a/products/tasks/backend/logic/repo_selection/__init__.py
+++ b/products/tasks/backend/logic/repo_selection/__init__.py
@@ -10,6 +10,7 @@ if TYPE_CHECKING:
REPO_SELECTION_DUMMY_REPOSITORY,
RepoSelectionRejectedError,
RepoSelectionUnavailableError,
+ list_team_connected_repositories,
resolve_team_github_integration,
select_repository,
)
@@ -20,6 +21,7 @@ __all__ = [
"RepoSelectionRejectedError",
"RepoSelectionResult",
"RepoSelectionUnavailableError",
+ "list_team_connected_repositories",
"resolve_team_github_integration",
"select_repository",
"select_repository_for_message",
@@ -33,6 +35,7 @@ _LAZY_FROM_AGENT = frozenset(
"REPO_SELECTION_DUMMY_REPOSITORY",
"RepoSelectionRejectedError",
"RepoSelectionUnavailableError",
+ "list_team_connected_repositories",
"resolve_team_github_integration",
"select_repository",
}
diff --git a/products/tasks/backend/logic/repo_selection/agent.py b/products/tasks/backend/logic/repo_selection/agent.py
index 2bf45c604350..9715cae03eaf 100644
--- a/products/tasks/backend/logic/repo_selection/agent.py
+++ b/products/tasks/backend/logic/repo_selection/agent.py
@@ -175,13 +175,17 @@ async def _github_reconnect_required(team_id: int) -> bool:
).aexists()
-def _list_candidate_repos(github: GitHubIntegrationBase, team_id: int, *, allow_refresh: bool = True) -> list[str]:
+def _list_candidate_repos(
+ github: GitHubIntegrationBase, team_id: int, *, allow_refresh: bool = True, exclude_archived: bool = False
+) -> list[str]:
"""Fetch all repositories accessible via the resolved GitHub source."""
repos: set[str] = set()
for repo in github.list_all_cached_repositories(max_repos=_MAX_GITHUB_REPOS, allow_refresh=allow_refresh):
full_name = repo.get("full_name")
if not full_name:
continue
+ if exclude_archived and repo.get("archived") is True:
+ continue
repos.add(full_name.lower())
if len(repos) >= _MAX_GITHUB_REPOS:
logger.warning(
@@ -194,6 +198,28 @@ def _list_candidate_repos(github: GitHubIntegrationBase, team_id: int, *, allow_
return sorted(repos)
+def list_team_connected_repositories(team_id: int) -> list[str]:
+ """The `owner/repo` names the team's own GitHub installation can reach, lowercased.
+
+ The candidate list without the agent — for a caller that already has a repository in hand and
+ only needs to know whether the team connected it. `team_only` because such a caller runs under
+ the team's identity with no requester to act for, and the personal-connection fallbacks would
+ let one member's private repos answer for the team. Reads the cache as-is: an unattended caller
+ should not make a repo check storm GitHub with refreshes.
+
+ Archived repos are dropped for the same reason `select_repository` drops them: a caller resolves
+ a repository to change code in, and an archived one accepts no change. The flag comes from the
+ light cache rather than `_list_eligible_full_names`, whose heavy `repository_cache_entries` rows
+ only `sync_full_cache()` writes — a sync this path deliberately never runs, so intersecting with
+ it would answer "nothing is connected" for every team yet to run a full selection. Absent heavy
+ metadata therefore reads as unknown here, not as archived.
+ """
+ github = resolve_team_github_integration(team_id, team_only=True)
+ if github is None:
+ return []
+ return _list_candidate_repos(github, team_id, allow_refresh=False, exclude_archived=True)
+
+
def _list_eligible_full_names(github: GitHubIntegrationBase, team_id: int) -> set[str]:
"""Repos the agent can reason about: present in the heavy cache and not archived.
Anything else is dropped from the candidate list (no SQL evidence, or unfixable code)."""
@@ -211,6 +237,9 @@ def _build_repo_selection_prompt(context_block: str, candidate_repos: list[str])
schema = RepoSelectionResult.model_json_schema()
# `task_id` is system-set after the run — keep it out of the agent's output contract.
schema.get("properties", {}).pop("task_id", None)
+ # So is `autostart_eligible`: it records how the repo was chosen, which is the caller's fact,
+ # not the model's. Offering it would let untrusted context talk the model into vetoing autostart.
+ schema.get("properties", {}).pop("autostart_eligible", None)
schema_json = json.dumps(schema, indent=2)
repo_list = "\n".join(f"{i + 1}. `{repo}`" for i, repo in enumerate(candidate_repos))
@@ -481,6 +510,9 @@ async def select_repository(
# Stamp the producing task onto the result (overwriting anything the LLM may have emitted)
# so downstream persistence can attribute the selection to it.
result.task_id = str(session.task.id)
+ # A selection this agent made is a candidate-list pick for a caller that asked for one, so it
+ # carries full autostart authority no matter what the model emitted.
+ result.autostart_eligible = True
try:
if result.repository is not None:
result.repository = result.repository.strip().lower()
diff --git a/products/tasks/backend/logic/repo_selection/types.py b/products/tasks/backend/logic/repo_selection/types.py
index 3860ff39acf2..7a749e62a3d0 100644
--- a/products/tasks/backend/logic/repo_selection/types.py
+++ b/products/tasks/backend/logic/repo_selection/types.py
@@ -29,3 +29,10 @@ class RepoSelectionResult(BaseModel):
default=None,
description="UUID of the sandbox task that performed the selection, when an agent ran.",
)
+ # Inferring a repo from content is weaker evidence than a caller naming one: it says "this is the
+ # repo a person would target", not "open a PR here". Autostart needs the second, so an inferred
+ # selection is a target for a human-triggered run only.
+ autostart_eligible: bool = Field(
+ default=True,
+ description="Whether this selection may start an implementation task without a person asking for one.",
+ )
diff --git a/products/tasks/backend/tests/test_repo_selection_cascade.py b/products/tasks/backend/tests/test_repo_selection_cascade.py
index 32fcf65433d9..2d7e841d97da 100644
--- a/products/tasks/backend/tests/test_repo_selection_cascade.py
+++ b/products/tasks/backend/tests/test_repo_selection_cascade.py
@@ -3,10 +3,12 @@ from unittest.mock import MagicMock, patch
from posthog.models.integration import Integration
+from products.tasks.backend.logic.repo_selection.agent import list_team_connected_repositories
from products.tasks.backend.logic.repo_selection.cascade import cascade_select_repository, select_repository_for_message
from products.tasks.backend.models import Task
_CASCADE = "products.tasks.backend.logic.repo_selection.cascade"
+_AGENT = "products.tasks.backend.logic.repo_selection.agent"
def _patch_candidates(github: object | None, candidates: list[str]):
@@ -67,3 +69,38 @@ class TestCascadeSelectRepository:
assert cascade_select_repository(team.id, None, "", single_repo_wins=True, allow_refresh=False) == (
"posthog/posthog"
)
+
+
+class TestListTeamConnectedRepositories:
+ @pytest.mark.django_db
+ def test_light_snapshot_answers_without_a_pre_warmed_heavy_cache(self, team):
+ # Only the full selector's sync_full_cache() writes repository_cache_entries, and the
+ # gate-skipped caller deliberately never runs it. Reading connectivity from those rows would
+ # answer "nothing is connected" for every team yet to run a full selection, so a report
+ # linking a repo would silently get no inferred target on the very first try.
+ Integration.objects.create(
+ team=team,
+ kind="github",
+ integration_id="gh-1",
+ config={"installation_id": "gh-1"},
+ sensitive_config={},
+ repository_cache=[
+ {"full_name": "PostHog/PostHog", "name": "PostHog", "id": 1},
+ {"full_name": "acme/retired", "name": "retired", "id": 2, "archived": True},
+ ],
+ )
+
+ assert list_team_connected_repositories(team.id) == ["posthog/posthog"]
+
+ def test_archived_repositories_are_excluded(self):
+ # An inferred selection is authoritative in the manual Create PR flow, so an archived repo
+ # hands a person a target that cannot accept the change. A repo cached before the flag
+ # existed carries none and stays a candidate rather than being treated as archived.
+ github = MagicMock()
+ github.list_all_cached_repositories.return_value = [
+ {"full_name": "owner/unknown"},
+ {"full_name": "owner/stale", "archived": True},
+ {"full_name": "owner/active", "archived": False},
+ ]
+ with patch(f"{_AGENT}.resolve_team_github_integration", return_value=github):
+ assert list_team_connected_repositories(1) == ["owner/active", "owner/unknown"]