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.

40.7 KB
Raw Blame
import { MakeLogicType, actions, connect, events, kea, listeners, path, reducers, selectors } from 'kea'
import { loaders } from 'kea-loaders'
import { subscriptions } from 'kea-subscriptions'

import api, { ApiConfig } from 'lib/api'
import { dayjs } from 'lib/dayjs'

import {
    signalsScoutRunsEmissionReportsBatch,
    signalsScoutRunsEmissionsBatch,
} from 'products/signals/frontend/generated/api'

import type { SignalScoutEmissionApi } from '../../generated/api.schemas'
import {
    LinkedSignalReport,
    SignalScoutEmission,
    SignalReport,
    SignalReportPriority,
    SignalScoutEmissionReportLink,
    SignalScoutRunSummary,
} from '../types'
import {
    isSettledRun,
    mostRecentEmittedRuns,
    prettifyScoutSkillName,
    runTouchedReports,
} from '../utils/scoutRunsWindow'
import { isReportUnreachable, rememberUnreachableReport } from '../utils/unreachableReports'
import { ScoutEmissionRow, ScoutReportAction } from './scoutDetailLogic'
import { scoutFleetLogic } from './scoutFleetLogic'

// Report linkage is eventually consistent, so keep retrying the reverse lookup on the runs-window
// poll, but only while a recently-emitted finding is still unlinked (past this it never will be).
const REPORT_LINK_RETRY_WINDOW_MINUTES = 30

// Cadence of the page's own runs-window poll (matches the fleet section's); retries cold/failed loads.
const RUNS_REFETCH_INTERVAL_MS = 60_000

// Bound the reports the fleet-wide surfaces consider (tallies, fetch fan-out, rendered list), the
// same way the per-scout detail view bounds its own report fetches. Applied in the `touchedReports`
// selector — keeping the most recently touched — so every consumer describes the same set.
const MAX_FLEET_TOUCHED_REPORTS = 50

/** A report the fleet touched via the report channel, joined with how and by which scout(s). */
export interface FleetScoutReportRow {
    report: SignalReport
    action: ScoutReportAction
    /** Primary attribution for the card: the authoring scout, else the most recent editor. */
    skillName: string
    /** Every scout that touched the report in the window — what the scout filter matches against. */
    skillNames: string[]
}

export type FindingsSortKey = 'newest' | 'oldest' | 'severity'
export const FINDINGS_SCOUT_FILTER_ALL = 'all'
export const FINDINGS_SEVERITY_FILTER_ALL = 'all'

