: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
feat(self-driving): BE for Wizard for Self-driving (#64869)
Alex Lebedev09c32499d800
diff --git a/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.test.tsx b/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.test.tsxnew file mode 100644index 000000000000..396974d97e56--- /dev/null+++ b/frontend/src/lib/components/CyclotronJob/integrations/IntegrationChoice.test.tsx@@ -0,0 +1,64 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen, waitFor } from '@testing-library/react'+import { Provider } from 'kea'++import { useMocks } from '~/mocks/jest'+import { initKeaTests } from '~/test/init'+import { IntegrationType } from '~/types'++import { IntegrationChoice } from './IntegrationChoice'++const GITHUB_INTEGRATION: IntegrationType = {+ id: 1,+ kind: 'github',+ display_name: 'sortafreel',+ icon_url: '',+ config: {},+ created_by: null,+ created_at: '2026-01-01T00:00:00Z',+}++describe('IntegrationChoice', () => {+ beforeEach(() => {+ useMocks({+ get: {+ '/api/environments/:team_id/integrations': () => [200, { results: [GITHUB_INTEGRATION] }],+ },+ })+ initKeaTests()+ })++ afterEach(() => {+ cleanup()+ })++ it('matches a string-typed id to its numeric connection (no false "no longer available")', async () => {+ // MCP-created data-warehouse sources persist the integration id as the string "1", while+ // the integration's real id is the number 1. The connection exists, so the warning must+ // NOT show — the connected integration resolves and the menu offers "Change".+ render(+ <Provider>+ <IntegrationChoice integration="github" value={'1' as unknown as number} onChange={jest.fn()} />+ </Provider>+ )++ await waitFor(() => {+ expect(screen.getByText('Change')).toBeInTheDocument()+ })+ expect(screen.queryByText(/no longer available/)).not.toBeInTheDocument()+ })++ it('still warns when the stored id matches no integration', async () => {+ // Regression guard: a genuinely dangling reference must keep surfacing the banner.+ render(+ <Provider>+ <IntegrationChoice integration="github" value={999} onChange={jest.fn()} />+ </Provider>+ )++ await waitFor(() => {+ expect(screen.getByText(/no longer available/)).toBeInTheDocument()+ })+ })+})diff --git a/products/integrations/mcp/tools.yaml b/products/integrations/mcp/tools.yamlindex f0eca9eb91f4..a0bbd53632ac 100644--- a/products/integrations/mcp/tools.yaml+++ b/products/integrations/mcp/tools.yaml@@ -114,7 +114,20 @@ tools:enabled: falseintegrations-github-repos-retrieve:operation: integrations_github_repos_retrieve- enabled: false+ enabled: true+ scopes:+ - integration:read+ annotations:+ readOnly: true+ destructive: false+ idempotent: true+ title: List GitHub integration repositories+ description: >+ List the repositories accessible to a GitHub integration (by integration ID). Serves the cached repository+ list from the GitHub App installation. Supports `search` (case-insensitive name match), `limit` (default+ 100, max 500), and `offset` query parameters. Returns repository id, name, and full_name (owner/repo) plus a+ has_more flag. Use this to validate that a repository is accessible to the integration before referencing it+ (e.g. when creating a GitHub data warehouse source).integrations-github-teams-retrieve:operation: integrations_github_teams_retrieveenabled: falsediff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.mdindex ee2c80a0a3f7..94810337ed98 100644--- a/products/signals/ARCHITECTURE.md+++ b/products/signals/ARCHITECTURE.md@@ -1016,6 +1016,31 @@ Both `report` and `task` FKs cascade on delete — deleting a report or task cleSeparate from report generation, the `emit-eval-signal` workflow uses `call_llm()` with extended thinking to turn an LLMA evaluation result into a signal-sized description plus significance score. Low-significance eval results are dropped before calling `emit_signal()`.+### Resetting self-driving state for local re-testing++The self-driving wizard (`npx @posthog/wizard … self-driving`) enables signal sources, materializes and enables the scout fleet, and creates custom `signals-scout-*` skills for the project. To re-test a run from a clean slate without manually undoing each change, use the dev-only `reset_signals_self_driving` command (the practical inverse of `enable_signals_autonomy`; `DEBUG`-gated like `cleanup_signals`):++```text+python manage.py reset_signals_self_driving --team-id 1 --yes \+ --install-dir /path/to/your/test/project+```++For a fresh team the signals config tables are empty, so the reset **deletes** rather than disables — the next wizard run's `sync` call re-creates the canonical fleet (enabled) exactly as it would for a brand-new team. (Disabling instead would leave the fleet off on the next run, since the wizard's scout step only _disables_ misfits and relies on the fresh default being enabled.)++Cleared for the team:++| What | Tables / artifacts |+| ------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| Signal sources | `SignalSourceConfig` (all rows) |+| Scout fleet config | `SignalScoutConfig` (all rows) |+| Custom scouts | `LLMSkill` rows whose `name` starts `signals-scout-` and are **not** seeded — i.e. not in the set of names carrying `metadata.seeded_by == "signals_scout_harness"` (covers the common case where the key is absent entirely) (cascades `LLMSkillFile`) |+| Scout run-state | `SignalScratchpad`, `SignalProjectProfile`, `SignalScoutRun`, `SignalEmissionRecord` |+| Emitted findings | `SignalReport` + artefacts + ClickHouse rows + Temporal workflows (delegates to `cleanup_signals`; skip with `--keep-findings`) |+| Wizard report | `<install-dir>/posthog-self-driving-report.md` (only if `--install-dir` is given) |+| Wizard log | `/tmp/posthog-wizard.log` → backed up to `/tmp/posthog-wizard-previous-<timestamp>.log` then removed (override `--wizard-log`, skip `--keep-log`) |++Preserved: canonical scouts and the `authoring-signals-scouts` companion, identified by `metadata.seeded_by == "signals_scout_harness"`. That tag is the practical marker this DEBUG reset uses; it is not a perfect canonical test on its own — `_scout_origin` also requires the name to ship on disk, since `duplicate_skill` copies the tag verbatim — but the wizard authors custom scouts via `llma-skill-create` with no tag, so tag-only suffices here. The command does **not** touch `SignalTeamConfig` or `SignalUserAutonomyConfig` (autostart / per-user opt-in are set by `enable_signals_autonomy`, not the wizard), and the `llm_analytics` source is always enabled in code regardless of its config row.+---## Data Types (`backend/temporal/types.py`)@@ -1120,6 +1145,7 @@ products/signals/│ │ ├── list_signal_reports.py│ │ ├── parse_sandbox_log.py│ │ ├── reingest_team_signals.py # Starts TeamSignalReingestionWorkflow for a team+│ │ ├── reset_signals_self_driving.py # Dev-only: undo a self-driving wizard run (configs, custom scouts, run-state)│ │ ├── run_signals_scout.py # One-shot scout run; bypasses the coordinator│ │ ├── select_repo.py│ │ ├── signal_pipeline_status.pydiff --git a/products/signals/backend/management/commands/reset_signals_self_driving.py b/products/signals/backend/management/commands/reset_signals_self_driving.pynew file mode 100644index 000000000000..97f27bfa1d36--- /dev/null+++ b/products/signals/backend/management/commands/reset_signals_self_driving.py@@ -0,0 +1,252 @@+import os+import shutil+from datetime import datetime++from django.conf import settings+from django.core.management import call_command+from django.core.management.base import BaseCommand, CommandError+from django.db import transaction+from django.utils import timezone++from posthog.models import Team++from products.signals.backend.models import (+ SignalEmissionRecord,+ SignalProjectProfile,+ SignalScoutConfig,+ SignalScoutRun,+ SignalScratchpad,+ SignalSourceConfig,+)+from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX+from products.skills.backend.models.skills import LLMSkill++# Seed tag stamped on canonical scouts + the `authoring-signals-scouts` companion; this DEBUG+# reset preserves tagged rows. Not a perfect canonical marker (`_scout_origin` also checks the+# name ships on disk), but wizard customs (`llma-skill-create`) carry no tag, so tag-only suffices.+SEEDED_BY_HARNESS = "signals_scout_harness"++# Basename the wizard's agent writes into its `--install-dir` after a self-driving run.+SELF_DRIVING_REPORT_FILE = "posthog-self-driving-report.md"+++class Command(BaseCommand):+ help = (+ "Reset a team to its pre-self-driving state so the self-driving wizard can be "+ "re-tested from scratch. Deletes signal sources, the scout fleet config, custom "+ "scouts, scout run-state (and, unless --keep-findings, emitted findings via "+ "cleanup_signals); optionally removes the wizard's report file and cycles its log. "+ "DEBUG only."+ )++ def add_arguments(self, parser):+ parser.add_argument(+ "--team-id",+ type=int,+ required=True,+ help="Team ID to reset self-driving state for",+ )+ parser.add_argument(+ "--yes",+ action="store_true",+ help="Skip confirmation prompt",+ )+ parser.add_argument(+ "--install-dir",+ type=str,+ default=None,+ help=(+ "The wizard's --install-dir (the test project). When given, removes "+ f"<install-dir>/{SELF_DRIVING_REPORT_FILE}."+ ),+ )+ parser.add_argument(+ "--wizard-log",+ type=str,+ default="/tmp/posthog-wizard.log",+ help="Path to the wizard log. Backed up to <stem>-previous-<timestamp><ext> then removed.",+ )+ parser.add_argument(+ "--keep-log",+ action="store_true",+ help="Do not back up or remove the wizard log.",+ )+ parser.add_argument(+ "--keep-findings",+ action="store_true",+ help="Do not clear emitted findings/reports (skips the cleanup_signals delegation).",+ )++ def handle(self, *args, **options):+ if not settings.DEBUG:+ raise CommandError("This command can only be run with DEBUG=True")++ try:+ team = Team.objects.get(id=options["team_id"])+ except Team.DoesNotExist:+ raise CommandError(f"Team {options['team_id']} not found")++ if not options["yes"]:+ self.stdout.write(+ self.style.WARNING(+ f"This will DELETE all Signals self-driving state for team {team.id} "+ f"(sources, scout fleet config, custom scouts, scout run-state"+ f"{'' if options['keep_findings'] else ', emitted findings'}). "+ f"Canonical scouts are preserved."+ )+ )+ confirm = input("Type 'yes' to confirm: ")+ if confirm != "yes":+ self.stdout.write("Aborted.")+ return++ # 1. Emitted findings/reports + ClickHouse rows + Temporal workflows. Delegated to+ # cleanup_signals because it owns the ClickHouse mutations and workflow termination;+ # run it first and OUTSIDE our Postgres transaction (it touches non-Postgres systems).+ if not options["keep_findings"]:+ self.stdout.write("Clearing emitted findings via cleanup_signals...")+ call_command("cleanup_signals", team_id=team.id, yes=True)++ # 2. Postgres self-driving state, atomically.+ with transaction.atomic():+ # Custom scouts: every version of each `signals-scout-*` skill NOT stamped by the+ # seeding harness. We partition by SET DIFFERENCE (all scout names minus seeded+ # names), NOT `.exclude(metadata__seeded_by=...)`. An ABSENT JSONB key makes+ # `metadata->>'seeded_by'` SQL NULL, and `NOT (NULL = '...')` is NULL (not TRUE),+ # so `.exclude()` silently skips rows whose metadata has no `seeded_by` key at all+ # — which is the common case for a wizard-/hand-authored scout. The set diff is+ # NULL-safe: a name is custom iff it is a scout name not among the seeded ones.+ # No seeded name can land in `custom_scout_names`, so deleting by `name__in`+ # (every version) never touches a canonical/companion row, and cascades LLMSkillFile.+ scout_skills = LLMSkill.objects.filter(+ team_id=team.id,+ name__startswith=SIGNALS_SCOUT_SKILL_PREFIX,+ is_latest=True,+ deleted=False,+ )+ all_scout_names = set(scout_skills.values_list("name", flat=True))+ seeded_scout_names = set(+ scout_skills.filter(metadata__seeded_by=SEEDED_BY_HARNESS).values_list("name", flat=True)+ )+ custom_scout_names = sorted(all_scout_names - seeded_scout_names)+ skills_deleted = 0+ if custom_scout_names:+ skills_deleted, _ = LLMSkill.objects.filter(team_id=team.id, name__in=custom_scout_names).delete()++ # Scout fleet config (canonical + custom). Deleting — not disabling — restores the+ # fresh-team shape: the next wizard `sync` re-creates canonical configs enabled.+ scout_configs_deleted, _ = SignalScoutConfig.all_teams.filter(team=team).delete()++ # Signal sources. A fresh team has none.+ source_configs_deleted, _ = SignalSourceConfig.objects.filter(team=team).delete()++ # Scout run-state, so the fleet cold-starts with no learned memory or stale runs.+ runs_deleted, _ = SignalScoutRun.all_teams.filter(team=team).delete()+ scratchpads_deleted, _ = SignalScratchpad.all_teams.filter(team=team).delete()+ profiles_deleted, _ = SignalProjectProfile.all_teams.filter(team=team).delete()+ emission_deleted, _ = SignalEmissionRecord.objects.filter(team=team).delete()++ self.stdout.write(f" ✓ custom scouts: {len(custom_scout_names)} ({skills_deleted} LLMSkill rows + files)")+ self.stdout.write(f" ✓ scout configs: {scout_configs_deleted}")+ self.stdout.write(f" ✓ source configs: {source_configs_deleted}")+ self.stdout.write(+ f" ✓ run-state: {runs_deleted} runs, {scratchpads_deleted} scratchpads, "+ f"{profiles_deleted} profiles, {emission_deleted} emission records"+ )++ # 2b. DWH-backed issue-tracker pipelines the wizard created (Github / Linear / Zendesk /+ # PgAnalyze). Not covered by the signals-owned models above — nothing FK-links them —+ # so they need their own teardown. Own transaction + best-effort Temporal cleanup.+ self._soft_delete_dwh_sources(team)++ # 3. Filesystem artifacts (wizard-side, outside the posthog repo).+ self._remove_report(options["install_dir"])+ if not options["keep_log"]:+ self._cycle_log(options["wizard_log"])++ self.stdout.write(+ self.style.SUCCESS(+ f"Done. Team {team.id} reset to pre-self-driving state — re-run the wizard to start clean."+ )+ )++ def _soft_delete_dwh_sources(self, team):+ """Soft-delete the self-driving-created data-warehouse pipelines (the Github / Linear /+ Zendesk / PgAnalyze issue/ticket sources) so a re-run starts clean.++ `SignalSourceConfig` (deleted above) has NO foreign key to these warehouse sources —+ the signals layer attaches to them only by (team, source_type, schema_name). So a naive+ reset leaves the pipeline behind; the wizard's `external-data-sources-list` then reports+ the source as already connected and skips the connector — the only place that asks for+ the repo and (re)binds the GitHub connection.++ Mirrors the source-destroy endpoint: soft-delete the schemas + the source (both the list+ and the status queries `.exclude(deleted=True)`), then best-effort tear down the Temporal+ sync schedules so they stop firing. Scoped to `created_via=MCP` so a user's own+ hand-connected warehouse source of the same type is never touched.+ """+ from products.data_warehouse.backend.data_load.service import (+ delete_discover_schemas_schedule,+ delete_external_data_schedule,+ )+ from products.signals.backend.serializers import _DATA_IMPORT_SOURCE_MAP+ from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource++ dwh_source_types = {ext_source_type for (ext_source_type, _schema_name) in _DATA_IMPORT_SOURCE_MAP.values()}+ sources = list(+ ExternalDataSource.objects.filter(+ team=team,+ source_type__in=dwh_source_types,+ created_via=ExternalDataSource.CreatedVia.MCP,+ deleted=False,+ )+ )+ if not sources:+ self.stdout.write(" · DWH sources: 0")+ return++ schema_ids: list[str] = []+ with transaction.atomic():+ for source in sources:+ schemas = source.schemas.filter(deleted=False)+ schema_ids.extend(str(schema_id) for schema_id in schemas.values_list("id", flat=True))+ schemas.update(deleted=True, deleted_at=timezone.now())+ source.soft_delete()++ # Temporal teardown runs AFTER the soft-deletes are committed and is best-effort: a+ # missing schedule or an unreachable Temporal must never abort the reset. The schema+ # sync schedules and the source-level sync schedule share `delete_external_data_schedule`.+ for schedule_id in [*schema_ids, *(str(source.id) for source in sources)]:+ try:+ delete_external_data_schedule(schedule_id)+ except Exception as e:+ self.stdout.write(self.style.WARNING(f" · could not delete sync schedule {schedule_id}: {e}"))+ for source in sources:+ try:+ delete_discover_schemas_schedule(str(source.id))+ except Exception as e:+ self.stdout.write(self.style.WARNING(f" · could not delete discovery schedule {source.id}: {e}"))++ types = ", ".join(sorted({source.source_type for source in sources}))+ self.stdout.write(f" ✓ DWH sources: {len(sources)} ({types})")++ def _remove_report(self, install_dir):+ if not install_dir:+ return+ report_path = os.path.join(install_dir, SELF_DRIVING_REPORT_FILE)+ if os.path.exists(report_path):+ os.remove(report_path)+ self.stdout.write(f" ✓ removed report: {report_path}")+ else:+ self.stdout.write(f" · no report at {report_path}")++ def _cycle_log(self, log_path):+ if not log_path or not os.path.exists(log_path):+ self.stdout.write(f" · no wizard log at {log_path}")+ return+ root, ext = os.path.splitext(log_path)+ timestamp = datetime.now().strftime("%Y%m%d-%H%M%S")+ backup_path = f"{root}-previous-{timestamp}{ext}"+ shutil.copy2(log_path, backup_path)+ os.remove(log_path)+ self.stdout.write(f" ✓ wizard log backed up to {backup_path} and cleared")diff --git a/products/signals/backend/scout_harness/lazy_seed.py b/products/signals/backend/scout_harness/lazy_seed.pyindex 95b4d8d721b4..8584b88f7095 100644--- a/products/signals/backend/scout_harness/lazy_seed.py+++ b/products/signals/backend/scout_harness/lazy_seed.py@@ -25,6 +25,16 @@ logger = logging.getLogger(__name__)# by the headless harness. Single source of truth, two distribution paths._SKILLS_DIR = Path(__file__).resolve().parent.parent.parent / "skills"+# Companion canonical skills seeded per-team alongside the scout fleet. Not scouts — their+# names don't carry the `signals-scout-` prefix, so the harness glob, `register_missing_configs`,+# and the prune pass all ignore their rows — but agents that work on a team's fleet through the+# skills store (e.g. the wizard's self-driving tailoring step reading the authoring guide+# via `llma-skill-get`) can only see per-team rows, so the guide has to be mirrored like the+# fleet is. Same divergence-aware sync; one caveat: removing a name from this tuple strands its+# existing per-team rows (prune only reaps `signals-scout-*` rows), so retiring a companion+# means cleaning up its rows out-of-band.+_COMPANION_SKILL_DIRS = ("authoring-signals-scouts",)+# Mirrors the regex in `products/posthog_ai/scripts/build_skills.py` so frontmatter parsing# stays consistent across the two consumers. Keep these in sync if the skill spec evolves._FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)@@ -129,7 +139,7 @@ class CanonicalSkillParseError(ValueError):"""A canonical SKILL.md on disk is malformed (missing frontmatter, bad YAML, etc.)."""-def _parse_canonical_skill(skill_dir: Path) -> CanonicalSkill:+def _parse_canonical_skill(skill_dir: Path, *, is_scout: bool = True) -> CanonicalSkill:skill_file = skill_dir / "SKILL.md"raw = skill_file.read_text(encoding="utf-8")match = _FRONTMATTER_RE.match(raw)@@ -148,10 +158,24 @@ def _parse_canonical_skill(skill_dir: Path) -> CanonicalSkill:raise CanonicalSkillParseError(f"SKILL.md frontmatter missing 'name': {skill_file}")if not isinstance(description, str) or not description:raise CanonicalSkillParseError(f"SKILL.md frontmatter missing 'description': {skill_file}")- if not name.startswith(SIGNALS_SCOUT_SKILL_PREFIX):- raise CanonicalSkillParseError(- f"Canonical skill name must start with '{SIGNALS_SCOUT_SKILL_PREFIX}': got {name!r} in {skill_file}"- )+ if is_scout:+ if not name.startswith(SIGNALS_SCOUT_SKILL_PREFIX):+ raise CanonicalSkillParseError(+ f"Canonical skill name must start with '{SIGNALS_SCOUT_SKILL_PREFIX}': got {name!r} in {skill_file}"+ )+ else:+ # Companion skills must NOT look like scouts — a scout-prefixed name would get a+ # `SignalScoutConfig` from `register_missing_configs` and be dispatched by the+ # coordinator. Pinning name == directory name keeps the allowlist in+ # `_COMPANION_SKILL_DIRS` authoritative over what actually lands per-team.+ if name.startswith(SIGNALS_SCOUT_SKILL_PREFIX):+ raise CanonicalSkillParseError(+ f"Companion skill name must not start with '{SIGNALS_SCOUT_SKILL_PREFIX}': got {name!r} in {skill_file}"+ )+ if name != skill_dir.name:+ raise CanonicalSkillParseError(+ f"Companion skill name must match its directory: got {name!r} in {skill_file}"+ )# The agentskills.io spec uses `allowed-tools` (hyphen). We prefer the spec form, but accept# the underscore form too — it predated the spec alignment in this codebase and is used by@@ -224,7 +248,8 @@ def _parse_canonical_skill(skill_dir: Path) -> CanonicalSkill:def discover_canonical_skills(skills_dir: Path | None = None) -> tuple[CanonicalSkill, ...]:- """Walk `products/signals/skills/signals-scout-*/` and return the parsed manifest.+ """Walk `products/signals/skills/` and return the parsed manifest: every+ `signals-scout-*` directory plus the `_COMPANION_SKILL_DIRS` allowlist.Skipping a malformed canonical entry would mask author errors; instead we let`CanonicalSkillParseError` propagate so the harness fails loud and the canonical source@@ -244,11 +269,12 @@ def discover_canonical_skills(skills_dir: Path | None = None) -> tuple[Canonicalfor entry in sorted(base.iterdir()):if not entry.is_dir():continue- if not entry.name.startswith(SIGNALS_SCOUT_SKILL_PREFIX):+ is_scout = entry.name.startswith(SIGNALS_SCOUT_SKILL_PREFIX)+ if not is_scout and entry.name not in _COMPANION_SKILL_DIRS:continueif not (entry / "SKILL.md").is_file():continue- skill = _parse_canonical_skill(entry)+ skill = _parse_canonical_skill(entry, is_scout=is_scout)if skill.name in by_name:raise CanonicalSkillParseError(f"Duplicate canonical skill name {skill.name!r}: declared in both {by_name[skill.name]} and {entry}"@@ -400,7 +426,8 @@ def _update_skill_from_canonical(def sync_canonical_skills(team: Team, *, prune: bool = False) -> SyncResult:- """Reconcile a team's `signals-scout-*` rows with the canonical fleet on disk.+ """Reconcile a team's rows with the canonical skills on disk — the `signals-scout-*`+ fleet plus the `_COMPANION_SKILL_DIRS` companions.Walks each canonical skill in `products/signals/skills/` and decides per-skill whetherto create, update, leave-as-diverged, or leave-as-tombstone (plus prune, when enabled).@@ -495,8 +522,10 @@ def sync_canonical_skills(team: Team, *, prune: bool = False) -> SyncResult:# removed from disk. The per-canonical loop above only visits skills still present in# the discovered fleet, so a scout deleted from `products/signals/skills/` would# otherwise leave orphaned live rows the coordinator keeps dispatching. Soft-delete them —- # never hard-delete (run history + audit). The `not canonicals` early-return above- # means a broken/empty disk read can't reach here and tombstone the whole fleet.+ # never hard-delete (run history + audit). The `scout_canonical_names` guard below+ # (and the `not canonicals` early-return above) means a broken/empty disk read —+ # including one that surfaced only companion skills — can't reach the reap and+ # tombstone the whole fleet.## Restrict to rows WE seeded (`metadata.seeded_by == "signals_scout_harness"`, stamped by# `_create_skill_from_canonical` / `_update_skill_from_canonical`). A team is free to@@ -506,14 +535,18 @@ def sync_canonical_skills(team: Team, *, prune: bool = False) -> SyncResult:# And only reap rows the team hasn't edited: an edited fork (hash diverged from the# stored `canonical_hash`, or no baseline hash to compare) is left alone, same as the# update path above. Retiring a canonical must not delete a scout the team customized.- canonical_names = {c.name for c in canonicals}- orphan_rows = LLMSkill.objects.filter(- team=team,- deleted=False,- is_latest=True,- name__startswith=SIGNALS_SCOUT_SKILL_PREFIX,- metadata__seeded_by=HARNESS_SEEDED_BY,- ).exclude(name__in=canonical_names)+ scout_canonical_names = {c.name for c in canonicals if c.name.startswith(SIGNALS_SCOUT_SKILL_PREFIX)}+ orphan_rows = (+ LLMSkill.objects.filter(+ team=team,+ deleted=False,+ is_latest=True,+ name__startswith=SIGNALS_SCOUT_SKILL_PREFIX,+ metadata__seeded_by=HARNESS_SEEDED_BY,+ ).exclude(name__in=scout_canonical_names)+ if scout_canonical_names+ else LLMSkill.objects.none()+ )for row in orphan_rows:stored_hash = (row.metadata or {}).get("canonical_hash")if stored_hash is None or _compute_row_hash(row, list(row.files.all())) != stored_hash:diff --git a/products/signals/backend/scout_harness/views.py b/products/signals/backend/scout_harness/views.pyindex 59784e939c11..75380dcbbd81 100644--- a/products/signals/backend/scout_harness/views.py+++ b/products/signals/backend/scout_harness/views.py@@ -40,6 +40,7 @@ from posthog.api.routing import TeamAndOrgViewSetMixin# password-only user in a 2FA-enforced org read scout runs/scratchpad without# completing 2FA.from posthog.auth import OAuthAccessTokenAuthentication, PersonalAPIKeyAuthentication, SessionAuthentication+from posthog.models.team.team import Teamfrom posthog.permissions import APIScopePermissionfrom products.signals.backend.models import (@@ -49,8 +50,16 @@ from products.signals.backend.models import (SignalScoutEmission,SignalScoutRun,)-from products.signals.backend.scout_harness.config_registry import enabled_scout_count, ensure_scout_category-from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, canonical_skill_names+from products.signals.backend.scout_harness.config_registry import (+ enabled_scout_count,+ ensure_scout_category,+ register_missing_configs,+)+from products.signals.backend.scout_harness.lazy_seed import (+ HARNESS_SEEDED_BY,+ canonical_skill_names,+ sync_canonical_skills,+)from products.signals.backend.scout_harness.limits import MAX_ENABLED_SCOUTS_PER_TEAMfrom products.signals.backend.scout_harness.serializers import (EmitFindingRequestSerializer,@@ -888,3 +897,42 @@ class SignalScoutConfigViewSet(TeamAndOrgViewSetMixin, viewsets.GenericViewSet):instance = serializer.save(**save_kwargs)skill_info = _skill_info_for(team_id, [instance.skill_name])return Response(SignalScoutConfigSerializer(instance, context={"skill_info": skill_info}).data)++ @extend_schema(+ request=None,+ responses={+ 200: OpenApiResponse(+ response=SignalScoutConfigSerializer(many=True),+ description="The team's full scout fleet after the sync, ordered by skill name.",+ ),+ },+ summary="Sync scout configs",+ description=(+ "Materialize the scout fleet for this project on demand (idempotent): seed the "+ "canonical `signals-scout-*` skills, create a default-schedule config for any scout "+ "lacking one, and return all scout configs. Normally the Temporal coordinator does "+ "this on its next tick; this action exists so setup flows (e.g. the wizard's "+ "self-driving program) can hand the user a tunable fleet immediately."+ ),+ operation_id="signals_scout_config_sync",+ )+ @action(+ detail=False,+ methods=["post"],+ url_path="sync",+ # Custom actions need explicit scopes — see the `current` action's note on the+ # "no scopes declared" rejection branch in `posthog/permissions.py`. Write scope:+ # the sync materializes configs, and fresh configs are enabled (they drive spend).+ required_scopes=["signal_scout:write"],+ pagination_class=None,+ )+ def sync(self, request: Request, *args, **kwargs) -> Response:+ # Scout rows persist under the canonical parent team (see `_canonical_team_id`);+ # seed and register against that team so child-environment requests don't fork+ # a second fleet.+ team = self.team if self.team.parent_team_id is None else Team.objects.get(id=self.team.parent_team_id)+ sync_canonical_skills(team)+ register_missing_configs(team.id)+ configs = SignalScoutConfig.objects.unscoped().filter(team_id=team.id).order_by("skill_name")+ skill_info = _skill_info_for(team.id, [c.skill_name for c in configs])+ return Response(SignalScoutConfigSerializer(configs, many=True, context={"skill_info": skill_info}).data)diff --git a/products/signals/backend/test/test_reset_signals_self_driving.py b/products/signals/backend/test/test_reset_signals_self_driving.pynew file mode 100644index 000000000000..899e692e561f--- /dev/null+++ b/products/signals/backend/test/test_reset_signals_self_driving.py@@ -0,0 +1,95 @@+from posthog.test.base import BaseTest+from unittest import mock++from django.core.management import call_command+from django.test import override_settings++from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource++_SERVICE = "products.data_warehouse.backend.data_load.service"+++@override_settings(DEBUG=True)[email protected](f"{_SERVICE}.delete_discover_schemas_schedule")[email protected](f"{_SERVICE}.delete_external_data_schedule")+class TestResetSignalsSelfDrivingDWHTeardown(BaseTest):+ """The reset command must tear down the DWH pipelines the wizard creates, since nothing+ FK-links them to the signals-owned models it already deletes. Scoped to created_via=MCP.++ The Temporal schedule helpers are mocked — this exercises the Postgres soft-deletes and the+ teardown wiring without a live Temporal. `keep_findings`/`keep_log` skip the unrelated+ cleanup_signals (ClickHouse + workflow termination) and log-cycling side effects.+ """++ def _github_source(self, created_via: str, *, deleted: bool = False):+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type="Github",+ status="Running",+ prefix=f"gh_{created_via}_",+ created_via=created_via,+ deleted=deleted,+ job_inputs={+ "repository": "acme/app",+ "auth_method": {"selection": "oauth", "github_integration_id": "1"},+ },+ )+ schema = ExternalDataSchema.objects.create(team=self.team, source=source, name="issues")+ return source, schema++ def _run_reset(self) -> None:+ call_command(+ "reset_signals_self_driving",+ team_id=self.team.id,+ yes=True,+ keep_findings=True,+ keep_log=True,+ )++ def test_soft_deletes_mcp_created_dwh_source_and_schema(self, mock_delete_schedule, mock_delete_discover) -> None:+ source, schema = self._github_source(ExternalDataSource.CreatedVia.MCP)++ self._run_reset()++ source.refresh_from_db()+ schema.refresh_from_db()+ assert source.deleted is True+ assert source.deleted_at is not None+ assert schema.deleted is True++ # Both the schema sync schedule and the source-level sync schedule are torn down.+ deleted_schedule_ids = {call.args[0] for call in mock_delete_schedule.call_args_list}+ assert str(schema.id) in deleted_schedule_ids+ assert str(source.id) in deleted_schedule_ids+ mock_delete_discover.assert_called_once_with(str(source.id))++ def test_leaves_non_mcp_dwh_source_untouched(self, mock_delete_schedule, mock_delete_discover) -> None:+ # A user's own UI-connected warehouse source of the same type must survive the reset.+ source, schema = self._github_source(ExternalDataSource.CreatedVia.WEB)++ self._run_reset()++ source.refresh_from_db()+ schema.refresh_from_db()+ assert source.deleted is False+ assert schema.deleted is False+ mock_delete_schedule.assert_not_called()+ mock_delete_discover.assert_not_called()++ def test_leaves_non_issue_tracker_source_type_untouched(self, mock_delete_schedule, mock_delete_discover) -> None:+ # Stripe is MCP-created but is not one of the issue-tracker signal sources — scoping is+ # by source_type (derived from _DATA_IMPORT_SOURCE_MAP), not "everything MCP made".+ stripe = ExternalDataSource.objects.create(+ team=self.team,+ source_type="Stripe",+ status="Running",+ prefix="stripe_",+ created_via=ExternalDataSource.CreatedVia.MCP,+ )++ self._run_reset()++ stripe.refresh_from_db()+ assert stripe.deleted is False+ mock_delete_schedule.assert_not_called()diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.pyindex b8fe1c17b73c..2bea6a119683 100644--- a/products/signals/backend/test/test_scout_harness_api.py+++ b/products/signals/backend/test/test_scout_harness_api.py@@ -27,7 +27,7 @@ from products.signals.backend.models import (SignalScoutRun,SignalScratchpad,)-from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY+from products.signals.backend.scout_harness.lazy_seed import HARNESS_SEEDED_BY, discover_canonical_skillsfrom products.signals.backend.scout_harness.tools.profile import compute_project_profilefrom products.signals.backend.temporal.signal_queries import fetch_report_ids_for_source_idsfrom products.skills.backend.models.skills import LLMSkill@@ -868,6 +868,74 @@ class TestScoutHarnessConfigAPI(APIBaseTest):response = self.client.patch(self._detail_url(str(config.id)), data={"enabled": False}, format="json")assert response.status_code == status.HTTP_404_NOT_FOUND+ def _sync_url(self) -> str:+ return f"/api/projects/{self.team.id}/signals/scout/configs/sync/"++ def test_sync_materializes_fleet_for_fresh_team(self) -> None:+ canonical_names = {c.name for c in discover_canonical_skills()}+ scout_names = {n for n in canonical_names if n.startswith("signals-scout-")}+ companion_names = canonical_names - scout_names+ assert scout_names, "expected canonical signals-scout-* skills on disk"+ assert "authoring-signals-scouts" in companion_names+ assert SignalScoutConfig.objects.filter(team=self.team).count() == 0++ response = self.client.post(self._sync_url())++ assert response.status_code == status.HTTP_200_OK+ body = response.json()+ # Only scouts get configs — companion skills (authoring-signals-scouts) are seeded+ # into the team's LLMSkill namespace below but never materialize a scout config.+ assert {c["skill_name"] for c in body} == scout_names+ assert [c["skill_name"] for c in body] == sorted(scout_names)+ assert all(c["enabled"] is True for c in body)+ assert all(c["emit"] is True for c in body)+ assert all(c["run_interval_minutes"] == 180 for c in body)+ assert SignalScoutConfig.objects.filter(team=self.team).count() == len(scout_names)+ # Every canonical skill — fleet and companions — was seeded into the team's+ # LLMSkill namespace.+ assert (+ set(LLMSkill.objects.filter(team=self.team, deleted=False).values_list("name", flat=True))+ == canonical_names+ )++ def test_sync_rejects_read_only_scope(self) -> None:+ from posthog.models.personal_api_key import PersonalAPIKey+ from posthog.models.utils import generate_random_token_personal, hash_key_value++ key_value = generate_random_token_personal()+ PersonalAPIKey.objects.create(+ label="read only",+ user=self.user,+ secure_value=hash_key_value(key_value),+ scoped_teams=[self.team.id],+ scopes=["signal_scout:read"],+ )+ self.client.logout()++ response = self.client.post(self._sync_url(), HTTP_AUTHORIZATION=f"Bearer {key_value}")++ assert response.status_code == status.HTTP_403_FORBIDDEN+ assert SignalScoutConfig.objects.filter(team=self.team).count() == 0++ def test_sync_is_idempotent_and_preserves_tuned_configs(self) -> None:+ first = self.client.post(self._sync_url())+ assert first.status_code == status.HTTP_200_OK+ fleet_size = len(first.json())++ # Tune one config the way a user would, then sync again.+ tuned = SignalScoutConfig.objects.filter(team=self.team).order_by("skill_name").first()+ assert tuned is not None+ tuned.enabled = False+ tuned.save(update_fields=["enabled"])++ second = self.client.post(self._sync_url())++ assert second.status_code == status.HTTP_200_OK+ assert len(second.json()) == fleet_size+ assert SignalScoutConfig.objects.filter(team=self.team).count() == fleet_size+ tuned.refresh_from_db()+ assert tuned.enabled is False, "sync must not reset existing configs"+def test_list_is_side_effect_free_for_unregistered_scout_skills(self) -> None:# The list MCP tool is annotated readOnly — a scout skill without a config must not# get one minted by a GET; registration is the coordinator's or `create`'s job.diff --git a/products/signals/backend/test/test_scout_harness_lazy_seed.py b/products/signals/backend/test/test_scout_harness_lazy_seed.pyindex 6976341eae79..e7b7cb2ba0d3 100644--- a/products/signals/backend/test/test_scout_harness_lazy_seed.py+++ b/products/signals/backend/test/test_scout_harness_lazy_seed.py@@ -7,6 +7,8 @@ import pytestfrom posthog.test.base import BaseTestfrom unittest.mock import patch+from products.signals.backend.models import SignalScoutConfig+from products.signals.backend.scout_harness.config_registry import register_missing_configsfrom products.signals.backend.scout_harness.lazy_seed import (CanonicalSkill,CanonicalSkillFile,@@ -90,6 +92,74 @@ class TestDiscoverCanonicalSkills:skills = discover_canonical_skills(tmp_path)assert [s.name for s in skills] == ["signals-scout-foo"]+ def test_discovers_companion_dirs_from_allowlist(self, tmp_path: Path) -> None:+ _write_canonical_skill(+ tmp_path,+ dir_name="signals-scout-foo",+ frontmatter="""+ ---+ name: signals-scout-foo+ description: foo skill+ ---+ """,+ body="# Foo\n",+ )+ _write_canonical_skill(+ tmp_path,+ dir_name="authoring-signals-scouts",+ frontmatter="""+ ---+ name: authoring-signals-scouts+ description: companion authoring guide+ ---+ """,+ body="# Authoring\n",+ )+ # Not in the allowlist → still skipped, same as before companions existed.+ _write_canonical_skill(+ tmp_path,+ dir_name="some-other-skill",+ frontmatter="""+ ---+ name: some-other-skill+ description: not canonical+ ---+ """,+ body="# nope\n",+ )+ skills = discover_canonical_skills(tmp_path)+ assert [s.name for s in skills] == ["authoring-signals-scouts", "signals-scout-foo"]++ def test_companion_name_with_scout_prefix_raises(self, tmp_path: Path) -> None:+ # A scout-prefixed name on a companion would get a SignalScoutConfig from+ # register_missing_configs and be dispatched as a scout — reject at parse time.+ _write_canonical_skill(+ tmp_path,+ dir_name="authoring-signals-scouts",+ frontmatter="""+ ---+ name: signals-scout-authoring+ description: masquerading companion+ ---+ """,+ )+ with pytest.raises(CanonicalSkillParseError, match="must not start with"):+ discover_canonical_skills(tmp_path)++ def test_companion_name_must_match_directory(self, tmp_path: Path) -> None:+ _write_canonical_skill(+ tmp_path,+ dir_name="authoring-signals-scouts",+ frontmatter="""+ ---+ name: authoring-scouts-renamed+ description: drifted frontmatter name+ ---+ """,+ )+ with pytest.raises(CanonicalSkillParseError, match="must match its directory"):+ discover_canonical_skills(tmp_path)+@pytest.mark.parametrize("frontmatter_key",[@@ -250,6 +320,9 @@ class TestDiscoverCanonicalSkills:"signals-scout-logs","signals-scout-error-tracking","signals-scout-revenue-analytics",+ # Companion (non-scout) skill, seeded so store-only agents can read the+ # authoring guide via llma-skill-get.+ "authoring-signals-scouts",}assert expected.issubset(names), f"missing canonical skills: {expected - names}"@@ -408,6 +481,36 @@ class TestSyncCanonicalSkills(BaseTest):# Hash is now stamped at create time so future syncs can compare.assert row.metadata["canonical_hash"] == _compute_canonical_hash(canonical)+ def test_companion_skill_seeds_without_scout_config(self) -> None:+ scout = _make_canonical("signals-scout-alpha")+ companion = _make_canonical("authoring-signals-scouts", body="# Authoring guide\n")+ with self._patch_canonicals((scout, companion)):+ result = sync_canonical_skills(self.team)++ assert set(result.created_skill_names) == {"signals-scout-alpha", "authoring-signals-scouts"}+ row = LLMSkill.objects.get(team=self.team, name="authoring-signals-scouts", is_latest=True, deleted=False)+ assert row.metadata["seeded_by"] == "signals_scout_harness"++ # The companion never materializes a scout config — only prefix-matching skills do.+ live_skills = register_missing_configs(self.team.id)+ assert live_skills == {"signals-scout-alpha"}+ assert not SignalScoutConfig.all_teams.filter(team=self.team, skill_name="authoring-signals-scouts").exists()++ def test_prune_skipped_when_no_scout_canonicals_discovered(self) -> None:+ # A disk read that surfaces only companions (broken checkout, partial deploy) must+ # not let the prune pass tombstone the team's entire seeded fleet.+ scout = _make_canonical("signals-scout-alpha")+ with self._patch_canonicals((scout,)):+ sync_canonical_skills(self.team)++ companion = _make_canonical("authoring-signals-scouts")+ with self._patch_canonicals((companion,)):+ result = sync_canonical_skills(self.team, prune=True)++ assert result.pruned_skill_names == ()+ row = LLMSkill.objects.get(team=self.team, name="signals-scout-alpha", is_latest=True)+ assert row.deleted is False+def test_no_op_when_team_row_already_matches_canonical(self) -> None:canonical = _make_canonical("signals-scout-alpha", body="initial")with self._patch_canonicals((canonical,)):diff --git a/products/signals/frontend/generated/api.ts b/products/signals/frontend/generated/api.tsindex 193cd1fc194b..d9fae2c36d2f 100644--- a/products/signals/frontend/generated/api.ts+++ b/products/signals/frontend/generated/api.ts@@ -291,6 +291,24 @@ export const signalsScoutConfigUpdate = async (})}+export const getSignalsScoutConfigSyncUrl = (projectId: string) => {+ return `/api/projects/${projectId}/signals/scout/configs/sync/`+}++/**+ * Materialize the scout fleet for this project on demand (idempotent): seed the canonical `signals-scout-*` skills, create a default-schedule config for any scout lacking one, and return all scout configs. Normally the Temporal coordinator does this on its next tick; this action exists so setup flows (e.g. the wizard's self-driving program) can hand the user a tunable fleet immediately.+ * @summary Sync scout configs+ */+export const signalsScoutConfigSync = async (+ projectId: string,+ options?: RequestInit+): Promise<SignalScoutConfigApi[]> => {+ return apiMutator<SignalScoutConfigApi[]>(getSignalsScoutConfigSyncUrl(projectId), {+ ...options,+ method: 'POST',+ })+}+export const getSignalsScoutProjectProfileGetUrl = (projectId: string,params?: SignalsScoutProjectProfileGetParamsdiff --git a/products/signals/mcp/tools.yaml b/products/signals/mcp/tools.yamlindex ec9d06d13f67..8bef6fee7412 100644--- a/products/signals/mcp/tools.yaml+++ b/products/signals/mcp/tools.yaml@@ -234,9 +234,28 @@ tools:description: >List the per-scout configs for this project — one row per `signals-scout-*` skill, each with its schedule(`run_interval_minutes`), `enabled` flag, and `emit` (dry-run) posture. A freshly authored scout appears- once its config is registered — immediately via `signals-scout-config-create`, or on the coordinator's next- tick. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with- `signals-scout-config-update` to tune them.+ once its config is registered — immediately via `signals-scout-config-create` (one skill) or+ `signals-scout-config-sync` (the whole fleet), or on the coordinator's next tick. Use this to see which+ scouts run, how often, and whether they emit findings to the inbox. Pair with `signals-scout-config-update`+ to tune them.+ signals-scout-config-sync:+ operation: signals_scout_config_sync+ enabled: true+ scopes:+ - signal_scout:write+ annotations:+ readOnly: false+ destructive: false+ idempotent: true+ list: true+ title: Sync scout configs+ description: >+ Materialize the Signals scout fleet for this project (idempotent): seeds the canonical `signals-scout-*`+ skills and creates a default-schedule config for any scout lacking one, then returns all scout configs. The+ Temporal coordinator does the same on its next tick; call this when a setup flow needs a tunable fleet+ immediately instead of waiting for the tick. Pair with `signals-scout-config-update` to tune the returned+ configs.+ requires_ai_consent: truesignals-scout-config-update:operation: signals_scout_config_updateenabled: truediff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex 734e413ec68d..7e6a2f4f1d7c 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -3908,6 +3908,20 @@"readOnlyHint": true}},+ "integrations-github-repos-retrieve": {+ "description": "List the repositories accessible to a GitHub integration (by integration ID). Serves the cached repository list from the GitHub App installation. Supports `search` (case-insensitive name match), `limit` (default 100, max 500), and `offset` query parameters. Returns repository id, name, and full_name (owner/repo) plus a has_more flag. Use this to validate that a repository is accessible to the integration before referencing it (e.g. when creating a GitHub data warehouse source).",+ "category": "Integrations",+ "feature": "integrations",+ "summary": "List GitHub integration repositories",+ "title": "List GitHub integration repositories",+ "required_scopes": ["integration:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"integrations-list": {"description": "List all third-party integrations configured in the current project. Returns each integration's type (kind), display name, non-sensitive configuration, error status, and creation metadata. Common kinds include slack, github, hubspot, salesforce, and various ad platforms. Sensitive credentials (access tokens, secrets) are never serialized.","category": "Integrations",@@ -6018,7 +6032,7 @@}},"signals-scout-config-list": {- "description": "List the per-scout configs for this project — one row per `signals-scout-*` skill, each with its schedule (`run_interval_minutes`), `enabled` flag, and `emit` (dry-run) posture. A freshly authored scout appears once its config is registered — immediately via `signals-scout-config-create`, or on the coordinator's next tick. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with `signals-scout-config-update` to tune them.",+ "description": "List the per-scout configs for this project — one row per `signals-scout-*` skill, each with its schedule (`run_interval_minutes`), `enabled` flag, and `emit` (dry-run) posture. A freshly authored scout appears once its config is registered — immediately via `signals-scout-config-create` (one skill) or `signals-scout-config-sync` (the whole fleet), or on the coordinator's next tick. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with `signals-scout-config-update` to tune them.","category": "Signals","feature": "signals","summary": "List scout configs",@@ -6031,6 +6045,21 @@"readOnlyHint": true}},+ "signals-scout-config-sync": {+ "description": "Materialize the Signals scout fleet for this project (idempotent): seeds the canonical `signals-scout-*` skills and creates a default-schedule config for any scout lacking one, then returns all scout configs. The Temporal coordinator does the same on its next tick; call this when a setup flow needs a tunable fleet immediately instead of waiting for the tick. Pair with `signals-scout-config-update` to tune the returned configs.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Sync scout configs",+ "title": "Sync scout configs",+ "required_scopes": ["signal_scout:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "requires_ai_consent": true+ },"signals-scout-config-update": {"description": "Tune one scout by its config `id`: change its schedule (`run_interval_minutes`, 10–43200), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.","category": "Signals",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex 7f633d58172f..31f3b7eb6eab 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -4190,6 +4190,20 @@"readOnlyHint": true}},+ "integrations-github-repos-retrieve": {+ "description": "List the repositories accessible to a GitHub integration (by integration ID). Serves the cached repository list from the GitHub App installation. Supports `search` (case-insensitive name match), `limit` (default 100, max 500), and `offset` query parameters. Returns repository id, name, and full_name (owner/repo) plus a has_more flag. Use this to validate that a repository is accessible to the integration before referencing it (e.g. when creating a GitHub data warehouse source).",+ "category": "Integrations",+ "feature": "integrations",+ "summary": "List GitHub integration repositories",+ "title": "List GitHub integration repositories",+ "required_scopes": ["integration:read"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": true+ }+ },"integrations-list": {"description": "List all third-party integrations configured in the current project. Returns each integration's type (kind), display name, non-sensitive configuration, error status, and creation metadata. Common kinds include slack, github, hubspot, salesforce, and various ad platforms. Sensitive credentials (access tokens, secrets) are never serialized.","category": "Integrations",@@ -6513,7 +6527,7 @@}},"signals-scout-config-list": {- "description": "List the per-scout configs for this project — one row per `signals-scout-*` skill, each with its schedule (`run_interval_minutes`), `enabled` flag, and `emit` (dry-run) posture. A freshly authored scout appears once its config is registered — immediately via `signals-scout-config-create`, or on the coordinator's next tick. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with `signals-scout-config-update` to tune them.",+ "description": "List the per-scout configs for this project — one row per `signals-scout-*` skill, each with its schedule (`run_interval_minutes`), `enabled` flag, and `emit` (dry-run) posture. A freshly authored scout appears once its config is registered — immediately via `signals-scout-config-create` (one skill) or `signals-scout-config-sync` (the whole fleet), or on the coordinator's next tick. Use this to see which scouts run, how often, and whether they emit findings to the inbox. Pair with `signals-scout-config-update` to tune them.","category": "Signals","feature": "signals","summary": "List scout configs",@@ -6526,6 +6540,21 @@"readOnlyHint": true}},+ "signals-scout-config-sync": {+ "description": "Materialize the Signals scout fleet for this project (idempotent): seeds the canonical `signals-scout-*` skills and creates a default-schedule config for any scout lacking one, then returns all scout configs. The Temporal coordinator does the same on its next tick; call this when a setup flow needs a tunable fleet immediately instead of waiting for the tick. Pair with `signals-scout-config-update` to tune the returned configs.",+ "category": "Signals",+ "feature": "signals",+ "summary": "Sync scout configs",+ "title": "Sync scout configs",+ "required_scopes": ["signal_scout:write"],+ "annotations": {+ "destructiveHint": false,+ "idempotentHint": true,+ "openWorldHint": true,+ "readOnlyHint": false+ },+ "requires_ai_consent": true+ },"signals-scout-config-update": {"description": "Tune one scout by its config `id`: change its schedule (`run_interval_minutes`, 10–43200), `enabled`, or `emit` (false = dry-run: the scout runs and logs but writes nothing to the inbox). `skill_name` is fixed. Enabling records who flipped it on and is activity-logged, since running a scout drives spend.","category": "Signals",diff --git a/services/mcp/src/generated/integrations/api.ts b/services/mcp/src/generated/integrations/api.tsindex 8d6a528ee850..ed8f961ab8ad 100644--- a/services/mcp/src/generated/integrations/api.ts+++ b/services/mcp/src/generated/integrations/api.ts@@ -3,7 +3,7 @@* MCP service uses these Zod schemas for generated tool handlers.* To regenerate: hogli build:openapi*- * PostHog API - MCP 4 enabled ops+ * PostHog API - MCP 5 enabled ops* OpenAPI spec version: 1.0.0*/import * as zod from 'zod'@@ -117,3 +117,38 @@ export const IntegrationsChannelsRetrieveQueryParams = /* @__PURE__ */ zod.objec.default(integrationsChannelsRetrieveQuerySearchDefault).describe('Optional case-insensitive channel name or ID search query.'),})++export const IntegrationsGithubReposRetrieveParams = /* @__PURE__ */ zod.object({+ id: zod.number().describe('A unique integer value identifying this integration.'),+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})++export const integrationsGithubReposRetrieveQueryLimitDefault = 100+export const integrationsGithubReposRetrieveQueryLimitMax = 500++export const integrationsGithubReposRetrieveQueryOffsetDefault = 0+export const integrationsGithubReposRetrieveQueryOffsetMin = 0++export const integrationsGithubReposRetrieveQuerySearchDefault = ``++export const IntegrationsGithubReposRetrieveQueryParams = /* @__PURE__ */ zod.object({+ limit: zod+ .number()+ .min(1)+ .max(integrationsGithubReposRetrieveQueryLimitMax)+ .default(integrationsGithubReposRetrieveQueryLimitDefault)+ .describe('Maximum number of repositories to return per request (max 500).'),+ offset: zod+ .number()+ .min(integrationsGithubReposRetrieveQueryOffsetMin)+ .default(integrationsGithubReposRetrieveQueryOffsetDefault)+ .describe('Number of repositories to skip before returning results.'),+ search: zod+ .string()+ .default(integrationsGithubReposRetrieveQuerySearchDefault)+ .describe('Optional case-insensitive repository name search query.'),+})diff --git a/services/mcp/src/generated/signals/api.ts b/services/mcp/src/generated/signals/api.tsindex e0e72710bb68..3db84245be9d 100644--- a/services/mcp/src/generated/signals/api.ts+++ b/services/mcp/src/generated/signals/api.ts@@ -298,6 +298,18 @@ export const SignalsScoutConfigUpdateBody = /* @__PURE__ */ zod'Per-(team, skill) scout config: schedule, enablement, and emit posture.\n\nOne row per `signals-scout-*` skill on the team. The coordinator auto-creates a row\nwhen it discovers a scout skill; this serializer lets agents tune the row.')+/**+ * Materialize the scout fleet for this project on demand (idempotent): seed the canonical `signals-scout-*` skills, create a default-schedule config for any scout lacking one, and return all scout configs. Normally the Temporal coordinator does this on its next tick; this action exists so setup flows (e.g. the wizard's self-driving program) can hand the user a tunable fleet immediately.+ * @summary Sync scout configs+ */+export const SignalsScoutConfigSyncParams = /* @__PURE__ */ zod.object({+ project_id: zod+ .string()+ .describe(+ "Project ID of the project you're trying to access. To find the ID of the project, make a call to /api/projects/."+ ),+})+/*** Return the team's deterministic project profile. For the internal scout token the response reflects the newest non-expired cached row or a freshly-built one (lazy compute on cache miss); `force_refresh=true` skips the cache and rebuilds from authoritative sources. Public read callers (session auth or a `signal_scout:read` PAK) get the newest cached profile, or 404 if none has been built yet — they never trigger a rebuild. Read this at the start of a run to orient on the team's product mix, integrations, warehouse sources, signal coverage, and existing inbox surface.* @summary Get the current project profilediff --git a/services/mcp/src/tools/generated/integrations.ts b/services/mcp/src/tools/generated/integrations.tsindex 1299cec9dfe0..2d8d21d9a0dc 100644--- a/services/mcp/src/tools/generated/integrations.ts+++ b/services/mcp/src/tools/generated/integrations.ts@@ -6,6 +6,8 @@ import {IntegrationsChannelsRetrieveParams,IntegrationsChannelsRetrieveQueryParams,IntegrationsDestroyParams,+ IntegrationsGithubReposRetrieveParams,+ IntegrationsGithubReposRetrieveQueryParams,IntegrationsListQueryParams,IntegrationsRetrieveParams,} from '@/generated/integrations/api'@@ -75,6 +77,31 @@ const integrationsChannelsRetrieve = (): ToolBase<},})+const IntegrationsGithubReposRetrieveSchema = IntegrationsGithubReposRetrieveParams.omit({ project_id: true }).extend(+ IntegrationsGithubReposRetrieveQueryParams.shape+)++const integrationsGithubReposRetrieve = (): ToolBase<+ typeof IntegrationsGithubReposRetrieveSchema,+ Schemas.GitHubReposResponse+> => ({+ name: 'integrations-github-repos-retrieve',+ schema: IntegrationsGithubReposRetrieveSchema,+ handler: async (context: Context, params: z.infer<typeof IntegrationsGithubReposRetrieveSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.GitHubReposResponse>({+ method: 'GET',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/integrations/${encodeURIComponent(String(params.id))}/github_repos/`,+ query: {+ limit: params.limit,+ offset: params.offset,+ search: params.search,+ },+ })+ return result+ },+})+const IntegrationsListSchema = IntegrationsListQueryParamsconst integrationsList = (): ToolBase<@@ -108,5 +135,6 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'integration-delete': integrationDelete,'integration-get': integrationGet,'integrations-channels-retrieve': integrationsChannelsRetrieve,+ 'integrations-github-repos-retrieve': integrationsGithubReposRetrieve,'integrations-list': integrationsList,}diff --git a/services/mcp/src/tools/generated/signals.ts b/services/mcp/src/tools/generated/signals.tsindex dd3e464a1e39..76c0cc9815d5 100644--- a/services/mcp/src/tools/generated/signals.ts+++ b/services/mcp/src/tools/generated/signals.ts@@ -370,6 +370,25 @@ const signalsScoutConfigList = (): ToolBase<},})+const SignalsScoutConfigSyncSchema = z.object({})++const signalsScoutConfigSync = (): ToolBase<+ typeof SignalsScoutConfigSyncSchema,+ WithPostHogUrl<Schemas.SignalScoutConfig[]>+> => ({+ name: 'signals-scout-config-sync',+ schema: SignalsScoutConfigSyncSchema,+ // eslint-disable-next-line no-unused-vars+ handler: async (context: Context, params: z.infer<typeof SignalsScoutConfigSyncSchema>) => {+ const projectId = await context.stateManager.getProjectId()+ const result = await context.api.request<Schemas.SignalScoutConfig[]>({+ method: 'POST',+ path: `/api/projects/${encodeURIComponent(String(projectId))}/signals/scout/configs/sync/`,+ })+ return await withPostHogUrl(context, result, '/inbox')+ },+})+const SignalsScoutConfigUpdateSchema = SignalsScoutConfigUpdateParams.omit({ project_id: true }).extend(SignalsScoutConfigUpdateBody.shape)@@ -637,6 +656,7 @@ export const GENERATED_TOOLS: Record<string, () => ToolBase<ZodObjectAny>> = {'inbox-source-configs-update': inboxSourceConfigsUpdate,'signals-scout-config-create': signalsScoutConfigCreate,'signals-scout-config-list': signalsScoutConfigList,+ 'signals-scout-config-sync': signalsScoutConfigSync,'signals-scout-config-update': signalsScoutConfigUpdate,'signals-scout-emit-signal': signalsScoutEmitSignal,'signals-scout-project-profile-get': signalsScoutProjectProfileGet,diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-github-repos-retrieve.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-github-repos-retrieve.jsonnew file mode 100644index 000000000000..b4d2857e3765--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/integrations-github-repos-retrieve.json@@ -0,0 +1,29 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {+ "id": {+ "description": "A unique integer value identifying this integration.",+ "type": "number"+ },+ "limit": {+ "default": 100,+ "description": "Maximum number of repositories to return per request (max 500).",+ "maximum": 500,+ "minimum": 1,+ "type": "number"+ },+ "offset": {+ "default": 0,+ "description": "Number of repositories to skip before returning results.",+ "minimum": 0,+ "type": "number"+ },+ "search": {+ "default": "",+ "description": "Optional case-insensitive repository name search query.",+ "type": "string"+ }+ },+ "required": ["id"],+ "type": "object"+}diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-sync.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-sync.jsonnew file mode 100644index 000000000000..7b7ea9186078--- /dev/null+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/signals-scout-config-sync.json@@ -0,0 +1,5 @@+{+ "$schema": "https://json-schema.org/draft/2020-12/schema",+ "properties": {},+ "type": "object"+}