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.

feat(signals): hardening + canonical sync (6/7) (#57760)

Andrew Maguireb18bec2c2eb6
diff --git a/posthog/temporal/tests/ai/test_module_integrity.py b/posthog/temporal/tests/ai/test_module_integrity.py
index 598ba6fca50b..004caeebcb5b 100644
--- a/posthog/temporal/tests/ai/test_module_integrity.py
+++ b/posthog/temporal/tests/ai/test_module_integrity.py
@@ -298,6 +298,7 @@ class TestSignalsProductModuleIntegrity:
"verify_match_specificity_activity",
"wait_for_signal_in_clickhouse_activity",
"fetch_enabled_signals_scout_runs_activity",
+ "stamp_dispatched_signals_scout_runs_activity",
"run_signals_scout_activity",
"run_custom_signal_agent_activity",
]
diff --git a/products/posthog_ai/scripts/build_skills.py b/products/posthog_ai/scripts/build_skills.py
index 408e3fd6834b..16f24108ed92 100755
--- a/products/posthog_ai/scripts/build_skills.py
+++ b/products/posthog_ai/scripts/build_skills.py
@@ -183,7 +183,8 @@ class SkillDiscoverer:
)
elif (
entry.is_file()
- and entry.name != "README.md"
+ # Convention docs that can live alongside skills — not skills themselves.
+ and entry.name not in ("README.md", "AGENTS.md", "CLAUDE.md")
and (entry.name.endswith(".md.j2") or entry.name.endswith(".md"))
):
if entry.name.endswith(".md") and (entry.parent / (entry.name + ".j2")).exists():
diff --git a/products/signals/ARCHITECTURE.md b/products/signals/ARCHITECTURE.md
index d278333aa00f..966ba4a39caf 100644
--- a/products/signals/ARCHITECTURE.md
+++ b/products/signals/ARCHITECTURE.md
@@ -2,7 +2,7 @@
## Overview
-The **Signals** product is a signal grouping and report-generation pipeline. Signals from multiple products and integrations — including session replay, AI observability, error tracking, GitHub, Linear, and Zendesk — are emitted into a shared ClickHouse embeddings table, grouped into **SignalReports** via embedding similarity + LLM matching, and then optionally promoted into an agentic report-research flow.
+The **Signals** product is a signal grouping and report-generation pipeline. Signals from multiple products and integrations — including session replay, AI observability, error tracking, GitHub, Linear, Zendesk, and the headless **Signals agent** itself (a scheduled scout that emits cross-source findings into the same pipeline) — are emitted into a shared ClickHouse embeddings table, grouped into **SignalReports** via embedding similarity + LLM matching, and then optionally promoted into an agentic report-research flow.
Today the active ingestion path is **emitter → buffer → grouping v2**. The summary path is no longer a simple "summarize signals" LLM step: it runs a report-level safety judge, selects a repository, then performs sandbox-backed multi-turn research that produces findings, actionability, priority, title, summary, and suggested reviewers. Reports that are immediately actionable can automatically start a Tasks coding run via the **autonomy** system.
@@ -17,10 +17,12 @@ The original `TeamSignalGroupingWorkflow` (v1) in `backend/temporal/grouping.py`
Signals workflows and activities are registered in `backend/temporal/__init__.py` and wired into the `VIDEO_EXPORT_TASK_QUEUE` worker by `posthog/management/commands/start_temporal_worker.py`.
If you add or remove a Signals workflow/activity from `backend/temporal/__init__.py`, you also need to update `posthog/temporal/tests/ai/test_module_integrity.py` (`TestSignalsProductModuleIntegrity`). That test intentionally snapshots the registered workflow/activity lists and will fail until its expected names are updated.
-Two additional Signals workflows also exist but are not part of the main report pipeline:
+Several additional Signals workflows also exist but are not part of the main report pipeline:
- `backfill-error-tracking` (`backend/temporal/backfill_error_tracking.py`) — backfills recent error tracking issues as signals
- `emit-eval-signal` (`backend/temporal/emit_eval_signal.py`) — converts LLMA evaluation results into Signals inputs on the Signals worker queue
+- `run-signals-scout-coordinator` (`backend/temporal/agentic/scout_coordinator.py`) — periodic tick (every `COORDINATOR_INTERVAL_MINUTES = 15`) that fans out scheduled `signals-scout-*` scout runs per (team, skill). Spec'd separately below.
+- `RunSignalsScoutWorkflow` (`backend/temporal/agentic/scout_scheduler.py`) — child workflow per planned run; thin wrapper around the harness activity. Spec'd separately below.
### Activity decoration
@@ -279,6 +281,52 @@ Defined in `backend/temporal/deletion.py`. Workflow ID: `signal-report-deletion-
This shares the same activities as reingestion; the only difference is that it stops after deletion.
+### `SignalsScoutCoordinatorWorkflow` (`run-signals-scout-coordinator`)
+
+Polling coordinator for the headless **Signals agent**. Driven by a Temporal Schedule
+defined in `backend/temporal/agentic/schedule.py` with `every=COORDINATOR_INTERVAL_MINUTES`
+(15min) and `ScheduleOverlapPolicy.SKIP` to drop ticks rather than queue them. The tick
+is just polling granularity — each scout's own `run_interval_minutes` schedule decides
+when it actually runs.
+
+Defined in `backend/temporal/agentic/scout_coordinator.py`.
+
+**Flow:**
+
+1. Activity `fetch_enabled_signals_scout_runs_activity` bounds candidates to dogfood teams — those with a `signals-scout-*` skill or config, gated by the `signals-scout` feature flag (`_participating_teams`). For each, it calls `sync_canonical_skills(team, prune=True)` to mirror the on-disk `signals-scout-*` skills onto the team's `LLMSkill` rows, then auto-registers a `SignalScoutConfig` for any scout skill missing one (`_register_missing_configs`). Failures here are logged and the tick continues — a stale skill is preferable to a dead tick.
+2. For each enabled config, the coordinator computes how overdue the scout is: due when `last_run_at is None`, or `now - last_run_at >= run_interval_minutes`. There is no sampling — every due scout is planned.
+3. Due runs are sorted most-overdue-first and truncated at `MAX_RUNS_PER_TICK` (50 per tick; the cost bound — overflow catches up next tick). `last_run_at` is advanced via `.update()` for everything dispatched (bypasses `save()`, so the per-tick write never hits the activity log). Planned runs are re-sorted by `(team_id, skill_name)` for stable child IDs.
+4. Each `PlannedRun` becomes a child `RunSignalsScoutWorkflow` started with `ParentClosePolicy.ABANDON` and a deterministic workflow ID per `(team_id, skill_name, tick_id)` so retried coordinators can't double-launch within a tick.
+
+The coordinator's lifetime is seconds regardless of fan-out width; throttling happens at the Temporal task queue + worker concurrency layer. Pausing a scout is `enabled=False` on its config; slowing it is a larger `run_interval_minutes` — both tunable via the `signals-scout-config-update` MCP tool.
+
+### `RunSignalsScoutWorkflow`
+
+Child workflow per planned run. Defined in `backend/temporal/agentic/scout_scheduler.py`.
+
+Thin wrapper around `run_signals_scout_activity`, which delegates to
+`scout_harness.runner.arun_signals_scout`. The activity inserts the `SignalScoutRun`
+bridge row at the start of the run; status, timing, and chat log live on the linked
+`tasks.TaskRun` via `MultiTurnSession`, not on the bridge row. The workflow's only
+job is to spawn the activity with `start_to_close_timeout=WORKFLOW_HARD_CEILING_S`,
+a 2-minute heartbeat, and `RetryPolicy(maximum_attempts=1)` — the spec calls for "fail
+safe and silent": a bad run does not retry blindly; the next scheduled tick will try
+again. Single-flight is a best-effort app-layer guard: `_has_running_run` skips
+dispatch when a prior run for the same `(team, skill_name)` has
+`task_run.status = IN_PROGRESS`. An earlier partial unique constraint on
+`(team, skill_name) WHERE status='running'` was dropped together with the bridge
+model's own status column; active recovery of stranded `IN_PROGRESS` task runs
+(`_self_heal_stale_runs` is a no-op today) is a tracked follow-up.
+
+Findings emitted during the run go through the harness's `emit_signal_*` tools,
+which call `emit_signal()` with `source_product="signals_scout"` and
+`source_type="cross_source_issue"` — from there the signal flows through the same
+emitter → buffer → grouping v2 path as any other source.
+
+See `backend/scout_harness/AGENTS.md` for the harness internals (runner, prompt
+assembly, scratchpad + profile + run-history reads, lazy seed) and
+`skills/AGENTS.md` for the scout fleet convention.
+
---
## Django Models (Postgres)
@@ -420,14 +468,14 @@ Notes:
Per-team configuration for which signal sources are enabled.
-| Field | Type | Description |
-| ---------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
-| `team` | FK → Team | Owning team (`related_name="signal_source_configs"`) |
-| `source_product` | CharField | One of: `session_replay`, `llm_analytics`, `github`, `linear`, `zendesk`, `error_tracking` (`SourceProduct` enum) |
-| `source_type` | CharField | One of: `session_analysis_cluster`, `evaluation`, `issue`, `ticket`, `issue_created`, `issue_reopened`, `issue_spiking` (`SourceType` enum) |
-| `enabled` | Boolean | Whether this source is active (default `True`) |
-| `config` | JSONField | Source-specific configuration |
-| `created_by` | FK → User | User who created the config (nullable) |
+| Field | Type | Description |
+| ---------------- | --------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `team` | FK → Team | Owning team (`related_name="signal_source_configs"`) |
+| `source_product` | CharField | One of: `session_replay`, `llm_analytics`, `github`, `linear`, `zendesk`, `conversations`, `error_tracking`, `signals_scout` (`SourceProduct` enum) |
+| `source_type` | CharField | One of: `session_analysis_cluster`, `evaluation`, `issue`, `ticket`, `issue_created`, `issue_reopened`, `issue_spiking`, `cross_source_issue` (`SourceType` enum) |
+| `enabled` | Boolean | Whether this source is active (default `True`) |
+| `config` | JSONField | Source-specific configuration |
+| `created_by` | FK → User | User who created the config (nullable) |
**Behavioral notes:**
@@ -436,9 +484,93 @@ Per-team configuration for which signal sources are enabled.
- The serializer exposes a computed `status` field:
- `session_analysis_cluster` derives status from the Temporal clustering workflow
- data-import-backed sources (`github`, `linear`, `zendesk`) derive status from `ExternalDataSchema`
+- The `signals_scout` source variant pairs with `source_type=cross_source_issue` and is the emission channel used by the headless Signals agent's `emit_signal_*` tools. It is the only `(source_product, source_type)` pair the agent emits today.
**Constraints:** Unique on `(team, source_product, source_type)`
+### `SignalScoutConfig`
+
+Per-scout binding for the headless **Signals agent**: one row per `(team, skill_name)`. The coordinator auto-creates a row when it discovers a `signals-scout-*` skill on a participating team. Changes are activity-logged (they drive spend); team-level participation is gated by the `signals-scout` flag at the coordinator, not here. See `backend/scout_harness/AGENTS.md` for the harness internals.
+
+| Field | Type | Description |
+| ---------------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `team` | FK → Team | Owning team (`related_name="signal_scout_configs"`). `unique_together(team, skill_name)`. |
+| `skill_name` | CharField | The `signals-scout-*` skill this row controls. Auto-registered by the coordinator when it finds the skill on a participating team. |
+| `enabled` | Boolean | Per-scout switch; defaults `True`. `False` pauses just this scout. |
+| `emit` | Boolean | Dry-run vs emit. Defaults `False`: the scout runs and logs but `emit_finding` writes nothing — lets a scout be validated on a team before its findings reach the inbox. |
+| `run_interval_minutes` | PositiveSmallInt | Minutes between runs. The coordinator dispatches when `last_run_at is None or now - last_run_at >= run_interval_minutes`. Default `1440` (daily). Validated `10 <= N <= 43200`. |
+| `last_run_at` | DateTime (nullable) | Stamped after each dispatch; drives the due-check. Excluded from activity logging (written every run). |
+| `created_by` | FK → User (nullable) | Audit pointer |
+| `enabled_by` | FK → User (nullable) | Who last flipped `enabled` — tracked because enablement drives spend. |
+
+### `SignalScoutRun`
+
+Thin bridge from a Tasks `TaskRun` to the scout skill that ran inside it. Mirrors `SignalReportTask` (the bridge used by the SignalReport research flow): one scout-domain row per scheduled agent run that links its `TaskRun` to the skill it executed. Status, timing, error context, and the full chat log live on the `TaskRun`; emitted findings are `Signal` / `SignalReport` rows written by `emit_signal()`. This row carries only the scout-specific fields that need to be queryable as real columns.
+
+| Field | Type | Description |
+| --------------- | --------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
+| `team` | FK → Team | Owning team (`related_name="signal_scout_runs"`). Denormalised tenant boundary; canonical value is `task_run.task.team`. |
+| `task_run` | OneToOne → tasks.TaskRun | The `TaskRun` the scout span ran inside (`related_name="signal_scout_run"`, CASCADE — bridge row goes when the `TaskRun` is purged). |
+| `scout_config` | FK → SignalScoutConfig (SET_NULL) | Audit pointer; `SET_NULL` so deleting and recreating a config doesn't destroy run history. |
+| `skill_name` | CharField(200) | The `signals-scout-*` skill the run executed. |
+| `skill_version` | Int | The `LLMSkill.version` snapshot at run start. |
+| `summary` | TextField | One-paragraph close-out the agent writes at end-of-run. Searchable via ILIKE on the list endpoint so future runs can dedupe even when no `Signal` row was emitted. |
+| `created_at` | DateTime | Auto-set on creation. |
+
+**Status, timing, and chat log live on the linked `TaskRun`.** The bridge row carries no `status` / `started_at` / `completed_at` / `findings` / `run_metrics` / `metadata` of its own — those moved to `tasks.TaskRun` so the LLM-analytics token / cost roll-up, the Tasks UI, and the harness all see one canonical record. `MultiTurnSession` owns the `TaskRun` lifecycle; the `on_task_run_created` hook attaches the `TaskRun` to the bridge row before the agent's first turn.
+
+**Tasks UI cross-link.** Run serializers expose a computed `task_url` field on `signals-scout-runs-list` and `signals-scout-runs-retrieve` MCP responses — `/project/{team_id}/tasks/{task_run.task_id}?runId={task_run_id}`. `task_url` is `null` for rows whose `task_run` link is missing (rows aborted before `MultiTurnSession.start()` returned).
+
+**Indexes:** `(team, skill_name)`.
+
+**Constraints:** None at the DB level today. Single-flight is a best-effort app-layer guard (`_has_running_run` against `task_run.status = IN_PROGRESS`). An earlier partial unique constraint on `(team, skill_name) WHERE status='running'` was dropped together with the bridge model's own status column; a `task_run.status`-based constraint plus active recovery of stranded `IN_PROGRESS` task runs (`_self_heal_stale_runs` is a no-op today) is a tracked follow-up.
+
+### `SignalScratchpad`
+
+Narrow per-team scratchpad surface the scout fleet writes during runs and reads back on future runs (known issues, false positives, dedupe fingerprints, learned team quirks). Distinct from `SignalProjectProfile`: profile is _deterministic ground truth_, scratchpad is the _scout's inferred learnings_ (possibly wrong). MCP-readable across agents so PostHog AI and other scouts can see what the fleet has learned about a team.
+
+| Field | Type | Description |
+| ---------------- | ------------------------------ | ----------------------------------------------------------------------------------------- |
+| `team` | FK → Team | Owning team (`related_name="signal_scratchpads"`) |
+| `key` | CharField(300) | Semantic key, agent-chosen; unique per team |
+| `content` | TextField | Prose for prompt injection — the agent reads this verbatim |
+| `created_by_run` | FK → SignalScoutRun (SET_NULL) | The run that wrote this entry; `SET_NULL` so deleting a run row doesn't destroy the entry |
+| `created_at` | DateTime | Auto-set on creation |
+| `updated_at` | DateTime | Auto-set on save |
+
+**Constraints:** Unique on `(team, key)`.
+
+`authority`, `tags`, and `expires_at` (with their backing GIN / expiry indexes) were dropped in the PR2 review simplification — retrieval is now plain ILIKE over `key` + `content`, and every entry is durable per-team scratchpad.
+
+### `SignalProjectProfile`
+
+Deterministic snapshot of "what's true about this project" — the agent's orientation surface. Time-series so future phases can diff a new profile against the previous row to populate `payload.deltas`. Computed by `scout_harness/profile/builders.py` from authoritative tables; v1 writes 10 inventory sections (events, properties, cohorts, feature flags, experiments, surveys, dashboards, insights, data warehouse sources, integrations).
+
+| Field | Type | Description |
+| ---------------- | ------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| `team` | FK → Team | Owning team (`related_name="signal_project_profiles"`) |
+| `computed_at` | DateTime | Auto-set on creation |
+| `expires_at` | DateTime | Soft TTL — `get_project_profile` treats rows past expiry as cache misses and recomputes (~36h gives a safety margin against the daily refresh). |
+| `source_version` | CharField(40) | Bumps when the inventory schema changes meaningfully so `get_project_profile` can invalidate stale rows without a manual backfill |
+| `payload` | JSONField | `{inventory: {...}}` in v1; `deltas`, `activity_notes`, `narrative` slots reserved for later phases. Inline jsonb is fine — even a rich profile is small. |
+
+**Indexes:** `(team, -computed_at)` — supports the `ORDER BY computed_at DESC LIMIT 1` lookup used by `get_project_profile`.
+
+### `SignalEmissionRecord`
+
+Tracks which source records have been emitted as signals. Owned by the signals app so source models (e.g. `Ticket`) stay decoupled. One row per source record, upserted on emission.
+
+| Field | Type | Description |
+| ---------------- | -------------- | -------------------------------------------- |
+| `team` | FK → Team | Owning team |
+| `source_product` | CharField(100) | Mirror of `SignalSourceConfig.SourceProduct` |
+| `source_type` | CharField(100) | Mirror of `SignalSourceConfig.SourceType` |
+| `source_id` | CharField(200) | Source-side primary key |
+| `emitted_at` | DateTime | When this record was last emitted |
+
+**Constraints:** Unique on `(team, source_product, source_type, source_id)`
+**Indexes:** `(team, source_product, source_type)`
+
---
## ClickHouse Storage
@@ -646,6 +778,26 @@ View + control API for the v2 grouping pipeline. Uses scope object `INTERNAL`.
| PUT | `signals/processing/pause/` | Pause grouping until a given timestamp |
| DELETE | `signals/processing/pause/` | Clear the paused state |
+#### Signals Agent endpoints (`backend/scout_harness/views.py`)
+
+The harness exposes three viewsets routed under `environment_signals_scout_*` basenames in `posthog/api/__init__.py`. They are surfaced to MCP callers as `signals-scout-*` tools via `products/signals/mcp/tools.yaml`. Reads are scoped to the team; writes (scratchpad remember / forget, signal emit) require the matching MCP scope.
+
+- **`SignalScoutRunViewSet`** — list / retrieve scout run rows; nested action `runs/{id}/emit-signal/` for the harness to push findings during a run.
+- **`SignalScratchpadViewSet`** — search / remember / forget `SignalScratchpad` rows for the team. The `signals-scout-scratchpad-search` tool is the agent's primary "what do I already know" read at prompt-assembly time.
+- **`SignalProjectProfileViewSet`** — `GET .../current/` returns the freshest non-expired `SignalProjectProfile` row for the team (recomputes if the cache is stale).
+
+Generated MCP tool names:
+
+| Tool | Purpose |
+| ----------------------------------- | ------------------------------------------------------------------------------ |
+| `signals-scout-runs-list` | List scout runs (filterable by skill / status / time) |
+| `signals-scout-runs-retrieve` | Fetch a single run row including the full findings payload |
+| `signals-scout-emit-signal` | Push a finding from inside a run (used by the harness's `emit_signal_*` tools) |
+| `signals-scout-scratchpad-search` | Search durable scratchpad entries for the team |
+| `signals-scout-scratchpad-remember` | Create or update a scratchpad entry |
+| `signals-scout-scratchpad-forget` | Remove a scratchpad entry |
+| `signals-scout-project-profile-get` | Read the current `SignalProjectProfile` snapshot |
+
### Serializers (`backend/serializers.py`)
- **`SignalSourceConfigSerializer`**
@@ -900,16 +1052,20 @@ Signal {index}:
## Key Configuration
-| Setting | Default | Description |
-| ------------------------------ | ----------------------------- | ---------------------------------------------------------------------------------- |
-| `SIGNAL_WEIGHT_THRESHOLD` | `1.0` | Total weight needed to promote a report to candidate |
-| `SIGNAL_MATCHING_LLM_MODEL` | `claude-sonnet-4-5` | LLM model for all signal operations |
-| `MAX_RESPONSE_TOKENS` | `4096` | Base max tokens for LLM responses (thinking uses 3× for max_tokens, 2× for budget) |
-| Embedding model | `text-embedding-3-small-1536` | OpenAI embedding model used for signal content |
-| Task queue | `VIDEO_EXPORT_TASK_QUEUE` | Temporal task queue for all workflows |
-| `BUFFER_MAX_SIZE` | `20` | Max signals buffered in memory before flush to S3 |
-| `BUFFER_FLUSH_TIMEOUT_SECONDS` | `5` | Max seconds to wait for buffer to fill before flushing |
-| S3 prefix | `signals/signal_batches/` | Object storage path for signal batch files (cleaned up by S3 lifecycle policies) |
+| Setting | Default | Description |
+| ---------------------------------------- | ----------------------------- | ------------------------------------------------------------------------------------------------ |
+| `SIGNAL_WEIGHT_THRESHOLD` | `1.0` | Total weight needed to promote a report to candidate |
+| `SIGNAL_MATCHING_LLM_MODEL` | `claude-sonnet-4-5` | LLM model for all signal operations |
+| `MAX_RESPONSE_TOKENS` | `4096` | Base max tokens for LLM responses (thinking uses 3× for max_tokens, 2× for budget) |
+| Embedding model | `text-embedding-3-small-1536` | OpenAI embedding model used for signal content |
+| Task queue | `VIDEO_EXPORT_TASK_QUEUE` | Temporal task queue for all workflows |
+| `BUFFER_MAX_SIZE` | `20` | Max signals buffered in memory before flush to S3 |
+| `BUFFER_FLUSH_TIMEOUT_SECONDS` | `5` | Max seconds to wait for buffer to fill before flushing |
+| S3 prefix | `signals/signal_batches/` | Object storage path for signal batch files (cleaned up by S3 lifecycle policies) |
+| `COORDINATOR_INTERVAL_MINUTES` | `15` | Signals agent coordinator poll cadence (Temporal schedule, `SKIP` overlap policy) |
+| `MAX_RUNS_PER_TICK` | `50` | Hard cap on planned runs per coordinator tick (most-overdue-first, truncated after sort) |
+| `SignalScoutConfig.run_interval_minutes` | `1440` | Per-scout default schedule in minutes (daily); due-check, no sampling (`10`–`43200`) |
+| `SignalScoutConfig.emit` | `False` | Per-scout dry-run gate — scout runs and logs, but `emit_finding` writes nothing until flipped on |
---
@@ -922,10 +1078,28 @@ products/signals/
│ ├── admin.py # Django admin for SignalReport + SignalReportArtefact
│ ├── api.py # emit_signal() entry point + source/org guards
│ ├── apps.py # Django app config
-│ ├── models.py # SignalReport, SignalReportArtefact, SignalTeamConfig, SignalUserAutonomyConfig, SignalReportTask, SignalSourceConfig
+│ ├── models.py # SignalReport, SignalReportArtefact, SignalTeamConfig, SignalUserAutonomyConfig, SignalReportTask, SignalSourceConfig, SignalScoutConfig, SignalScoutRun, SignalScratchpad, SignalProjectProfile, SignalEmissionRecord
│ ├── serializers.py # DRF serializers for source configs, reports, artefacts, team config, user autonomy config, report tasks
│ ├── utils.py # Compatibility re-exports for signal query helpers
│ ├── views.py # SignalViewSet, InternalSignalViewSet, SignalSourceConfigViewSet, SignalTeamConfigViewSet, SignalReportViewSet, SignalReportTaskViewSet, SignalProcessingViewSet
+│ ├── scout_harness/ # Headless Signals agent — see scout_harness/AGENTS.md
+│ │ ├── AGENTS.md
+│ │ ├── __init__.py # Public re-exports (LoadedSkill, sync helpers, …)
+│ │ ├── runner.py # Per-run entrypoint; owns SignalScoutRun lifecycle + sandbox loop
+│ │ ├── prompt.py # System prompt assembly (skill + scratchpad + profile + run history)
+│ │ ├── skill_loader.py # Resolves signals-scout-* LLMSkill rows for a run
+│ │ ├── lazy_seed.py # Canonical SKILL.md → LLMSkill sync (sync_canonical_skills)
+│ │ ├── limits.py # DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S + WORKFLOW_HARD_CEILING_S
+│ │ ├── serializers.py # DRF serializers for runs / scratchpad / project profile
+│ │ ├── views.py # SignalScoutRunViewSet, SignalScratchpadViewSet, SignalProjectProfileViewSet
+│ │ ├── profile/
+│ │ │ ├── builders.py # Deterministic builders for SignalProjectProfile inventory
+│ │ │ └── schema.py # Dataclasses for the inventory payload shape
+│ │ └── tools/ # Harness-internal tools the agent calls inside a run
+│ │ ├── emit.py # emit_signal_* — pushes findings as cross_source_issue signals
+│ │ ├── scratchpad.py # remember / forget / search_scratchpad — read/write/delete SignalScratchpad
+│ │ ├── profile.py # project_profile_* — read SignalProjectProfile snapshot
+│ │ └── runs.py # runs_* — read past SignalScoutRun rows for dedupe
│ ├── github_issues/ # Placeholder directory
│ ├── management/
│ │ ├── AGENTS.md
@@ -941,9 +1115,11 @@ products/signals/
│ │ ├── list_signal_reports.py
│ │ ├── parse_sandbox_log.py
│ │ ├── reingest_team_signals.py # Starts TeamSignalReingestionWorkflow for a team
+│ │ ├── run_signals_scout.py # One-shot scout run; bypasses the coordinator
│ │ ├── select_repo.py
│ │ ├── signal_pipeline_status.py
-│ │ └── summarize_single_session.py
+│ │ ├── summarize_single_session.py
+│ │ └── sync_signals_scout_skills.py # Force a canonical SKILL.md sync to LLMSkill rows
│ ├── report_generation/
│ │ ├── AGENTS.md # Documentation for the agentic report generation flow
│ │ ├── research.py # Multi-turn sandbox research orchestration + output schemas + SignalReportTask(RESEARCH) creation
@@ -969,11 +1145,25 @@ products/signals/
│ │ ├── 0011_add_error_tracking_signal_types.py
│ │ ├── 0012_signalreport_run_count_and_more.py
│ │ ├── 0013_signalreport_suggested_reviewers.py
-│ │ └── 0014_signalautonomyconfig_alter_signalreportartefact_type.py # SignalTeamConfig, SignalUserAutonomyConfig, SignalReportTask
+│ │ ├── 0014_signalreportartefact_report_type_idx.py
+│ │ ├── 0015_alter_signalsourceconfig_source_product_and_more.py
+│ │ ├── 0016_signalautonomyconfig_alter_signalreportartefact_type.py # SignalTeamConfig, SignalUserAutonomyConfig, SignalReportTask
+│ │ ├── 0017_add_resolved_signal_report_status.py
+│ │ ├── 0018_alter_signalreportartefact_type.py
+│ │ ├── 0019_alter_signalsourceconfig_source_product_and_more.py
+│ │ ├── 0020_signaluserautonomyconfig_slack_notification_fields.py
+│ │ ├── 0021_add_signals_scout_source.py # cross_source_issue source variant
+│ │ ├── 0022_add_signal_scout_models.py # SignalScoutConfig, SignalScoutRun, SignalScratchpad
+│ │ ├── 0023_signalscoutrun_summary.py # SignalScoutRun.summary
+│ │ ├── 0024_signalprojectprofile.py # SignalProjectProfile
+│ │ └── 0027_reshape_scout_config_per_scout.py # per-(team, skill) config + per-scout schedules (drops runs_per_tick/enabled_skill_names)
│ └── temporal/
│ ├── __init__.py # Registers Signals workflows and activities
│ ├── agentic/
│ │ ├── __init__.py # Sandbox env / user-resolution helpers
+│ │ ├── scout_coordinator.py # SignalsScoutCoordinatorWorkflow + per-tick due-check activity
+│ │ ├── scout_scheduler.py # RunSignalsScoutWorkflow + run_signals_scout_activity
+│ │ ├── schedule.py # Temporal Schedule definition (cadence + SKIP overlap policy)
│ │ ├── report.py # Agentic report activity + artefact persistence
│ │ └── select_repository.py # Repository selection activity
│ ├── backfill_error_tracking.py # Backfill recent error tracking issues as signals
@@ -991,5 +1181,17 @@ products/signals/
│ ├── signal_queries.py # Canonical HogQL helpers for fetch/search/soft-delete/wait
│ ├── summary.py # SignalReportSummaryWorkflow + report state transition activities
│ └── types.py # Shared dataclasses + signal rendering helpers
+├── skills/ # Signals skills — see skills/AGENTS.md
+│ ├── AGENTS.md
+│ ├── signals/ # Official PostHog skill (published via posthog_ai/dist): querying signals data
+│ ├── inbox-exploration/ # Official PostHog skill (published via posthog_ai/dist): browsing the inbox
+│ ├── signals-scout-general/ # Scout fleet: cross-product generalist (SKILL.md + emit.md + conventions.md)
+│ ├── signals-scout-llm-analytics/ # Scout fleet: LLM analytics anomaly watcher
+│ ├── signals-scout-logs/ # Scout fleet: logs anomaly watcher
+│ ├── signals-scout-error-tracking/ # Scout fleet: error tracking anomaly watcher
+│ ├── signals-scout-revenue-analytics/ # Scout fleet: revenue anomaly watcher
+│ ├── signals-scout-surveys/ # Scout fleet: surveys anomaly + theme-aggregation watcher
+│ ├── signals-scout-observability-gaps/ # Scout fleet: structural-gap watcher (P3 recommendations)
+│ └── signals-scout-csp-violations/ # Scout fleet: CSP violation watcher
└── frontend/ # Frontend components (not covered here)
```
diff --git a/products/signals/backend/management/AGENTS.md b/products/signals/backend/management/AGENTS.md
index 25115753a051..0825b3674212 100644
--- a/products/signals/backend/management/AGENTS.md
+++ b/products/signals/backend/management/AGENTS.md
@@ -96,6 +96,59 @@ python manage.py select_repo --verbose
Uses synthetic JS SDK signals by default. The agent uses `gh` CLI to explore candidates and pick the best match.
+## Signals agent (headless scout)
+
+Two commands cover the day-to-day loop on the headless `signals-scout-*` scouts.
+Background and architecture: `../scout_harness/AGENTS.md` and `../../skills/AGENTS.md`.
+
+### Running one scout locally
+
+`run_signals_scout` triggers a single `(team, skill)` run end-to-end without waiting
+for the Temporal coordinator. Inserts a `SignalScoutRun` row, opens a sandbox, pumps
+the agent loop until budget exhaustion or natural completion, finalizes the run.
+
+```bash
+# Single specialist run against a dogfood team
+python manage.py run_signals_scout \
+ --team-id 1 \
+ --skill-name signals-scout-llm-analytics
+
+# Pin a skill version (default: latest LLMSkill row for the team)
+python manage.py run_signals_scout --team-id 1 --skill-name signals-scout-general --skill-version 4
+
+# Optional: pin the sandbox repository
+python manage.py run_signals_scout --team-id 1 --skill-name signals-scout-general \
+ --repository posthog/posthog --verbose
+```
+
+The team must have a `SignalScoutConfig` row for the scout (the coordinator auto-creates
+one; the command also seeds it). Configs default to `emit=False` — the scout runs and
+logs but `emit_finding` writes nothing, so no finding reaches the Signals inbox until you
+flip `emit=True` on that scout's config (e.g. via the `signals-scout-config-update` MCP tool).
+
+### Canonical skill sync
+
+`sync_signals_scout_skills` forces a `sync_canonical_skills` pass without waiting for
+the next coordinator tick. Reads `products/signals/skills/signals-scout-*/` from disk
+and reconciles each scout against the team's `LLMSkill` rows.
+
+```bash
+# After merging a SKILL.md change — fan out to every dogfood team now
+python manage.py sync_signals_scout_skills --all-enabled
+
+# Onboard one team synchronously
+python manage.py sync_signals_scout_skills --team-id 1
+
+# See what would change without writing
+python manage.py sync_signals_scout_skills --all-enabled --dry-run
+```
+
+Output buckets per team: `created`, `updated`, `diverged` (team-edited or hand-authored rows
+left alone), `tombstoned` (rows the team already soft-deleted — left alone, never resurrected),
+`pruned` (live rows whose canonical skill was removed from disk — soft-deleted so the
+coordinator stops dispatching them). Same function the coordinator and runner call lazily —
+this command is just the impatient path.
+
## Tips
- Compare runs by saving output: `list_signal_reports --json > run_baseline.json`
diff --git a/products/signals/backend/management/commands/sync_signals_scout_skills.py b/products/signals/backend/management/commands/sync_signals_scout_skills.py
new file mode 100644
index 000000000000..e97b790aec35
--- /dev/null
+++ b/products/signals/backend/management/commands/sync_signals_scout_skills.py
@@ -0,0 +1,156 @@
+"""Force a `sync_canonical_skills` pass for one or more teams without waiting for the
+coordinator tick.
+
+Use cases:
+
+- You merged a SKILL.md change and want it propagated to dogfood teams *now*, not on the
+ next ≤15min coordinator tick.
+- You shipped a quick revert and want every team back to the fixed canonical immediately.
+- You're onboarding a new team and want the canonical fleet seeded synchronously.
+
+Reads the canonical fleet from `products/signals/skills/signals-scout-*/` (whatever the
+worker process sees on disk), then calls `sync_canonical_skills(team)` per team. Same
+function the coordinator and runner call lazily — this command is just the impatient path.
+"""
+
+from __future__ import annotations
+
+from django.core.management.base import BaseCommand, CommandError
+from django.db import transaction
+
+from posthog.models.team.team import Team
+
+from products.signals.backend.models import SignalScoutConfig
+from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
+
+
+class Command(BaseCommand):
+ help = "Sync canonical signals-scout-* skills from disk to teams' LLMSkill rows."
+
+ def add_arguments(self, parser):
+ # `--team-id` and `--all-enabled` are mutually exclusive; one is required. Plain
+ # default would either skip everything or fan out to the whole DB without intent.
+ parser.add_argument(
+ "--team-id",
+ type=int,
+ help="Sync a specific team. Mutually exclusive with --all-enabled.",
+ )
+ parser.add_argument(
+ "--all-enabled",
+ action="store_true",
+ help=(
+ "Sync every team that has an enabled SignalScoutConfig. Use this after "
+ "merging a SKILL.md change to fan it out to all dogfood teams."
+ ),
+ )
+ parser.add_argument(
+ "--dry-run",
+ action="store_true",
+ help="Print what would change without writing to the DB.",
+ )
+
+ def handle(self, *args, **options):
+ team_id: int | None = options.get("team_id")
+ all_enabled: bool = options.get("all_enabled", False)
+ dry_run: bool = options.get("dry_run", False)
+
+ if not team_id and not all_enabled:
+ raise CommandError("Pass either --team-id <id> or --all-enabled")
+ if team_id and all_enabled:
+ raise CommandError("--team-id and --all-enabled are mutually exclusive")
+
+ teams = self._resolve_teams(team_id=team_id, all_enabled=all_enabled)
+ if not teams:
+ self.stdout.write(self.style.WARNING("No teams matched the selection — nothing to sync."))
+ return
+
+ if dry_run:
+ # Dry-run is a transaction-rolled-back sync so we get the real per-team report
+ # without persisting. Pulled into a separate helper to keep the no-op path
+ # obvious; callers can lean on the output to decide whether to run for real.
+ self._dry_run(teams)
+ return
+
+ totals = {
+ "created": 0,
+ "updated": 0,
+ "diverged": 0,
+ "tombstoned": 0,
+ "pruned": 0,
+ }
+ for team in teams:
+ # Explicit reconciliation path → prune orphaned rows (canonical removed from disk).
+ result = sync_canonical_skills(team, prune=True)
+ totals["created"] += len(result.created_skill_names)
+ totals["updated"] += len(result.updated_skill_names)
+ totals["diverged"] += len(result.diverged_skill_names)
+ totals["tombstoned"] += len(result.tombstoned_skill_names)
+ totals["pruned"] += len(result.pruned_skill_names)
+ self._print_team_result(team, result)
+
+ self.stdout.write("")
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Synced {len(teams)} team(s): "
+ f"+{totals['created']} created, "
+ f"~{totals['updated']} updated, "
+ f"={totals['diverged']} diverged (left alone), "
+ f"#{totals['tombstoned']} tombstoned, "
+ f"-{totals['pruned']} pruned"
+ )
+ )
+
+ def _resolve_teams(self, *, team_id: int | None, all_enabled: bool) -> list[Team]:
+ if team_id:
+ try:
+ return [Team.objects.get(id=team_id)]
+ except Team.DoesNotExist:
+ raise CommandError(f"Team {team_id} not found")
+ # all_enabled — pull every team that has at least one enabled SignalScoutConfig.
+ # `.unscoped()` is intentional: this is a cross-team management scan, same as the
+ # Temporal coordinator. The default `.objects` manager is fail-closed
+ # (TeamScopedRootMixin) so without the unscoped sibling it would either raise or
+ # silently return only the team in the current scope context, hiding teams the
+ # operator is trying to sync.
+ # `select_related("team")` to avoid an N+1 in the loop above.
+ configs = SignalScoutConfig.objects.unscoped().filter(enabled=True).select_related("team").order_by("team__id")
+ # Distinct teams only; one config per team is the norm but we don't depend on it.
+ seen: set[int] = set()
+ teams: list[Team] = []
+ for config in configs:
+ if config.team.id in seen:
+ continue
+ seen.add(config.team.id)
+ teams.append(config.team)
+ return teams
+
+ def _dry_run(self, teams: list[Team]) -> None:
+ # Run inside a transaction we always roll back, so the output reflects what *would*
+ # happen if we ran for real. Cheaper than re-implementing the decision branches here.
+ self.stdout.write(self.style.WARNING("[dry-run] no changes will be persisted"))
+ with transaction.atomic():
+ for team in teams:
+ # Preview prune too (rolled back below), so the dry-run shows what would be reaped.
+ result = sync_canonical_skills(team, prune=True)
+ self._print_team_result(team, result, prefix="[dry-run] ")
+ transaction.set_rollback(True)
+
+ def _print_team_result(self, team: Team, result, prefix: str = "") -> None:
+ if result.skipped_reason:
+ self.stdout.write(f"{prefix}team {team.id}: skipped — {result.skipped_reason}")
+ return
+ parts: list[str] = []
+ if result.created_skill_names:
+ parts.append(f"+created {list(result.created_skill_names)}")
+ if result.updated_skill_names:
+ parts.append(f"~updated {list(result.updated_skill_names)}")
+ if result.diverged_skill_names:
+ parts.append(f"=diverged {list(result.diverged_skill_names)}")
+ if result.tombstoned_skill_names:
+ parts.append(f"#tombstoned {list(result.tombstoned_skill_names)}")
+ if result.pruned_skill_names:
+ parts.append(f"-pruned {list(result.pruned_skill_names)}")
+ if not parts:
+ self.stdout.write(f"{prefix}team {team.id}: no changes")
+ return
+ self.stdout.write(f"{prefix}team {team.id}: " + ", ".join(parts))
diff --git a/products/signals/backend/scout_harness/AGENTS.md b/products/signals/backend/scout_harness/AGENTS.md
new file mode 100644
index 000000000000..e5001c29b36b
--- /dev/null
+++ b/products/signals/backend/scout_harness/AGENTS.md
@@ -0,0 +1,152 @@
+# Signals Agent Harness
+
+This directory contains the headless **Signals agent** — a scheduled scout that explores
+a project, writes durable scratchpad entries across runs, and emits findings into the
+Signals inbox via `emit_signal()` using the `signals_scout` source variant.
+
+It is the second agentic surface in Signals. The other one — `report_generation/` — runs
+on demand when a `SignalReport` is promoted to `candidate` and produces a single research
+output for one report. The harness here is the inverse: it runs on a schedule, decides
+_what_ to investigate from scratch, and pushes new signals into the same pipeline rather
+than acting on existing ones.
+
+In production it is driven by `SignalsScoutCoordinatorWorkflow` (periodic tick every
+`COORDINATOR_INTERVAL_MINUTES = 15` → fan out per-(team, skill) child workflows). Locally
+it is exercised via the `run_signals_scout` management command (see `../management/AGENTS.md`).
+
+## What lives here
+
+- `runner.py`
+ Per-run entrypoint (`arun_signals_scout` / `run_signals_scout`). Inserts the
+ `SignalScoutRun` row, builds the prompt + toolset, spawns the sandbox session,
+ pumps the agent loop until budget exhaustion or natural completion, finalizes the run,
+ and returns a `RunResult`. The activity wrapper in `temporal/agentic/scout_scheduler.py`
+ delegates straight to this.
+- `prompt.py`
+ Assembles the system prompt: persona + skill body + relevant scratchpad entries +
+ project profile inventory + recent run summaries. Scratchpad and run history are
+ filtered by skill so a specialist only sees its own past work.
+- `skill_loader.py`
+ Resolves `signals-scout-*` skills from the team's `LLMSkill` rows. Defines
+ `SIGNALS_SCOUT_SKILL_PREFIX` and `LoadedSkill` (body + version + allowed_tools).
+- `lazy_seed.py`
+ Canonical skill sync. Reads `products/signals/skills/signals-scout-*/` from disk and
+ reconciles them against the team's `LLMSkill` rows: creates missing rows, updates
+ ones the team hasn't edited, leaves diverged / hand-authored rows alone, tombstones
+ rows whose canonical skill was deleted. Only rows tagged
+ `metadata.seeded_by="signals_scout_harness"` are ever updated. Called both lazily
+ (coordinator tick, runner cold-start) and explicitly via the `sync_signals_scout_skills`
+ management command.
+- `tools/`
+ Implementations of the four harness-internal tools the agent calls during a run.
+ The effective toolset for a run is the intersection of the skill's `allowed_tools`
+ list with what `tools/__init__.py` re-exports — there is no separate registry
+ module today.
+ - `emit.py` — `emit_signal_*` tools that push findings as `cross_source_issue`
+ signals into the standard ingestion pipeline.
+ - `scratchpad.py` — `remember`, `forget`, and `search_scratchpad` tools backed by
+ the `SignalScratchpad` model.
+ - `profile.py` — `project_profile_*` tools that read the deterministic
+ `SignalProjectProfile` snapshot.
+ - `runs.py` — `runs_*` tools that read past `SignalScoutRun` rows for dedupe and
+ cross-skill awareness.
+- `profile/`
+ - `builders.py` — deterministic builders that compute the inventory payload for
+ `SignalProjectProfile`. Sections fall into three layers: capability / configured
+ (sticky — `products_in_use`, `integrations`, `external_data_sources`,
+ `signal_source_configs`, …), aggregated recency (`recent_activity` — per-scope
+ counts off the activity log, cross-cutting orientation across every entity type),
+ and per-entity recent inventory (`recent_surveys`, `recent_feature_flags`,
+ `recent_experiments`, `recent_alerts`, `recent_hog_functions`, `recent_hog_flows`,
+ `recent_notebooks`, `recent_cohorts`, `recent_actions`, `recent_dashboards`).
+ Per-entity sections are deliberately light (counts + 5 most-recent items with
+ name, status, timestamp); deep drilldowns go via the per-entity MCP list tools.
+ See the module docstring at `profile/builders.py` for the authoritative section
+ list — when adding or renaming a section, bump `INVENTORY_SOURCE_VERSION` so
+ the cache invalidates cleanly.
+- `limits.py`
+ Runtime ceilings as module constants: `DEFAULT_MAX_RUNTIME_S` (per-run budget),
+ `ACTIVITY_SLACK_S`, and `WORKFLOW_HARD_CEILING_S` (`= DEFAULT_MAX_RUNTIME_S +
+ACTIVITY_SLACK_S`, the activity-level ceiling that gates the workflow's
+ `start_to_close_timeout`).
+- `serializers.py`
+ DRF serializers for the harness HTTP surface (runs, scratchpad, project profile).
+ Annotated for drf-spectacular so the generated MCP tools have informative schemas.
+- `views.py`
+ `SignalScoutRunViewSet`, `SignalScratchpadViewSet`, `SignalProjectProfileViewSet`.
+ Routed under `environment_signals_scout_*` basenames in `posthog/api/__init__.py`
+ and exposed as `signals-scout-*` MCP tools via `products/signals/mcp/tools.yaml`.
+
+## Mental model
+
+`arun_signals_scout()` is the main entrypoint. One call → one `SignalScoutRun` row →
+one sandbox session → zero or more emitted signals.
+
+- The harness inserts the bridge row at the start of a run (inside `_spawn_and_run`).
+ `SignalScoutRun` is now a thin bridge to a Tasks `TaskRun` — run status / timing / error
+ live on `task_run`, not on the bridge row. Single-flight is a best-effort app-layer guard:
+ `_has_running_run` skips dispatch when a prior run for the same `(team, skill_name)` has
+ `task_run.status = IN_PROGRESS`. The old `WHERE status='running'` partial unique index was
+ dropped in the bridge simplification; a `task_run.status`-based constraint plus active
+ stale-run recovery (`_self_heal_stale_runs` is a no-op today) is a tracked follow-up.
+- The sandbox is opened with the team's MCP token plus the harness-internal tools.
+ The skill body is loaded into the system prompt; each scout has its own
+ `SignalScoutConfig` row (keyed on `(team, skill_name)`) whose `enabled` flag and
+ `run_interval_minutes` schedule the coordinator's per-scout due-check honors.
+- `MultiTurnSession.start()` creates a Tasks `(Task, TaskRun)` pair to drive the
+ sandbox. The bridge row links to its `TaskRun` via a `OneToOne` FK (`task_run`), created
+ by the `on_task_run_created` hook before the agent's first turn — this powers the
+ `task_url` deep-link on the run serializers
+ (`/project/{team_id}/tasks/{task_id}?runId={task_run_id}`) and is the join key for the
+ LLM-analytics token / cost roll-up. Failure context (status, error, full chat log via
+ LLMA) lives on the `TaskRun`; the harness persists no run state on the bridge row.
+- Emit happens via the harness's `emit_signal_*` tools, which call `emit_signal()`
+ with `source_product="signals_scout"` and `source_type="cross_source_issue"`.
+ From there the signal flows through the same emitter → buffer → grouping v2 path
+ as any other source.
+- Scratchpad entries and run history are read at prompt assembly time. The agent can
+ also write scratchpad entries mid-run via `remember` / `forget` — that's how a
+ specialist with no anomalies to chase records "no LLM activity here, close out
+ fast" so future runs of the same skill short-circuit cold.
+
+## Where the rest of the system meets this directory
+
+- **Coordinator** — `temporal/agentic/scout_coordinator.py` and `scout_scheduler.py`.
+ Polls every `COORDINATOR_INTERVAL_MINUTES = 15`; dispatches each scout whose
+ per-scout schedule (`run_interval_minutes`, default daily) is due, most-overdue
+ first, hard cap `MAX_RUNS_PER_TICK = 50` per tick, `ScheduleOverlapPolicy.SKIP` to
+ drop ticks rather than queue them.
+- **Models** — `SignalScoutConfig`, `SignalScoutRun`, `SignalScratchpad`,
+ `SignalProjectProfile` in `../models.py`.
+- **Source variant** — `SignalSourceConfig.SourceProduct.SIGNALS_SCOUT` paired with
+ `SourceType.CROSS_SOURCE_ISSUE`.
+- **Scout fleet** — the `signals-scout-*` skills live at
+ `../../skills/signals-scout-*/` (generalist + 7 specialists). See
+ `../../skills/AGENTS.md` for the fleet convention.
+- **Local commands** — `run_signals_scout` (one-shot run) and
+ `sync_signals_scout_skills` (force a canonical-skill sync). Both documented in
+ `../management/AGENTS.md`.
+
+## When editing this flow
+
+- Keep the harness loop generic. Skill-specific logic belongs in the SKILL.md of the
+ scout, not in `runner.py` or `prompt.py`.
+- New harness-internal tools: add the implementation under `tools/`, re-export it
+ from `tools/__init__.py`, and add a corresponding scope check on the viewset in
+ `views.py` so the MCP surface and the sandbox surface stay aligned.
+- If you change the canonical SKILL.md format or directory layout, update
+ `lazy_seed.discover_canonical_skills()` and the parser tests — the coordinator
+ call to `sync_canonical_skills()` runs on every tick and silently swallows parser
+ errors (logs only), so a quiet schema break can leave canonical content stale on
+ every team.
+- Run lifecycle lives on the linked `TaskRun` (`task_run.status`), managed by
+ `MultiTurnSession` — the `SignalScoutRun` bridge row carries no status of its own. A
+ `TaskRun` stranded in `IN_PROGRESS` (worker SIGKILL before finalize) blocks new runs for
+ that `(team, skill)` via `_has_running_run` until it transitions out; active recovery of
+ such rows is a deferred follow-up (`_self_heal_stale_runs` is currently a no-op).
+- Emit path goes through `emit_signal()` and only `emit_signal()`. Do not write to
+ the embeddings pipeline or `SignalReport` directly from harness code.
+- **If you add or rename a workflow/activity in `temporal/agentic/`, update
+ `posthog/temporal/tests/ai/test_module_integrity.py` (`TestSignalsProductModuleIntegrity`)
+ to match.**
+- **If you change the harness layout or tool surface, update this file to match.**
diff --git a/products/signals/backend/scout_harness/CLAUDE.md b/products/signals/backend/scout_harness/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/signals/backend/scout_harness/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/signals/backend/scout_harness/__init__.py b/products/signals/backend/scout_harness/__init__.py
index ed6917f711fe..734d8bfc122d 100644
--- a/products/signals/backend/scout_harness/__init__.py
+++ b/products/signals/backend/scout_harness/__init__.py
@@ -9,8 +9,10 @@ from products.signals.backend.scout_harness.lazy_seed import (
CanonicalSkillFile,
CanonicalSkillParseError,
SeedResult,
+ SyncResult,
discover_canonical_skills,
seed_canonical_skills,
+ sync_canonical_skills,
)
from products.signals.backend.scout_harness.skill_loader import LoadedSkill, SkillNotFoundError, load_skill_for_run
@@ -21,7 +23,9 @@ __all__ = [
"LoadedSkill",
"SeedResult",
"SkillNotFoundError",
+ "SyncResult",
"discover_canonical_skills",
"load_skill_for_run",
"seed_canonical_skills",
+ "sync_canonical_skills",
]
diff --git a/products/signals/backend/scout_harness/lazy_seed.py b/products/signals/backend/scout_harness/lazy_seed.py
index a09f92857c85..65b6a0c535b4 100644
--- a/products/signals/backend/scout_harness/lazy_seed.py
+++ b/products/signals/backend/scout_harness/lazy_seed.py
@@ -1,6 +1,8 @@
from __future__ import annotations
import re
+import json
+import hashlib
import logging
from dataclasses import dataclass
from pathlib import Path
@@ -72,17 +74,44 @@ class CanonicalSkill:
@dataclass(frozen=True)
-class SeedResult:
- """Outcome of `seed_canonical_skills`.
-
- `created_skill_names` is empty when the team already had at least one signals-scout-*
- skill (the seed is a no-op in that case — edits and forks on team copies are preserved).
+class SyncResult:
+ """Outcome of `sync_canonical_skills` for one team.
+
+ Each tuple lists the canonical skill names that fell into a particular branch:
+
+ - `created_skill_names`: rows that didn't exist on the team and were created from canonical.
+ - `updated_skill_names`: live rows whose stored hash matched their content (so the team had
+ not edited them) but whose content differed from the latest canonical — overwritten with
+ the latest canonical, version bumped, hash refreshed.
+ - `diverged_skill_names`: live rows we leave untouched — either a row we seeded whose
+ content hash no longer matches the stored `canonical_hash` (the team edited their copy),
+ or a row we never seeded (hand-authored, sharing a canonical name — no `seeded_by` tag).
+ - `tombstoned_skill_names`: rows that exist only as soft-deleted tombstones — the team
+ removed this skill from their rotation. Left untouched (no resurrection).
+ - `pruned_skill_names`: live `signals-scout-*` rows whose canonical skill was removed from
+ disk (no longer in the discovered fleet). Soft-deleted (`deleted=True`, `is_latest=False`)
+ so the coordinator stops dispatching a scout that's no longer part of the canonical fleet.
+ Unlike `tombstoned_skill_names` (a passive observation that the team already removed it),
+ this is an active reconciliation we perform.
+
+ A skill name appears in at most one tuple per call. `skipped_reason` is set when no per-skill
+ work was even attempted (e.g. the canonical dir is missing on disk in tests).
"""
- created_skill_names: tuple[str, ...]
+ created_skill_names: tuple[str, ...] = ()
+ updated_skill_names: tuple[str, ...] = ()
+ diverged_skill_names: tuple[str, ...] = ()
+ tombstoned_skill_names: tuple[str, ...] = ()
+ pruned_skill_names: tuple[str, ...] = ()
skipped_reason: str | None = None
+# Backwards-compat alias. The first emit-only deploy returned `SeedResult`; downstream callers
+# may still import the old name. The new `SyncResult` is a strict superset (created_skill_names
+# + skipped_reason are present and behave the same), so the alias is safe.
+SeedResult = SyncResult
+
+
class CanonicalSkillParseError(ValueError):
"""A canonical SKILL.md on disk is malformed (missing frontmatter, bad YAML, etc.)."""
@@ -187,11 +216,18 @@ def discover_canonical_skills(skills_dir: Path | None = None) -> tuple[Canonical
Skipping a malformed canonical entry would mask author errors; instead we let
`CanonicalSkillParseError` propagate so the harness fails loud and the canonical source
gets fixed.
+
+ Frontmatter `name`s must be unique across the fleet. The sync reconciles per skill name,
+ so two directories declaring the same `name` with differing content would make each
+ coordinator tick rewrite the team's row to the first definition and then the second,
+ bumping versions forever. We reject the collision here so a misauthored fleet fails loud
+ on the first read instead of flapping silently.
"""
base = skills_dir or _SKILLS_DIR
if not base.is_dir():
return ()
discovered: list[CanonicalSkill] = []
+ by_name: dict[str, Path] = {}
for entry in sorted(base.iterdir()):
if not entry.is_dir():
continue
@@ -199,83 +235,290 @@ def discover_canonical_skills(skills_dir: Path | None = None) -> tuple[Canonical
continue
if not (entry / "SKILL.md").is_file():
continue
- discovered.append(_parse_canonical_skill(entry))
+ skill = _parse_canonical_skill(entry)
+ 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}"
+ )
+ by_name[skill.name] = entry
+ discovered.append(skill)
return tuple(discovered)
-def seed_canonical_skills(team: Team) -> SeedResult:
- """Idempotently seed canonical `signals-scout-*` skills into a team's namespace.
+def _compute_canonical_hash(canonical: CanonicalSkill) -> str:
+ """Stable content fingerprint for a canonical skill on disk.
- No-op when the team already has any `signals-scout-*` skill (deleted or live). Edits
- and forks on team copies are preserved across calls — once a team has been seeded
- (or has authored its own row under the prefix), the canonical set never overwrites
- their content. Existence of any row under the prefix counts as "already seeded",
- including archived (`deleted=True`) rows; re-seeding archived skills would resurrect
- content the team deliberately removed.
+ Includes everything that could meaningfully change between revisions: description and body
+ text, the allowed-tools list (sorted so reordering doesn't invalidate), and the bundle
+ treated as a sorted list of `(path, content, content_type)` tuples. The bundle inclusion
+ means a references-only change (e.g. tweaking `references/calibration.md`) still triggers
+ an update — easy to forget if the hash only covered SKILL.md body.
- Concurrent calls are safe: the create path uses `transaction.atomic()` plus the model's
- unique constraint (`unique_llm_skill_latest_per_team`) to drop duplicate inserts.
+ SHA-256 is overkill cryptographically but content-addressable hashes are cheap and we want
+ no false positives.
"""
- existing = list(
- LLMSkill.objects.filter(team=team, name__startswith=SIGNALS_SCOUT_SKILL_PREFIX).values_list("name", flat=True)
- )
- if existing:
- return SeedResult(
- created_skill_names=(),
- skipped_reason=f"team already has {len(set(existing))} signals-scout-* skill(s)",
+ payload = {
+ "description": canonical.description,
+ "body": canonical.body,
+ "allowed_tools": sorted(canonical.allowed_tools),
+ "files": sorted([(f.path, f.content, f.content_type) for f in canonical.files]),
+ }
+ return hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
+
+
+def _compute_row_hash(skill: LLMSkill, files: list[LLMSkillFile]) -> str:
+ """Hash a team's `LLMSkill` row in the same shape as `_compute_canonical_hash` so the two
+ can be compared directly. Caller must pre-fetch `files` to avoid an N+1 inside the hash."""
+ payload = {
+ "description": skill.description,
+ "body": skill.body,
+ "allowed_tools": sorted(skill.allowed_tools or []),
+ "files": sorted([(f.path, f.content, f.content_type) for f in files]),
+ }
+ return hashlib.sha256(json.dumps(payload, sort_keys=True).encode("utf-8")).hexdigest()
+
+
+def _create_skill_from_canonical(team: Team, canonical: CanonicalSkill, canonical_hash: str) -> None:
+ """Insert a brand-new row for a (team, canonical.name) that has no prior history.
+
+ Caller already verified no row exists. The unique constraint on
+ `(team, name, deleted=False, is_latest=True)` is our race guard — if two coordinator runs
+ fire for the same team at once, one wins and the other gets `IntegrityError`, which the
+ caller swallows.
+ """
+ with transaction.atomic():
+ skill = LLMSkill.objects.create(
+ team=team,
+ name=canonical.name,
+ description=canonical.description,
+ body=canonical.body,
+ allowed_tools=list(canonical.allowed_tools),
+ metadata={
+ "seeded_by": "signals_scout_harness",
+ "source": "products/signals/skills",
+ "canonical_hash": canonical_hash,
+ },
+ version=1,
+ is_latest=True,
)
+ if canonical.files:
+ LLMSkillFile.objects.bulk_create(
+ [
+ LLMSkillFile(
+ skill=skill,
+ path=f.path,
+ content=f.content,
+ content_type=f.content_type,
+ )
+ for f in canonical.files
+ ]
+ )
+
+
+def _update_skill_from_canonical(
+ team: Team, current_latest: LLMSkill, canonical: CanonicalSkill, canonical_hash: str
+) -> None:
+ """Replace the team's live row for this skill with the latest canonical content, bumping
+ the version. Mirrors the version-bump pattern a user-facing PHS edit would produce — old
+ rows aren't mutated; we mark them `is_latest=False` and create a new row at `version+1`.
+ The `metadata.seeded_by="signals_scout_harness"` tag distinguishes our updates from
+ user edits in the version-history view.
+
+ Concurrency: `select_for_update` on the existing latest row pins it for the duration of
+ the txn. If a user-edit racing us has already bumped to `version+1`, we observe their
+ write at lock acquisition and our subsequent insert at `version+1` collides with the
+ unique constraint — caller swallows the IntegrityError (their edit wins, we'll re-evaluate
+ next tick and find their content diverged).
+ """
+ with transaction.atomic():
+ # Re-fetch under FOR UPDATE so concurrent edits serialize behind us.
+ locked = LLMSkill.objects.select_for_update().get(pk=current_latest.pk)
+ new_version = locked.version + 1
+ locked.is_latest = False
+ locked.save(update_fields=["is_latest", "updated_at"])
+
+ new_metadata = dict(locked.metadata or {})
+ new_metadata["seeded_by"] = "signals_scout_harness"
+ new_metadata["source"] = "products/signals/skills"
+ new_metadata["canonical_hash"] = canonical_hash
+
+ new_skill = LLMSkill.objects.create(
+ team=team,
+ name=canonical.name,
+ description=canonical.description,
+ body=canonical.body,
+ allowed_tools=list(canonical.allowed_tools),
+ metadata=new_metadata,
+ version=new_version,
+ is_latest=True,
+ )
+ if canonical.files:
+ LLMSkillFile.objects.bulk_create(
+ [
+ LLMSkillFile(
+ skill=new_skill,
+ path=f.path,
+ content=f.content,
+ content_type=f.content_type,
+ )
+ for f in canonical.files
+ ]
+ )
+
+def sync_canonical_skills(team: Team, *, prune: bool = False) -> SyncResult:
+ """Reconcile a team's `signals-scout-*` rows with the canonical fleet on disk.
+
+ Walks each canonical skill in `products/signals/skills/` and decides per-skill whether
+ to create, update, leave-as-diverged, or leave-as-tombstone (plus prune, when enabled).
+ Only rows we seeded (`metadata.seeded_by="signals_scout_harness"`) are ever updated.
+ See `SyncResult` for the outcome buckets and the section comments below for the full
+ decision table.
+
+ `prune` (default off) additionally tombstones live `signals-scout-*` rows whose canonical
+ was removed from disk. It's a destructive reconciliation reserved for the deliberate paths
+ — the coordinator tick and the explicit `sync_signals_scout_skills` command. The runner's
+ cold-start sync leaves it off: a single ad-hoc run should only ensure its own skill exists
+ and is current, not reap the rest of the team's fleet.
+
+ Idempotent and safe to call on every coordinator tick — the only DB writes happen when
+ something actually needs to change, and IntegrityError on races is logged-and-swallowed.
+ """
canonicals = discover_canonical_skills()
if not canonicals:
- return SeedResult(created_skill_names=(), skipped_reason="no canonical signals-scout-* skills on disk")
+ return SyncResult(skipped_reason="no canonical signals-scout-* skills on disk")
created: list[str] = []
- # Seed the full set in one transaction: a mid-loop failure rolls back every insert, so the
- # next run retries the whole set instead of getting wedged with a partial seed the
- # "already seeded" guard above would treat as complete.
- # Direct ORM path is intentional: there's no `create_skill_from_scratch_with_files` helper at
- # the service layer, and the universal contract limits are enforced at parse time in
- # `_parse_canonical_skill` to match the REST API.
- try:
- with transaction.atomic():
- for canonical in canonicals:
- skill = LLMSkill.objects.create(
- team=team,
- name=canonical.name,
- description=canonical.description,
- body=canonical.body,
- allowed_tools=list(canonical.allowed_tools),
- metadata={
- "seeded_by": "signals_scout_harness",
- "source": "products/signals/skills",
- },
- version=1,
- is_latest=True,
- )
- if canonical.files:
- LLMSkillFile.objects.bulk_create(
- [
- LLMSkillFile(
- skill=skill,
- path=f.path,
- content=f.content,
- content_type=f.content_type,
- )
- for f in canonical.files
- ]
- )
+ updated: list[str] = []
+ diverged: list[str] = []
+ tombstoned: list[str] = []
+ pruned: list[str] = []
+
+ for canonical in canonicals:
+ canonical_hash = _compute_canonical_hash(canonical)
+
+ # Pull every row for this (team, name), live or tombstoned. Existence of any row —
+ # including soft-deleted — counts as "team has seen this skill name before"; we
+ # never resurrect tombstones.
+ rows = list(LLMSkill.objects.filter(team=team, name=canonical.name).order_by("-version"))
+
+ if not rows:
+ # Brand-new for this team. Either a freshly-enabled team, or a specialist
+ # added to the canonical fleet after this team was first seeded.
+ try:
+ _create_skill_from_canonical(team, canonical, canonical_hash)
created.append(canonical.name)
- except IntegrityError:
- # A concurrent caller seeded this team first; their atomic stands, ours rolls back.
- logger.info(
- "signals_scout: concurrent seed dropped, canonical skills already created",
- extra={"team_id": team.id},
- )
- return SeedResult(created_skill_names=(), skipped_reason="concurrent seed won")
+ except IntegrityError:
+ logger.info(
+ "signals_scout: concurrent create lost the race; skipping",
+ extra={"team_id": team.id, "skill_name": canonical.name},
+ )
+ continue
+
+ live = next((r for r in rows if not r.deleted and r.is_latest), None)
+ if live is None:
+ # All rows for this name are deleted or non-latest archives. Treat as
+ # tombstoned: the team explicitly removed this skill from their rotation.
+ tombstoned.append(canonical.name)
+ continue
+
+ # Only manage rows we seeded. A team can hand-author a signals-scout-* skill that
+ # shares a canonical name — no seeded_by tag — and we must never touch it.
+ if (live.metadata or {}).get("seeded_by") != "signals_scout_harness":
+ diverged.append(canonical.name)
+ continue
+
+ live_files = list(live.files.all())
+ live_hash = _compute_row_hash(live, live_files)
+ stored_hash = (live.metadata or {}).get("canonical_hash")
+
+ if stored_hash is None:
+ # One of our rows with no baseline hash — only reachable for a row seeded before
+ # hash tracking (e.g. an existing dogfood team). Can't tell if the team edited it,
+ # so leave it alone rather than risk clobbering; a re-seed adopts it cleanly.
+ diverged.append(canonical.name)
+ continue
- if created:
+ if live_hash == canonical_hash:
+ continue # already at the latest canonical content
+
+ if live_hash != stored_hash:
+ # Team edited their copy since our last write → leave it alone.
+ diverged.append(canonical.name)
+ continue
+
+ # Unedited since our last write but canonical changed → safe to overwrite.
+ try:
+ _update_skill_from_canonical(team, live, canonical, canonical_hash)
+ updated.append(canonical.name)
+ except IntegrityError:
+ logger.info(
+ "signals_scout: concurrent update lost the race; skipping",
+ extra={"team_id": team.id, "skill_name": canonical.name},
+ )
+
+ if prune:
+ # Reverse reconciliation: tombstone live `signals-scout-*` rows whose canonical was
+ # 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.
+ #
+ # 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
+ # hand-author its own `signals-scout-*` skill; pruning by name+prefix alone would
+ # silently soft-delete it every coordinator tick. We only reap our own seeded orphans.
+ #
+ # 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="signals_scout_harness",
+ ).exclude(name__in=canonical_names)
+ 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:
+ diverged.append(row.name)
+ continue
+ # Re-scope the soft-delete to seeded rows too, so a team-authored row sharing the
+ # name is never caught by the bulk update.
+ LLMSkill.objects.filter(
+ team=team, name=row.name, deleted=False, metadata__seeded_by="signals_scout_harness"
+ ).update(deleted=True, is_latest=False)
+ pruned.append(row.name)
+
+ if created or updated or pruned:
logger.info(
- "signals_scout: seeded canonical skills",
- extra={"team_id": team.id, "skill_names": created},
+ "signals_scout: synced canonical skills",
+ extra={
+ "team_id": team.id,
+ "created_skills": created,
+ "updated_skills": updated,
+ "diverged_skills": diverged,
+ "tombstoned_skills": tombstoned,
+ "pruned_skills": pruned,
+ },
)
- return SeedResult(created_skill_names=tuple(created))
+
+ return SyncResult(
+ created_skill_names=tuple(created),
+ updated_skill_names=tuple(updated),
+ diverged_skill_names=tuple(diverged),
+ tombstoned_skill_names=tuple(tombstoned),
+ pruned_skill_names=tuple(pruned),
+ )
+
+
+def seed_canonical_skills(team: Team) -> SyncResult:
+ """Backwards-compat alias for `sync_canonical_skills`.
+
+ Older callsites and tests reference this name; they get the richer sync semantics for free.
+ Prefer `sync_canonical_skills` in new code — the name reflects what it actually does.
+ """
+ return sync_canonical_skills(team)
diff --git a/products/signals/backend/scout_harness/limits.py b/products/signals/backend/scout_harness/limits.py
index df2089deda94..d15b1ba6701c 100644
--- a/products/signals/backend/scout_harness/limits.py
+++ b/products/signals/backend/scout_harness/limits.py
@@ -5,3 +5,14 @@ from __future__ import annotations
# at this point, the activity is killed and the run row is marked failed by the
# bridge. Tuning this is a config decision, not a per-run override knob.
DEFAULT_MAX_RUNTIME_S = 30 * 60
+
+# Slack added on top of `DEFAULT_MAX_RUNTIME_S` for the Temporal activity
+# `start_to_close_timeout`, so heartbeat-based failures get a chance to surface
+# before Temporal's own timeout fires.
+ACTIVITY_SLACK_S = 60
+
+# Hard ceiling on how long a single agent activity can actually be running. The
+# workflow always sets `start_to_close_timeout = DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S`,
+# providing a heartbeat window before Temporal's own timeout fires. The stale-RUNNING
+# self-heal in `runner.py` uses this as the staleness base.
+WORKFLOW_HARD_CEILING_S = DEFAULT_MAX_RUNTIME_S + ACTIVITY_SLACK_S
diff --git a/products/signals/backend/scout_harness/runner.py b/products/signals/backend/scout_harness/runner.py
index 13885ed84f2c..bf0d452df7e2 100644
--- a/products/signals/backend/scout_harness/runner.py
+++ b/products/signals/backend/scout_harness/runner.py
@@ -13,7 +13,7 @@ from posthog.models.utils import uuid7
from posthog.sync import database_sync_to_async
from products.signals.backend.models import SignalScoutConfig, SignalScoutRun
-from products.signals.backend.scout_harness.lazy_seed import seed_canonical_skills
+from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
from products.signals.backend.scout_harness.prompt import SignalScoutRunSummary, build_run_prompt
from products.signals.backend.scout_harness.skill_loader import LoadedSkill, load_skill_for_run
from products.signals.backend.temporal.agentic import (
@@ -86,13 +86,15 @@ async def arun_signals_scout(
) -> RunResult:
"""Async core. Safe to call from inside a running event loop (Temporal activity)."""
team = await database_sync_to_async(_get_team, thread_sensitive=False)(team_id)
- # Lazy-seed canonical signals-scout-* skills if the team has none yet, so the run
- # has something to load. Failures here are logged, not fatal.
+ # Sync canonical signals-scout-* skills before we resolve the skill the run asked for.
+ # Creates rows for newly-shipped specialists, updates harness-seeded rows the team
+ # hasn't edited, and leaves forked / tombstoned rows alone. Failures here should not
+ # crash the run — we log and continue with whatever skills the team already has.
try:
- await database_sync_to_async(seed_canonical_skills, thread_sensitive=False)(team)
+ await database_sync_to_async(sync_canonical_skills, thread_sensitive=False)(team)
except Exception:
logger.exception(
- "signals_scout: canonical skill seed failed; continuing with existing team skills",
+ "signals_scout: canonical skill sync failed; continuing with existing team skills",
extra={"team_id": team_id},
)
skill = await database_sync_to_async(load_skill_for_run, thread_sensitive=False)(
@@ -100,9 +102,18 @@ async def arun_signals_scout(
)
config = await database_sync_to_async(_resolve_config, thread_sensitive=False)(team, skill.name)
- # Skip-if-running guard. Best-effort — there is a race window between this check
- # and the row insert below (a second trigger could land in between), which we
- # accept until a claim/lease primitive lands.
+ # Hook for stale-run recovery — currently a no-op (see `_self_heal_stale_runs`). The
+ # partial unique index that made orphaned RUNNING rows block dispatch was dropped when
+ # `SignalScoutRun` became a `TaskRun` bridge (status now lives on `task_run.status`), so
+ # stale bridge rows no longer gate new runs at the DB level. Kept as a seam for the
+ # `task_run.status`-based recovery follow-up.
+ await database_sync_to_async(_self_heal_stale_runs, thread_sensitive=False)(team_id, skill_name)
+
+ # Skip-if-running guard, keyed on (team, skill_name). Different skills for the same
+ # team are allowed to run concurrently — the coordinator can dispatch several due
+ # scouts for one team in a single tick. Best-effort — there is a race window between
+ # this check and the bridge-row insert inside _spawn_and_run (a second trigger could
+ # land in between), which we accept until a claim/lease primitive lands.
if await database_sync_to_async(_has_running_run, thread_sensitive=False)(
team_id=team.parent_team_id or team.id, skill_name=skill.name
):
@@ -176,6 +187,26 @@ async def arun_signals_scout(
skill_name=skill.name,
skill_version=skill.version,
)
+ except BaseException as exc:
+ # Cancellation / worker-shutdown / system-exit: re-raise so Temporal sees the
+ # activity as failed. Post-collapse the bridge row's status flows from its
+ # linked TaskRun (managed by MultiTurnSession), so we don't update anything
+ # here directly. A TaskRun stranded in IN_PROGRESS (e.g. SIGKILL before
+ # MultiTurnSession finalizes) blocks new runs for this (team, skill) via
+ # `_has_running_run` until it transitions out — active recovery is a deferred
+ # follow-up (see `_self_heal_stale_runs`).
+ runtime_s = time.monotonic() - started
+ logger.warning(
+ "signals_scout: run cancelled mid-flight",
+ extra={
+ "team_id": team_id,
+ "run_id": str(run_id),
+ "skill_name": skill.name,
+ "exception_type": type(exc).__name__,
+ "runtime_s": runtime_s,
+ },
+ )
+ raise
async def _spawn_and_run(
@@ -287,7 +318,7 @@ def _resolve_config(team: Team, skill_name: str) -> SignalScoutConfig:
def _has_running_run(*, team_id: int, skill_name: str) -> bool:
# Locked on (canonical team, skill_name) — different skills for the same team are
- # allowed to fan out, which is the whole point of `runs_per_tick > 1`. Status flows
+ # allowed to fan out (the coordinator can dispatch several due scouts per tick). Status flows
# from the linked TaskRun now that SignalScoutRun is just a bridge; treat both QUEUED
# and IN_PROGRESS as active, since a TaskRun sits in QUEUED before transitioning and a
# second trigger landing in that window would otherwise slip past the guard. Not keyed
@@ -305,6 +336,27 @@ def _has_running_run(*, team_id: int, skill_name: str) -> bool:
)
+def _self_heal_stale_runs(team_id: int, skill_name: str) -> None:
+ """No-op pending the task_run-based partial unique index follow-up.
+
+ The original self-heal recovered RUNNING rows orphaned by a worker / sandbox
+ crash, because a DB-level partial unique index on
+ `(team_id, skill_name) WHERE status='running'` would otherwise block all
+ future dispatches for the same (team, skill). That index was dropped during
+ the 2026-05-21 restack — it referenced `SignalScoutRun.status`, which no
+ longer exists on the slim bridge row (status lives on `task_run.status`).
+
+ `_has_running_run` queries `task_run__status=IN_PROGRESS` so single-flighting
+ still works at the app layer; stale bridge rows no longer block dispatch,
+ they just take up space. The Tasks subsystem owns `task_run.status` and has
+ its own timeout / cleanup path, so cross-product writes from here would be
+ inappropriate. Restore real recovery logic once a `task_run.status`-based
+ DB constraint lands as a follow-up.
+ """
+ _ = team_id, skill_name
+ return
+
+
def _create_run_row(
*,
run_id: Any,
diff --git a/products/signals/backend/temporal/__init__.py b/products/signals/backend/temporal/__init__.py
index dddd45fc14bd..72fc490bcd2c 100644
--- a/products/signals/backend/temporal/__init__.py
+++ b/products/signals/backend/temporal/__init__.py
@@ -2,6 +2,7 @@ from products.signals.backend.temporal.agentic.report import run_agentic_report_
from products.signals.backend.temporal.agentic.scout_coordinator import (
SignalsScoutCoordinatorWorkflow,
fetch_enabled_signals_scout_runs_activity,
+ stamp_dispatched_signals_scout_runs_activity,
)
from products.signals.backend.temporal.agentic.scout_scheduler import (
RunSignalsScoutWorkflow,
@@ -85,6 +86,7 @@ ACTIVITIES = [
emit_backfill_signal_activity,
fetch_error_tracking_issues_activity,
fetch_enabled_signals_scout_runs_activity,
+ stamp_dispatched_signals_scout_runs_activity,
assign_and_emit_signal_activity,
delete_report_activity,
emit_eval_signal_activity,
diff --git a/products/signals/backend/temporal/agentic/scout_coordinator.py b/products/signals/backend/temporal/agentic/scout_coordinator.py
index 406dc856b712..d516c05c3e91 100644
--- a/products/signals/backend/temporal/agentic/scout_coordinator.py
+++ b/products/signals/backend/temporal/agentic/scout_coordinator.py
@@ -4,6 +4,7 @@ import json
from dataclasses import dataclass
from datetime import datetime, timedelta
+from django.db.models import Q
from django.utils import timezone
import structlog
@@ -12,13 +13,14 @@ from temporalio import activity, workflow
from temporalio.common import RetryPolicy, WorkflowIDReusePolicy
from temporalio.exceptions import WorkflowAlreadyStartedError
+from posthog.exceptions_capture import capture_exception
from posthog.models import Team
from posthog.sync import database_sync_to_async
from posthog.temporal.common.heartbeat import Heartbeater
from products.ai_observability.backend.models.skills import LLMSkill
from products.signals.backend.models import SignalScoutConfig
-from products.signals.backend.scout_harness.lazy_seed import seed_canonical_skills
+from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
from products.signals.backend.scout_harness.skill_loader import SIGNALS_SCOUT_SKILL_PREFIX
from products.signals.backend.temporal.agentic.scout_scheduler import RunSignalsScoutInput, RunSignalsScoutWorkflow
@@ -57,6 +59,13 @@ class FetchEnabledRunsOutput:
planned_runs: list[PlannedRun]
+@dataclass
+class StampDispatchedRunsInput:
+ """The (team, skill) runs whose child workflow was dispatched this tick."""
+
+ dispatched_runs: list[PlannedRun]
+
+
@dataclass
class CoordinatorWorkflowInput:
"""Placeholder input for forward-compat (e.g. future dry-run / debug flags)."""
@@ -87,6 +96,34 @@ async def fetch_enabled_signals_scout_runs_activity(
return FetchEnabledRunsOutput(planned_runs=planned)
+async def stamp_dispatched_signals_scout_runs_activity(
+ stamp_input: StampDispatchedRunsInput,
+) -> None:
+ """Advance `last_run_at` for the configs whose child workflow was dispatched this tick.
+
+ Split out of planning so the schedule only advances for scouts a child was actually
+ launched for: if fan-out fails (or the coordinator dies) before dispatch, the config
+ stays unstamped and re-dispatches next tick instead of being silently suppressed for a
+ full interval. The trade is a rare double-run if this stamp fails after children started
+ — far less harmful than a day of suppression, and bounded by the activity retry policy.
+ """
+ async with Heartbeater():
+ await database_sync_to_async(_stamp_dispatched_runs, thread_sensitive=False)(stamp_input.dispatched_runs)
+
+
+def _stamp_dispatched_runs(dispatched_runs: list[PlannedRun]) -> None:
+ """Sync bulk stamp. `.update()` bypasses save(), so this per-tick write never hits the
+ activity log."""
+ if not dispatched_runs:
+ return
+ now = timezone.now()
+ predicate = Q()
+ for run in dispatched_runs:
+ predicate |= Q(team_id=run.team_id, skill_name=run.skill_name)
+ SignalScoutConfig.all_teams.filter(predicate).update(last_run_at=now)
+
+
@dataclass
class _DueRun:
overdue_s: float
@@ -100,13 +137,17 @@ def _collect_planned_runs() -> list[PlannedRun]:
now = timezone.now()
due: list[_DueRun] = []
for team in _participating_teams():
- # Seed canonical scouts so a freshly-enrolled team has skills to register on.
- # Idempotent; a failure here doesn't abort the tick.
+ # Sync canonical scouts so a freshly-enrolled team has skills to register on.
+ # `prune=True`: the periodic tick is a deliberate reconciliation path, so it also
+ # tombstones rows whose canonical was removed from disk (the runner cold-start sync
+ # leaves prune off). The sync also propagates updates to canonical content for any
+ # harness-seeded row the team hasn't edited, so a merged SKILL.md change rolls out
+ # within one coordinator tick. Idempotent; a failure here doesn't abort the tick.
try:
- seed_canonical_skills(team)
+ sync_canonical_skills(team, prune=True)
except Exception:
logger.exception(
- "signals_scout coordinator: canonical skill seed failed for team; continuing",
+ "signals_scout coordinator: canonical skill sync failed for team; continuing",
team_id=team.id,
)
live_skills = _register_missing_configs(team)
@@ -133,10 +174,6 @@ def _collect_planned_runs() -> list[PlannedRun]:
)
due = due[:MAX_RUNS_PER_TICK]
- # Advance the schedule for everything we dispatch. `.update()` bypasses save(), so this
- # per-tick write never hits the activity log.
- SignalScoutConfig.all_teams.filter(pk__in=[d.config_pk for d in due]).update(last_run_at=now)
-
planned = [PlannedRun(team_id=d.team_id, skill_name=d.skill_name) for d in due]
# Stable order for predictable child-workflow ids within the tick.
planned.sort(key=lambda p: (p.team_id, p.skill_name))
@@ -162,9 +199,37 @@ def _participating_teams() -> list[Team]:
candidates = Team.objects.filter(id__in=team_ids)
canonical_ids = {team.parent_team_id or team.id for team in candidates}
canonical_teams = Team.objects.filter(id__in=canonical_ids).order_by("id")
- return [
- team for team in canonical_teams if posthoganalytics.feature_enabled(SIGNALS_SCOUT_DOGFOOD_FLAG, str(team.id))
- ]
+ return [team for team in canonical_teams if _team_passes_rollout_flag(team)]
+
+
+def _team_passes_rollout_flag(team: Team) -> bool:
+ """Whether the `signals-scout` dogfood flag is on for this team.
+
+ Passes organization + project group context — mirroring the inbox gate in
+ `backend/access.py` and the house pattern in `posthog/permissions.py` — so the flag is
+ targetable per project/org from the PostHog UI. A group-aggregated release condition only
+ matches when its group is supplied here, so without this the flag could only ever be a
+ blanket rollout %. Remote eval; fails closed (eval error → team dropped).
+ """
+ org_id = str(team.organization_id)
+ project_id = str(team.id)
+ try:
+ return bool(
+ posthoganalytics.feature_enabled(
+ SIGNALS_SCOUT_DOGFOOD_FLAG,
+ project_id,
+ groups={"organization": org_id, "project": project_id},
+ group_properties={
+ "organization": {"id": org_id},
+ "project": {"id": project_id},
+ },
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+ )
+ except Exception as error:
+ capture_exception(error)
+ return False
def _register_missing_configs(team: Team) -> set[str]:
@@ -201,12 +266,16 @@ class SignalsScoutCoordinatorWorkflow:
"""Coordinator: scans dogfood teams, fans out per-(team, skill) child runs for due scouts.
Dispatch is fire-and-forget: each child is started with `ParentClosePolicy.ABANDON`
- so it outlives this workflow, and the coordinator returns immediately after the
- last `start_child_workflow` call. This keeps the coordinator's lifetime to seconds
- regardless of how many children are dispatched, so the schedule's `SKIP` overlap
+ so it outlives this workflow, and the coordinator returns right after the last
+ `start_child_workflow` call plus one fast bookkeeping activity that advances
+ `last_run_at` for the children it dispatched. This keeps the coordinator's lifetime to
+ seconds regardless of how many children are dispatched, so the schedule's `SKIP` overlap
policy never collapses ticks at scale. Temporal's task queue + worker concurrency
handles the throttling — if workers are saturated, the children just queue.
+ The schedule advances only after dispatch (not during planning) so a fan-out failure
+ re-dispatches next tick rather than silently suppressing a scout for a full interval.
+
Idempotency: child workflow IDs are deterministic per `(team_id, skill_name, tick_id)`,
so a retried coordinator can't double-launch within a single tick. A separate
skip-if-running guard inside the runner protects against tick-over-tick collisions.
@@ -242,11 +311,25 @@ class SignalsScoutCoordinatorWorkflow:
tick_id = workflow.info().workflow_id
started = 0
skipped = 0
+ dispatched: list[PlannedRun] = []
for idx, planned in enumerate(planned_runs):
if await _start_child(planned=planned, tick_id=tick_id, idx=idx):
started += 1
else:
skipped += 1
+ # Both branches mean a child for this (team, skill, tick) now exists (started, or
+ # dedupe-skipped because a retry already started it) — so its schedule should
+ # advance. A hard `start_child` error raises out of `_start_child` before reaching
+ # here, leaving that config unstamped to re-dispatch next tick.
+ dispatched.append(planned)
+
+ # Stamp only after dispatch, so a fan-out failure can't suppress a scout for a day.
+ await workflow.execute_activity(
+ stamp_dispatched_signals_scout_runs_activity,
+ StampDispatchedRunsInput(dispatched_runs=dispatched),
+ start_to_close_timeout=timedelta(minutes=1),
+ retry_policy=RetryPolicy(maximum_attempts=5),
+ )
return CoordinatorWorkflowOutput(
planned_count=len(planned_runs),
started_count=started,
diff --git a/products/signals/backend/temporal/agentic/scout_scheduler.py b/products/signals/backend/temporal/agentic/scout_scheduler.py
index aad7efb56021..7548f4839533 100644
--- a/products/signals/backend/temporal/agentic/scout_scheduler.py
+++ b/products/signals/backend/temporal/agentic/scout_scheduler.py
@@ -9,15 +9,11 @@ from temporalio.common import RetryPolicy
from posthog.temporal.common.heartbeat import Heartbeater
-from products.signals.backend.scout_harness.limits import DEFAULT_MAX_RUNTIME_S
+from products.signals.backend.scout_harness.limits import WORKFLOW_HARD_CEILING_S
from products.signals.backend.scout_harness.runner import RunResult, arun_signals_scout
logger = structlog.get_logger(__name__)
-# Hard activity timeout = budget runtime + slack so heartbeat-based failures surface
-# before Temporal's own timeout fires.
-_ACTIVITY_SLACK_S = 60
-
@dataclass
class RunSignalsScoutInput:
@@ -91,7 +87,7 @@ class RunSignalsScoutWorkflow:
return await temporalio.workflow.execute_activity(
run_signals_scout_activity,
input,
- start_to_close_timeout=timedelta(seconds=DEFAULT_MAX_RUNTIME_S + _ACTIVITY_SLACK_S),
+ start_to_close_timeout=timedelta(seconds=WORKFLOW_HARD_CEILING_S),
heartbeat_timeout=timedelta(minutes=2),
# No retries: failures are persisted as `status='failed'` on the run row and
# we don't want a bad skill / prompt to spin retry loops. The next scheduled
diff --git a/products/signals/backend/test/test_management_sync_signals_scout_skills.py b/products/signals/backend/test/test_management_sync_signals_scout_skills.py
new file mode 100644
index 000000000000..09c1b3f29189
--- /dev/null
+++ b/products/signals/backend/test/test_management_sync_signals_scout_skills.py
@@ -0,0 +1,115 @@
+"""Tests for the `sync_signals_scout_skills` management command.
+
+The underlying `sync_canonical_skills` is covered exhaustively in
+`test_scout_harness_lazy_seed.py`; here we lock the command surface — argument
+plumbing, team selection, dry-run rollback, output formatting.
+"""
+
+from __future__ import annotations
+
+from io import StringIO
+
+import pytest
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+from products.ai_observability.backend.models.skills import LLMSkill
+from products.signals.backend.models import SignalScoutConfig
+from products.signals.backend.scout_harness.lazy_seed import CanonicalSkill
+
+
+def _fake_canonical(name: str, body: str = "# canonical body\n") -> CanonicalSkill:
+ from pathlib import Path
+
+ return CanonicalSkill(
+ name=name,
+ description="test canonical",
+ body=body,
+ allowed_tools=(),
+ files=(),
+ source_path=Path("/tmp/fake"),
+ )
+
+
+class TestSyncSignalsScoutSkillsCommand(BaseTest):
+ def _patch_canonicals(self, canonicals):
+ return patch(
+ "products.signals.backend.scout_harness.lazy_seed.discover_canonical_skills",
+ return_value=canonicals,
+ )
+
+ def test_requires_team_id_or_all_enabled(self) -> None:
+ with pytest.raises(CommandError, match="--team-id"):
+ call_command("sync_signals_scout_skills")
+
+ def test_team_id_and_all_enabled_are_mutually_exclusive(self) -> None:
+ with pytest.raises(CommandError, match="mutually exclusive"):
+ call_command("sync_signals_scout_skills", "--team-id", str(self.team.id), "--all-enabled")
+
+ def test_unknown_team_id_raises(self) -> None:
+ with pytest.raises(CommandError, match="not found"):
+ call_command("sync_signals_scout_skills", "--team-id", "999999999")
+
+ def test_team_id_seeds_canonicals(self) -> None:
+ canonical = _fake_canonical("signals-scout-alpha")
+ out = StringIO()
+ with self._patch_canonicals((canonical,)):
+ call_command("sync_signals_scout_skills", "--team-id", str(self.team.id), stdout=out)
+
+ assert LLMSkill.objects.filter(team=self.team, name="signals-scout-alpha", is_latest=True).exists()
+ output = out.getvalue()
+ assert "+created" in output
+ assert "signals-scout-alpha" in output
+
+ def test_all_enabled_iterates_only_enabled_configs(self) -> None:
+ # Two teams; only one has enabled config.
+ from posthog.models import Team
+
+ other_team = Team.objects.create(organization=self.organization, name="OtherTeam")
+ SignalScoutConfig.objects.create(team=self.team, enabled=True)
+ SignalScoutConfig.objects.create(team=other_team, enabled=False)
+
+ canonical = _fake_canonical("signals-scout-alpha")
+ out = StringIO()
+ with self._patch_canonicals((canonical,)):
+ call_command("sync_signals_scout_skills", "--all-enabled", stdout=out)
+
+ # Enabled team got the canonical.
+ assert LLMSkill.objects.filter(team=self.team, name="signals-scout-alpha").exists()
+ # Disabled team did not.
+ assert not LLMSkill.objects.filter(team=other_team, name="signals-scout-alpha").exists()
+ assert "Synced 1 team" in out.getvalue()
+
+ def test_dry_run_does_not_persist(self) -> None:
+ canonical = _fake_canonical("signals-scout-alpha")
+ out = StringIO()
+ with self._patch_canonicals((canonical,)):
+ call_command(
+ "sync_signals_scout_skills",
+ "--team-id",
+ str(self.team.id),
+ "--dry-run",
+ stdout=out,
+ )
+
+ # Nothing persisted.
+ assert not LLMSkill.objects.filter(team=self.team, name="signals-scout-alpha").exists()
+ output = out.getvalue()
+ assert "[dry-run]" in output
+
+ def test_no_op_team_renders_no_changes_line(self) -> None:
+ # Pre-seed the team with canonical content + matching hash, then re-run sync. Should
+ # be a clean no-op without any +/~/= line items.
+ canonical = _fake_canonical("signals-scout-alpha")
+ with self._patch_canonicals((canonical,)):
+ # First call writes canonical + hash.
+ call_command("sync_signals_scout_skills", "--team-id", str(self.team.id), stdout=StringIO())
+ # Second call should be a clean no-op.
+ out = StringIO()
+ call_command("sync_signals_scout_skills", "--team-id", str(self.team.id), stdout=out)
+
+ output = out.getvalue()
+ assert "no changes" in output
diff --git a/products/signals/backend/test/test_scout_coordinator.py b/products/signals/backend/test/test_scout_coordinator.py
index a6cceb2b8bf9..eb390e7b735f 100644
--- a/products/signals/backend/test/test_scout_coordinator.py
+++ b/products/signals/backend/test/test_scout_coordinator.py
@@ -20,14 +20,16 @@ from posthog.sync import database_sync_to_async
from products.ai_observability.backend.models.skills import LLMSkill
from products.signals.backend.models import SignalScoutConfig
-from products.signals.backend.scout_harness.lazy_seed import seed_canonical_skills
+from products.signals.backend.scout_harness.lazy_seed import sync_canonical_skills
from products.signals.backend.temporal.agentic.scout_coordinator import (
CoordinatorWorkflowInput,
CoordinatorWorkflowOutput,
FetchEnabledRunsInput,
PlannedRun,
SignalsScoutCoordinatorWorkflow,
+ StampDispatchedRunsInput,
fetch_enabled_signals_scout_runs_activity,
+ stamp_dispatched_signals_scout_runs_activity,
)
_FLAG_PATH = "products.signals.backend.temporal.agentic.scout_coordinator.posthoganalytics.feature_enabled"
@@ -101,16 +103,16 @@ def _flag_on(request):
@pytest.fixture(autouse=True)
-def _stub_canonical_seed(request):
- """Stub `seed_canonical_skills` to a no-op so tests assert on hand-authored skills only.
+def _stub_canonical_sync(request):
+ """Stub `sync_canonical_skills` to a no-op so tests assert on hand-authored skills only.
- Tests that exercise the real sync opt out via `@pytest.mark.real_canonical_seed`.
+ Tests that exercise the real sync opt out via `@pytest.mark.real_canonical_sync`.
"""
- if request.node.get_closest_marker("real_canonical_seed"):
+ if request.node.get_closest_marker("real_canonical_sync"):
yield
return
with patch(
- "products.signals.backend.temporal.agentic.scout_coordinator.seed_canonical_skills",
+ "products.signals.backend.temporal.agentic.scout_coordinator.sync_canonical_skills",
return_value=None,
):
yield
@@ -147,6 +149,41 @@ async def test_disabled_config_is_skipped(ateam):
assert await _run_activity() == []
+async def test_rollout_flag_evaluated_with_project_group(ateam):
+ # The flag is group-aggregated on the project, so the call must supply project (+org) group
+ # context or no release condition could ever match. Locks that contract in.
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")
+
+ with patch(_FLAG_PATH, return_value=True) as mock_flag:
+ await _run_activity()
+
+ org_id = str(ateam.organization_id)
+ project_id = str(ateam.id)
+ mock_flag.assert_called_once_with(
+ "signals-scout",
+ project_id,
+ groups={"organization": org_id, "project": project_id},
+ group_properties={"organization": {"id": org_id}, "project": {"id": project_id}},
+ only_evaluate_locally=False,
+ send_feature_flag_events=False,
+ )
+
+
+async def test_rollout_flag_eval_error_fails_closed(ateam):
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-errors")
+
+ with patch(_FLAG_PATH, side_effect=RuntimeError("flag service down")):
+ planned = await _run_activity()
+
+ assert planned == []
+
+
# ── Auto-register: author a skill, get a scout ──────────────────────────────────
@@ -206,17 +243,39 @@ async def test_config_within_interval_is_not_due(ateam):
@pytest.mark.asyncio
@pytest.mark.django_db
-async def test_overdue_config_runs_and_stamps_last_run_at(ateam):
+async def test_overdue_config_is_planned_without_stamping(ateam):
+ # Planning only selects due runs — it must NOT advance last_run_at. The schedule is
+ # stamped after dispatch (see test_stamp_activity_advances_dispatched_configs) so a
+ # fan-out failure can't suppress a scout for a full interval.
await database_sync_to_async(_create_skill)(ateam, "signals-scout-foo")
old = timezone.now() - timedelta(minutes=2000)
config = await database_sync_to_async(_create_config)(
ateam, "signals-scout-foo", enabled=True, run_interval_minutes=1440, last_run_at=old
)
- before = timezone.now()
planned = await _run_activity()
assert [p.skill_name for p in planned] == ["signals-scout-foo"]
+ refreshed = await database_sync_to_async(SignalScoutConfig.all_teams.get)(pk=config.pk)
+ assert refreshed.last_run_at == old
+
+
+async def test_stamp_activity_advances_dispatched_configs(ateam):
+ await database_sync_to_async(_create_skill)(ateam, "signals-scout-foo")
+ old = timezone.now() - timedelta(minutes=2000)
+ config = await database_sync_to_async(_create_config)(
+ ateam, "signals-scout-foo", enabled=True, run_interval_minutes=1440, last_run_at=old
+ )
+
+ before = timezone.now()
+ env = ActivityEnvironment()
+ await env.run(
+ stamp_dispatched_signals_scout_runs_activity,
+ StampDispatchedRunsInput(dispatched_runs=[PlannedRun(team_id=ateam.id, skill_name="signals-scout-foo")]),
+ )
+
refreshed = await database_sync_to_async(SignalScoutConfig.all_teams.get)(pk=config.pk)
assert refreshed.last_run_at is not None and refreshed.last_run_at >= before
@@ -290,7 +349,7 @@ async def test_seed_failure_does_not_abort_tick(ateam):
await database_sync_to_async(_create_skill)(ateam, "signals-scout-existing")
with patch(
- "products.signals.backend.temporal.agentic.scout_coordinator.seed_canonical_skills",
+ "products.signals.backend.temporal.agentic.scout_coordinator.sync_canonical_skills",
side_effect=RuntimeError("simulated seed failure"),
):
planned = await _run_activity()
@@ -300,11 +359,11 @@ async def test_seed_failure_does_not_abort_tick(ateam):
@pytest.mark.asyncio
@pytest.mark.django_db
[email protected]_canonical_seed
[email protected]_canonical_sync
async def test_enrolled_team_registers_and_runs_canonical_fleet(ateam):
# Enrolling a team seeds the canonical fleet; the coordinator then auto-registers a
# config per seeded skill and dispatches the due ones.
- await database_sync_to_async(seed_canonical_skills)(ateam)
+ await database_sync_to_async(sync_canonical_skills)(ateam)
seeded = await database_sync_to_async(
lambda: set(
LLMSkill.objects.filter(team=ateam, name__startswith="signals-scout-").values_list("name", flat=True)
@@ -397,3 +456,40 @@ async def test_workflow_dispatches_children_fire_and_forget():
(1, "signals-scout-b"),
(2, "signals-scout-c"),
]
+
+
+async def test_hard_dispatch_error_does_not_stamp():
+ # A non-dedupe start_child error must abort before the stamp activity, so the affected
+ # configs stay unstamped and re-dispatch next tick instead of being suppressed.
+ planned = [PlannedRun(team_id=1, skill_name="signals-scout-a")]
+ fake_fetch_result = type("R", (), {"planned_runs": planned})()
+ execute_activity_calls: list[Any] = []
+
+ async def fake_execute_activity(activity, *args, **kwargs):
+ execute_activity_calls.append(activity)
+ return fake_fetch_result
+
+ async def fake_start_child(_workflow_run, run_input, **kwargs):
+ raise RuntimeError("temporal unavailable")
+
+ coordinator = SignalsScoutCoordinatorWorkflow()
+ with (
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.execute_activity",
+ side_effect=fake_execute_activity,
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.info",
+ return_value=type("Info", (), {"workflow_id": "tick-1"})(),
+ ),
+ patch(
+ "products.signals.backend.temporal.agentic.scout_coordinator.workflow.start_child_workflow",
+ side_effect=fake_start_child,
+ ),
+ ):
+ with pytest.raises(RuntimeError, match="temporal unavailable"):
+ await coordinator.run(CoordinatorWorkflowInput())
+
+ # Only the planning activity ran — the stamp activity never executed.
+ assert execute_activity_calls == [fetch_enabled_signals_scout_runs_activity]
diff --git a/products/signals/backend/test/test_scout_harness.py b/products/signals/backend/test/test_scout_harness.py
index f559f07c38b6..ae7eea23583f 100644
--- a/products/signals/backend/test/test_scout_harness.py
+++ b/products/signals/backend/test/test_scout_harness.py
@@ -1,6 +1,7 @@
from __future__ import annotations
import random
+import asyncio
from datetime import UTC, datetime
import pytest
@@ -315,6 +316,63 @@ async def test_skip_if_running_prevents_concurrent_runs(ateam, aerrors_skill):
assert count == 1
+async def test_skip_if_running_lock_keys_on_team_and_skill_not_just_team(ateam, aerrors_skill):
+ """Different skills for the same team must be allowed to run concurrently — the
+ coordinator can dispatch several due scouts for one team in a single tick. The
+ skip-if-running guard locks on `(team, skill_name)` rather than `(team, config_id)`
+ so this works."""
+ config = await database_sync_to_async(SignalScoutConfig.objects.create)(team=ateam)
+ # A different skill for the same team is in flight — should NOT block. Run status lives
+ # on the linked TaskRun now, so stand up a real IN_PROGRESS TaskRun + bridge row.
+ other_task_run = await database_sync_to_async(_make_task_run)(ateam)
+ await database_sync_to_async(TaskRun.objects.filter(id=other_task_run.id).update)(status=TaskRun.Status.IN_PROGRESS)
+ await database_sync_to_async(SignalScoutRun.objects.create)(
+ task_run=other_task_run,
+ team=ateam,
+ scout_config=config,
+ skill_name="signals-scout-other",
+ skill_version=1,
+ )
+
+ spawn_calls: list[dict] = []
+
+ async def fake_spawn(**kwargs):
+ spawn_calls.append(kwargs)
+ return "ok"
+
+ with patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn):
+ result = await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
+
+ # Spawn went through — the OTHER skill's RUNNING row didn't gate ours.
+ assert len(spawn_calls) == 1
+ assert result.run_id is not None
+ assert result.skip_reason is None
+
+
+async def test_cancelled_run_re_raises(ateam, aerrors_skill):
+ """asyncio.CancelledError is BaseException, not Exception — the runner must let it
+ propagate so Temporal marks the activity failed, rather than swallowing it. Run status
+ now lives on the linked TaskRun (managed by MultiTurnSession); the bridge row is created
+ inside `_spawn_and_run`, so a cancellation that escapes before the session starts leaves
+ no orphaned bridge row.
+ """
+
+ async def fake_spawn(**_kwargs):
+ raise asyncio.CancelledError("worker is shutting down")
+
+ with patch("products.signals.backend.scout_harness.runner._spawn_and_run", side_effect=fake_spawn):
+ with pytest.raises(asyncio.CancelledError):
+ await arun_signals_scout(team_id=ateam.id, skill_name="signals-scout-errors")
+
+ # No bridge row orphaned — it's created inside the patched-out `_spawn_and_run`.
+ count = await database_sync_to_async(SignalScoutRun.objects.filter(team=ateam).count)()
+ assert count == 0
+
+
@pytest.mark.asyncio
@pytest.mark.django_db
async def test_activity_returns_completed_outcome(ateam):
diff --git a/products/signals/backend/test/test_scout_harness_api.py b/products/signals/backend/test/test_scout_harness_api.py
index 8e024828a932..5ac76d54e612 100644
--- a/products/signals/backend/test/test_scout_harness_api.py
+++ b/products/signals/backend/test/test_scout_harness_api.py
@@ -370,9 +370,6 @@ class TestAgentHarnessProjectProfileAPI(APIBaseTest):
"""
def _list_url(self) -> str:
- # The viewset exposes the singleton via an explicit `@action(url_path="current")`
- # (not `list()`), so the route is /project_profile/current/. Generated TS clients
- # call /current/; tests must match or the requests 404 and never exercise the view.
return f"/api/projects/{self.team.id}/signals/scout/project_profile/current/"
def _seed_profile(self, *, team: Team | None = None) -> str:
diff --git a/products/signals/backend/test/test_scout_harness_lazy_seed.py b/products/signals/backend/test/test_scout_harness_lazy_seed.py
index c338f7205b7a..8cad6206dec5 100644
--- a/products/signals/backend/test/test_scout_harness_lazy_seed.py
+++ b/products/signals/backend/test/test_scout_harness_lazy_seed.py
@@ -7,12 +7,17 @@ import pytest
from posthog.test.base import BaseTest
from unittest.mock import patch
-from products.ai_observability.backend.models.skills import LLMSkill
+from products.ai_observability.backend.models.skills import LLMSkill, LLMSkillFile
from products.signals.backend.scout_harness.lazy_seed import (
CanonicalSkill,
+ CanonicalSkillFile,
CanonicalSkillParseError,
+ SyncResult,
+ _compute_canonical_hash,
+ _compute_row_hash,
discover_canonical_skills,
seed_canonical_skills,
+ sync_canonical_skills,
)
from products.signals.backend.scout_harness.skill_loader import load_skill_for_run
@@ -36,6 +41,25 @@ def _write_canonical_skill(
return skill_dir
+def _make_canonical(
+ name: str,
+ *,
+ description: str = "test skill",
+ body: str = "# Body\n",
+ allowed_tools: tuple[str, ...] = (),
+ files: tuple[CanonicalSkillFile, ...] = (),
+) -> CanonicalSkill:
+ """Build a CanonicalSkill for a unit test without going through disk + frontmatter."""
+ return CanonicalSkill(
+ name=name,
+ description=description,
+ body=body,
+ allowed_tools=allowed_tools,
+ files=files,
+ source_path=Path("/tmp/fake"),
+ )
+
+
class TestDiscoverCanonicalSkills:
def test_returns_empty_for_missing_dir(self, tmp_path: Path) -> None:
assert discover_canonical_skills(tmp_path / "does-not-exist") == ()
@@ -193,11 +217,41 @@ class TestDiscoverCanonicalSkills:
with pytest.raises(CanonicalSkillParseError):
discover_canonical_skills(tmp_path)
+ def test_duplicate_frontmatter_name_raises(self, tmp_path: Path) -> None:
+ # Two directories declaring the same `name` would make the sync flap the team's row
+ # between both definitions every coordinator tick — reject it at discovery.
+ for dir_name in ("signals-scout-dup-a", "signals-scout-dup-b"):
+ _write_canonical_skill(
+ tmp_path,
+ dir_name=dir_name,
+ frontmatter="""
+ ---
+ name: signals-scout-dup
+ description: dup skill
+ ---
+ """,
+ body=f"# {dir_name}\n",
+ )
+ with pytest.raises(CanonicalSkillParseError, match="Duplicate canonical skill name"):
+ discover_canonical_skills(tmp_path)
+
def test_in_repo_canonical_set_parses_cleanly(self) -> None:
# Exercises the production manifest at `products/signals/skills/` — growing the
# canonical set is a deliberate edit, so this serves as the lock.
skills = discover_canonical_skills()
- assert any(s.name == "signals-scout-general" for s in skills)
+ names = {s.name for s in skills}
+ # A subset lock on the canonical fleet: general (cross-product) + 4 focused
+ # specialists. Each scout is self-contained (no deps between skills) and runs on
+ # its own schedule. Adding a new specialist is a deliberate edit — extend this set
+ # when shipping.
+ expected = {
+ "signals-scout-general",
+ "signals-scout-llm-analytics",
+ "signals-scout-logs",
+ "signals-scout-error-tracking",
+ "signals-scout-revenue-analytics",
+ }
+ assert expected.issubset(names), f"missing canonical skills: {expected - names}"
def test_oversized_body_raises(self, tmp_path: Path) -> None:
# Body byte limit mirrors the REST API contract (MAX_SKILL_BODY_BYTES = 1 MB).
@@ -276,49 +330,409 @@ class TestDiscoverCanonicalSkills:
discover_canonical_skills(tmp_path)
-class TestSeedCanonicalSkills(BaseTest):
- def test_seeds_canonicals_when_team_has_no_signals_scout_skills(self) -> None:
- result = seed_canonical_skills(self.team)
- assert "signals-scout-general" in result.created_skill_names
- seeded = LLMSkill.objects.get(team=self.team, name="signals-scout-general")
- assert seeded.is_latest is True
- assert seeded.body # body copied from SKILL.md
- assert seeded.metadata["seeded_by"] == "signals_scout_harness"
+class TestComputeCanonicalHash:
+ def test_same_input_yields_same_hash(self) -> None:
+ a = _make_canonical("signals-scout-foo", body="hello", allowed_tools=("a", "b"))
+ b = _make_canonical("signals-scout-foo", body="hello", allowed_tools=("a", "b"))
+ assert _compute_canonical_hash(a) == _compute_canonical_hash(b)
+
+ def test_body_change_changes_hash(self) -> None:
+ a = _make_canonical("signals-scout-foo", body="v1")
+ b = _make_canonical("signals-scout-foo", body="v2")
+ assert _compute_canonical_hash(a) != _compute_canonical_hash(b)
+
+ def test_description_change_changes_hash(self) -> None:
+ a = _make_canonical("signals-scout-foo", description="alpha", body="x")
+ b = _make_canonical("signals-scout-foo", description="beta", body="x")
+ assert _compute_canonical_hash(a) != _compute_canonical_hash(b)
+
+ def test_allowed_tools_reorder_does_not_change_hash(self) -> None:
+ # Sorted internally so frontmatter-listing-order changes don't churn the hash.
+ a = _make_canonical("signals-scout-foo", allowed_tools=("a", "b"))
+ b = _make_canonical("signals-scout-foo", allowed_tools=("b", "a"))
+ assert _compute_canonical_hash(a) == _compute_canonical_hash(b)
+
+ def test_bundle_change_changes_hash(self) -> None:
+ # References-only edits are the easy thing to forget; this is the lock.
+ f1 = (CanonicalSkillFile(path="references/x.md", content="v1"),)
+ f2 = (CanonicalSkillFile(path="references/x.md", content="v2"),)
+ a = _make_canonical("signals-scout-foo", files=f1)
+ b = _make_canonical("signals-scout-foo", files=f2)
+ assert _compute_canonical_hash(a) != _compute_canonical_hash(b)
+
+ def test_canonical_and_row_hashes_agree_when_content_matches(self) -> None:
+ """When a row's content matches the canonical exactly, the two hashing helpers
+ produce the same digest. This is the round-trip the sync function depends on."""
+ canonical = _make_canonical(
+ "signals-scout-foo",
+ description="d",
+ body="b",
+ allowed_tools=("x", "y"),
+ files=(CanonicalSkillFile(path="references/r.md", content="r"),),
+ )
+ # Build a fake LLMSkill / LLMSkillFile pair that mirrors the canonical exactly. We
+ # avoid hitting the DB for this — _compute_row_hash only reads attributes.
+ skill = LLMSkill(
+ description=canonical.description,
+ body=canonical.body,
+ allowed_tools=list(canonical.allowed_tools),
+ )
+ files = [LLMSkillFile(path=f.path, content=f.content, content_type=f.content_type) for f in canonical.files]
+ assert _compute_canonical_hash(canonical) == _compute_row_hash(skill, files)
+
+
+class TestSyncCanonicalSkills(BaseTest):
+ """End-to-end behavior of the canonical-sync function on a real DB.
+
+ Each test patches `discover_canonical_skills` so we control what "canonical" means
+ rather than depending on the in-repo fleet content. The in-repo behavior is locked
+ by `test_in_repo_canonical_set_parses_cleanly` above.
+ """
+
+ def _patch_canonicals(self, canonicals: tuple[CanonicalSkill, ...]):
+ return patch(
+ "products.signals.backend.scout_harness.lazy_seed.discover_canonical_skills",
+ return_value=canonicals,
+ )
- def test_no_op_when_team_already_has_signals_scout_skill(self) -> None:
+ def test_creates_rows_for_brand_new_team(self) -> None:
+ canonical = _make_canonical("signals-scout-alpha", body="initial")
+ with self._patch_canonicals((canonical,)):
+ result = sync_canonical_skills(self.team)
+
+ assert result.created_skill_names == ("signals-scout-alpha",)
+ assert result.updated_skill_names == ()
+ row = LLMSkill.objects.get(team=self.team, name="signals-scout-alpha", is_latest=True, deleted=False)
+ assert row.body == "initial"
+ assert row.metadata["seeded_by"] == "signals_scout_harness"
+ # Hash is now stamped at create time so future syncs can compare.
+ assert row.metadata["canonical_hash"] == _compute_canonical_hash(canonical)
+
+ 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,)):
+ sync_canonical_skills(self.team)
+ # Second call against unchanged canonical produces no further work.
+ result = sync_canonical_skills(self.team)
+
+ assert result.created_skill_names == ()
+ assert result.updated_skill_names == ()
+ assert LLMSkill.objects.filter(team=self.team, name="signals-scout-alpha", is_latest=True).count() == 1
+
+ def test_updates_when_canonical_changes_and_team_has_not_edited(self) -> None:
+ # Initial sync writes v1 with the original content.
+ v1 = _make_canonical("signals-scout-alpha", body="v1 body")
+ with self._patch_canonicals((v1,)):
+ sync_canonical_skills(self.team)
+
+ # We ship a SKILL.md change. Same name, different body. Team hasn't touched theirs.
+ v2 = _make_canonical("signals-scout-alpha", body="v2 body — improved scout calibration")
+ with self._patch_canonicals((v2,)):
+ result = sync_canonical_skills(self.team)
+
+ assert result.updated_skill_names == ("signals-scout-alpha",)
+ # Old row demoted, new row at version=2 with the new content.
+ rows = LLMSkill.objects.filter(team=self.team, name="signals-scout-alpha").order_by("version")
+ assert [r.version for r in rows] == [1, 2]
+ latest = rows.get(version=2)
+ assert latest.is_latest is True
+ assert latest.body == "v2 body — improved scout calibration"
+ assert latest.metadata["canonical_hash"] == _compute_canonical_hash(v2)
+ # Old row is preserved as version history but no longer latest.
+ old = rows.get(version=1)
+ assert old.is_latest is False
+ assert old.body == "v1 body"
+
+ def test_leaves_diverged_team_edits_alone(self) -> None:
+ v1 = _make_canonical("signals-scout-alpha", body="v1 body")
+ with self._patch_canonicals((v1,)):
+ sync_canonical_skills(self.team)
+
+ # Simulate a user edit: bump the row's body without touching the canonical_hash
+ # in metadata. Real PHS edits would do the version-bump dance; for the test we
+ # mutate in place since the hash mismatch is what matters.
+ row = LLMSkill.objects.get(team=self.team, name="signals-scout-alpha", is_latest=True)
+ row.body = "team edited this"
+ row.save()
+
+ # Now we ship a v2 canonical. Team's content drifted from stored hash → diverged.
+ v2 = _make_canonical("signals-scout-alpha", body="v2 body")
+ with self._patch_canonicals((v2,)):
+ result = sync_canonical_skills(self.team)
+
+ assert result.diverged_skill_names == ("signals-scout-alpha",)
+ assert result.updated_skill_names == ()
+ # Team's edit survived.
+ latest = LLMSkill.objects.get(team=self.team, name="signals-scout-alpha", is_latest=True)
+ assert latest.body == "team edited this"
+
+ def test_leaves_hand_authored_row_sharing_a_canonical_name_alone(self) -> None:
+ # A team hand-authors a row whose name collides with a canonical, with no seeded_by
+ # tag. We must never overwrite it: first sync reports it diverged, and a later
+ # canonical change still leaves the content intact.
LLMSkill.objects.create(
team=self.team,
- name="signals-scout-existing",
- description="team-edited copy",
- body="team body",
+ name="signals-scout-alpha",
+ description="team's own",
+ body="hand authored",
+ is_latest=True,
)
- result = seed_canonical_skills(self.team)
- assert result.created_skill_names == ()
- assert result.skipped_reason and "already has" in result.skipped_reason
- existing = LLMSkill.objects.get(team=self.team, name="signals-scout-existing")
- assert existing.body == "team body"
- def test_no_op_preserves_archived_team_copies(self) -> None:
+ v1 = _make_canonical("signals-scout-alpha", body="canonical v1")
+ with self._patch_canonicals((v1,)):
+ first = sync_canonical_skills(self.team)
+ assert first.diverged_skill_names == ("signals-scout-alpha",)
+
+ v2 = _make_canonical("signals-scout-alpha", body="canonical v2")
+ with self._patch_canonicals((v2,)):
+ second = sync_canonical_skills(self.team)
+ assert second.diverged_skill_names == ("signals-scout-alpha",)
+ assert second.updated_skill_names == ()
+
+ latest = LLMSkill.objects.get(team=self.team, name="signals-scout-alpha", is_latest=True)
+ assert latest.body == "hand authored"
+
+ def test_skips_tombstoned_rows(self) -> None:
+ # Team explicitly deleted the skill — no live row, just a soft-deleted archive.
+ # The sync must respect that and not re-create the canonical content.
LLMSkill.objects.create(
team=self.team,
- name="signals-scout-archived",
- description="team archived this",
+ name="signals-scout-alpha",
+ description="archived",
body="team body",
deleted=True,
is_latest=False,
)
- # Re-seeding archived rows would resurrect content the team deliberately removed.
- result = seed_canonical_skills(self.team)
+ canonical = _make_canonical("signals-scout-alpha", body="latest canonical")
+ with self._patch_canonicals((canonical,)):
+ result = sync_canonical_skills(self.team)
+
+ assert result.tombstoned_skill_names == ("signals-scout-alpha",)
+ assert result.created_skill_names == ()
+ assert not LLMSkill.objects.filter(
+ team=self.team, name="signals-scout-alpha", deleted=False, is_latest=True
+ ).exists()
+
+ def test_creates_new_specialist_for_already_seeded_team(self) -> None:
+ # A team got seeded before we shipped a new specialist. Per-canonical iteration
+ # means the new one shows up; the existing ones are no-ops.
+ existing = _make_canonical("signals-scout-alpha", body="alpha body")
+ with self._patch_canonicals((existing,)):
+ sync_canonical_skills(self.team)
+
+ new_specialist = _make_canonical("signals-scout-beta", body="beta body")
+ with self._patch_canonicals((existing, new_specialist)):
+ result = sync_canonical_skills(self.team)
+
+ assert result.created_skill_names == ("signals-scout-beta",)
+ assert result.updated_skill_names == ()
+ assert LLMSkill.objects.filter(team=self.team, name="signals-scout-beta", is_latest=True).exists()
+
+ def test_prunes_rows_whose_canonical_was_removed_from_disk(self) -> None:
+ # Two specialists seeded, then one is removed from the canonical fleet on disk. The
+ # reverse-reconciliation pass must tombstone the orphaned live row so the coordinator
+ # stops dispatching a scout that's no longer part of the fleet.
+ alpha = _make_canonical("signals-scout-alpha", body="alpha body")
+ beta = _make_canonical("signals-scout-beta", body="beta body")
+ with self._patch_canonicals((alpha, beta)):
+ sync_canonical_skills(self.team)
+ assert LLMSkill.objects.filter(
+ team=self.team, name="signals-scout-beta", is_latest=True, deleted=False
+ ).exists()
+
+ # beta is deleted from disk — only alpha remains canonical.
+ with self._patch_canonicals((alpha,)):
+ result = sync_canonical_skills(self.team, prune=True)
+
+ assert result.pruned_skill_names == ("signals-scout-beta",)
+ assert result.updated_skill_names == ()
+ # beta's live row is soft-deleted; alpha is untouched and still live.
+ beta_row = LLMSkill.objects.get(team=self.team, name="signals-scout-beta")
+ assert beta_row.deleted is True
+ assert beta_row.is_latest is False
+ assert LLMSkill.objects.filter(
+ team=self.team, name="signals-scout-alpha", is_latest=True, deleted=False
+ ).exists()
+
+ def test_prune_leaves_edited_fork_alone(self) -> None:
+ # A team edits a scout we seeded (a "fork"), then we retire that canonical from disk.
+ # Prune must NOT tombstone the fork — deleting a scout the team customized and chose to
+ # keep would be a nasty surprise. Mirrors the fork-protection the update path applies.
+ alpha = _make_canonical("signals-scout-alpha", body="alpha body")
+ beta = _make_canonical("signals-scout-beta", body="beta body")
+ with self._patch_canonicals((alpha, beta)):
+ sync_canonical_skills(self.team)
+
+ # Team edits their beta copy — body diverges from the stored canonical_hash, while
+ # seeded_by and the old hash carry forward (what a real PHS edit produces).
+ beta_row = LLMSkill.objects.get(team=self.team, name="signals-scout-beta", is_latest=True)
+ beta_row.body = "team's customized beta body"
+ beta_row.save(update_fields=["body"])
+
+ # beta removed from disk; prune runs.
+ with self._patch_canonicals((alpha,)):
+ result = sync_canonical_skills(self.team, prune=True)
+
+ assert "signals-scout-beta" not in result.pruned_skill_names
+ assert "signals-scout-beta" in result.diverged_skill_names
+ beta_row.refresh_from_db()
+ assert beta_row.deleted is False
+ assert beta_row.is_latest is True
+
+ def test_prune_leaves_team_authored_scout_skills_alone(self) -> None:
+ # A team hand-authors its own `signals-scout-*` skill — no `seeded_by` tag, and not in
+ # the canonical fleet. Prune must NOT tombstone it: we only reap rows we seeded, never a
+ # user-defined scout that happens to share the reserved prefix.
+ alpha = _make_canonical("signals-scout-alpha", body="alpha body")
+ with self._patch_canonicals((alpha,)):
+ sync_canonical_skills(self.team)
+ team_authored = LLMSkill.objects.create(
+ team=self.team,
+ name="signals-scout-custom",
+ description="team's own scout",
+ body="custom body",
+ is_latest=True,
+ )
+
+ with self._patch_canonicals((alpha,)):
+ result = sync_canonical_skills(self.team, prune=True)
+
+ assert "signals-scout-custom" not in result.pruned_skill_names
+ team_authored.refresh_from_db()
+ assert team_authored.deleted is False
+ assert team_authored.is_latest is True
+
+ def test_does_not_prune_when_disk_read_is_empty(self) -> None:
+ # Defensive: a broken / empty canonical dir must NOT tombstone the whole fleet, even
+ # with prune on. The `not canonicals` early-return guards this — an empty discover
+ # result is treated as "couldn't read", not "delete everything".
+ alpha = _make_canonical("signals-scout-alpha", body="alpha body")
+ with self._patch_canonicals((alpha,)):
+ sync_canonical_skills(self.team)
+
+ with self._patch_canonicals(()):
+ result = sync_canonical_skills(self.team, prune=True)
+
+ assert result.pruned_skill_names == ()
+ assert result.skipped_reason is not None
+ assert LLMSkill.objects.filter(
+ team=self.team, name="signals-scout-alpha", is_latest=True, deleted=False
+ ).exists()
+
+ def test_does_not_prune_by_default(self) -> None:
+ # The runner's cold-start sync calls without `prune`, so an ad-hoc run must NOT reap
+ # the rest of the team's fleet — it only ensures its own skill exists / is current.
+ alpha = _make_canonical("signals-scout-alpha", body="alpha body")
+ beta = _make_canonical("signals-scout-beta", body="beta body")
+ with self._patch_canonicals((alpha, beta)):
+ sync_canonical_skills(self.team)
+
+ # beta removed from disk, but prune defaults off → beta's live row survives.
+ with self._patch_canonicals((alpha,)):
+ result = sync_canonical_skills(self.team)
+
+ assert result.pruned_skill_names == ()
+ assert LLMSkill.objects.filter(
+ team=self.team, name="signals-scout-beta", is_latest=True, deleted=False
+ ).exists()
+
+ def test_leaves_pre_hash_harness_row_alone(self) -> None:
+ # A harness-seeded row missing `canonical_hash` (only reachable for rows seeded before
+ # hash tracking, e.g. an existing dogfood team). We can't tell whether the team edited
+ # it, so leave it alone rather than risk clobbering — diverged, never updated.
+ row = LLMSkill.objects.create(
+ team=self.team,
+ name="signals-scout-alpha",
+ description="legacy",
+ body="legacy body",
+ metadata={"seeded_by": "signals_scout_harness", "source": "products/signals/skills"},
+ is_latest=True,
+ )
+ v2 = _make_canonical("signals-scout-alpha", description="legacy", body="new canonical body")
+ with self._patch_canonicals((v2,)):
+ result = sync_canonical_skills(self.team)
+
+ assert result.diverged_skill_names == ("signals-scout-alpha",)
+ assert result.updated_skill_names == ()
+ row.refresh_from_db()
+ assert row.body == "legacy body"
+
+ def test_bundle_only_change_triggers_update(self) -> None:
+ # Editing only references/* should still propagate. Easy to miss if the hash
+ # only covered SKILL.md body.
+ v1 = _make_canonical(
+ "signals-scout-alpha",
+ body="same body",
+ files=(CanonicalSkillFile(path="references/calib.md", content="v1"),),
+ )
+ with self._patch_canonicals((v1,)):
+ sync_canonical_skills(self.team)
+
+ v2 = _make_canonical(
+ "signals-scout-alpha",
+ body="same body",
+ files=(CanonicalSkillFile(path="references/calib.md", content="v2"),),
+ )
+ with self._patch_canonicals((v2,)):
+ result = sync_canonical_skills(self.team)
+
+ assert result.updated_skill_names == ("signals-scout-alpha",)
+ latest = LLMSkill.objects.get(team=self.team, name="signals-scout-alpha", is_latest=True)
+ bundle = {f.path: f.content for f in latest.files.all()}
+ assert bundle["references/calib.md"] == "v2"
+
+ def test_returns_skipped_reason_when_no_canonicals_on_disk(self) -> None:
+ with self._patch_canonicals(()):
+ result = sync_canonical_skills(self.team)
+ assert result.skipped_reason == "no canonical signals-scout-* skills on disk"
assert result.created_skill_names == ()
- assert not LLMSkill.objects.filter(team=self.team, name="signals-scout-general", deleted=False).exists()
- def test_idempotent_on_repeat_call(self) -> None:
- first = seed_canonical_skills(self.team)
- assert first.created_skill_names
- second = seed_canonical_skills(self.team)
- assert second.created_skill_names == ()
- count = LLMSkill.objects.filter(team=self.team, name__startswith="signals-scout-").count()
- assert count == len(first.created_skill_names)
+ def test_unrelated_team_skill_is_not_touched(self) -> None:
+ # A row whose name doesn't match any canonical (and isn't even prefix-matched)
+ # is invisible to the sync — the whole loop is keyed on canonical.name.
+ LLMSkill.objects.create(
+ team=self.team,
+ name="custom-team-skill",
+ description="custom",
+ body="custom body",
+ )
+ canonical = _make_canonical("signals-scout-alpha", body="canonical body")
+ with self._patch_canonicals((canonical,)):
+ sync_canonical_skills(self.team)
+ custom = LLMSkill.objects.get(team=self.team, name="custom-team-skill")
+ assert custom.body == "custom body"
+
+ def test_returns_sync_result_dataclass(self) -> None:
+ # Light shape lock so external callers (management command, coordinator) keep
+ # access to all five outcome buckets.
+ canonical = _make_canonical("signals-scout-alpha", body="x")
+ with self._patch_canonicals((canonical,)):
+ result = sync_canonical_skills(self.team)
+ assert isinstance(result, SyncResult)
+ assert hasattr(result, "created_skill_names")
+ assert hasattr(result, "updated_skill_names")
+ assert hasattr(result, "diverged_skill_names")
+ assert hasattr(result, "tombstoned_skill_names")
+
+
+class TestSeedCanonicalSkillsAlias(BaseTest):
+ """`seed_canonical_skills` is kept as a thin alias for `sync_canonical_skills` so older
+ callsites and external consumers don't break. These tests pin that contract."""
+
+ def test_alias_returns_sync_result(self) -> None:
+ result = seed_canonical_skills(self.team)
+ assert isinstance(result, SyncResult)
+
+ def test_alias_seeds_real_in_repo_canonicals(self) -> None:
+ # No mocking — exercises the real `products/signals/skills/` manifest end-to-end
+ # so the in-repo fleet stays loadable and seedable. Equivalent to the legacy
+ # "first seed creates rows" invariant.
+ result = seed_canonical_skills(self.team)
+ assert "signals-scout-general" in result.created_skill_names
+ seeded = LLMSkill.objects.get(team=self.team, name="signals-scout-general", is_latest=True)
+ assert seeded.body
+ assert seeded.metadata["seeded_by"] == "signals_scout_harness"
+ assert seeded.metadata.get("canonical_hash")
def test_seeded_skill_is_loadable_via_load_skill_for_run(self) -> None:
seed_canonical_skills(self.team)
@@ -326,29 +740,3 @@ class TestSeedCanonicalSkills(BaseTest):
assert loaded.name == "signals-scout-general"
assert loaded.version == 1
assert "Signals scout" in loaded.body
-
- def test_partial_failure_rolls_back_whole_seed_and_retries(self) -> None:
- # A mid-loop failure must roll back every insert, so the next run retries the full set
- # instead of getting wedged with a partial seed the "already seeded" guard treats as done.
- fakes = (
- CanonicalSkill("signals-scout-a", "d", "body", (), (), Path(".")),
- CanonicalSkill("signals-scout-b", "d", "body", (), (), Path(".")),
- )
- real_create = LLMSkill.objects.create
- seen = {"n": 0}
-
- def flaky_create(**kwargs: object) -> LLMSkill:
- seen["n"] += 1
- if seen["n"] == 2:
- raise RuntimeError("boom")
- return real_create(**kwargs)
-
- with patch("products.signals.backend.scout_harness.lazy_seed.discover_canonical_skills", return_value=fakes):
- with patch.object(LLMSkill.objects, "create", side_effect=flaky_create):
- with pytest.raises(RuntimeError):
- seed_canonical_skills(self.team)
- assert not LLMSkill.objects.filter(team=self.team, name__startswith="signals-scout-").exists()
-
- with patch("products.signals.backend.scout_harness.lazy_seed.discover_canonical_skills", return_value=fakes):
- result = seed_canonical_skills(self.team)
- assert set(result.created_skill_names) == {"signals-scout-a", "signals-scout-b"}
diff --git a/products/signals/skills/AGENTS.md b/products/signals/skills/AGENTS.md
new file mode 100644
index 000000000000..64b206f036e3
--- /dev/null
+++ b/products/signals/skills/AGENTS.md
@@ -0,0 +1,126 @@
+# Signals Skills
+
+Two distinct skill families live in this directory:
+
+1. **Official PostHog skills** — `signals/`, `inbox-exploration/`. First-party PostHog
+ skills published via `products/posthog_ai/dist/skills/` and loaded by users through
+ the PostHog MCP. They teach a caller how to query, browse, and reason about signals
+ data. They are not part of the automated agent path — humans (and human-driven
+ agents) reach for them on demand.
+2. **Scout fleet** — `signals-scout-*/`. Canonical default skills that the headless
+ Signals agent loads into its system prompt at runtime. These are also the first
+ example of PostHog shipping templated skills _into a user's PostHog Skills Store_:
+ `lazy_seed` mirrors them onto each agent-enabled team's `LLMSkill` rows on the first
+ coordinator tick, where users can then edit or override them per-team. They are not
+ designed to be invoked by humans directly; the prompt and tool affordances assume
+ they are running inside the harness.
+
+## Scout fleet convention (`signals-scout-*`)
+
+The harness discovers scouts by globbing `signals-scout-*` over the team's `LLMSkill`
+table. The canonical content on disk in this directory is mirrored to each
+agent-enabled team's `LLMSkill` rows by `scout_harness/lazy_seed.py` — see
+`../backend/scout_harness/AGENTS.md` for the sync mechanics, and the
+`sync_signals_scout_skills` management command for the manual fan-out path.
+
+### Generalist + specialists
+
+- `signals-scout-general/` — cross-product generalist. Looks for cross-product
+ correlations and surfaces no specialist covers, rather than deep-diving a single
+ product. Carries two progressively-disclosed references: `references/emit.md` (the
+ emit contract) and `references/conventions.md` (scratchpad key prefixes + the
+ four-states dedupe classifier + cross-project noise patterns). This is the entry
+ point if you want to understand how a scout decides what to investigate end-to-end.
+- `signals-scout-llm-analytics/` — anomaly watcher for LLM analytics
+ (cost / latency / error / token-share regressions).
+- `signals-scout-logs/` — anomaly watcher for logs (rate / level / pattern shifts).
+- `signals-scout-error-tracking/` — anomaly watcher for error tracking
+ (issue spikes, regressions, suppression-rule churn).
+- `signals-scout-revenue-analytics/` — anomaly watcher for revenue
+ (MRR / churn / segment shifts).
+- `signals-scout-surveys/` — anomaly watcher for surveys
+ (response-rate drops, sentiment shifts, completion-funnel regressions).
+- `signals-scout-observability-gaps/` — the odd one out. Watches for _structural
+ gaps_ between events being captured and existing insight / dashboard / alert
+ coverage, and emits P3 _recommendations_ rather than P0–P2 _anomalies_.
+- `signals-scout-csp-violations/` — anomaly watcher for Content Security Policy
+ violations (`$csp_violation` blocked-URL clusters, per-directive bursts,
+ post-deploy page-scoped regressions, suspicious third-party domains).
+
+### How the coordinator decides what runs
+
+There is no sampling. Each scout has its own `SignalScoutConfig` row (one per
+`(team, skill_name)`) carrying a `run_interval_minutes` schedule (default 1440 =
+daily) and a `last_run_at` stamp. Every tick the coordinator:
+
+1. Bounds candidates to dogfood teams — those with a `signals-scout-*` skill or
+ config, gated by the `signals-scout` feature flag (`_participating_teams`).
+2. Auto-registers a config for any `signals-scout-*` skill missing one
+ (`_register_missing_configs`) — authoring a skill is enough to get a scout.
+3. Dispatches every enabled scout whose schedule is due (`last_run_at is None`, or
+ `now - last_run_at >= run_interval_minutes`), most-overdue first, capped at
+ `MAX_RUNS_PER_TICK` per tick. Each due scout becomes one `RunSignalsScoutWorkflow`
+ child run; `last_run_at` is advanced for everything dispatched.
+
+Pausing a scout is `enabled=False` on its config; slowing it is a larger
+`run_interval_minutes`. Both are tunable via the `signals-scout-config-update` MCP
+tool. See `scout_coordinator._collect_planned_runs` for the exact due-check.
+
+### Authoring a new scout
+
+Creating a new `signals-scout-foo/SKILL.md` directory and merging it is enough.
+The next coordinator tick (or an explicit `sync_signals_scout_skills --all-enabled` run)
+will:
+
+- discover it via `lazy_seed.discover_canonical_skills()`,
+- create matching `LLMSkill` rows on each agent-enabled team,
+- auto-register an enabled, daily-schedule `SignalScoutConfig` for it so the next
+ due tick dispatches it.
+
+No coordinator-side code change is needed. Use `signals-scout-general` as the
+template if your scout is broad; pick a specialist as the template if it is
+domain-tight.
+
+### What lives inside a scout SKILL.md
+
+Each scout's body is an instruction set the harness loads verbatim into the system
+prompt. References (siblings of `SKILL.md`) are progressively disclosed via
+`Skill.read_file()` from inside the run. Keep the body lean — every line is a
+recurring token cost on every run — and push detail into references that are only
+read when needed.
+
+The generalist (`signals-scout-general`) carries two references the rest of the
+fleet also reasons in terms of:
+
+- **`references/emit.md`** — the emit contract: required/recommended fields, the
+ weight vs. confidence rubrics, severity mapping, dedupe keys, `finding_id`
+ idempotency, and a worked example.
+- **`references/conventions.md`** — the four-states dedupe classifier, scratchpad
+ key-prefix vocabulary, and cross-project noise patterns.
+
+The 7 specialists are each currently a single self-contained `SKILL.md` carrying
+their own domain discriminator + investigation patterns. A simplification pass to
+compress them and share the generalist's references is planned; until then, treat
+the generalist as the reference shape.
+
+## When editing skills in this directory
+
+- **Official skills (`signals/`, `inbox-exploration/`).** Disk in this directory is
+ the source of truth. Changes get published to `products/posthog_ai/dist/skills/`
+ for distribution as part of the official PostHog skill set; they are not
+ auto-synced onto teams' `LLMSkill` rows.
+- **Scout skills (`signals-scout-*/`).** Disk in this directory is the source of
+ truth, and `lazy_seed` mirrors changes onto each agent-enabled team's `LLMSkill`
+ rows on the next coordinator tick (or immediately via
+ `python manage.py sync_signals_scout_skills --all-enabled`). Teams that have
+ manually edited a row are treated as "diverged" and left alone — the sync logs
+ them so you can decide whether to nudge those teams to reset.
+- **If you change the scout fleet shape (add a new specialist, rename, or change
+ the SKILL.md schema), update this file.**
+
+## Reference
+
+- Harness layout and run lifecycle — `../backend/scout_harness/AGENTS.md`
+- Coordinator + per-scout due-check rules — `../backend/temporal/agentic/scout_coordinator.py`
+- Canonical sync mechanics + manual command —
+ `../backend/management/AGENTS.md` (Canonical skill sync section)
diff --git a/products/signals/skills/CLAUDE.md b/products/signals/skills/CLAUDE.md
new file mode 120000
index 000000000000..47dc3e3d863c
--- /dev/null
+++ b/products/signals/skills/CLAUDE.md
@@ -0,0 +1 @@
+AGENTS.md
\ No newline at end of file
diff --git a/products/signals/skills/signals-scout-general/SKILL.md b/products/signals/skills/signals-scout-general/SKILL.md
index f82251100bf2..9020390417cf 100644
--- a/products/signals/skills/signals-scout-general/SKILL.md
+++ b/products/signals/skills/signals-scout-general/SKILL.md
@@ -6,8 +6,8 @@ description: >
(signals-scout-llm-analytics, -logs, -error-tracking, -revenue-analytics, -surveys,
-observability-gaps, -csp-violations) cover individual product surfaces; this
scout looks for cross-product correlations and explores what specialists don't
- cover. The coordinator samples one scout per (team, tick) at random, so general
- fires intermixed with specialists over time.
+ cover. Each scout runs on its own schedule (default daily), so general fires
+ independently of the specialists over time.
compatibility: >
Runs as the PostHog Signals scout in a Claude sandbox with PostHog MCP scopes: signal_scout:read + signal_scout_internal:write (for
scratchpad-remember/forget and emit-signal), llm_skill:read, plus standard analytics reads. Uses the
@@ -79,9 +79,9 @@ recognize) live in [`references/conventions.md`](references/conventions.md).
## Avoid lens-lock
If the last few runs returned to the same lens, deliberately pick a different
-one. The coordinator already rotates which scout runs each tick — your job
-within a run is to follow what's interesting in the data, not to ceremonially
-rotate lenses.
+one. Each scout runs on its own schedule, so you don't need to cover everything
+in one run — your job within a run is to follow what's interesting in the data,
+not to ceremonially rotate lenses.
## Close out