/** Lowest number = most severe, so the severity sort is a plain ascending compare. Null sinks last. */
const SEVERITY_RANK: Record<SignalReportPriority, number> = { P0: 0, P1: 1, P2: 2, P3: 3, P4: 4 }
function severityRank(severity: SignalReportPriority | null): number {
    return severity == null ? 5 : SEVERITY_RANK[severity]
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface findingsLogicValues {
    runsWindow: {
        complete: boolean
        runs: SignalScoutRunSummary[]
    } // scoutFleetLogic
    runsWindowLoadedOnce: boolean // scoutFleetLogic
    authoredReportCount: number
    availableScouts: {
        count: number
        label: string
        skillName: string
    }[]
    editedReportCount: number
    emissionReports: SignalScoutEmissionReportLink[]
    emissionReportsLoading: boolean
    emissions: SignalScoutEmission[]
    emissionsLoadFailed: boolean
    emissionsLoading: boolean
    emittedRuns: SignalScoutRunSummary[]
    emittedRunsKey: string
    filteredReportRows: FleetScoutReportRow[]
    filteredRows: ScoutEmissionRow[]
    hasLoadedOnce: boolean
    latestEmittedAt: string | null
    reportBySourceId: Map<string, LinkedSignalReport>
    reportRows: FleetScoutReportRow[]
    rows: ScoutEmissionRow[]
    scoutCount: number
    scoutFilter: string
    scoutReports: SignalReport[]
    scoutReportsLoadFailed: boolean
    scoutReportsLoading: boolean
    searchText: string
    severityFilter: string
    sortKey: FindingsSortKey
    totalCount: number
    touchedReports: {
        action: ScoutReportAction
        hasLiveTouch: boolean
        id: string
        runIds: string[]
        skillName: string
        skillNames: string[]
    }[]
    touchedReportsKey: string
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface findingsLogicActions {
    loadEmissionReports: () => any
    loadEmissionReportsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadEmissionReportsSuccess: (
        emissionReports: SignalScoutEmissionReportLink[],
        payload?: any
    ) => {
        emissionReports: SignalScoutEmissionReportLink[]
        payload?: any
    }
    loadEmissions: () => any
    loadEmissionsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadEmissionsSuccess: (
        emissions: SignalScoutEmissionApi[],
        payload?: any
    ) => {
        emissions: SignalScoutEmissionApi[]
        payload?: any
    }
    loadScoutReports: (ids?: string[]) => {
        ids: string[] | undefined
    }
    loadScoutReportsFailure: (
        error: string,
        errorObject?: any
    ) => {
        error: string
        errorObject?: any
    }
    loadScoutReportsSuccess: (
        scoutReports: SignalReport[],
        payload?: {
            ids: string[] | undefined
        }
    ) => {
        scoutReports: SignalReport[]
        payload?: {
            ids: string[] | undefined
        }
    }
    setScoutFilter: (scoutFilter: string) => {
        scoutFilter: string
    }
    setSearchText: (searchText: string) => {
        searchText: string
    }
    setSeverityFilter: (severityFilter: string) => {
        severityFilter: string
    }
    setSortKey: (sortKey: FindingsSortKey) => {
        sortKey: FindingsSortKey
    }
}

// Generated by kea-typegen. Update if you're an agent, ignore if you're human.
export interface findingsLogicMeta {
    __keaTypeGenInternalSelectorTypes: {
        emittedRuns: (runsWindow: { complete: boolean; runs: SignalScoutRunSummary[] }) => SignalScoutRunSummary[]
        emittedRunsKey: (emittedRuns: SignalScoutRunSummary[]) => string
        touchedReports: (emittedRuns: SignalScoutRunSummary[]) => {
            action: ScoutReportAction
            hasLiveTouch: boolean
            id: string
            runIds: string[]
            skillName: string
            skillNames: string[]
        }[]
        touchedReportsKey: (
            touchedReports: {
                action: ScoutReportAction
                hasLiveTouch: boolean
                id: string
                runIds: string[]
                skillName: string
                skillNames: string[]
            }[]
        ) => string
        reportRows: (
            scoutReports: SignalReport[],
            touchedReports: {
                action: ScoutReportAction
                hasLiveTouch: boolean
                id: string
                runIds: string[]
                skillName: string
                skillNames: string[]
            }[]
        ) => FleetScoutReportRow[]
        filteredReportRows: (
            reportRows: FleetScoutReportRow[],
            searchText: string,
            scoutFilter: string,
            severityFilter: string,
            sortKey: FindingsSortKey
        ) => FleetScoutReportRow[]
        reportBySourceId: (emissionReports: SignalScoutEmissionReportLink[]) => Map<string, LinkedSignalReport>
        rows: (
            emissions: SignalScoutEmission[],
            emittedRuns: SignalScoutRunSummary[],
            reportBySourceId: Map<string, LinkedSignalReport>
        ) => ScoutEmissionRow[]
        availableScouts: (
            rows: ScoutEmissionRow[],
            touchedReports: {
                action: ScoutReportAction
                hasLiveTouch: boolean
                id: string
                runIds: string[]
                skillName: string
                skillNames: string[]
            }[]
        ) => {
            count: number
            label: string
            skillName: string
        }[]
        filteredRows: (
            rows: ScoutEmissionRow[],
            searchText: string,
            scoutFilter: string,
            severityFilter: string,
            sortKey: FindingsSortKey
        ) => ScoutEmissionRow[]
        totalCount: (rows: ScoutEmissionRow[]) => number
        authoredReportCount: (
            touchedReports: {
                action: ScoutReportAction
                hasLiveTouch: boolean
                id: string
                runIds: string[]
                skillName: string
                skillNames: string[]
            }[]
        ) => number
        editedReportCount: (
            touchedReports: {
                action: ScoutReportAction
                hasLiveTouch: boolean
                id: string
                runIds: string[]
                skillName: string
                skillNames: string[]
            }[]
        ) => number
        scoutCount: (
            availableScouts: {
                count: number
                label: string
                skillName: string
            }[]
        ) => number
        latestEmittedAt: (rows: ScoutEmissionRow[], emittedRuns: SignalScoutRunSummary[]) => string | null
        hasLoadedOnce: (
            runsWindowLoadedOnce: boolean,
            emittedRuns: SignalScoutRunSummary[],
            emissionsLoading: boolean,
            emissions: SignalScoutEmission[],
            touchedReports: {
                action: ScoutReportAction
                hasLiveTouch: boolean
                id: string
                runIds: string[]
                skillName: string
                skillNames: string[]
            }[],
            scoutReportsLoading: boolean,
            scoutReports: SignalReport[]
        ) => boolean
    }
}

export type findingsLogicType = MakeLogicType<
    findingsLogicValues,
    findingsLogicActions,
    Record<string, any>,
    findingsLogicMeta
>

/**
 * Fleet-wide findings logic — the cross-troop counterpart of the per-scout `scoutDetailLogic`. Reuses
 * `scoutFleetLogic`'s polled runs window to find every scout's recent output runs, fetches their
 * emissions + report links in two batched requests, and flattens them into one
 * searchable/filterable/sortable list. Also resolves the reports the fleet authored/edited via the
 * report channel (`emit_report` / `edit_report`) so the page lists both emit channels. Singleton,
 * mounted only by the findings page, so the fetch stays lazy (the callout reads the cheap
 * `scoutFleetLogic.emittedFindingsSummary` instead).
 */
export const findingsLogic = kea<findingsLogicType>([
    path(['scenes', 'inbox', 'logics', 'findingsLogic']),

    connect(() => ({
        values: [scoutFleetLogic, ['runsWindow', 'runsWindowLoadedOnce']],
    })),

    actions({
        setSearchText: (searchText: string) => ({ searchText }),
        setScoutFilter: (scoutFilter: string) => ({ scoutFilter }),
        setSeverityFilter: (severityFilter: string) => ({ severityFilter }),
        setSortKey: (sortKey: FindingsSortKey) => ({ sortKey }),
        // `ids` = targeted refresh (the poll retries): fetch only those reports and merge into the
        // retained set. Omitted = full load of every touched report. Each retrieve is an expensive
        // annotated query server-side, so the 60s poll must not re-fetch all ~50 for one needy id.
        loadScoutReports: (ids?: string[]) => ({ ids }),
    }),

    loaders(({ values }) => ({
        emissions: [
            [] as SignalScoutEmission[],
            {
                loadEmissions: async () => {
                    // Only runs that emitted a finding — report-only runs have no emissions to fetch,
                    // and a report-only fleet must not hit (or surface an error from) this legacy
                    // endpoint at all.
                    const runs = values.emittedRuns.filter((run) => (run.emitted_count ?? 0) > 0)
                    if (runs.length === 0) {
                        return []
                    }
                    // One batched request for the whole window: the backend flattens every run's
                    // findings newest-first (each row carries its run_id). A throw surfaces as the
                    // page's error/retry state — far cheaper than the old per-run fan-out.
                    return await signalsScoutRunsEmissionsBatch(String(ApiConfig.getCurrentProjectId()), {
                        run_ids: runs.map((run) => run.run_id),
                    })
                },
            },
        ],
        emissionReports: [
            [] as SignalScoutEmissionReportLink[],
            {
                loadEmissionReports: async () => {
                    // Report links only exist for emitted findings — same finding-producing subset
                    // as `loadEmissions`.
                    const runs = values.emittedRuns.filter((run) => (run.emitted_count ?? 0) > 0)
                    if (runs.length === 0) {
                        return []
                    }
                    // One batched request → one ClickHouse round-trip for every run's report links,
                    // replacing the per-run fan-out. Report chips are optional enrichment over findings
                    // that already loaded via `emissions`, and the retry listener re-polls this while any
                    // recent finding is unlinked — so swallow failures and keep the prior links rather than
                    // letting the throw hit the global loaders error handler (a token with `signal_scout:read`
                    // but not `task:read` 403s this endpoint on every poll). The `emissions` loader keeps
                    // throwing: that one is the page's actual content and should surface an error/retry state.
                    try {
                        return await signalsScoutRunsEmissionReportsBatch(String(ApiConfig.getCurrentProjectId()), {
                            run_ids: runs.map((run) => run.run_id),
                        })
                    } catch {
                        return values.emissionReports
                    }
                },
            },
        ],
        // The reports the fleet authored/edited directly via the report channel. Unlike findings, the
        // run already carries the report id (no async grouping), so each report is fetched straight by
        // id to resolve its title + live status. The `touchedReports` selector already caps the set.
        // On a partially failed fan-out, a still-touched report that resolved on a *previous* round is
        // kept (possibly stale) rather than dropped — otherwise retries would oscillate between
        // subsets as different requests fail. When *every* fetch fails while touched ids exist, throw —
        // an outage must show the Reports section's error/retry state, not a false "no reports".
        scoutReports: [
            [] as SignalReport[],
            {
                loadScoutReports: async ({ ids }: { ids?: string[] } = {}) => {
                    const touched = values.touchedReports
                    if (touched.length === 0) {
                        return []
                    }
                    const touchedIds = new Set(touched.map(({ id }) => id))
                    // Targeted refresh fetches only the named (still-touched) ids; a full load
                    // fetches the whole capped set. Ids a previous round found unreachable are
                    // dropped: a deleted report stays deleted, so re-asking only burns requests.
                    const fetchIds = (
                        ids ? [...new Set(ids)].filter((id) => touchedIds.has(id)) : [...touchedIds]
                    ).filter((id) => !isReportUnreachable(id))
                    if (fetchIds.length === 0) {
                        return values.scoutReports
                    }
                    const settled = await Promise.allSettled(fetchIds.map((id) => api.signalReports.get(id)))
                    const byId = new Map<string, SignalReport>()
                    let transientFailure = false
                    settled.forEach((result, index) => {
                        if (result.status === 'fulfilled') {
                            byId.set(result.value.id, result.value)
                            return
                        }
                        transientFailure =
                            !rememberUnreachableReport(fetchIds[index], result.reason) || transientFailure
                    })
                    // Every fetch rejected and at least one can recover — throw BEFORE merging cached
                    // rows, so an outage flags `scoutReportsLoadFailed` (warning banner over the stale
                    // set kea-loaders keeps) instead of laundering the cache into a "successful"
                    // refresh. An all-404 round is not an outage: those reports are simply gone.
                    if (byId.size === 0 && transientFailure) {
                        throw new Error('Failed to load the reports scouts touched')
                    }
                    // Keep prior resolved reports for still-touched ids that weren't (successfully)
                    // fetched this round — a partial failure must not drop them, and a targeted
                    // refresh must not discard the untargeted rest.
                    for (const previous of values.scoutReports) {
                        if (!byId.has(previous.id) && touchedIds.has(previous.id)) {
                            byId.set(previous.id, previous)
                        }
                    }
                    return [...byId.values()]
                },
            },
        ],
    })),

    reducers({
        searchText: ['', { setSearchText: (_, { searchText }) => searchText }],
        scoutFilter: [FINDINGS_SCOUT_FILTER_ALL as string, { setScoutFilter: (_, { scoutFilter }) => scoutFilter }],
        severityFilter: [
            FINDINGS_SEVERITY_FILTER_ALL as string,
            { setSeverityFilter: (_, { severityFilter }) => severityFilter },
        ],
        sortKey: ['newest' as FindingsSortKey, { setSortKey: (_, { sortKey }) => sortKey }],
        // True only when the most recent emissions load failed outright (the batched fetch rejected).
        emissionsLoadFailed: [
            false,
            {
                loadEmissions: () => false,
                loadEmissionsSuccess: () => false,
                loadEmissionsFailure: () => true,
            },
        ],
        // True only when the most recent reports load failed outright (every per-report fetch
        // rejected). Lets the Reports section show an error/retry state instead of a false empty.
        scoutReportsLoadFailed: [
            false,
            {
                loadScoutReports: () => false,
                loadScoutReportsSuccess: () => false,
                loadScoutReportsFailure: () => true,
            },
        ],
    }),

    selectors({
        // Emitted runs newest-first, capped fleet-wide. Shares `mostRecentEmittedRuns` with the callout
        // summary so the two count the exact same run set.
        emittedRuns: [
            (s) => [s.runsWindow],
            (runsWindow: { runs: SignalScoutRunSummary[]; complete: boolean }): SignalScoutRunSummary[] =>
                mostRecentEmittedRuns(runsWindow.runs),
        ],
        // Stable key over the emitted runs — refetch only when the set changes, not on every poll.
        // Includes `emitted_count` so an in-progress run that emits more findings retriggers.
        emittedRunsKey: [
            (s) => [s.emittedRuns],
            (emittedRuns: SignalScoutRunSummary[]): string =>
                emittedRuns
                    .map((run) => `${run.run_id}:${run.emitted_count ?? 0}`)
                    .sort()
                    .join(','),
        ],
        // The distinct reports the fleet touched via the report channel in the window, most recently
        // touched first, each tagged with how (authoring supersedes a later edit of the same report,
        // matching the scout detail view) and by which scout — the authoring run's skill wins; an
        // edited-only report gets the most recent editing run's skill. Runs arrive newest first, so
        // first-writer-wins per pass. Capped at MAX_FLEET_TOUCHED_REPORTS *here* — not just in the
        // loader — so the header tallies, the fetch, and the rendered list all describe the same set,
        // and the cap keeps the most recently touched reports rather than arbitrary ones.
        touchedReports: [
            (s) => [s.emittedRuns],
            (
                emittedRuns: SignalScoutRunSummary[]
            ): {
                id: string
                action: ScoutReportAction
                skillName: string
                skillNames: string[]
                runIds: string[]
                hasLiveTouch: boolean
            }[] => {
                // First-touch order (runs arrive newest first) drives the recency cap. Also collects
                // *every* touching run (for the refetch key — a run first observed after it settled
                // must still trigger a reload), whether any touching run is still live (the poll
                // refreshes live-touched reports; the live→settled flip changes the key so the run's
                // final pre-completion edit gets one last reload), and every touching scout, so a
                // report scout B edited stays findable under B's filter even when scout A's
                // authoring wins the card attribution.
                const orderedIds = new Map<string, null>()
                const runIdsById = new Map<string, string[]>()
                const liveTouchIds = new Set<string>()
                const skillNamesById = new Map<string, string[]>()
                for (const run of emittedRuns) {
                    for (const id of [...(run.edited_report_ids ?? []), ...(run.emitted_report_ids ?? [])]) {
                        if (!orderedIds.has(id)) {
                            orderedIds.set(id, null)
                        }
                        const runIds = runIdsById.get(id) ?? []
                        if (!runIds.includes(run.run_id)) {
                            runIds.push(run.run_id)
                            runIdsById.set(id, runIds)
                        }
                        if (!isSettledRun(run)) {
                            liveTouchIds.add(id)
                        }
                        const skills = skillNamesById.get(id) ?? []
                        if (!skills.includes(run.skill_name)) {
                            skills.push(run.skill_name)
                            skillNamesById.set(id, skills)
                        }
                    }
                }
                const byId = new Map<string, { action: ScoutReportAction; skillName: string }>()
                for (const run of emittedRuns) {
                    for (const id of run.edited_report_ids ?? []) {
                        if (!byId.has(id)) {
                            byId.set(id, { action: 'edited', skillName: run.skill_name })
                        }
                    }
                }
                for (const run of emittedRuns) {
                    for (const id of run.emitted_report_ids ?? []) {
                        if (byId.get(id)?.action !== 'authored') {
                            byId.set(id, { action: 'authored', skillName: run.skill_name })
                        }
                    }
                }
                // orderedIds' insertion order is newest-touch-first, so slicing keeps recency.
                return [...orderedIds.keys()].slice(0, MAX_FLEET_TOUCHED_REPORTS).map((id) => ({
                    id,
                    ...byId.get(id)!,
                    skillNames: skillNamesById.get(id) ?? [],
                    runIds: runIdsById.get(id) ?? [],
                    hasLiveTouch: liveTouchIds.has(id),
                }))
            },
        ],
        // Stable key over the touched report set — refetch the reports only when the set actually
        // changes, not on every runs-window poll that returns the same runs. Includes *every*
        // touching run id, so any newly observed touch refetches the report's live title/status —
        // including an overlapping run's edit first observed after that run settled — plus the
        // live/settled state, so a touching run completing fires one final reload that catches its
        // last pre-completion edit (which no id in the key would otherwise reflect).
        touchedReportsKey: [
            (s) => [s.touchedReports],
            (
                touchedReports: {
                    id: string
                    action: ScoutReportAction
                    skillName: string
                    runIds: string[]
                    hasLiveTouch: boolean
                }[]
            ): string =>
                touchedReports
                    .map(
                        ({ id, action, runIds, hasLiveTouch }) =>
                            `${id}:${action}:${[...runIds].sort().join('+')}:${hasLiveTouch ? 'live' : 'settled'}`
                    )
                    .sort()
                    .join(','),
        ],
        // Join the fetched reports back to how/who touched each, newest-updated first. A touched id
        // whose report fetch failed (deleted/inaccessible) is skipped.
        reportRows: [
            (s) => [s.scoutReports, s.touchedReports],
            (
                scoutReports: SignalReport[],
                touchedReports: {
                    id: string
                    action: ScoutReportAction
                    skillName: string
                    skillNames: string[]
                }[]
            ): FleetScoutReportRow[] => {
                const touchedById = new Map(touchedReports.map((touched) => [touched.id, touched]))
                return scoutReports
                    .map((report) => {
                        const touched = touchedById.get(report.id)
                        return touched
                            ? {
                                  report,
                                  action: touched.action,
                                  skillName: touched.skillName,
                                  skillNames: touched.skillNames,
                              }
                            : null
                    })
                    .filter((row): row is FleetScoutReportRow => row !== null)
                    .sort((a, b) => (b.report.updated_at ?? '').localeCompare(a.report.updated_at ?? ''))
            },
        ],
        // Visible report set: same search / scout / severity filters and sort control as the findings
        // (severity matches the report's priority): newest/oldest by report update time, severity by
        // priority.
        filteredReportRows: [
            (s) => [s.reportRows, s.searchText, s.scoutFilter, s.severityFilter, s.sortKey],
            (
                reportRows: FleetScoutReportRow[],
                searchText: string,
                scoutFilter: string,
                severityFilter: string,
                sortKey: FindingsSortKey
            ): FleetScoutReportRow[] => {
                const needle = searchText.trim().toLowerCase()
                const filtered = reportRows.filter((row) => {
                    // Match any touching scout, not just the card's primary attribution — a report
                    // scout B edited must surface under B's filter even when scout A authored it.
                    if (scoutFilter !== FINDINGS_SCOUT_FILTER_ALL && !row.skillNames.includes(scoutFilter)) {
                        return false
                    }
                    if (severityFilter !== FINDINGS_SEVERITY_FILTER_ALL && row.report.priority !== severityFilter) {
                        return false
                    }
                    if (needle) {
                        // Title + summary (matching the backend report search) + touching scout names.
                        const haystack = `${row.report.title ?? ''} ${row.report.summary ?? ''} ${row.skillNames
                            .map(prettifyScoutSkillName)
                            .join(' ')}`.toLowerCase()
                        if (!haystack.includes(needle)) {
                            return false
                        }
                    }
                    return true
                })
                const byNewest = (a: FleetScoutReportRow, b: FleetScoutReportRow): number =>
                    (b.report.updated_at ?? '').localeCompare(a.report.updated_at ?? '')
                return filtered.slice().sort((a, b) => {
                    if (sortKey === 'oldest') {
                        return -byNewest(a, b)
                    }
                    if (sortKey === 'severity') {
                        const diff = severityRank(a.report.priority ?? null) - severityRank(b.report.priority ?? null)
                        return diff !== 0 ? diff : byNewest(a, b)
                    }
                    return byNewest(a, b)
                })
            },
        ],
        reportBySourceId: [
            (s) => [s.emissionReports],
            (emissionReports: SignalScoutEmissionReportLink[]): Map<string, LinkedSignalReport> =>
                new Map(
                    emissionReports
                        .filter((link) => link.report !== null)
                        .map((link) => [link.source_id, link.report as LinkedSignalReport])
                ),
        ],
        // Join emissions back to their run (for skill_name + task-run link) and the report they grouped into.
        rows: [
            (s) => [s.emissions, s.emittedRuns, s.reportBySourceId],
            (
                emissions: SignalScoutEmission[],
                emittedRuns: SignalScoutRunSummary[],
                reportBySourceId: Map<string, LinkedSignalReport>
            ): ScoutEmissionRow[] => {
                const runsById = new Map(emittedRuns.map((run) => [run.run_id, run]))
                return emissions
                    .map((emission) => {
                        const run = runsById.get(emission.run_id)
                        return run ? { emission, run, report: reportBySourceId.get(emission.source_id) ?? null } : null
                    })
                    .filter((row): row is ScoutEmissionRow => row !== null)
            },
        ],
        // Distinct scouts present in the loaded findings and touched reports, with a per-scout row
        // count (findings + reports), for the scout filter. Report-side scouts come from the touched
        // set — not the resolved rows — so a failed report fetch can't contradict the header tallies
        // ("1 report authored · 0 scouts") or drop the scout from the filter; every touching scout
        // counts, not just the card's primary attribution.
        availableScouts: [
            (s) => [s.rows, s.touchedReports],
            (
                rows: ScoutEmissionRow[],
                touchedReports: {
                    id: string
                    action: ScoutReportAction
                    skillName: string
                    skillNames: string[]
                }[]
            ): { skillName: string; label: string; count: number }[] => {
                const counts = new Map<string, number>()
                for (const row of rows) {
                    counts.set(row.run.skill_name, (counts.get(row.run.skill_name) ?? 0) + 1)
                }
                for (const touched of touchedReports) {
                    for (const skillName of touched.skillNames) {
                        counts.set(skillName, (counts.get(skillName) ?? 0) + 1)
                    }
                }
                return [...counts.entries()]
                    .map(([skillName, count]) => ({ skillName, label: prettifyScoutSkillName(skillName), count }))
                    .sort((a, b) => a.label.localeCompare(b.label))
            },
        ],
        // Visible set: search (over finding text + prettified scout name) + scout + severity, then sort.
        filteredRows: [
            (s) => [s.rows, s.searchText, s.scoutFilter, s.severityFilter, s.sortKey],
            (
                rows: ScoutEmissionRow[],
                searchText: string,
                scoutFilter: string,
                severityFilter: string,
                sortKey: FindingsSortKey
            ): ScoutEmissionRow[] => {
                const needle = searchText.trim().toLowerCase()
                const filtered = rows.filter((row) => {
                    if (scoutFilter !== FINDINGS_SCOUT_FILTER_ALL && row.run.skill_name !== scoutFilter) {
                        return false
                    }
                    if (severityFilter !== FINDINGS_SEVERITY_FILTER_ALL && row.emission.severity !== severityFilter) {
                        return false
                    }
                    if (needle) {
                        const haystack = `${row.emission.description ?? ''} ${prettifyScoutSkillName(
                            row.run.skill_name
                        )}`.toLowerCase()
                        if (!haystack.includes(needle)) {
                            return false
                        }
                    }
                    return true
                })
                const byNewest = (a: ScoutEmissionRow, b: ScoutEmissionRow): number =>
                    (b.emission.emitted_at ?? '').localeCompare(a.emission.emitted_at ?? '')
                return filtered.slice().sort((a, b) => {
                    if (sortKey === 'oldest') {
                        return -byNewest(a, b)
                    }
                    if (sortKey === 'severity') {
                        const diff = severityRank(a.emission.severity) - severityRank(b.emission.severity)
                        return diff !== 0 ? diff : byNewest(a, b)
                    }
                    return byNewest(a, b)
                })
            },
        ],
        // Page header tallies, from the loaded set (not the cheap window sum the callout uses).
        totalCount: [(s) => [s.rows], (rows: ScoutEmissionRow[]): number => rows.length],
        authoredReportCount: [
            (s) => [s.touchedReports],
            (touchedReports: { id: string; action: ScoutReportAction; skillName: string }[]): number =>
                touchedReports.filter(({ action }) => action === 'authored').length,
        ],
        editedReportCount: [
            (s) => [s.touchedReports],
            (touchedReports: { id: string; action: ScoutReportAction; skillName: string }[]): number =>
                touchedReports.filter(({ action }) => action === 'edited').length,
        ],
        scoutCount: [
            (s) => [s.availableScouts],
            (
                availableScouts: {
                    count: number
                    label: string
                    skillName: string
                }[]
            ): number => availableScouts.length,
        ],
        // Most recent output across both channels: finding emission times, plus the completion (or
        // creation) time of report-touching runs — mirroring the backend summary's `latest_at`, so a
        // report-only fleet still gets a "latest" and a fresh report edit isn't outdated by an older
        // finding timestamp.
        latestEmittedAt: [
            (s) => [s.rows, s.emittedRuns],
            (rows: ScoutEmissionRow[], emittedRuns: SignalScoutRunSummary[]): string | null => {
                let latest: string | null = null
                for (const row of rows) {
                    const at = row.emission.emitted_at
                    if (at && (!latest || at > latest)) {
                        latest = at
                    }
                }
                for (const run of emittedRuns) {
                    if (!runTouchedReports(run)) {
                        continue
                    }
                    const at = run.completed_at ?? run.created_at
                    if (at && (!latest || at > latest)) {
                        latest = at
                    }
                }
                return latest
            },
        ],
        // "Loaded once" — distinguishes "not loaded yet" from "loaded, empty" without a skeleton flash.
        // With no emitted runs there's nothing to fetch, so resolve immediately; otherwise the
        // `!...Loading` guards suppress poll flicker once content is in hand. Waits on *both* channels:
        // a report-only fleet must not flash the "haven't surfaced anything" empty state in the gap
        // between the emissions load settling and the per-report fetches resolving.
        hasLoadedOnce: [
            (s) => [
                s.runsWindowLoadedOnce,
                s.emittedRuns,
                s.emissionsLoading,
                s.emissions,
                s.touchedReports,
                s.scoutReportsLoading,
                s.scoutReports,
            ],
            (
                runsWindowLoadedOnce: boolean,
                emittedRuns: SignalScoutRunSummary[],
                emissionsLoading: boolean,
                emissions: SignalScoutEmission[],
                touchedReports: { id: string; action: ScoutReportAction; skillName: string; latestRunId: string }[],
                scoutReportsLoading: boolean,
                scoutReports: SignalReport[]
            ): boolean =>
                runsWindowLoadedOnce &&
                (emittedRuns.length === 0 || !emissionsLoading || emissions.length > 0) &&
                (touchedReports.length === 0 || !scoutReportsLoading || scoutReports.length > 0),
        ],
    }),

    subscriptions(({ actions }) => ({
        // Fires on mount and whenever the emitted-run set changes; the key holds equal across no-op polls.
        emittedRunsKey: () => {
            actions.loadEmissions()
            actions.loadEmissionReports()
        },
        // Fires on mount and whenever the set of reports the fleet touched changes; the key holds
        // equal across no-op polls so we don't refetch.
        touchedReportsKey: () => {
            actions.loadScoutReports()
        },
    })),

    listeners(({ actions, values }) => ({
        // Ride the fleet's runs-window poll to refetch report links while a recent finding is unlinked.
        [scoutFleetLogic.actionTypes.loadRunsWindowSuccess]: () => {
            const cutoff = dayjs().subtract(REPORT_LINK_RETRY_WINDOW_MINUTES, 'minute')
            const hasRecentUnlinked = values.rows.some(
                (row) =>
                    row.report === null && row.emission.emitted_at && dayjs(row.emission.emitted_at).isAfter(cutoff)
            )
            if (hasRecentUnlinked) {
                actions.loadEmissionReports()
            }
            // Same ride for touched reports: the `touchedReportsKey` subscription won't refire for an
            // unchanged set, so without this (a) a report whose fetch failed transiently stays missing
            // until remount, and (b) a live run editing the same report repeatedly (dedup keeps
            // `edited_report_ids` unchanged after the first edit) serves a stale card until the run
            // settles. Refresh is *targeted*: only the needy ids are refetched — a report touched by
            // ANY still-live run (self-bounding since runs settle), or unresolved (transient failure
            // or deleted; no recency gate — the page's window is 72h, so an age gate would strand an
            // older report's failed fetch while the header still counts it. A deleted report costs
            // one targeted GET per poll until its touch leaves the window — bounded and rare).
            if (!values.scoutReportsLoading && values.touchedReports.length > 0) {
                const resolvedIds = new Set(values.scoutReports.map((report) => report.id))
                const needyIds = values.touchedReports
                    .filter(({ id, hasLiveTouch }) => hasLiveTouch || !resolvedIds.has(id))
                    .map(({ id }) => id)
                if (needyIds.length > 0) {
                    actions.loadScoutReports(needyIds)
                }
            }
        },
    })),

    events(({ cache }) => ({
        afterMount: () => {
            // The page can be reached cold (shared URL, or narrow viewport with no rail) when the fleet
            // section that normally polls the runs window isn't mounted. Own a poll here so the page
            // loads, *retries* a failed initial load (else `hasLoadedOnce` would never flip), and gives
            // the report-link retry listener a poll to ride. It lives on this logic's own disposables
            // under its own key, so it never disposes the section's `runsPoll` — when both are mounted
            // the overlap just costs one extra capped request, since `loadRunsWindow` is idempotent.
            scoutFleetLogic.findMounted()?.actions.loadRunsWindow()
            cache.disposables.add(() => {
                const interval = setInterval(
                    () => scoutFleetLogic.findMounted()?.actions.loadRunsWindow(),
                    RUNS_REFETCH_INTERVAL_MS
                )
                return () => clearInterval(interval)
            }, 'findingsRunsPoll')
        },
    })),
])