:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(today): mark key clauses and sourced numbers with jev (#111473)
Shy Alter4dd8982749f3
diff --git a/frontend/src/lib/constants.tsx b/frontend/src/lib/constants.tsxindex fb0b174d89e0..a9e45ec9ec9a 100644--- a/frontend/src/lib/constants.tsx+++ b/frontend/src/lib/constants.tsx@@ -555,6 +555,7 @@ export const FEATURE_FLAGS = {TAXONOMIC_FILTER_SEARCH_INTENT: 'taxonomic-filter-search-intent', // owner: @pauldambra multivariate=control,banner,promote, classifies a picker search with the decision model. Every arm promotes the predicted group on the All tab; only banner also suggests the right tabTEXT_CARD_WORD_ART: 'text-card-word-art', // owner: @jonmcwest, gates the word art insert button in dashboard text cardsTODAY_RAIL_NAV: 'today-rail-nav', // owner: @k11kirky, replaces the left navigation with a rail (Home, Spaces, Library, Tools) and makes the Today briefing the homepage+ TODAY_REPORT_JEV: 'today-report-jev', // owner: @puemos, asks the decision model to label the problem, cause and fix in a Today report, to mark the numbers a source states, and to pick the code excerpt a finding describesTOOLBAR_PAID_HEATMAPS: 'toolbar-paid-heatmaps', // owner: #team-web-analyticsTRACING: 'tracing', // owner: #team-apm (@jonmcwest, @frankh)TRACING_AI_EVENTS: 'tracing-ai-events', // owner: #team-apm — shows a trace's LLM analytics events inline in the trace drawer waterfalldiff --git a/frontend/src/scenes/project-homepage/today/Today.scss b/frontend/src/scenes/project-homepage/today/Today.scssindex ef831448e3a1..df55463f9fa5 100644--- a/frontend/src/scenes/project-homepage/today/Today.scss+++ b/frontend/src/scenes/project-homepage/today/Today.scss@@ -21,6 +21,7 @@--today-ease-nudge: cubic-bezier(0.2, 0.8, 0.2, 1);--today-card-shadow: 0 1px 2px #00000008, 0 12px 32px -24px #00000059;--today-marker: #f54e00;+ --today-key-clause: rgb(29 74 255 / 75%);[theme='dark'] & {--today-ink: #f1f1ee;@@ -36,6 +37,7 @@--today-button: #f1f1ee;--today-button-text: #151515;--today-marker: #ff8a4c;+ --today-key-clause: rgb(138 164 255 / 85%);}}@@ -451,6 +453,28 @@}}+.TodayKeyClauseMark {+ padding-bottom: 0.12em;+ background-image: linear-gradient(var(--today-key-clause), var(--today-key-clause));+ background-repeat: no-repeat;+ background-position: 0 100%;+ background-size: 100% 1.5px;+ transition: background-size 0.15s var(--today-ease);+ animation: TodayKeyClauseMark__sweep 0.7s var(--today-ease-in-out) 0.5s both;++ &:hover,+ &:focus-visible,+ &[data-popup-open] {+ background-size: 100% 2.5px;+ }+}++@keyframes TodayKeyClauseMark__sweep {+ from {+ background-size: 0% 1.5px;+ }+}+.TodayPenMark__stroke {position: absolute;bottom: -0.18em;diff --git a/frontend/src/scenes/project-homepage/today/TodayEvidenceAge.tsx b/frontend/src/scenes/project-homepage/today/TodayEvidenceAge.tsxnew file mode 100644index 000000000000..a13f3cc912c6--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayEvidenceAge.tsx@@ -0,0 +1,40 @@+import { useValues } from 'kea'++import { IconWarning } from '@posthog/icons'+import { Text } from '@posthog/quill'++import { dayjs } from 'lib/dayjs'++import type { SignalReport } from 'products/signals/frontend/inbox/types'++import { daysAgo } from './todayFigureSources'+import { shortDate } from './todayProse'+import { todayReportLogic } from './todayReportLogic'++export function TodayEvidenceAge({ report }: { report: Pick<SignalReport, 'id'> }): JSX.Element | null {+ const { lastSeen, staleFiguresDate: date } = useValues(todayReportLogic({ reportId: report.id }))+ if (!date) {+ return null+ }+ const seenSince = lastSeen && dayjs(lastSeen).isAfter(date, 'day') ? lastSeen : null+ return (+ <Text+ size="xs"+ variant="muted"+ render={<p />}+ className="mt-1 flex items-center gap-1"+ data-attr="today-report-evidence-age"+ >+ <IconWarning className="size-3.5 shrink-0 text-[var(--warning-foreground)]" aria-hidden />+ <span>+ Figures as of <time dateTime={date}>{shortDate(date)}</time> ·{' '}+ <span className="font-medium text-foreground">{daysAgo(date)} days old</span>+ {seenSince && (+ <>+ {' · '}Last seen <time dateTime={seenSince}>{shortDate(seenSince)}</time>+ </>+ )}+ </span>+ </Text>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayFigureCard.tsx b/frontend/src/scenes/project-homepage/today/TodayFigureCard.tsxindex 321220adefdb..8f8c97104a8d 100644--- a/frontend/src/scenes/project-homepage/today/TodayFigureCard.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayFigureCard.tsx@@ -25,17 +25,20 @@ import { signalSourceLabel } from './todaySignalText'const PEN_DELAY_MS = 180const PEN_STAGGER_MS = 140-type QuotedContent = Extract<TodayFigureCardContent, { kind: 'signal' }>+type QuotedContent = Extract<TodayFigureCardContent, { kind: 'signal' | 'research' }>type MetricContent = Extract<TodayFigureCardContent, { kind: 'metric' }>interface QuoteSource {icon: TodayReportIconlabel: stringdate: string- signal: SignalViewApi+ signal: SignalViewApi | null}function quoteSource(content: QuotedContent): QuoteSource {+ if (content.kind === 'research') {+ return { icon: 'scout', label: 'Agent’s research', date: content.at, signal: null }+ }return {icon: sourceStyle(content.signal.source_product).icon,label: signalSourceLabel(content.signal),@@ -110,10 +113,10 @@ function FullReportLink({ reportId, children }: { reportId: string; children: st)}-function SignalAction({ signal, reportId }: { signal: SignalViewApi; reportId: string }): JSX.Element | null {+function SignalAction({ signal, reportId }: { signal: SignalViewApi | null; reportId: string }): JSX.Element | null {const { openSessionPlayer } = useActions(sessionPlayerModalLogic)- const destination = signalDestination(signal)- if (destination.kind === 'recording') {+ const destination = signal ? signalDestination(signal) : null+ if (destination?.kind === 'recording') {return (<Buttonvariant="link"@@ -127,7 +130,7 @@ function SignalAction({ signal, reportId }: { signal: SignalViewApi; reportId: s</Button>)}- if (destination.kind === 'link') {+ if (destination?.kind === 'link') {return (<CardLink to={destination.to} external={destination.external} dataAttr="today-report-figure-open">{destination.label}@@ -168,7 +171,7 @@ function QuoteCard({reportId: string}): JSX.Element {const source = quoteSource(content)- const { working } = content+ const working = content.kind === 'signal' ? content.working : undefinedconst segments = quoteSegments(content, figure).map((segment) =>source.date && !segment.marked ? { ...segment, text: anchorToday(segment.text, source.date) } : segment)diff --git a/frontend/src/scenes/project-homepage/today/TodayFigureMark.tsx b/frontend/src/scenes/project-homepage/today/TodayFigureMark.tsxindex 4a074ed17324..f30f17864a6a 100644--- a/frontend/src/scenes/project-homepage/today/TodayFigureMark.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayFigureMark.tsx@@ -6,7 +6,7 @@ import { TodayFigureCardContent } from './todayFigureSources'import { TodayHoverMark } from './TodayHoverMark'import { TodayPenMark } from './TodayPenMark'import { circlePath } from './todayPenPaths'-import { todayReportLogic } from './todayReportLogic'+import { type TodayMarkKind, todayReportLogic } from './todayReportLogic'const PEN_DELAY_MS = 250const PEN_STAGGER_MS = 160@@ -17,19 +17,21 @@ export function TodayFigureMark({content,reportId,order,+ kind,}: {children: ReactNodefigure: stringcontent: TodayFigureCardContentreportId: stringorder: number+ kind: TodayMarkKind}): JSX.Element {const { markOpened } = useActions(todayReportLogic({ reportId }))return (<TodayHoverMarkclassName="TodayFigureMark"dataAttr="today-report-figure"- onOpen={() => markOpened('impact')}+ onOpen={() => markOpened(kind)}card={<TodayFigureCard content={content} figure={figure} reportId={reportId} />}><TodayPenMark seed={figure} delayMs={PEN_DELAY_MS + order * PEN_STAGGER_MS}>diff --git a/frontend/src/scenes/project-homepage/today/TodayHoverMark.tsx b/frontend/src/scenes/project-homepage/today/TodayHoverMark.tsxindex adb9413d4e65..b60fa0aa16c5 100644--- a/frontend/src/scenes/project-homepage/today/TodayHoverMark.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayHoverMark.tsx@@ -24,7 +24,7 @@ function pointerMovedRecently(): boolean {}function cardAnchor(trigger: HTMLElement | null): Element | undefined {- return trigger?.closest('li, p') ?? undefined+ return trigger?.closest('[data-today-figures]') ?? trigger?.closest('li, p') ?? undefined}export function TodayHoverMark({diff --git a/frontend/src/scenes/project-homepage/today/TodayInlineMarkdown.tsx b/frontend/src/scenes/project-homepage/today/TodayInlineMarkdown.tsxdeleted file mode 100644index 81dc360ca984..000000000000--- a/frontend/src/scenes/project-homepage/today/TodayInlineMarkdown.tsx+++ /dev/null@@ -1,33 +0,0 @@-import { LinkPrimitive } from 'lib/lemon-ui/Link'--import { inlineSegments } from './todayProse'--export function TodayInlineMarkdown({ markdown }: { markdown: string }): JSX.Element {- return (- <>- {inlineSegments(markdown).map((segment, index) => {- switch (segment.kind) {- case 'code':- return (- <code key={index} className="text-[0.9em]">- {segment.text}- </code>- )- case 'link':- return (- <LinkPrimitive- key={index}- to={segment.href}- target="_blank"- className="underline underline-offset-2"- >- {segment.text}- </LinkPrimitive>- )- default:- return <span key={index}>{segment.text}</span>- }- })}- </>- )-}diff --git a/frontend/src/scenes/project-homepage/today/TodayKeyClauseMark.tsx b/frontend/src/scenes/project-homepage/today/TodayKeyClauseMark.tsxnew file mode 100644index 000000000000..23f5263f1d11--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayKeyClauseMark.tsx@@ -0,0 +1,70 @@+import { useActions } from 'kea'+import type { ReactNode } from 'react'++import { IconArrowRight, IconSparkles } from '@posthog/icons'+import { Button, Text } from '@posthog/quill'++import { LinkPrimitive } from 'lib/lemon-ui/Link'+import { urls } from 'scenes/urls'++import type { KeyClauseApi, KeyClauseRoleEnumApi } from 'products/today/frontend/generated/api.schemas'++import { TodayHoverMark } from './TodayHoverMark'+import { todayReportLogic } from './todayReportLogic'++const ROLE_LABEL: Record<KeyClauseRoleEnumApi, string> = {+ problem: 'The problem',+ cause: 'The cause',+ fix: 'The fix',+}++export function TodayKeyClauseMark({+ keyClause,+ reportId,+ children,+}: {+ keyClause: KeyClauseApi+ reportId: string+ children: ReactNode+}): JSX.Element {+ const { markOpened } = useActions(todayReportLogic({ reportId }))+ return (+ <TodayHoverMark+ className="TodayKeyClauseMark"+ dataAttr={`today-report-key-${keyClause.role}`}+ onOpen={() => markOpened('key_clause')}+ card={+ <div className="flex flex-col gap-2 p-3">+ <Text size="xs" variant="muted" render={<div />} className="flex items-center gap-1.5">+ <IconSparkles className="size-3.5" aria-hidden />+ <span className="font-medium text-foreground">{ROLE_LABEL[keyClause.role]}</span>+ <span aria-hidden>·</span>+ <span>AI picked this because the full report explains it further</span>+ </Text>+ <Text+ size="sm"+ render={<blockquote />}+ className="m-0 flex flex-col gap-1.5 border-l-2 border-solid ps-3 text-pretty text-foreground"+ >+ {keyClause.expansion.map((sentence) => (+ <span key={sentence}>{sentence}</span>+ ))}+ </Text>+ <Button+ variant="link"+ size="sm"+ className="self-start px-0"+ nativeButton={false}+ render={<LinkPrimitive to={urls.inboxReport('reports', reportId)} />}+ data-attr="today-report-key-full-report"+ >+ Open the full report+ <IconArrowRight />+ </Button>+ </div>+ }+ >+ {children}+ </TodayHoverMark>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayMarkedText.tsx b/frontend/src/scenes/project-homepage/today/TodayMarkedText.tsxnew file mode 100644index 000000000000..31ddc5c62e04--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/TodayMarkedText.tsx@@ -0,0 +1,65 @@+import { Fragment } from 'react'++import { LinkPrimitive } from 'lib/lemon-ui/Link'++import type { KeyClauseApi } from 'products/today/frontend/generated/api.schemas'++import { TodayFigureMark } from './TodayFigureMark'+import type { TodayMarkedFigure } from './todayFigureSources'+import { TodayKeyClauseMark } from './TodayKeyClauseMark'+import { TodayMarkedPiece, markedRuns } from './todayMarkedRuns'++function MarkedPiece({ piece, reportId }: { piece: TodayMarkedPiece; reportId: string }): JSX.Element {+ switch (piece.kind) {+ case 'code':+ return <code className="text-[0.9em]">{piece.text}</code>+ case 'link':+ return (+ <LinkPrimitive to={piece.href} target="_blank" className="underline underline-offset-2">+ {piece.text}+ </LinkPrimitive>+ )+ case 'figure':+ return (+ <TodayFigureMark+ figure={piece.figure.text}+ content={piece.figure.content}+ reportId={reportId}+ order={piece.order}+ kind="figure"+ >+ {piece.figure.text}+ </TodayFigureMark>+ )+ default:+ return <span>{piece.text}</span>+ }+}++export function TodayMarkedText({+ markdown,+ marked,+ keyClauses,+ reportId,+}: {+ markdown: string+ marked: TodayMarkedFigure[]+ keyClauses: KeyClauseApi[]+ reportId: string+}): JSX.Element {+ const runs = markedRuns(markdown, marked, keyClauses)+ return (+ <>+ {runs.map(({ keyClause, pieces }) => {+ const content = pieces.map((piece) => <MarkedPiece key={piece.key} piece={piece} reportId={reportId} />)+ return keyClause ? (+ <TodayKeyClauseMark key={pieces[0].key} keyClause={keyClause} reportId={reportId}>+ {content}+ </TodayKeyClauseMark>+ ) : (+ <Fragment key={pieces[0].key}>{content}</Fragment>+ )+ })}+ </>+ )+}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsx b/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsxindex 4e29eed57a0b..c84c28adbd12 100644--- a/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayReportAbstract.tsx@@ -5,14 +5,16 @@ import { Text } from '@posthog/quill'import { SignalReport } from 'products/signals/frontend/inbox/types'import { TodayFigureMark } from './TodayFigureMark'-import { TodayInlineMarkdown } from './TodayInlineMarkdown'import { TodayInlineTrend } from './TodayInlineTrend'+import { TodayMarkedText } from './TodayMarkedText'import { todayReportLogic } from './todayReportLogic'export function TodayReportAbstract({ report }: { report: SignalReport }): JSX.Element | null {const {impactNumbers: numbers,impactText,+ impactMarks,+ shownKeyClauses,leadStatesNumber,} = useValues(todayReportLogic({ reportId: report.id }))@@ -29,9 +31,16 @@ export function TodayReportAbstract({ report }: { report: SignalReport }): JSX.Eif (numbers.length === 0) {return (- <Text size="sm" render={<p />} className="leading-relaxed text-pretty" data-attr="today-report-abstract">- <TodayInlineMarkdown markdown={impactText} />- </Text>+ <div data-attr="today-report-abstract" data-today-figures>+ <Text size="sm" render={<p />} className="leading-relaxed text-pretty">+ <TodayMarkedText+ markdown={impactText}+ marked={impactMarks}+ keyClauses={shownKeyClauses?.impact ?? []}+ reportId={report.id}+ />+ </Text>+ </div>)}@@ -45,6 +54,7 @@ export function TodayReportAbstract({ report }: { report: SignalReport }): JSX.Econtent={number.content}reportId={report.id}order={index}+ kind="impact"><span translate="no" className="tabular-nums">{number.value}diff --git a/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsx b/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsxindex 44fcdf91937e..144cf4f2a5bf 100644--- a/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayReportHeader.tsx@@ -14,8 +14,9 @@ import { displayConventionalCommitTitle } from 'products/signals/frontend/inbox/import { TodayActionButton } from './TodayActionButton'import { itemStateLabel } from './todayBriefingItems'-import { TodayInlineMarkdown } from './TodayInlineMarkdown'+import { TodayEvidenceAge } from './TodayEvidenceAge'import { TodayReportVerdict, todayLogic } from './todayLogic'+import { TodayMarkedText } from './TodayMarkedText'import { resolveDisabledReason } from './todayNextStep'import { todayReportLogic } from './todayReportLogic'import { SAMPLE_REPORT_REASON } from './todaySampleReports'@@ -23,7 +24,9 @@ import { priorityBadgeVariant, reportSourceLine, reportTitle } from './todaySignexport function TodayReportHeader({ report }: { report: SignalReport }): JSX.Element {const { requestReportVerdict } = useActions(todayLogic)- const { lead, reportState, isSample } = useValues(todayReportLogic({ reportId: report.id }))+ const { lead, leadMarks, shownKeyClauses, reportState, isSample } = useValues(+ todayReportLogic({ reportId: report.id })+ )const sampleReason = isSample ? SAMPLE_REPORT_REASON : nullconst stateLabel = itemStateLabel({ state: reportState })const sources = reportSourceLine(report)@@ -109,15 +112,23 @@ export function TodayReportHeader({ report }: { report: SignalReport }): JSX.Ele{capitalizeFirstLetter(displayConventionalCommitTitle(report.title, 'Untitled report'))}</Heading>{lead && (- <Text size="sm" render={<p />} className="leading-relaxed text-pretty">- <TodayInlineMarkdown markdown={lead} />- </Text>+ <div data-today-figures>+ <Text size="sm" render={<p />} className="leading-relaxed text-pretty">+ <TodayMarkedText+ markdown={lead}+ marked={leadMarks}+ keyClauses={shownKeyClauses?.lead ?? []}+ reportId={report.id}+ />+ </Text>+ </div>)}{stillInvestigating && (<Text variant="muted" render={<p />}>No summary yet. An agent is still investigating.</Text>)}+ <TodayEvidenceAge report={report} /></div></header>)diff --git a/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsx b/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsxindex 5dc9135a4cc3..9e7ca73a04b2 100644--- a/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsx+++ b/frontend/src/scenes/project-homepage/today/TodayReportProposal.tsx@@ -2,18 +2,23 @@ import { useValues } from 'kea'import { Text } from '@posthog/quill'-import { TodayInlineMarkdown } from './TodayInlineMarkdown'+import { TodayMarkedText } from './TodayMarkedText'import { todayReportLogic } from './todayReportLogic'import { TodayReportSectionTitle } from './TodayReportSectionTitle'export function TodayReportProposal({ reportId }: { reportId: string }): JSX.Element {- const { proposal } = useValues(todayReportLogic({ reportId }))+ const { proposal, shownKeyClauses } = useValues(todayReportLogic({ reportId }))return (<div className="flex flex-col gap-2"><TodayReportSectionTitle>Proposal</TodayReportSectionTitle>{proposal ? (<Text size="sm" render={<p />} className="leading-relaxed text-pretty">- <TodayInlineMarkdown markdown={proposal} />+ <TodayMarkedText+ markdown={proposal}+ marked={[]}+ keyClauses={shownKeyClauses?.proposal ?? []}+ reportId={reportId}+ /></Text>) : (<Text size="sm" variant="muted" render={<p />}>diff --git a/frontend/src/scenes/project-homepage/today/todayFigureSources.test.ts b/frontend/src/scenes/project-homepage/today/todayFigureSources.test.tsindex 711a99b6a126..ad6c28cb13ec 100644--- a/frontend/src/scenes/project-homepage/today/todayFigureSources.test.ts+++ b/frontend/src/scenes/project-homepage/today/todayFigureSources.test.ts@@ -1,6 +1,29 @@import { dayjs } from 'lib/dayjs'-import { anchorToday } from './todayFigureSources'+import type { FigureMarkApi } from 'products/today/frontend/generated/api.schemas'++import { anchorToday, markedFigures } from './todayFigureSources'+import { signal } from './todayTestFixtures'++const LEAD = 'Since `syncCart` shipped, [checkout](https://example.com) fails for 212 users.'+const SHOWN = 'Since syncCart shipped, checkout fails for 212 users.'++function mark(figure: string, at: number): FigureMarkApi {+ return {+ text: 'lead',+ start: at,+ end: at + figure.length,+ figure,+ quote: {+ kind: 'signal',+ signal: signal({ signal_id: 'carts' }),+ at: '2026-10-01T10:00:00Z',+ sentence: 'Checkout failed for 212 users.',+ start: 20,+ end: 23,+ },+ }+}describe('todayFigureSources', () => {test.each([@@ -14,4 +37,13 @@ describe('todayFigureSources', () => {])('dates "today" in %s', (_, date, text, expected) => {expect(anchorToday(text, date, dayjs('2026-10-03T12:00:00Z'))).toEqual(expected)})++ test.each([+ ['a number after code and a link', mark('212', SHOWN.indexOf('212')), [[SHOWN.indexOf('212'), '212']]],+ ['no number where the page text differs', mark('212', SHOWN.indexOf('212') + 1), []],+ ['no number inside code', mark('Cart', SHOWN.indexOf('Cart')), []],+ ])('places %s', (_, figureMark, expected) => {+ const placed = markedFigures(LEAD, [figureMark])+ expect(placed.map((figure) => [figure.start, figure.text])).toEqual(expected)+ })})diff --git a/frontend/src/scenes/project-homepage/today/todayFigureSources.ts b/frontend/src/scenes/project-homepage/today/todayFigureSources.tsindex 4122bf222dba..ea20ef786fda 100644--- a/frontend/src/scenes/project-homepage/today/todayFigureSources.ts+++ b/frontend/src/scenes/project-homepage/today/todayFigureSources.ts@@ -1,12 +1,19 @@import { Dayjs, dayjs } from 'lib/dayjs'+import { isNotNil } from 'lib/utils/guards'-import type { SignalViewApi } from 'products/today/frontend/generated/api.schemas'+import type { FigureMarkApi, FigureQuoteApi, SignalViewApi } from 'products/today/frontend/generated/api.schemas'-import { shortDate } from './todayProse'+import { inlineSegments, shortDate } from './todayProse'++interface TodayTextSpan {+ start: number+ end: number+}export interface TodayQuotedText {excerpt: stringvalues?: string[]+ highlight?: TodayTextSpan}export type TodayFigureCardContent =@@ -15,6 +22,7 @@ export type TodayFigureCardContent =signal: SignalViewApiworking?: { expression: string; result: string }} & TodayQuotedText)+ | ({ kind: 'research'; at: string } & TodayQuotedText)| {kind: 'metric'total: string@@ -28,10 +36,63 @@ export type TodayFigureCardContent =}| { kind: 'none' }-function daysAgo(date: string, now: Dayjs = dayjs()): number {+export interface TodayMarkedFigure extends TodayTextSpan {+ text: string+ content: TodayFigureCardContent+}++function quoteContent(quote: FigureQuoteApi): TodayFigureCardContent | null {+ const quoted = { excerpt: quote.sentence, highlight: { start: quote.start, end: quote.end } }+ if (quote.kind === 'research') {+ return { kind: 'research', at: quote.at, ...quoted }+ }+ return quote.signal ? { kind: 'signal', signal: quote.signal, ...quoted } : null+}++export function markedFigures(markdown: string, marks: FigureMarkApi[]): TodayMarkedFigure[] {+ let offset = 0+ const prose = inlineSegments(markdown).flatMap((segment) => {+ const start = offset+ offset += segment.text.length+ return segment.kind === 'text' ? [{ start, text: segment.text }] : []+ })+ return marks.flatMap((mark) => {+ const segment = prose.find(+ (candidate) => candidate.start <= mark.start && mark.end <= candidate.start + candidate.text.length+ )+ const content = quoteContent(mark.quote)+ const placed =+ segment?.text.slice(mark.start - segment.start, mark.end - segment.start) === mark.figure && content+ return placed ? [{ start: mark.start, end: mark.end, text: mark.figure, content }] : []+ })+}++const STALE_AFTER_DAYS = 7++export function daysAgo(date: string, now: Dayjs = dayjs()): number {return now.startOf('day').diff(dayjs(date).startOf('day'), 'day')}+function sourceDate(content: TodayFigureCardContent): string | null {+ switch (content.kind) {+ case 'research':+ return content.at+ case 'signal':+ return content.signal.timestamp+ default:+ return null+ }+}++export function staleEvidenceDate(figures: TodayMarkedFigure[], now: Dayjs = dayjs()): string | null {+ const newest = figures+ .map((figure) => sourceDate(figure.content))+ .filter(isNotNil)+ .sort()+ .at(-1)+ return newest && daysAgo(newest, now) > STALE_AFTER_DAYS ? newest : null+}+export function anchorToday(text: string, date: string, now: Dayjs = dayjs()): string {return daysAgo(date, now) > 0 ? text.replace(/\btoday\b/gi, (word) => `${word} [${shortDate(date)}]`) : text}diff --git a/frontend/src/scenes/project-homepage/today/todayFigures.test.ts b/frontend/src/scenes/project-homepage/today/todayFigures.test.tsindex 0dbf104ab3a5..870b85b6f72a 100644--- a/frontend/src/scenes/project-homepage/today/todayFigures.test.ts+++ b/frontend/src/scenes/project-homepage/today/todayFigures.test.ts@@ -1,4 +1,4 @@-import { highlightSegments } from './todayFigures'+import { highlightSegments, quoteSegments } from './todayFigures'describe('todayFigures', () => {test.each([@@ -20,4 +20,13 @@ describe('todayFigures', () => {expect(segments.filter((segment) => segment.marked).map((segment) => segment.text)).toEqual(expected)expect(segments.map((segment) => segment.text).join('')).toEqual(text)})++ test('emphasizes the exact number a source states when its value repeats', () => {+ const quote = { excerpt: '4 events came from 4 issues.', highlight: { start: 19, end: 20 } }+ expect(quoteSegments(quote, '4')).toEqual([+ { text: '4 events came from ', marked: false },+ { text: '4', marked: true },+ { text: ' issues.', marked: false },+ ])+ })})diff --git a/frontend/src/scenes/project-homepage/today/todayFigures.ts b/frontend/src/scenes/project-homepage/today/todayFigures.tsindex 871abba743d8..c2773ed5ee43 100644--- a/frontend/src/scenes/project-homepage/today/todayFigures.ts+++ b/frontend/src/scenes/project-homepage/today/todayFigures.ts@@ -58,5 +58,13 @@ export function highlightSegments(text: string, values: string[]): TodayQuoteSeg}export function quoteSegments(quote: TodayQuotedText, figure: string): TodayQuoteSegment[] {- return highlightSegments(quote.excerpt, quote.values ?? [figure])+ const { excerpt, highlight } = quote+ if (!highlight) {+ return highlightSegments(excerpt, quote.values ?? [figure])+ }+ return [+ { text: excerpt.slice(0, highlight.start), marked: false },+ { text: excerpt.slice(highlight.start, highlight.end), marked: true },+ { text: excerpt.slice(highlight.end), marked: false },+ ].filter((segment) => segment.text)}diff --git a/frontend/src/scenes/project-homepage/today/todayMarkedRuns.test.ts b/frontend/src/scenes/project-homepage/today/todayMarkedRuns.test.tsnew file mode 100644index 000000000000..1f07483a5f08--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayMarkedRuns.test.ts@@ -0,0 +1,84 @@+import type { KeyClauseApi, KeyClauseRoleEnumApi } from 'products/today/frontend/generated/api.schemas'++import type { TodayMarkedFigure } from './todayFigureSources'+import { TodayMarkedPiece, markedRuns } from './todayMarkedRuns'+import { renderedText } from './todayProse'++function figureIn(markdown: string, text: string): TodayMarkedFigure {+ const start = renderedText(markdown).indexOf(text)+ return { start, end: start + text.length, text, content: { kind: 'none' } }+}++function keyClausesIn(markdown: string, picks: [KeyClauseRoleEnumApi, string][]): KeyClauseApi[] {+ const shown = renderedText(markdown)+ return picks.map(([role, text]) => ({+ start: shown.indexOf(text),+ end: shown.indexOf(text) + text.length,+ role,+ expansion: ['The report explains it.'],+ }))+}++function described(piece: TodayMarkedPiece): [string, string] {+ if (piece.kind === 'figure') {+ return ['figure', piece.figure.text]+ }+ return [piece.kind, piece.text]+}++describe('todayMarkedRuns', () => {+ test.each([+ [+ 'a figure, code and a link inside key clauses',+ 'Shoppers in 41 teams see an empty cart because `syncCart` drops the [session token](https://example.com/token).',+ [+ ['problem', 'Shoppers in 41 teams see an empty cart'],+ ['cause', 'because syncCart drops the session token'],+ ] as [KeyClauseRoleEnumApi, string][],+ [+ ['problem', [['text', 'Shoppers in ']]],+ [null, [['figure', '41']]],+ ['problem', [['text', ' teams see an empty cart']]],+ [null, [['text', ' ']]],+ [+ 'cause',+ [+ ['text', 'because '],+ ['code', 'syncCart'],+ ['text', ' drops the '],+ ['link', 'session token'],+ ],+ ],+ [null, [['text', '.']]],+ ],+ ],+ [+ 'a key clause that starts inside code',+ 'Payments fail for 41 teams in `retryCart because the queue stalls` at peak.',+ [['cause', 'because the queue stalls at peak']] as [KeyClauseRoleEnumApi, string][],+ [+ [+ null,+ [+ ['text', 'Payments fail for '],+ ['figure', '41'],+ ['text', ' teams in '],+ ['code', 'retryCart '],+ ],+ ],+ [+ 'cause',+ [+ ['code', 'because the queue stalls'],+ ['text', ' at peak'],+ ],+ ],+ [null, [['text', '.']]],+ ],+ ],+ ])('places the pieces of %s', (_, markdown, picks, expected) => {+ const keyClauses = keyClausesIn(markdown, picks)+ const runs = markedRuns(markdown, [figureIn(markdown, '41')], keyClauses)+ expect(runs.map((run) => [run.keyClause?.role ?? null, run.pieces.map(described)])).toEqual(expected)+ })+})diff --git a/frontend/src/scenes/project-homepage/today/todayMarkedRuns.ts b/frontend/src/scenes/project-homepage/today/todayMarkedRuns.tsnew file mode 100644index 000000000000..3d830570ddac--- /dev/null+++ b/frontend/src/scenes/project-homepage/today/todayMarkedRuns.ts@@ -0,0 +1,79 @@+import type { KeyClauseApi } from 'products/today/frontend/generated/api.schemas'++import type { TodayMarkedFigure } from './todayFigureSources'+import { type TodayInlineSegment, inlineSegments } from './todayProse'++export type TodayMarkedPiece =+ | { kind: 'text' | 'code'; key: string; text: string }+ | { kind: 'link'; key: string; text: string; href: string }+ | { kind: 'figure'; key: string; figure: TodayMarkedFigure; order: number }++interface TodayMarkedRun {+ keyClause: KeyClauseApi | null+ pieces: TodayMarkedPiece[]+}++interface PlacedPiece {+ piece: TodayMarkedPiece+ from: number+ to: number+}++function segmentPieces(+ segment: TodayInlineSegment,+ index: number,+ from: number,+ figures: TodayMarkedFigure[],+ keyClauses: KeyClauseApi[]+): PlacedPiece[] {+ const to = from + segment.text.length+ const own = segment.kind === 'text' ? figures.filter((figure) => from <= figure.start && figure.end <= to) : []+ const insideFigure = (point: number): boolean => own.some((figure) => point > figure.start && point < figure.end)+ const cuts = [+ ...own.flatMap((figure) => [figure.start, figure.end]),+ ...keyClauses.flatMap((keyClause) => [keyClause.start, keyClause.end]).filter((point) => !insideFigure(point)),+ ].filter((point) => point > from && point < to)+ const points = [...new Set([from, to, ...cuts])].sort((first, second) => first - second)+ return points.slice(0, -1).map((start, position) => {+ const end = points[position + 1]+ const key = `${index}-${start - from}`+ const text = segment.text.slice(start - from, end - from)+ const figure = own.find((candidate) => candidate.start === start)+ const piece: TodayMarkedPiece = figure+ ? { kind: 'figure', key, figure, order: figures.indexOf(figure) }+ : segment.kind === 'link'+ ? { kind: 'link', key, text, href: segment.href }+ : { kind: segment.kind, key, text }+ return { piece, from: start, to: end }+ })+}++function placedPieces(markdown: string, figures: TodayMarkedFigure[], keyClauses: KeyClauseApi[]): PlacedPiece[] {+ let offset = 0+ return inlineSegments(markdown).flatMap((segment, index) => {+ const from = offset+ offset += segment.text.length+ return segmentPieces(segment, index, from, figures, keyClauses)+ })+}++export function markedRuns(+ markdown: string,+ figures: TodayMarkedFigure[],+ keyClauses: KeyClauseApi[]+): TodayMarkedRun[] {+ const runs: TodayMarkedRun[] = []+ for (const { piece, from, to } of placedPieces(markdown, figures, keyClauses)) {+ const keyClause =+ piece.kind === 'figure'+ ? null+ : (keyClauses.find((candidate) => from >= candidate.start && to <= candidate.end) ?? null)+ const last = runs[runs.length - 1]+ if (last && last.keyClause === keyClause) {+ last.pieces.push(piece)+ } else {+ runs.push({ keyClause, pieces: [piece] })+ }+ }+ return runs+}diff --git a/frontend/src/scenes/project-homepage/today/todayProse.ts b/frontend/src/scenes/project-homepage/today/todayProse.tsindex 9393cd016bdb..fa2f956bad66 100644--- a/frontend/src/scenes/project-homepage/today/todayProse.ts+++ b/frontend/src/scenes/project-homepage/today/todayProse.ts@@ -21,7 +21,7 @@ function readableDates(text: string): string {return text.replace(ISO_DATE, readableDate)}-type TodayInlineSegment = { kind: 'text' | 'code'; text: string } | { kind: 'link'; text: string; href: string }+export type TodayInlineSegment = { kind: 'text' | 'code'; text: string } | { kind: 'link'; text: string; href: string }interface MarkdownNode {type: stringdiff --git a/frontend/src/scenes/project-homepage/today/todayQuotedCode.test.ts b/frontend/src/scenes/project-homepage/today/todayQuotedCode.test.tsindex 54e09788e1b9..0540449eab49 100644--- a/frontend/src/scenes/project-homepage/today/todayQuotedCode.test.ts+++ b/frontend/src/scenes/project-homepage/today/todayQuotedCode.test.ts@@ -97,4 +97,14 @@ describe('todayQuotedCode', () => {const chosen = findCodeQuote([OWN, SIBLING], reads, ['CARDS_MAX = 120'])expect(chosen?.file.path.split('/').pop() ?? null).toEqual(expected)})++ test('offers the excerpts of every file that holds the quote, taking turns between files', () => {+ const twice = read(OWN.path, ['export const CARDS_MAX = 120', ...Array(12).fill(''), 'use(CARDS_MAX)'])+ const quote = findCodeQuote([OWN, SIBLING], [twice, SIBLING_READ], ['CARDS_MAX'])+ expect(quote?.candidates.map((candidate) => [candidate.file, candidate.excerpt.startLine])).toEqual([+ [OWN, 1],+ [SIBLING, 1],+ [OWN, 14],+ ])+ })})diff --git a/frontend/src/scenes/project-homepage/today/todayQuotedCode.ts b/frontend/src/scenes/project-homepage/today/todayQuotedCode.tsindex e073b7418e41..3ffe8ddd6ff9 100644--- a/frontend/src/scenes/project-homepage/today/todayQuotedCode.ts+++ b/frontend/src/scenes/project-homepage/today/todayQuotedCode.ts@@ -114,12 +114,16 @@ export function codeExcerptCandidates(return excerpts}-export interface TodayCodeQuote {+export interface TodayCodeCandidate {file: CodeFileApiread: RepositoryFileApiexcerpt: TodayCodeWindow}+export interface TodayCodeQuote extends TodayCodeCandidate {+ candidates: TodayCodeCandidate[]+}+function distinctMarked(excerpt: TodayCodeWindow): number {return new Set(excerpt.marks.map((mark) => excerpt.lines[mark.line].slice(mark.start, mark.end))).size}@@ -129,15 +133,22 @@ export function findCodeQuote(reads: (RepositoryFileApi | null)[],identifiers: string[]): TodayCodeQuote | null {- let best: TodayCodeQuote | null = null- for (const [index, file] of files.entries()) {- const read = reads[index]- const candidates = read ? codeExcerptCandidates(read.content, identifiers) : []- const excerpt = candidates[0]- const marksMore = !best || (excerpt && distinctMarked(excerpt) > distinctMarked(best.excerpt))- if (read && excerpt && marksMore) {- best = { file, read, excerpt }- }+ const perFile = files+ .map((file, index): TodayCodeCandidate[] => {+ const read = reads[index]+ return read+ ? codeExcerptCandidates(read.content, identifiers).map((excerpt) => ({ file, read, excerpt }))+ : []+ })+ .filter((candidates) => candidates.length > 0)+ if (!perFile.length) {+ return null}- return best+ const best = perFile.reduce((chosen, candidates) =>+ distinctMarked(candidates[0].excerpt) > distinctMarked(chosen[0].excerpt) ? candidates : chosen+ )+ const ordered = [best, ...perFile.filter((own) => own !== best)]+ const depth = Math.max(...ordered.map((own) => own.length))+ const candidates = Array.from({ length: depth }, (_, rank) => ordered.flatMap((own) => own[rank] ?? []))+ return { ...best[0], candidates: candidates.flat() }}diff --git a/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts b/frontend/src/scenes/project-homepage/today/todayReportLogic.test.tsindex ab545ebd4772..b935d3c64c62 100644--- a/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts+++ b/frontend/src/scenes/project-homepage/today/todayReportLogic.test.ts@@ -1,5 +1,8 @@import { expectLogic } from 'kea-test-utils'+import { FEATURE_FLAGS } from 'lib/constants'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { useMocks } from '~/mocks/jest'import { initKeaTests } from '~/test/init'@@ -61,4 +64,42 @@ describe('todayReportLogic', () => {).toNotHaveDispatchedActions([other])})++ test('asks Jev once per mark while a request is in flight and hides the marks when the flag turns off', async () => {+ const report = makeReport({ actionability: 'immediately_actionable', status: SignalReportStatus.READY })+ const calls = { keyClauses: 0, figureMarks: 0 }+ useMocks({+ get: {+ '/api/projects/:team_id/signals/reports/:id/': () => [200, report],+ '/api/projects/:team_id/today/reports/:id/page/': () => [200, PAGE],+ '/api/projects/:team_id/today/reports/:id/figure_marks/': () => {+ calls.figureMarks += 1+ return [200, { marks: [] }]+ },+ '/api/projects/:team_id/today/reports/:id/key_clauses/': () => {+ calls.keyClauses += 1+ return [200, { lead: [], impact: [], proposal: [] }]+ },+ },+ })+ initKeaTests()+ featureFlagLogic.mount()+ const logic = todayReportLogic({ reportId: report.id })+ logic.mount()+ await expectLogic(logic).toDispatchActions(['loadFullReportSuccess', 'loadPageSuccess'])++ featureFlagLogic.actions.setFeatureFlags([FEATURE_FLAGS.TODAY_REPORT_JEV], {+ [FEATURE_FLAGS.TODAY_REPORT_JEV]: true,+ })+ logic.actions.loadKeyClauses()+ logic.actions.loadFigureMarks()+ await expectLogic(logic).toFinishAllListeners()++ expect(calls).toEqual({ keyClauses: 1, figureMarks: 1 })+ expect(logic.values.shownKeyClauses).toEqual(logic.values.keyClauses)++ featureFlagLogic.actions.setFeatureFlags([], {})+ expect(logic.values.shownKeyClauses).toBeNull()+ expect(logic.values.shownFigureMarks).toBeNull()+ })})diff --git a/frontend/src/scenes/project-homepage/today/todayReportLogic.ts b/frontend/src/scenes/project-homepage/today/todayReportLogic.tsindex eb638db2d495..898dd7802281 100644--- a/frontend/src/scenes/project-homepage/today/todayReportLogic.ts+++ b/frontend/src/scenes/project-homepage/today/todayReportLogic.ts@@ -3,6 +3,8 @@ import { loaders } from 'kea-loaders'import posthog from 'posthog-js'import api from 'lib/api'+import { FEATURE_FLAGS } from 'lib/constants'+import { FeatureFlagsSet, featureFlagLogic } from 'lib/logic/featureFlagLogic'import { addProjectIdIfMissing } from 'lib/utils/kea-router'import { teamLogic } from 'scenes/teamLogic'import { urls } from 'scenes/urls'@@ -12,16 +14,30 @@ import type { RepositoryFileApi } from 'products/business_knowledge/frontend/genimport { captureInboxReportAction, discussQuestionProperties } from 'products/signals/frontend/inbox/inboxAnalytics'import { inboxTaskKickoffLogic } from 'products/signals/frontend/inbox/inboxTaskKickoffLogic'import { SignalReport } from 'products/signals/frontend/inbox/types'-import { todayReportsPageRetrieve } from 'products/today/frontend/generated/api'+import {+ todayExcerptChoiceCreate,+ todayReportsFigureMarksRetrieve,+ todayReportsKeyClausesRetrieve,+ todayReportsPageRetrieve,+} from 'products/today/frontend/generated/api'import type {BriefingItemStateEnumApi,CodeFileApi,+ FigureMarkApi,+ FigureTextEnumApi,+ ReportKeyClausesApi,ReportPageApi,SignalViewApi,} from 'products/today/frontend/generated/api.schemas'+import {+ todayExcerptChoiceCreateBodyExcerptsItemMax,+ todayExcerptChoiceCreateBodyExcerptsMax,+ todayExcerptChoiceCreateBodyFindingMax,+} from 'products/today/frontend/generated/api.zod'import { reportItemState } from './todayBriefingItems'import { type TodaySignalDestination } from './todayEvidence'+import { type TodayMarkedFigure, markedFigures, staleEvidenceDate } from './todayFigureSources'import { TodayImpactNumber, impactNumbers } from './todayImpact'import { type TodayAskSource, todayLogic } from './todayLogic'import { reportWorkKind, reportWorkPrompt } from './todayNextStep'@@ -30,21 +46,27 @@ import { TodayCodeQuote, codeIdentifiers, findCodeQuote } from './todayQuotedCodimport { findSampleReport, isSampleReportId } from './todaySampleReports'export type TodayCodeQuoteState = TodayCodeQuote | null | 'loading'-export type TodayMarkKind = 'impact'+export type TodayMarkKind = 'impact' | 'figure' | 'key_clause'const INVESTIGATE_QUESTION = 'Investigate this report. Confirm the problem and find the root cause.'+function marksIn(figureMarks: FigureMarkApi[] | null, text: FigureTextEnumApi): FigureMarkApi[] {+ return (figureMarks ?? []).filter((mark) => mark.text === text)+}+export interface TodayReportLogicProps {reportId: string}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface todayReportLogicValues {+ featureFlags: FeatureFlagsSet // featureFlagLogiccurrentProjectId: number | string // teamLogiccurrentTeamId: number | null // teamLogicaskingAi: boolean // todayLogicreportStateOverrides: Record<string, BriefingItemStateEnumApi> // todayLogicreports: SignalReport[] // todayLogic+ asksJev: booleancodeQuotes: Record<string, TodayCodeQuoteState>composerOpen: booleancurrentReport: SignalReport | null@@ -52,12 +74,19 @@ export interface todayReportLogicValues {evidenceCount: numberexpandedEvidence: Record<string, boolean>feedbackNoteFocused: boolean+ figureMarks: FigureMarkApi[] | null+ figureMarksLoading: booleanfullReport: SignalReport | nullfullReportLoading: boolean+ impactMarks: TodayMarkedFigure[]impactNumbers: TodayImpactNumber[]impactText: stringisSample: boolean+ keyClauses: ReportKeyClausesApi | null+ keyClausesLoading: boolean+ lastSeen: string | nulllead: string+ leadMarks: TodayMarkedFigure[]leadStatesNumber: booleanpage: ReportPageApi | nullpageLoading: boolean@@ -66,6 +95,9 @@ export interface todayReportLogicValues {reportState: BriefingItemStateEnumApireportUrl: stringshownEvidence: SignalViewApi[]+ shownFigureMarks: FigureMarkApi[] | null+ shownKeyClauses: ReportKeyClausesApi | null+ staleFiguresDate: string | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.@@ -112,6 +144,9 @@ export interface todayReportLogicActions {codeQuoteCleared: (signalId: string) => {signalId: string}+ codeQuotePicksCleared: () => {+ value: true+ }codeQuoteRead: (signalId: string,quote: TodayCodeQuoteState@@ -135,6 +170,21 @@ export interface todayReportLogicActions {focusFeedbackNote: () => {value: true}+ loadFigureMarks: () => any+ loadFigureMarksFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadFigureMarksSuccess: (+ figureMarks: FigureMarkApi[] | null,+ payload?: any+ ) => {+ figureMarks: FigureMarkApi[] | null+ payload?: any+ }loadFullReport: () => anyloadFullReportFailure: (error: string,@@ -150,6 +200,21 @@ export interface todayReportLogicActions {fullReport: SignalReportpayload?: any}+ loadKeyClauses: () => any+ loadKeyClausesFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadKeyClausesSuccess: (+ keyClauses: ReportKeyClausesApi | null,+ payload?: any+ ) => {+ keyClauses: ReportKeyClausesApi | null+ payload?: any+ }loadPage: () => anyloadPageFailure: (error: string,@@ -166,7 +231,7 @@ export interface todayReportLogicActions {payload?: any}markOpened: (kind: TodayMarkKind) => {- kind: 'impact'+ kind: TodayMarkKind}openComposer: () => {value: true@@ -198,14 +263,21 @@ export interface todayReportLogicMeta {lead: (page: ReportPageApi | null) => stringshownEvidence: (page: ReportPageApi | null) => SignalViewApi[]evidenceCount: (page: ReportPageApi | null) => number+ lastSeen: (page: ReportPageApi | null) => string | nullimpactNumbers: (currentReport: SignalReport | null, page: ReportPageApi | null) => TodayImpactNumber[]reportState: (currentReport: SignalReport | null,reportStateOverrides: Record<string, BriefingItemStateEnumApi>) => BriefingItemStateEnumApiisSample: (reportId: string) => boolean+ asksJev: (featureFlags: FeatureFlagsSet, isSample: boolean) => booleanproposal: (page: ReportPageApi | null) => stringimpactText: (page: ReportPageApi | null, impactNumbers: TodayImpactNumber[]) => string+ shownFigureMarks: (asksJev: boolean, figureMarks: FigureMarkApi[] | null) => FigureMarkApi[] | null+ shownKeyClauses: (asksJev: boolean, keyClauses: ReportKeyClausesApi | null) => ReportKeyClausesApi | null+ leadMarks: (lead: string, shownFigureMarks: FigureMarkApi[] | null) => TodayMarkedFigure[]+ impactMarks: (impactText: string, shownFigureMarks: FigureMarkApi[] | null) => TodayMarkedFigure[]+ staleFiguresDate: (leadMarks: TodayMarkedFigure[], impactMarks: TodayMarkedFigure[]) => string | nullleadStatesNumber: (lead: string) => booleanreportUrl: (currentTeamId: number | null) => string}@@ -228,6 +300,8 @@ export const todayReportLogic = kea<todayReportLogicType>([['currentTeamId', 'currentProjectId'],todayLogic,['reports', 'reportStateOverrides', 'askingAi'],+ featureFlagLogic,+ ['featureFlags'],],actions: [todayLogic,@@ -244,6 +318,7 @@ export const todayReportLogic = kea<todayReportLogicType>([readCode: (signal: SignalViewApi, files: CodeFileApi[]) => ({ signal, files }),codeQuoteRead: (signalId: string, quote: TodayCodeQuoteState) => ({ signalId, quote }),codeQuoteCleared: (signalId: string) => ({ signalId }),+ codeQuotePicksCleared: true,askAboutReport: (question: string) => ({ question }),expandEvidence: (signalId: string) => ({ signalId }),collapseEvidence: (signalId: string) => ({ signalId }),@@ -253,7 +328,7 @@ export const todayReportLogic = kea<todayReportLogicType>([startWithPostHog: true,markOpened: (kind: TodayMarkKind) => ({ kind }),}),- loaders(({ props, values }) => ({+ loaders(({ props, values, cache }) => ({fullReport: [null as SignalReport | null,{@@ -277,6 +352,46 @@ export const todayReportLogic = kea<todayReportLogicType>([await todayReportsPageRetrieve(String(values.currentProjectId), props.reportId),},],+ figureMarks: [+ null as FigureMarkApi[] | null,+ {+ loadFigureMarks: async (): Promise<FigureMarkApi[] | null> => {+ if (!values.asksJev) {+ return values.figureMarks+ }+ cache.figureMarks ??= todayReportsFigureMarksRetrieve(+ String(values.currentProjectId),+ props.reportId+ ).then(+ ({ marks }) => marks,+ (): FigureMarkApi[] => {+ cache.figureMarks = null+ return []+ }+ )+ return await cache.figureMarks+ },+ },+ ],+ keyClauses: [+ null as ReportKeyClausesApi | null,+ {+ loadKeyClauses: async (): Promise<ReportKeyClausesApi | null> => {+ if (!values.asksJev || !values.fullReport || !values.page) {+ return values.keyClauses+ }+ cache.keyClauses ??= todayReportsKeyClausesRetrieve(+ String(values.currentProjectId),+ props.reportId,+ { include_impact: !!values.impactText }+ ).catch((): null => {+ cache.keyClauses = null+ return null+ })+ return await cache.keyClauses+ },+ },+ ],})),reducers({reportFailed: [@@ -296,6 +411,13 @@ export const todayReportLogic = kea<todayReportLogicType>([const { [signalId]: _, ...rest } = statereturn rest},+ codeQuotePicksCleared: (state) =>+ Object.fromEntries(+ Object.entries(state).map(([signalId, quote]) => [+ signalId,+ quote && quote !== 'loading' ? { ...quote, ...quote.candidates[0] } : quote,+ ])+ ),},],expandedEvidence: [@@ -326,6 +448,7 @@ export const todayReportLogic = kea<todayReportLogicType>([lead: [(s) => [s.page], (page: ReportPageApi | null): string => page?.lead ?? ''],shownEvidence: [(s) => [s.page], (page: ReportPageApi | null): SignalViewApi[] => page?.evidence ?? []],evidenceCount: [(s) => [s.page], (page: ReportPageApi | null): number => page?.source_count ?? 0],+ lastSeen: [(s) => [s.page], (page: ReportPageApi | null): string | null => page?.last_seen ?? null],impactNumbers: [(s) => [s.currentReport, s.page],(currentReport: SignalReport | null, page: ReportPageApi | null): TodayImpactNumber[] =>@@ -342,12 +465,42 @@ export const todayReportLogic = kea<todayReportLogicType>([(currentReport ? reportItemState(currentReport.status) : 'open'),],isSample: [(_, p) => [p.reportId], (reportId: string): boolean => isSampleReportId(reportId)],+ asksJev: [+ (s) => [s.featureFlags, s.isSample],+ (featureFlags: FeatureFlagsSet, isSample: boolean): boolean =>+ !!featureFlags[FEATURE_FLAGS.TODAY_REPORT_JEV] && !isSample,+ ],proposal: [(s) => [s.page], (page: ReportPageApi | null): string => page?.proposal ?? ''],impactText: [(s) => [s.page, s.impactNumbers],(page: ReportPageApi | null, impactNumbers: TodayImpactNumber[]): string =>impactNumbers.length ? '' : (page?.impact_sentence ?? ''),],+ shownFigureMarks: [+ (s) => [s.asksJev, s.figureMarks],+ (asksJev: boolean, figureMarks: FigureMarkApi[] | null): FigureMarkApi[] | null =>+ asksJev ? figureMarks : null,+ ],+ shownKeyClauses: [+ (s) => [s.asksJev, s.keyClauses],+ (asksJev: boolean, keyClauses: ReportKeyClausesApi | null): ReportKeyClausesApi | null =>+ asksJev ? keyClauses : null,+ ],+ leadMarks: [+ (s) => [s.lead, s.shownFigureMarks],+ (lead: string, figureMarks: FigureMarkApi[] | null): TodayMarkedFigure[] =>+ markedFigures(lead, marksIn(figureMarks, 'lead')),+ ],+ impactMarks: [+ (s) => [s.impactText, s.shownFigureMarks],+ (impactText: string, figureMarks: FigureMarkApi[] | null): TodayMarkedFigure[] =>+ markedFigures(impactText, marksIn(figureMarks, 'impact')),+ ],+ staleFiguresDate: [+ (s) => [s.leadMarks, s.impactMarks],+ (leadMarks: TodayMarkedFigure[], impactMarks: TodayMarkedFigure[]): string | null =>+ staleEvidenceDate([...leadMarks, ...impactMarks]),+ ],leadStatesNumber: [(s) => [s.lead], (lead: string): boolean => /\d/.test(renderedText(lead))],reportUrl: [(s) => [s.currentTeamId],@@ -377,6 +530,18 @@ export const todayReportLogic = kea<todayReportLogicType>([return cache.fileReads.get(key)}return {+ loadFullReportSuccess: () => actions.loadKeyClauses(),+ loadPageSuccess: () => {+ actions.loadKeyClauses()+ actions.loadFigureMarks()+ },+ [featureFlagLogic.actionTypes.setFeatureFlags]: () => {+ actions.loadKeyClauses()+ actions.loadFigureMarks()+ if (!values.asksJev) {+ actions.codeQuotePicksCleared()+ }+ },readCode: async ({ signal, files }) => {if (signal.signal_id in values.codeQuotes) {return@@ -388,7 +553,20 @@ export const todayReportLogic = kea<todayReportLogicType>([actions.codeQuoteCleared(signal.signal_id)return}- actions.codeQuoteRead(signal.signal_id, quote)+ if (!quote || quote.candidates.length < 2 || !values.asksJev) {+ actions.codeQuoteRead(signal.signal_id, quote)+ return+ }+ const choices = quote.candidates.slice(0, todayExcerptChoiceCreateBodyExcerptsMax)+ const excerpts = choices.map((candidate) =>+ candidate.excerpt.lines.join('\n').slice(0, todayExcerptChoiceCreateBodyExcerptsItemMax)+ )+ const { index: pick } = await todayExcerptChoiceCreate(String(values.currentProjectId), {+ finding: signal.content.slice(0, todayExcerptChoiceCreateBodyFindingMax),+ excerpts,+ }).catch(() => ({ index: null }))+ const chosen = pick === null || !values.asksJev ? null : choices[pick]+ actions.codeQuoteRead(signal.signal_id, chosen ? { ...quote, ...chosen } : quote)},askAboutReport: ({ question }) => {const report = values.currentReportdiff --git a/products/signals/backend/facade/api.py b/products/signals/backend/facade/api.pyindex f0e6961b8a38..78289f0b462f 100644--- a/products/signals/backend/facade/api.py+++ b/products/signals/backend/facade/api.py@@ -59,8 +59,10 @@ from products.signals.backend.report_metrics import (ReportMetricSnapshot as ReportMetricSnapshot,)from products.signals.backend.report_page_source import (+ ReportArtefactText as ReportArtefactText,ReportPageSource as ReportPageSource,ReportSignal as ReportSignal,+ report_agent_texts as report_agent_texts,report_page_source as report_page_source,)from products.signals.backend.report_sections import (diff --git a/products/signals/backend/report_page_source.py b/products/signals/backend/report_page_source.pyindex a3eb2a0fb230..e023e44a6207 100644--- a/products/signals/backend/report_page_source.py+++ b/products/signals/backend/report_page_source.py@@ -1,12 +1,15 @@+from collections.abc import Collectionfrom datetime import datetimefrom typing import Any+from django.db.models import Q+from posthog.dataclasses import frozenfrom posthog.models import Teamfrom products.signals.backend.artefact_schemas import ActionabilityChoicefrom products.signals.backend.implementation_pr import fetch_implementation_prs_for_reports-from products.signals.backend.models import SignalReport+from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportArtefactfrom products.signals.backend.report_sections import ReportSections, report_sectionsfrom products.signals.backend.signal_metadata import fetch_signals_for_report_sync@@ -31,6 +34,14 @@ class ReportPageSource:signals: list[ReportSignal]+@frozen+class ReportArtefactText:+ artefact_id: str+ type: str+ content: str+ created_at: datetime++_STARTABLE_STATUSES = frozenset({SignalReport.Status.READY, SignalReport.Status.PENDING_INPUT})@@ -61,7 +72,7 @@ def _report_signals(team: Team, report_id: str) -> list[ReportSignal]:]-def report_page_source(*, team: Team, report_id: str) -> ReportPageSource | None:+def report_page_source(*, team: Team, report_id: str, with_signals: bool = True) -> ReportPageSource | None:team_id = team.idreport = (SignalReport.objects.filter(team_id=team_id, id=report_id)@@ -79,5 +90,24 @@ def report_page_source(*, team: Team, report_id: str) -> ReportPageSource | Nonesections=report_sections(report.summary),action_prompts=prompts if _can_start_work(report, has_pull_requests) else [],repo_slug=report.selected_repository(),- signals=_report_signals(team, report_id),+ signals=_report_signals(team, report_id) if with_signals else [],)+++def report_agent_texts(+ *, team: Team, report_id: str, types: Collection[str], per_type: int = 20+) -> list[ReportArtefactText]:+ """The newest artefacts of each type that an agent wrote, oldest first. Notes people wrote are left out."""+ written_by_person = Q(actor_kind=SignalActorKind.USER) | Q(actor_kind__isnull=True, created_by__isnull=False)+ artefacts = SignalReportArtefact.objects.filter(team_id=team.id, report_id=report_id).exclude(written_by_person)+ rows = [+ row+ for artefact_type in types+ for row in artefacts.filter(type=artefact_type)+ .order_by("-created_at")+ .values_list("id", "type", "content", "created_at")[:per_type]+ ]+ return [+ ReportArtefactText(artefact_id=str(artefact_id), type=artefact_type, content=content, created_at=created_at)+ for artefact_id, artefact_type, content, created_at in sorted(rows, key=lambda row: row[3])+ ]diff --git a/products/signals/backend/test/test_report_page_source.py b/products/signals/backend/test/test_report_page_source.pyindex a98cf3a60544..afc5cd33e055 100644--- a/products/signals/backend/test/test_report_page_source.py+++ b/products/signals/backend/test/test_report_page_source.py@@ -9,9 +9,9 @@ from posthog.constants import AvailableFeaturefrom posthog.models import Team, Userfrom products.access_control.backend.models.access_control import AccessControl-from products.signals.backend.models import SignalReport+from products.signals.backend.models import SignalActorKind, SignalReport, SignalReportArtefactfrom products.signals.backend.report_access import may_read_reports-from products.signals.backend.report_page_source import report_page_source+from products.signals.backend.report_page_source import report_agent_texts, report_page_sourceclass TestReportPageSource(BaseTest):@@ -56,11 +56,11 @@ class TestReportPageSource(BaseTest):assert source is not Noneassert source.action_prompts == expected- def test_finds_no_page_for_a_deleted_or_foreign_report(self) -> None:+ def test_finds_no_page_or_summary_for_a_deleted_or_foreign_report(self) -> None:deleted = self._report(status=SignalReport.Status.DELETED)foreign = self._report(team=Team.objects.create(organization=self.organization))- assert self._source(str(deleted.id)) is None- assert self._source(str(foreign.id)) is None+ for report in (deleted, foreign):+ assert self._source(str(report.id)) is Noneclass TestReportAccess(BaseTest):@@ -77,3 +77,29 @@ class TestReportAccess(BaseTest):True,False,)+++class TestReportAgentTexts(BaseTest):+ def test_returns_the_newest_texts_an_agent_wrote(self) -> None:+ report = SignalReport.objects.create(+ team=self.team, status=SignalReport.Status.READY, title="t", summary="s", signal_count=1, total_weight=1.0+ )+ for content, actor_kind, created_by in [+ ("Old agent note.", SignalActorKind.AGENT, self.user),+ ("New agent note.", SignalActorKind.AGENT, self.user),+ ("By a person.", SignalActorKind.USER, self.user),+ ("By a deleted person.", SignalActorKind.USER, None),+ ("Legacy person note.", None, self.user),+ ]:+ SignalReportArtefact.objects.create(+ team=self.team,+ report=report,+ type=SignalReportArtefact.ArtefactType.NOTE,+ content=content,+ actor_kind=actor_kind,+ created_by=created_by,+ )++ texts = report_agent_texts(team=self.team, report_id=str(report.id), types=["note"], per_type=1)++ assert [text.content for text in texts] == ["New agent note."]diff --git a/products/today/backend/facade/api.py b/products/today/backend/facade/api.pyindex 0f5a790abe42..cd47b3475eec 100644--- a/products/today/backend/facade/api.py+++ b/products/today/backend/facade/api.py@@ -6,12 +6,16 @@ from products.signals.backend.facade import api as signalsfrom ..feature_flags import (is_enabled_for as is_enabled_for,+ may_ask_jev as may_ask_jev,may_get_briefing as may_get_briefing,)from ..logic import (briefings,+ code_excerpts,+ figure_sources,report_page as report_pages,)+from ..logic.jev import GatewayJevfrom . import contractsfrom .enums import BriefingStatus@@ -51,6 +55,29 @@ def list_candidates(*, team: Team, user: User, timezone_name: str | None) -> conreturn briefings.list_candidates(team=team, user=user, timezone_name=timezone_name)+def _jev(team: Team, user: User, model: str | None = None) -> GatewayJev:+ return GatewayJev(team_id=team.id, distinct_id=str(user.distinct_id), model=model)+++def report_key_clauses(+ *, team: Team, user: User, report_id: str, include_impact: bool+) -> contracts.ReportKeyClauses | None:+ page = signals.report_page_source(team=team, report_id=report_id, with_signals=False)+ return report_pages.key_clauses(page, include_impact, _jev(team, user)) if page is not None else None+++def pick_code_excerpt(*, team: Team, user: User, finding: str, excerpts: list[str]) -> int | None:+ return code_excerpts.which_excerpt(finding, excerpts, _jev(team, user))++def report_page(*, team: Team, report_id: str) -> contracts.ReportPage | None:source = report_pages.page_source(team=team, report_id=report_id)return report_pages.report_page(source) if source is not None else None+++def report_figure_marks(*, team: Team, user: User, report_id: str) -> list[contracts.FigureMark] | None:+ page = signals.report_page_source(team=team, report_id=report_id)+ if page is None:+ return None+ artefacts = signals.report_agent_texts(team=team, report_id=report_id, types=figure_sources.RESEARCH_TYPES)+ return report_pages.figure_marks(page, artefacts, _jev(team, user, figure_sources.FIGURE_MODEL))diff --git a/products/today/backend/facade/contracts.py b/products/today/backend/facade/contracts.pyindex e3a88bcccf7c..ce8772fa1288 100644--- a/products/today/backend/facade/contracts.py+++ b/products/today/backend/facade/contracts.py@@ -9,11 +9,14 @@ from .enums import (BriefingStatus,BriefingWriter,CitedSource,+ FigureSourceKind,+ FigureText,ImpactNumberKey,ItemGroup,ItemReason,ItemSource,ItemState,+ KeyClauseRole,)@@ -208,3 +211,41 @@ class ReportPage:source_count: intimpact_numbers: list[ImpactNumber]last_seen: datetime | None+++@dataclass(frozen=True)+class KeyClause:+ start: int+ end: int+ role: KeyClauseRole+ expansion: list[str]+++@dataclass(frozen=True)+class ReportKeyClauses:+ lead: list[KeyClause]+ impact: list[KeyClause]+ proposal: list[KeyClause]+++@dataclass(frozen=True)+class FigureQuote:+ kind: FigureSourceKind+ signal: SignalView | None+ at: datetime+ sentence: str+ start: int+ end: int+++@dataclass(frozen=True)+class FigureMark:+ text: FigureText+ start: int+ end: int+ figure: str+ quote: FigureQuote+++class JevTimedOut(Exception):+ passdiff --git a/products/today/backend/facade/enums.py b/products/today/backend/facade/enums.pyindex 0c1c463a9c8d..35ede53361e9 100644--- a/products/today/backend/facade/enums.py+++ b/products/today/backend/facade/enums.py@@ -61,11 +61,27 @@ class ItemState(StrEnum):DISMISSED = "dismissed"+class KeyClauseRole(LabeledStrEnum):+ PROBLEM = "problem", "Problem"+ CAUSE = "cause", "Cause"+ FIX = "fix", "Fix"++class CitedSource(LabeledStrEnum):CODE = "code", "Code"SLACK = "slack", "Slack"+class FigureText(LabeledStrEnum):+ LEAD = "lead", "Lead"+ IMPACT = "impact", "Impact"++class ImpactNumberKey(LabeledStrEnum):TICKETS = "tickets", "Support tickets"QUERY_HOURS = "query-hours", "Database hours"+++class FigureSourceKind(LabeledStrEnum):+ SIGNAL = "signal", "Signal"+ RESEARCH = "research", "Agent's research"diff --git a/products/today/backend/feature_flags.py b/products/today/backend/feature_flags.pyindex 313304bfa681..2bfe6685a6c8 100644--- a/products/today/backend/feature_flags.py+++ b/products/today/backend/feature_flags.py@@ -11,13 +11,18 @@ logger = structlog.get_logger(__name__)# The briefing is part of the new navigation, so it uses the same flag.TODAY_RAIL_NAV_FLAG = "today-rail-nav"+TODAY_REPORT_JEV_FLAG = "today-report-jev"def is_enabled_for(user: User, team: Team) -> bool:"""Whether the new navigation (and so the briefing) is on for this person. Fails closed."""+ return _flag_on(TODAY_RAIL_NAV_FLAG, user, team)+++def _flag_on(flag: str, user: User, team: Team) -> bool:try:return feature_enabled_or_false(- TODAY_RAIL_NAV_FLAG,+ flag,str(user.distinct_id),groups={"organization": str(team.organization_id), "project": str(team.id)},group_properties={"organization": {"id": str(team.organization_id)}, "project": {"id": str(team.id)}},@@ -39,9 +44,23 @@ def may_get_briefing(user: User, team: Team) -> bool:scheduler and the run all ask this, so a person who fails it gets the report list andno row, no workflow and no LLM call."""+ return _may_use_ai(user, team, TODAY_RAIL_NAV_FLAG)+++def may_ask_jev(user: User, team: Team) -> bool:+ """Jev calls are not billed as AI credits, so they skip the organization's credit limit."""+ return _may_send_to_ai(user, team) and all(+ _flag_on(flag, user, team) for flag in (TODAY_REPORT_JEV_FLAG, TODAY_RAIL_NAV_FLAG)+ )+++def _may_send_to_ai(user: User, team: Team) -> bool:+ return bool(team.organization.is_ai_data_processing_approved and user.teams.filter(id=team.id).exists())+++def _may_use_ai(user: User, team: Team, flag: str) -> bool:return bool(- team.organization.is_ai_data_processing_approved+ _may_send_to_ai(user, team)and not is_team_limited(team.api_token, QuotaResource.AI_CREDITS, QuotaLimitingCaches.QUOTA_LIMITER_CACHE_KEY)- and user.teams.filter(id=team.id).exists()- and is_enabled_for(user, team)+ and _flag_on(flag, user, team))diff --git a/products/today/backend/logic/code_excerpts.py b/products/today/backend/logic/code_excerpts.pynew file mode 100644index 000000000000..6eb1cba7f4eb--- /dev/null+++ b/products/today/backend/logic/code_excerpts.py@@ -0,0 +1,14 @@+from .jev import JevClient++_EXCERPT_QUESTION = "Which numbered code excerpt shows the code that the finding describes?"+_EXCERPT_LABELS = ["1", "2", "3", "4", "5"]+_MIN_EXCERPT_PROBABILITY = 0.5+++def which_excerpt(finding: str, excerpts: list[str], jev: JevClient) -> int | None:+ numbered = [f"Code excerpt {index + 1}:\n{excerpt}" for index, excerpt in enumerate(excerpts)]+ item = "\n\n".join([f"Finding:\n{finding}", *numbered])+ [pick] = jev.choice([item], _EXCERPT_QUESTION, _EXCERPT_LABELS[: len(excerpts)])+ if pick is None or pick.probability < _MIN_EXCERPT_PROBABILITY:+ return None+ return int(pick.label) - 1diff --git a/products/today/backend/logic/figure_sources.py b/products/today/backend/logic/figure_sources.pynew file mode 100644index 000000000000..651ba897666c--- /dev/null+++ b/products/today/backend/logic/figure_sources.py@@ -0,0 +1,295 @@+import json+from collections.abc import Callable, Sequence+from datetime import datetime++from posthog.dataclasses import frozen++from products.signals.backend.facade import api as signals++from ..facade.enums import FigureSourceKind, FigureText+from .figures import Figure, is_zero, numbers_in, same_amount+from .jev import JevClient, JevPick+from .prose import plain_line, without_code_blocks+from .sentences import split_sentences+from .signal_text import SignalInput++FIGURE_MODEL = "posthog/hogference/jevk5-fp8-0.2"+KIND_THRESHOLD = 0.7+SOURCE_THRESHOLD = 0.6+RELATION_THRESHOLD = 0.6+NAMED_THRESHOLD = 0.75+_MAX_MARKS = 4+_MAX_CLAIMS = 12+_MAX_CANDIDATES = 6+_WINDOW = 200+_LETTERS = "ABCDEF"+_SOURCE_ORDER = {FigureSourceKind.SIGNAL: 0, FigureSourceKind.RESEARCH: 1}+_RESEARCH_FIELDS = {+ "priority_judgment": "explanation",+ "actionability_judgment": "explanation",+ "signal_finding": "data_queried",+ "check_scheduled": "rationale",+ "note": "note",+}+RESEARCH_TYPES = tuple(_RESEARCH_FIELDS)+_PLAN_HEADING = "verification plan"+_AUDIENCE_NOUNS = frozenset(+ "people person persons user users team teams customer customers organization organizations organisation "+ "organisations org orgs account accounts companies company project projects workspace workspaces session "+ "sessions visitor visitors member members".split()+)+KIND_QUESTION = "What does the number marked with [[ ]] in the claim describe?"+KIND_MEASURED = "measured result: a count, total, rate, share, amount of money or duration that was observed"+KIND_LABELS = [+ KIND_MEASURED,+ "date or time: a day, month, year or time of day",+ "identifier: an ID, version, ticket or issue number, or status code",+ "window length: the length of the period that a result covers",+ "limit or target: a value that is set, not observed",+ "other",+]+SOURCE_QUESTION = "Which source states the same result as the number marked with [[ ]] in the claim?"+SOURCE_NONE = "none: no source states this result"+RELATION_QUESTION = (+ "How does the number marked with [[ ]] in the source relate to the number marked with [[ ]] in the claim?"+)+RELATION_SAME = "same: the source number is the same result, about the same thing, group and period"+RELATION_LABELS = [+ RELATION_SAME,+ "different: the source number is about another thing, group or period",+ "unclear: the source does not say enough to tell",+]+NAMED_QUESTION = "Does this source sentence say what the number marked with [[ ]] counts?"+UNNAMED = "unnamed: a reader needs other sentences to know what the number counts"+NAMED = "named: the sentence alone says what the number counts"+NAMED_LABELS = [NAMED, UNNAMED]+++@frozen+class ResearchNote:+ artefact_id: str+ text: str+ at: datetime+++@frozen+class SourceSentence:+ kind: FigureSourceKind+ source_id: str+ sentence: str+ at: datetime+++@frozen+class Candidate:+ source: SourceSentence+ number: Figure+++@frozen+class FigureClaim:+ text_name: FigureText+ figure: Figure+ claim: str+ candidates: list[Candidate]+++@frozen+class FigureMatch:+ claim: FigureClaim+ source: Candidate+++def _content_dict(content: str) -> dict[str, object]:+ try:+ parsed = json.loads(content)+ except ValueError:+ return {}+ return parsed if isinstance(parsed, dict) else {}+++def research_notes(artefacts: Sequence[signals.ReportArtefactText]) -> list[ResearchNote]:+ notes: list[ResearchNote] = []+ for artefact in artefacts:+ field = _RESEARCH_FIELDS.get(artefact.type)+ value = _content_dict(artefact.content).get(field or "")+ text = value.strip() if isinstance(value, str) else ""+ if not text or text.lstrip("# ").lower().startswith(_PLAN_HEADING):+ continue+ notes.append(ResearchNote(artefact_id=artefact.artefact_id, text=text, at=artefact.created_at))+ return notes+++def _sentences_of(text: str) -> list[str]:+ lines = [plain_line(line) for line in without_code_blocks(text).split("\n")]+ return [sentence.strip() for line in lines if line for _, sentence in split_sentences(line) if sentence.strip()]+++def source_sentences(report_signals: Sequence[SignalInput], notes: Sequence[ResearchNote]) -> list[SourceSentence]:+ from_signals = [+ SourceSentence(kind=FigureSourceKind.SIGNAL, source_id=signal.signal_id, sentence=sentence, at=signal.timestamp)+ for signal in report_signals+ for sentence in _sentences_of(signal.content)+ ]+ from_notes = [+ SourceSentence(kind=FigureSourceKind.RESEARCH, source_id=note.artefact_id, sentence=sentence, at=note.at)+ for note in notes+ for sentence in _sentences_of(note.text)+ ]+ return [*from_signals, *from_notes]+++def _with_mark(text: str, start: int, end: int) -> str:+ return f"{text[:start]}[[{text[start:end]}]]{text[end:]}"+++def _claim_sentence(text: str, figure: Figure) -> str:+ for start, sentence in split_sentences(text):+ if start <= figure.start < start + len(sentence):+ return _with_mark(sentence, figure.start - start, figure.end - start).strip()+ return _with_mark(text, figure.start, figure.end)+++def _candidates(figure: Figure, sources: list[SourceSentence]) -> list[Candidate]:+ seen: set[str] = set()+ candidates: list[Candidate] = []+ for source in sorted(sources, key=lambda source: _SOURCE_ORDER[source.kind]):+ if source.sentence in seen:+ continue+ seen.add(source.sentence)+ candidates.extend(+ Candidate(source=source, number=number)+ for number in numbers_in(source.sentence)+ if same_amount(figure.amount, number.amount)+ )+ return candidates[:_MAX_CANDIDATES]+++def figure_claims(+ texts: dict[FigureText, str], sources: list[SourceSentence], prose: dict[FigureText, str]+) -> list[FigureClaim]:+ claims: list[FigureClaim] = []+ for name, text in texts.items():+ for figure in numbers_in(prose[name]):+ candidates = [] if is_zero(figure.amount) else _candidates(figure, sources)+ if candidates:+ claims.append(+ FigureClaim(+ text_name=name, figure=figure, claim=_claim_sentence(text, figure), candidates=candidates+ )+ )+ return claims+++def _window(candidate: Candidate) -> str:+ sentence, number = candidate.source.sentence, candidate.number+ start = max(0, number.start - _WINDOW)+ end = min(len(sentence), number.end + _WINDOW)+ if start > 0:+ space = sentence.find(" ", start, number.start)+ start = space + 1 if space >= 0 else start+ if end < len(sentence):+ space = sentence.rfind(" ", number.end, end)+ end = space if space >= 0 else end+ before = "…" if start > 0 else ""+ after = "…" if end < len(sentence) else ""+ return f"{before}{_with_mark(sentence[start:end], number.start - start, number.end - start)}{after}"+++def kind_item(claim: FigureClaim) -> str:+ return f"Claim: {claim.claim}"+++def source_item(claim: FigureClaim, ordered: Sequence[Candidate]) -> str:+ sources = [f"Source {letter}: {_window(candidate)}" for letter, candidate in zip(_LETTERS, ordered)]+ return "\n".join([f"Claim: {claim.claim}", "", *sources])+++def source_labels(count: int) -> list[str]:+ return [*_LETTERS[:count], SOURCE_NONE]+++def relation_item(claim: FigureClaim, candidate: Candidate) -> str:+ return f"Claim: {claim.claim}\n\nSource: {_window(candidate)}"+++def named_item(candidate: Candidate) -> str:+ return f"Source: {_window(candidate)}"+++def _orders(claim: FigureClaim) -> list[list[Candidate]]:+ return [list(claim.candidates), list(reversed(claim.candidates))]+++def _sure(pick: JevPick | None, label: str, threshold: float) -> bool:+ return pick is not None and pick.label == label and pick.probability >= threshold+++def _picked(claim: FigureClaim, ordered: list[Candidate], picks: dict[str, JevPick | None]) -> Candidate | None:+ pick = picks.get(source_item(claim, ordered))+ letters = _LETTERS[: len(ordered)]+ if pick is None or pick.probability < SOURCE_THRESHOLD or pick.label not in letters:+ return None+ return ordered[letters.index(pick.label)]+++def _agreed_source(claim: FigureClaim, picks: dict[str, JevPick | None]) -> Candidate | None:+ forward, backward = (_picked(claim, ordered, picks) for ordered in _orders(claim))+ return forward if forward is not None and forward == backward else None+++def _about_people(figure: Figure) -> bool:+ return (figure.noun or "").lower() in _AUDIENCE_NOUNS+++def _people_first[T](items: list[T], figure: Callable[[T], Figure], limit: int) -> list[T]:+ order = sorted(range(len(items)), key=lambda index: (not _about_people(figure(items[index])), index))+ kept = set(order[:limit])+ return [item for index, item in enumerate(items) if index in kept]+++def _picks(jev: JevClient, items: list[str], question: str, labels: list[str]) -> dict[str, JevPick | None]:+ unique = list(dict.fromkeys(items))+ return dict(zip(unique, jev.choice(unique, question, labels))) if unique else {}+++def _source_picks(jev: JevClient, claims: list[FigureClaim]) -> dict[str, JevPick | None]:+ picks: dict[str, JevPick | None] = {}+ for count in sorted({len(claim.candidates) for claim in claims}):+ items = [+ source_item(claim, ordered)+ for claim in claims+ if len(claim.candidates) == count+ for ordered in _orders(claim)+ ]+ picks |= _picks(jev, items, SOURCE_QUESTION, source_labels(count))+ return picks+++def match_figures(+ texts: dict[FigureText, str],+ report_signals: Sequence[SignalInput],+ notes: Sequence[ResearchNote],+ jev: JevClient,+ prose: dict[FigureText, str],+) -> list[FigureMatch]:+ sources = source_sentences(report_signals, notes)+ claims = _people_first(figure_claims(texts, sources, prose), lambda claim: claim.figure, _MAX_CLAIMS)+ kinds = _picks(jev, [kind_item(claim) for claim in claims], KIND_QUESTION, KIND_LABELS)+ measured = [claim for claim in claims if _sure(kinds.get(kind_item(claim)), KIND_MEASURED, KIND_THRESHOLD)]+ picks = _source_picks(jev, measured)+ agreed = [(claim, candidate) for claim in measured if (candidate := _agreed_source(claim, picks))]+ relation_items = [relation_item(claim, candidate) for claim, candidate in agreed]+ relations = _picks(jev, relation_items, RELATION_QUESTION, RELATION_LABELS)+ same = [+ (claim, candidate)+ for claim, candidate in agreed+ if _sure(relations.get(relation_item(claim, candidate)), RELATION_SAME, RELATION_THRESHOLD)+ ]+ named = _picks(jev, [named_item(candidate) for _, candidate in same], NAMED_QUESTION, NAMED_LABELS)+ matches = [+ FigureMatch(claim=claim, source=candidate)+ for claim, candidate in same+ if _sure(named.get(named_item(candidate)), NAMED, NAMED_THRESHOLD)+ ]+ return _people_first(matches, lambda match: match.claim.figure, _MAX_MARKS)diff --git a/products/today/backend/logic/figures.py b/products/today/backend/logic/figures.pynew file mode 100644index 000000000000..1356fd3131a5--- /dev/null+++ b/products/today/backend/logic/figures.py@@ -0,0 +1,197 @@+from decimal import Decimal+from typing import Literal++from posthog.dataclasses import frozen++from .formats import digits_end, is_digit, is_word_char++_CURRENCIES = frozenset("$€£")+_BLOCKED_BEFORE = frozenset(".,-/:#$@→")+_BLOCKED_AFTER = frozenset(":/→")+_RANGE_DASHES = frozenset("–-")+_SCALES = {"K": Decimal(1_000), "M": Decimal(1_000_000)}+_UNIT_WORDS = ("ms", "K", "M")+_DURATION_UNITS = frozenset(+ {"second", "seconds", "minute", "minutes", "hour", "hours", "day", "days", "week", "weeks", "month", "months"}+)+_NOUN_QUOTES = frozenset("'\"‘“")++type AmountKind = Literal["percent", "milliseconds", "money", "count"]+++@frozen+class Amount:+ kind: AmountKind+ low: Decimal+ high: Decimal+ upper: Decimal | None+++@frozen+class Figure:+ start: int+ end: int+ text: str+ noun: str | None+ amount: Amount+++@frozen+class _Token:+ upper: str | None+ unit: str | None+ end: int+++def _number_end(text: str, start: int) -> int:+ end = digits_end(text, start)+ if end - start <= 3:+ while text.startswith(",", end) and digits_end(text, end + 1) - (end + 1) == 3:+ end = digits_end(text, end + 1)+ if text.startswith(".", end) and end + 1 < len(text) and is_digit(text[end + 1]):+ end = digits_end(text, end + 1)+ return end+++def _after_space(text: str, index: int) -> int:+ return index + 1 if text.startswith(" ", index) else index+++def _range_upper(text: str, index: int) -> tuple[str | None, int]:+ dash = _after_space(text, index)+ if dash >= len(text) or text[dash] not in _RANGE_DASHES:+ return None, index+ second = _after_space(text, dash + 1)+ if second >= len(text) or not is_digit(text[second]):+ return None, index+ end = _number_end(text, second)+ return text[second:end], end+++def _unit(text: str, index: int) -> tuple[str | None, int]:+ if text.startswith("%", index):+ return "%", index + 1+ start = _after_space(text, index)+ for unit in _UNIT_WORDS:+ end = start + len(unit)+ if text.startswith(unit, start) and (end == len(text) or not is_word_char(text[end])):+ return unit, end+ return None, index+++def _token(text: str, number_end: int) -> _Token:+ upper, range_end = _range_upper(text, number_end)+ unit, end = _unit(text, range_end)+ if upper is not None or unit is None:+ return _Token(upper=upper, unit=unit, end=end)+ unit_upper, unit_range_end = _range_upper(text, end)+ upper_unit, upper_end = _unit(text, unit_range_end)+ if unit_upper is None or upper_unit != unit:+ return _Token(upper=None, unit=unit, end=end)+ return _Token(upper=unit_upper, unit=unit, end=upper_end)+++def _free_after(text: str, end: int) -> bool:+ following = text[end] if end < len(text) else ""+ decimal_after = following in ".," and end + 1 < len(text) and is_digit(text[end + 1])+ return not is_word_char(following) and following not in _BLOCKED_AFTER and not decimal_after+++def _noun_after(text: str, end: int) -> str | None:+ index = end+ while index < len(text) and text[index].isspace():+ index += 1+ if index == end:+ return None+ if index < len(text) and text[index] in _NOUN_QUOTES:+ index += 1+ start = index+ while (+ index < len(text)+ and text[index].isascii()+ and (text[index].isalpha() or (index > start and text[index] == "-"))+ ):+ index += 1+ return text[start:index] or None+++def _duration_end(text: str, end: int, noun: str | None, bare: bool) -> int:+ if not bare or noun is None or noun.lower() not in _DURATION_UNITS:+ return end+ word_start = end+ while word_start < len(text) and text[word_start].isspace():+ word_start += 1+ return word_start + len(noun) if text.startswith(noun, word_start) else end+++def _spread(value: str, unit: str | None) -> Decimal:+ scale = _SCALES.get(unit or "")+ if scale is None:+ return Decimal(0)+ decimals = len(value.split(".")[1]) if "." in value else 0+ return Decimal(5) * scale / Decimal(10) ** (decimals + 1)+++def _kind(unit: str | None, currency: bool) -> AmountKind:+ if unit == "%":+ return "percent"+ if unit == "ms":+ return "milliseconds"+ return "money" if currency else "count"+++def _amount(value: str, token: _Token, currency: bool) -> Amount:+ scale = _SCALES.get(token.unit or "", Decimal(1))+ center = Decimal(value.replace(",", "")) * scale+ spread = _spread(value, token.unit)+ return Amount(+ kind=_kind(token.unit, currency),+ low=center - spread,+ high=center + spread,+ upper=Decimal(token.upper.replace(",", "")) * scale if token.upper else None,+ )+++def _number_start(text: str, index: int) -> tuple[int, bool] | None:+ currency = text[index] in _CURRENCIES+ digit_start = index + 1 if currency else index+ if digit_start >= len(text) or not is_digit(text[digit_start]):+ return None+ before = text[index - 1] if index > 0 else ""+ if is_word_char(before) or before in _BLOCKED_BEFORE:+ return None+ return digit_start, currency+++def numbers_in(text: str) -> list[Figure]:+ figures: list[Figure] = []+ index = 0+ while index < len(text):+ start = _number_start(text, index)+ if start is None:+ index = digits_end(text, index) if is_digit(text[index]) else index + 1+ continue+ digit_start, currency = start+ number_end = _number_end(text, digit_start)+ value = text[digit_start:number_end]+ token = _token(text, number_end)+ if not _free_after(text, token.end):+ index = token.end+ continue+ noun = _noun_after(text, token.end)+ end = _duration_end(text, token.end, noun, bare=token.unit is None and not currency)+ figures.append(+ Figure(start=index, end=end, text=text[index:end], noun=noun, amount=_amount(value, token, currency))+ )+ index = end+ return figures+++def is_zero(amount: Amount) -> bool:+ return amount.low <= 0 <= amount.high and not amount.upper+++def same_amount(claim: Amount, source: Amount) -> bool:+ if claim.kind != source.kind or claim.upper != source.upper:+ return False+ return claim.low <= source.low and source.high <= claim.highdiff --git a/products/today/backend/logic/formats.py b/products/today/backend/logic/formats.pyindex 26bec41dcf37..f63f88116c9f 100644--- a/products/today/backend/logic/formats.py+++ b/products/today/backend/logic/formats.py@@ -108,3 +108,7 @@ def colon_duration_seconds(value: str) -> float | None:def collapsed_whitespace(text: str) -> str:return " ".join(text.split())+++def utf16_offset(text: str, index: int) -> int:+ return len(text[:index].encode("utf-16-le")) // 2diff --git a/products/today/backend/logic/jev.py b/products/today/backend/logic/jev.pynew file mode 100644index 000000000000..4d88ace206a8--- /dev/null+++ b/products/today/backend/logic/jev.py@@ -0,0 +1,137 @@+import json+import time+import asyncio+import hashlib+from collections.abc import Callable+from dataclasses import replace+from functools import cached_property+from typing import Protocol++from django.conf import settings+from django.core.cache import cache++from asgiref.sync import async_to_sync++from posthog.dataclasses import frozen+from posthog.llm.system_one import Answer, ChoiceAnswer, ChoiceQuestion, NoulAnswer, NoulQuestion, Question+from posthog.llm.system_one_client import GATEWAY_MAX_QUESTIONS, GatewaySystemOneClient, build_system_one_client++from ..facade import contracts++_AI_PRODUCT = "today_report"+_CONCURRENCY = 4+_DEADLINE_SECONDS = 45+_REQUEST_SECONDS = 30+_CACHE_SECONDS = 30 * 24 * 60 * 60+++@frozen+class JevPick:+ label: str+ probability: float+++class JevClient(Protocol):+ def choice(self, items: list[str], question: str, labels: list[str]) -> list[JevPick | None]: ...++ def yes_probability(self, items: list[str], question: str) -> list[float | None]: ...+++def _pick(answer: Answer) -> JevPick | None:+ return JevPick(label=answer.choice, probability=answer.confidence) if isinstance(answer, ChoiceAnswer) else None+++def _probability(answer: Answer) -> float | None:+ return answer.probability if isinstance(answer, NoulAnswer) else None+++def _outcome(task: asyncio.Task[list[Answer]]) -> list[Answer] | BaseException:+ if task.cancelled():+ return contracts.JevTimedOut()+ return task.exception() or task.result()+++class GatewayJev:+ def __init__(self, *, team_id: int, distinct_id: str, model: str | None = None) -> None:+ self._team_id = team_id+ self._distinct_id = distinct_id+ self._model = model or settings.HOGQL_PROMPT_JEV_MODEL+ self._deadline: float | None = None++ @cached_property+ def _client(self) -> GatewaySystemOneClient:+ client = build_system_one_client(+ model=self._model,+ ai_product=_AI_PRODUCT,+ team_id=self._team_id,+ distinct_id=self._distinct_id,+ )+ assert isinstance(client, GatewaySystemOneClient)+ return client++ def _cache_key(self, question: Question, item: str) -> str:+ body = json.dumps([self._team_id, self._model, question.to_json(), item], sort_keys=True)+ return f"today_jev:{hashlib.sha256(body.encode()).hexdigest()}"++ async def _ask_batch(self, items: list[str], question: Question, deadline: float) -> list[Answer]:+ keys = [f"row_{index}" for index in range(len(items))]+ questions: dict[str, Question] = {+ key: replace(+ question,+ instructions={"input": f"Evaluate only the text in state.{key}.", "question": question.instructions},+ )+ for key in keys+ }+ client = replace(self._client, timeout=min(deadline - time.monotonic(), _REQUEST_SECONDS))+ result = await client.adecide(state=dict(zip(keys, items)), questions=questions)+ return [result.answers[key] for key in keys]++ async def _ask(self, batches: list[list[str]], question: Question) -> list[list[Answer] | BaseException]:+ semaphore = asyncio.Semaphore(_CONCURRENCY)+ self._deadline = self._deadline or time.monotonic() + _DEADLINE_SECONDS+ deadline = self._deadline+ if deadline <= time.monotonic():+ return [contracts.JevTimedOut() for _ in batches]++ async def ask_batch(batch: list[str]) -> list[Answer]:+ async with semaphore:+ return await self._ask_batch(batch, question, deadline)++ tasks = [asyncio.create_task(ask_batch(batch)) for batch in batches]+ try:+ await asyncio.wait(tasks, timeout=max(deadline - time.monotonic(), 0))+ finally:+ for task in tasks:+ task.cancel()+ await asyncio.gather(*tasks, return_exceptions=True)+ return [_outcome(task) for task in tasks]++ def _answers[T](self, items: list[str], question: Question, value: Callable[[Answer], T]) -> list[T]:+ keys = [self._cache_key(question, item) for item in items]+ saved = cache.get_many(keys)+ missing = list({key: item for key, item in zip(keys, items) if key not in saved}.items())+ batches = [+ missing[start : start + GATEWAY_MAX_QUESTIONS] for start in range(0, len(missing), GATEWAY_MAX_QUESTIONS)+ ]+ outcomes = (+ async_to_sync(self._ask)([[item for _, item in batch] for batch in batches], question) if batches else []+ )+ fresh: dict[str, T] = {}+ failures: list[BaseException] = []+ for batch, outcome in zip(batches, outcomes):+ if isinstance(outcome, BaseException):+ failures.append(outcome)+ else:+ fresh |= {key: value(answer) for (key, _), answer in zip(batch, outcome)}+ cache.set_many(fresh, timeout=_CACHE_SECONDS)+ if failures:+ raise failures[0]+ found = saved | fresh+ return [found[key] for key in keys]++ def choice(self, items: list[str], question: str, labels: list[str]) -> list[JevPick | None]:+ criteria: dict[str, None] = dict.fromkeys(labels)+ return self._answers(items, ChoiceQuestion(instructions=question, criteria=criteria), _pick)++ def yes_probability(self, items: list[str], question: str) -> list[float | None]:+ return self._answers(items, NoulQuestion(instructions=question), _probability)diff --git a/products/today/backend/logic/key_clauses.py b/products/today/backend/logic/key_clauses.pynew file mode 100644index 000000000000..03337c674654--- /dev/null+++ b/products/today/backend/logic/key_clauses.py@@ -0,0 +1,237 @@+import re+from collections.abc import Sequence+from dataclasses import replace+from itertools import accumulate++from posthog.dataclasses import frozen++from ..facade import contracts+from ..facade.enums import KeyClauseRole+from .formats import utf16_offset+from .jev import JevClient, JevPick+from .prose import block_lines+from .report_text import rendered_text+from .sentences import split_sentences++_WORD = re.compile(r"[^\W_](?:\w|(?<=[^\W_])['’.](?=[^\W_])|(?<=\d)[,;](?=\d))*|_+\w*")+_IN_PHRASE = set("'’‘-./_\"“”`$€£%#@*+=")+_DASHES = set("–—")+_CLAUSE_OPENERS = frozenset(+ "because since so but and or which while when after until unless although though whereas".split()+)+_MIN_SIDE_WORDS = 3+_MIN_CLAUSE_WORDS = 2+_MAX_CLAUSES = 15+_MIN_ROLE_PROBABILITY = 0.75+_MAX_KEY_CLAUSE_WORDS = 16+_MIN_SENTENCE_WORDS = 6+_MAX_REPORT_SENTENCES = 25+_MAX_EXPANSION_SENTENCES = 2+_MIN_EXPANSION_PROBABILITY = 0.6+_MIN_SECOND_EXPANSION_PROBABILITY = 0.75+_MAX_KEY_CLAUSES = 2+_CANDIDATES_PER_ROLE = 2+_EXPANSION_QUESTION = "Answer true if the sentence explains the marked part in more detail."+_ROLE_LABELS = ["problem", "cause", "fix", "detail"]+_ROLE_QUESTION = (+ "What does this part tell the reader? problem: what goes wrong or who is hurt. cause: why it happens. "+ "fix: what to change. detail: anything else, such as numbers, background, tests, or follow-ups."+)+++@frozen+class KeyClauseRequest:+ text: str+ roles: list[KeyClauseRole]+++@frozen+class Clause:+ start: int+ end: int+ text: str+ words: int+++@frozen+class _ScoredClause:+ start: int+ end: int+ text: str+ role: KeyClauseRole+ confidence: float+ expansion: list[str]+++@frozen+class _Word:+ start: int+ end: int+ text: str+++def _joins_words(sentence: str, index: int) -> bool:+ char = sentence[index]+ before = sentence[index - 1] if index > 0 else " "+ after = sentence[index + 1] if index + 1 < len(sentence) else " "+ return char in _IN_PHRASE or (char in _DASHES and not before.isspace() and not after.isspace())+++def _has_break(sentence: str, start: int, end: int) -> bool:+ return any(not sentence[index].isspace() and not _joins_words(sentence, index) for index in range(start, end))+++def _word_runs(sentence: str, offset: int) -> list[list[_Word]]:+ runs: list[list[_Word]] = [[]]+ last = 0+ for match in _WORD.finditer(sentence):+ if _has_break(sentence, last, match.start()):+ runs.append([])+ runs[-1].append(_Word(start=offset + match.start(), end=offset + match.end(), text=match.group(0)))+ last = match.end()+ return runs+++def _split_at_openers(run: list[_Word]) -> list[list[_Word]]:+ parts: list[list[_Word]] = [[]]+ for index, word in enumerate(run):+ both_sides_long = len(parts[-1]) >= _MIN_SIDE_WORDS and len(run) - index >= _MIN_SIDE_WORDS+ if word.text in _CLAUSE_OPENERS and both_sides_long:+ parts.append([])+ parts[-1].append(word)+ return parts+++def _clause(text: str, words: list[_Word]) -> Clause:+ start, end = words[0].start, words[-1].end+ return Clause(start=start, end=end, text=text[start:end], words=len(words))+++def text_clauses(text: str) -> list[Clause]:+ parts = [+ part+ for sentence_start, sentence in split_sentences(text)+ for run in _word_runs(sentence, sentence_start)+ for part in _split_at_openers(run)+ ]+ return [_clause(text, words) for words in parts if len(words) >= _MIN_CLAUSE_WORDS][:_MAX_CLAUSES]+++def _clause_role_input(text: str, clause: Clause) -> str:+ return f"Text:\n{text}\n\nPart of the text:\n{clause.text}"+++def _is_sure_role(pick: JevPick, role: KeyClauseRole, clause: Clause) -> bool:+ return pick.label == role and pick.probability >= _MIN_ROLE_PROBABILITY and clause.words <= _MAX_KEY_CLAUSE_WORDS+++def _surest_clauses(clauses: list[Clause], picks: list[JevPick | None], role: KeyClauseRole) -> list[_ScoredClause]:+ sure = [+ (pick, clause) for clause, pick in zip(clauses, picks) if pick is not None and _is_sure_role(pick, role, clause)+ ]+ sure.sort(key=lambda candidate: -candidate[0].probability)+ return [+ _ScoredClause(+ start=clause.start, end=clause.end, text=clause.text, role=role, confidence=pick.probability, expansion=[]+ )+ for pick, clause in sure[:_CANDIDATES_PER_ROLE]+ ]+++def _key_clauses(clauses: list[Clause], roles: list[KeyClauseRole], picks: list[JevPick | None]) -> list[_ScoredClause]:+ chosen = [key_clause for role in roles for key_clause in _surest_clauses(clauses, picks, role)]+ return sorted(chosen, key=lambda key_clause: key_clause.start)+++def _chunked[T](values: Sequence[T], sizes: list[int]) -> list[list[T]]:+ edges = list(accumulate(sizes, initial=0))+ return [list(values[start:end]) for start, end in zip(edges, edges[1:])]+++def _word_count(text: str) -> int:+ return len(_WORD.findall(text))+++def _report_sentences(summary: str, shown: list[str]) -> list[str]:+ seen = {text.strip() for text in shown}+ sentences: list[str] = []+ for line in block_lines(summary):+ text = rendered_text(line).strip()+ if not text or text in seen:+ continue+ for _, sentence in split_sentences(text):+ value = sentence.strip()+ already_read = any(value in part for part in shown) or value in sentences+ if _word_count(value) >= _MIN_SENTENCE_WORDS and not already_read:+ sentences.append(value)+ return sentences[:_MAX_REPORT_SENTENCES]+++def _expansion_input(key_clause: _ScoredClause, sentence: str) -> str:+ return f"Marked part:\n{key_clause.text}\n\nSentence from the report:\n{sentence}"+++def _expansion_for(sentences: list[str], probabilities: Sequence[float | None]) -> list[str]:+ likely = sorted(+ (+ (probability, index)+ for index, probability in zip(range(len(sentences)), probabilities)+ if probability is not None and probability >= _MIN_EXPANSION_PROBABILITY+ ),+ key=lambda candidate: -candidate[0],+ )+ kept = [+ index+ for rank, (probability, index) in enumerate(likely)+ if rank == 0 or probability >= _MIN_SECOND_EXPANSION_PROBABILITY+ ]+ return [sentences[index] for index in sorted(kept[:_MAX_EXPANSION_SENTENCES])]+++def _best_explained(key_clauses: list[_ScoredClause]) -> list[_ScoredClause]:+ best: dict[KeyClauseRole, _ScoredClause] = {}+ for key_clause in key_clauses:+ current = best.get(key_clause.role)+ if key_clause.expansion and (current is None or key_clause.confidence > current.confidence):+ best[key_clause.role] = key_clause+ return sorted(best.values(), key=lambda key_clause: key_clause.start)+++def _contract(text: str, key_clause: _ScoredClause) -> contracts.KeyClause:+ return contracts.KeyClause(+ start=utf16_offset(text, key_clause.start),+ end=utf16_offset(text, key_clause.end),+ role=key_clause.role,+ expansion=key_clause.expansion,+ )+++def find_key_clauses(requests: list[KeyClauseRequest], summary: str, jev: JevClient) -> list[list[contracts.KeyClause]]:+ sentences = _report_sentences(summary, [request.text for request in requests])+ if not sentences:+ return [[] for _ in requests]+ clauses = [text_clauses(request.text) for request in requests]+ picks = jev.choice(+ [_clause_role_input(request.text, clause) for request, own in zip(requests, clauses) for clause in own],+ _ROLE_QUESTION,+ _ROLE_LABELS,+ )+ picked = [+ _key_clauses(own, request.roles, own_picks)+ for request, own, own_picks in zip(requests, clauses, _chunked(picks, [len(own) for own in clauses]))+ ]+ flat = [key_clause for own in picked for key_clause in own]+ answers = jev.yes_probability(+ [_expansion_input(key_clause, sentence) for key_clause in flat for sentence in sentences],+ _EXPANSION_QUESTION,+ )+ expanded = [+ replace(key_clause, expansion=_expansion_for(sentences, own_answers))+ for key_clause, own_answers in zip(flat, _chunked(answers, [len(sentences)] * len(flat)))+ ]+ best = [_best_explained(own) for own in _chunked(expanded, [len(own) for own in picked])]+ shown = sorted((key_clause for own in best for key_clause in own), key=lambda k: -k.confidence)[:_MAX_KEY_CLAUSES]+ return [+ [_contract(request.text, key_clause) for key_clause in own if key_clause in shown]+ for request, own in zip(requests, best)+ ]diff --git a/products/today/backend/logic/prose.py b/products/today/backend/logic/prose.pyindex d9ae59dba5e8..22bbf23f85ac 100644--- a/products/today/backend/logic/prose.py+++ b/products/today/backend/logic/prose.py@@ -74,7 +74,7 @@ def paragraphs(markdown: str) -> list[str]:return [paragraph.strip() for paragraph in _PARAGRAPH_BREAK.split(markdown) if paragraph.strip()]-def _block_lines(markdown: str) -> list[str]:+def block_lines(markdown: str) -> list[str]:inline_blocks = [token.content for token in MARKDOWN.parse(markdown) if token.type == "inline"]return [line.strip() for block in inline_blocks for line in block.split("\n") if line.strip()]@@ -84,7 +84,7 @@ def _balanced(text: str, marker: str) -> str:def concise_text(markdown: str | None, max_chars: int) -> str:- lines = [line if line.endswith(_SENTENCE_ENDS) else f"{line}." for line in _block_lines(markdown or "")]+ lines = [line if line.endswith(_SENTENCE_ENDS) else f"{line}." for line in block_lines(markdown or "")]pieces = [sentence.strip() for line in lines for _, sentence in split_markdown_sentences(line) if sentence.strip()]text = ""for piece in pieces:diff --git a/products/today/backend/logic/report_page.py b/products/today/backend/logic/report_page.pyindex f39f468dcbd6..9394c159274c 100644--- a/products/today/backend/logic/report_page.py+++ b/products/today/backend/logic/report_page.py@@ -5,10 +5,14 @@ from posthog.models import Teamfrom products.signals.backend.facade import api as signalsfrom ..facade import contracts-from . import evidence, impact, samples-from .formats import digits_end, github_links, is_word_char+from ..facade.enums import FigureSourceKind, FigureText, KeyClauseRole+from . import evidence, figure_sources, impact, samples+from .formats import digits_end, github_links, is_word_char, utf16_offset+from .jev import JevClient+from .key_clauses import KeyClauseRequest, find_key_clausesfrom .prose import concise_text-from .report_text import MARKDOWN+from .report_text import MARKDOWN, rendered_prose, rendered_text+from .signal_text import SignalInput_PROPOSAL_CHARS = 260_IMPACT_CHARS = 180@@ -86,3 +90,50 @@ def page_source(*, team: Team, report_id: str) -> signals.ReportPageSource | Nonreturn signals.report_page_source(team=team, report_id=report_id)sample = samples.sample_report(report_id)return samples.sample_page_source(sample) if sample is not None else None+++_PROBLEM_AND_CAUSE = [KeyClauseRole.PROBLEM, KeyClauseRole.CAUSE]+++def key_clauses(page: signals.ReportPageSource, include_impact: bool, jev: JevClient) -> contracts.ReportKeyClauses:+ impact = impact_sentence(page.sections.impact) if include_impact else ""+ requests = [+ KeyClauseRequest(text=rendered_text(page.sections.lead), roles=_PROBLEM_AND_CAUSE),+ KeyClauseRequest(text=rendered_text(impact), roles=_PROBLEM_AND_CAUSE),+ KeyClauseRequest(text=rendered_text(proposal(page)), roles=[KeyClauseRole.FIX]),+ ]+ lead, impact_clauses, proposal_clauses = find_key_clauses(requests, page.summary, jev)+ return contracts.ReportKeyClauses(lead=lead, impact=impact_clauses, proposal=proposal_clauses)+++def _figure_quote(candidate: figure_sources.Candidate, report_signals: list[SignalInput]) -> contracts.FigureQuote:+ source = candidate.source+ signal = next((own for own in report_signals if own.signal_id == source.source_id), None)+ return contracts.FigureQuote(+ kind=source.kind,+ signal=evidence.signal_view(signal) if signal and source.kind == FigureSourceKind.SIGNAL else None,+ at=source.at,+ sentence=source.sentence,+ start=utf16_offset(source.sentence, candidate.number.start),+ end=utf16_offset(source.sentence, candidate.number.end),+ )+++def figure_marks(+ page: signals.ReportPageSource, artefacts: list[signals.ReportArtefactText], jev: JevClient+) -> list[contracts.FigureMark]:+ markdowns = {FigureText.LEAD: page.sections.lead, FigureText.IMPACT: impact_sentence(page.sections.impact)}+ texts = {name: rendered_text(markdown) for name, markdown in markdowns.items()}+ prose = {name: rendered_prose(markdown) for name, markdown in markdowns.items()}+ notes = figure_sources.research_notes(artefacts)+ matches = figure_sources.match_figures(texts, page.signals, notes, jev, prose)+ return [+ contracts.FigureMark(+ text=match.claim.text_name,+ start=utf16_offset(texts[match.claim.text_name], match.claim.figure.start),+ end=utf16_offset(texts[match.claim.text_name], match.claim.figure.end),+ figure=match.claim.figure.text,+ quote=_figure_quote(match.source, page.signals),+ )+ for match in matches+ ]diff --git a/products/today/backend/logic/report_text.py b/products/today/backend/logic/report_text.pyindex e646c2643c9e..a1ee273ac1ba 100644--- a/products/today/backend/logic/report_text.py+++ b/products/today/backend/logic/report_text.py@@ -3,6 +3,8 @@ from datetime import datefrom markdown_it import MarkdownItfrom markdown_it.token import Token+from posthog.dataclasses import frozen+from .formats import GitHubLink, collapsed_whitespace, github_links, is_word_char, replace_iso_datesMARKDOWN = MarkdownIt("commonmark")@@ -27,40 +29,60 @@ def _is_bare_link(text: str, link: GitHubLink) -> bool:return not opened and not is_word_char(following) and following != "/"-def _shortened_github_links(text: str) -> str:- parts: list[str] = []+@frozen+class _Part:+ text: str+ prose: bool+++def _dated(text: str) -> str:+ return replace_iso_dates(text, readable_date)+++def _prose_parts(text: str) -> list[_Part]:+ parts: list[_Part] = []last = 0for link in github_links(text, lambda link: _is_bare_link(text, link)):- parts.extend((text[last : link.start], f"#{link.number}"))+ parts.extend(+ (_Part(text=_dated(text[last : link.start]), prose=True), _Part(text=f"#{link.number}", prose=False))+ )last = link.end- parts.append(text[last:])- return "".join(parts)---def _prose_text(text: str, in_link: bool) -> str:- return replace_iso_dates(text if in_link else _shortened_github_links(text), readable_date)+ parts.append(_Part(text=_dated(text[last:]), prose=True))+ return parts-def _inline_text(tokens: list[Token]) -> str:- parts: list[str] = []+def _inline_parts(tokens: list[Token]) -> list[_Part]:+ parts: list[_Part] = []link_depth = 0for token in tokens:if token.type == "link_open":link_depth += 1elif token.type == "link_close":link_depth -= 1+ elif token.type == "text" and link_depth:+ parts.append(_Part(text=_dated(token.content), prose=False))elif token.type == "text":- parts.append(_prose_text(token.content, link_depth > 0))+ parts.extend(_prose_parts(token.content))elif token.type in _RAW_TOKENS:- parts.append(token.content)+ parts.append(_Part(text=token.content, prose=False))elif token.type in _BREAK_TOKENS:- parts.append(" ")+ parts.append(_Part(text=" ", prose=True))elif token.type == "image":- parts.append("".join(child.content for child in token.children or [] if child.type in _ALT_TOKENS))- return "".join(parts)+ alt = "".join(child.content for child in token.children or [] if child.type in _ALT_TOKENS)+ parts.append(_Part(text=alt, prose=False))+ return parts+++def _rendered_parts(markdown: str) -> list[_Part]:+ tokens: list[Token] = MARKDOWN.parseInline(collapsed_whitespace(markdown))+ return [part for token in tokens for part in _inline_parts(token.children or [])]def rendered_text(markdown: str) -> str:"""The text a reader sees. Dates and bare GitHub links change only in prose, never in code or link targets."""- tokens: list[Token] = MARKDOWN.parseInline(collapsed_whitespace(markdown))- return "".join(_inline_text(token.children or []) for token in tokens)+ return "".join(part.text for part in _rendered_parts(markdown))+++def rendered_prose(markdown: str) -> str:+ """`rendered_text` with code, links and images blanked, so offsets still match it."""+ return "".join(part.text if part.prose else " " * len(part.text) for part in _rendered_parts(markdown))diff --git a/products/today/backend/logic/sentences.py b/products/today/backend/logic/sentences.pyindex 4bc9fb0f54c9..d6fdcc3c5611 100644--- a/products/today/backend/logic/sentences.py+++ b/products/today/backend/logic/sentences.py@@ -65,6 +65,10 @@ def _sentences_at(text: str, breaks: list[int]) -> list[tuple[int, str]]:return [(start, text[start:end]) for start, end in zip(edges, edges[1:]) if start < end]+def split_sentences(text: str) -> list[tuple[int, str]]:+ return _sentences_at(text, _sentence_breaks(text, _CLOSE))++def _backtick_run_end(text: str, start: int) -> int:end = startwhile end < len(text) and text[end] == _BACKTICK:diff --git a/products/today/backend/presentation/serializers.py b/products/today/backend/presentation/serializers.pyindex 6709828aeaee..41149722c98d 100644--- a/products/today/backend/presentation/serializers.py+++ b/products/today/backend/presentation/serializers.py@@ -16,17 +16,21 @@ from ..facade.contracts import (CandidateFact,CandidateList,CodeFile,+ FigureMark,+ FigureQuote,ImpactNumber,ImpactWorking,+ KeyClause,PageLink,PreviewLine,PullRequestLink,RecordingTarget,+ ReportKeyClauses,ReportPage,SignalPreview,SignalView,)-from ..facade.enums import CitedSource, ImpactNumberKey+from ..facade.enums import CitedSource, FigureSourceKind, FigureText, ImpactNumberKey, KeyClauseRoleclass TodayQuerySerializer(serializers.Serializer):@@ -189,6 +193,22 @@ class CandidateListSerializer(DataclassSerializer):dataclass = CandidateList+class ExcerptChoiceRequestSerializer(serializers.Serializer):+ finding = serializers.CharField(max_length=6000, help_text="The finding the code excerpts should show.")+ excerpts = serializers.ListField(+ child=serializers.CharField(max_length=2000),+ min_length=2,+ max_length=5,+ help_text="Candidate code excerpts, best scored first.",+ )+++class ExcerptChoiceSerializer(serializers.Serializer):+ index = serializers.IntegerField(+ allow_null=True, help_text="The excerpt that shows what the finding describes, or null when unsure."+ )++class PullRequestLinkSerializer(DataclassSerializer):url = serializers.CharField(help_text="The pull request on GitHub.")number = serializers.IntegerField(help_text="The pull request number.")@@ -329,3 +349,66 @@ class ReportPageSerializer(DataclassSerializer):class Meta:dataclass = ReportPage+++class KeyClausesQuerySerializer(serializers.Serializer):+ include_impact = serializers.BooleanField(+ default=True,+ help_text="Whether to mark the impact sentence. Pass false when the page shows an impact number instead.",+ )+++class KeyClauseSerializer(DataclassSerializer):+ start = serializers.IntegerField(help_text="Where the clause starts in its text, as the reader sees it.")+ end = serializers.IntegerField(help_text="Where the clause ends in its text.")+ role = serializers.ChoiceField(choices=KeyClauseRole.choices, help_text="What the clause tells the reader.")+ expansion = serializers.ListField(+ child=serializers.CharField(), help_text="Sentences from the report that explain the clause further."+ )++ class Meta:+ dataclass = KeyClause+++class ReportKeyClausesSerializer(DataclassSerializer):+ lead = KeyClauseSerializer(many=True, help_text="The clauses that state the problem or its cause in the lead.")+ impact = KeyClauseSerializer(+ many=True, help_text="The clauses that state the problem or its cause in the impact sentence."+ )+ proposal = KeyClauseSerializer(many=True, help_text="The clause that states the fix in the proposal.")++ class Meta:+ dataclass = ReportKeyClauses+++class FigureQuoteSerializer(DataclassSerializer):+ kind = serializers.ChoiceField(+ choices=FigureSourceKind.choices, help_text="Where the number comes from: a signal or the agent's research."+ )+ signal = SignalViewSerializer(+ allow_null=True, help_text="The signal that states the number. Null when the agent's research states it."+ )+ at = serializers.DateTimeField(help_text="When the source was written.")+ sentence = serializers.CharField(help_text="The source sentence that states the number.")+ start = serializers.IntegerField(help_text="Where the number starts in the sentence.")+ end = serializers.IntegerField(help_text="Where the number ends in the sentence.")++ class Meta:+ dataclass = FigureQuote+++class FigureMarkSerializer(DataclassSerializer):+ text = serializers.ChoiceField(+ choices=FigureText.choices, help_text="The page text the number is in: the lead or the impact sentence."+ )+ start = serializers.IntegerField(help_text="Where the number starts in that text, as the reader sees it.")+ end = serializers.IntegerField(help_text="Where the number ends in that text.")+ figure = serializers.CharField(help_text="The number as the page shows it.")+ quote = FigureQuoteSerializer(help_text="The sentence that states the same result.")++ class Meta:+ dataclass = FigureMark+++class FigureMarksSerializer(serializers.Serializer):+ marks = FigureMarkSerializer(many=True, help_text="The numbers to mark, at most 4, each with its source.")diff --git a/products/today/backend/presentation/views.py b/products/today/backend/presentation/views.pyindex 2ed086784e84..ca1b24e70bd5 100644--- a/products/today/backend/presentation/views.py+++ b/products/today/backend/presentation/views.py@@ -1,28 +1,78 @@"""DRF views for today. They read the request, call the facade and serialize the result."""+from collections.abc import Iterator+from contextlib import contextmanagerfrom typing import cast+import structlogfrom drf_spectacular.utils import OpenApiResponse-from rest_framework import viewsets+from rest_framework import status, viewsetsfrom rest_framework.decorators import action-from rest_framework.exceptions import NotFound, PermissionDenied+from rest_framework.exceptions import APIException, NotFound, PermissionDeniedfrom rest_framework.request import Requestfrom rest_framework.response import Response+from rest_framework.throttling import UserRateThrottlefrom posthog.api.mixins import validated_requestfrom posthog.api.routing import TeamAndOrgViewSetMixin+from posthog.llm.system_one import SystemOneNotConfigured, SystemOneRequestFailedfrom posthog.models import User+from posthog.rate_limit import BurstRateThrottle, SustainedRateThrottlefrom posthog.utils import UUID_REGEXfrom products.signals.backend.facade import api as signals-from ..facade import api-from .serializers import BriefingSerializer, CandidateListSerializer, ReportPageSerializer, TodayQuerySerializer+from ..facade import api, contracts+from .serializers import (+ BriefingSerializer,+ CandidateListSerializer,+ ExcerptChoiceRequestSerializer,+ ExcerptChoiceSerializer,+ FigureMarksSerializer,+ KeyClausesQuerySerializer,+ ReportKeyClausesSerializer,+ ReportPageSerializer,+ TodayQuerySerializer,+)++logger = structlog.get_logger(__name__)+JEV_UNAVAILABLE = OpenApiResponse(description="The decision model is unavailable.")+++class JevUnavailable(APIException):+ status_code = status.HTTP_503_SERVICE_UNAVAILABLE+ default_detail = "The decision model is unavailable."+ default_code = "jev_unavailable"+++class JevBurstThrottle(UserRateThrottle):+ scope = "today_jev_burst"+ rate = "60/minute"+++class JevSustainedThrottle(UserRateThrottle):+ scope = "today_jev_sustained"+ rate = "1500/day"+++JEV_THROTTLES = [BurstRateThrottle, SustainedRateThrottle, JevBurstThrottle, JevSustainedThrottle]+++@contextmanager+def _jev_errors_as_responses(team_id: int) -> Iterator[None]:+ try:+ yield+ except SystemOneRequestFailed as error:+ logger.warning("today_jev_unavailable", team_id=team_id, reason=type(error).__name__, status=error.status_code)+ raise JevUnavailable() from error+ except (SystemOneNotConfigured, contracts.JevTimedOut) as error:+ logger.warning("today_jev_unavailable", team_id=team_id, reason=type(error).__name__)+ raise JevUnavailable() from errorclass TodayViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):scope_object = "today"- scope_object_read_actions = ["briefing", "candidates"]+ scope_object_read_actions = ["briefing", "candidates", "excerpt_choice"]scope_object_write_actions = ["refresh"]def _user(self) -> User:@@ -32,6 +82,12 @@ class TodayViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):raise NotFound()return user+ def _jev_user(self) -> User:+ user = cast(User, self.request.user)+ if not api.may_ask_jev(user, self.team):+ raise NotFound()+ return user+def _check_report_access(self, user: User) -> None:if not signals.may_read_reports(user=user, team=self.team):raise PermissionDenied()@@ -104,3 +160,73 @@ class TodayViewSet(TeamAndOrgViewSetMixin, viewsets.ViewSet):if page is None:raise NotFound()return Response(ReportPageSerializer(page).data)++ @validated_request(+ query_serializer=KeyClausesQuerySerializer,+ responses={+ 200: OpenApiResponse(response=ReportKeyClausesSerializer),+ 503: JEV_UNAVAILABLE,+ },+ summary="Mark the key clauses of a report",+ description="The clauses in the report page's lead, impact sentence and proposal that state the problem, its cause or the fix, each with sentences from the report that explain it. Only clauses the report explains further are returned, at most 2 across all texts. 404 when the report is missing or the person may not use Jev.",+ )+ @action(+ detail=False,+ methods=["get"],+ url_path=rf"reports/(?P<report_id>{UUID_REGEX})/key_clauses",+ required_scopes=["today:read", "task:read"],+ throttle_classes=JEV_THROTTLES,+ )+ def key_clauses(self, request: Request, report_id: str, **kwargs) -> Response:+ user = self._jev_user()+ self._check_report_access(user)+ include_impact = request.validated_query_data["include_impact"]+ with _jev_errors_as_responses(self.team.id):+ found = api.report_key_clauses(+ team=self.team, user=user, report_id=report_id, include_impact=include_impact+ )+ if found is None:+ raise NotFound()+ return Response(ReportKeyClausesSerializer(found).data)++ @validated_request(+ responses={200: OpenApiResponse(response=FigureMarksSerializer), 503: JEV_UNAVAILABLE},+ summary="Mark the numbers of a report with their sources",+ description="The numbers in the report's lead and impact sentence that a signal or the agent's research states, each with the sentence that states it. A number is marked only when the decision model is sure it is a measured result and that one source states the same result. 404 when the report is missing or the person may not use Jev.",+ )+ @action(+ detail=False,+ methods=["get"],+ url_path=rf"reports/(?P<report_id>{UUID_REGEX})/figure_marks",+ required_scopes=["today:read", "task:read"],+ throttle_classes=JEV_THROTTLES,+ )+ def figure_marks(self, request: Request, report_id: str, **kwargs) -> Response:+ user = self._jev_user()+ self._check_report_access(user)+ with _jev_errors_as_responses(self.team.id):+ marks = api.report_figure_marks(team=self.team, user=user, report_id=report_id)+ if marks is None:+ raise NotFound()+ return Response(FigureMarksSerializer({"marks": marks}).data)++ @validated_request(+ request_serializer=ExcerptChoiceRequestSerializer,+ responses={+ 200: OpenApiResponse(response=ExcerptChoiceSerializer),+ 503: JEV_UNAVAILABLE,+ },+ summary="Pick the code excerpt a finding describes",+ description="Asks the decision model which of several code excerpts shows what a finding describes. Returns null when it is unsure. 404 when the person may not use Jev.",+ )+ @action(detail=False, methods=["post"], url_path="excerpt_choice", throttle_classes=JEV_THROTTLES)+ def excerpt_choice(self, request: Request, **kwargs) -> Response:+ user = self._jev_user()+ with _jev_errors_as_responses(self.team.id):+ index = api.pick_code_excerpt(+ team=self.team,+ user=user,+ finding=request.validated_data["finding"],+ excerpts=request.validated_data["excerpts"],+ )+ return Response(ExcerptChoiceSerializer({"index": index}).data)diff --git a/products/today/backend/tests/factories.py b/products/today/backend/tests/factories.pyindex 7b11e2142642..b716295ad11b 100644--- a/products/today/backend/tests/factories.py+++ b/products/today/backend/tests/factories.py@@ -2,6 +2,16 @@ from datetime import datetimefrom typing import Anyfrom products.signals.backend.facade import api as signals+from products.today.backend.logic.figure_sources import (+ KIND_MEASURED,+ KIND_QUESTION,+ NAMED_LABELS,+ NAMED_QUESTION,+ RELATION_QUESTION,+ RELATION_SAME,+ SOURCE_QUESTION,+)+from products.today.backend.logic.jev import JevPickfrom products.today.backend.logic.signal_text import SignalInput@@ -40,3 +50,56 @@ def page_source(repo_slug="example/web",signals=[],)+++SURE = 0.95+AGREEING = {+ KIND_QUESTION: JevPick(label=KIND_MEASURED, probability=SURE),+ SOURCE_QUESTION: JevPick(label="A", probability=SURE),+ RELATION_QUESTION: JevPick(label=RELATION_SAME, probability=SURE),+ NAMED_QUESTION: JevPick(label=NAMED_LABELS[0], probability=SURE),+}+++class SameAnswerJev:+ def __init__(self, answers: dict[str, JevPick]) -> None:+ self._answers = answers+ self.asked: list[str] = []++ def choice(self, items: list[str], question: str, labels: list[str]) -> list[JevPick | None]:+ self.asked.append(question)+ return [self._answers[question] for _ in items]++ def yes_probability(self, items: list[str], question: str) -> list[float | None]:+ return [None for _ in items]+++class FakeJev:+ def __init__(self, texts: list[str], roles: dict[str, JevPick], explanations: dict[str, str]) -> None:+ self.texts = texts+ self.roles = roles+ self.explanations = explanations++ def _marked_part(self, item: str) -> str:+ part = item+ for text in self.texts:+ part = part.replace(text, "")+ return next((clause for clause in self.roles if clause in part), "")++ def choice(self, items: list[str], question: str, labels: list[str]) -> list[JevPick | None]:+ return [self.roles.get(self._marked_part(item)) for item in items]++ def yes_probability(self, items: list[str], question: str) -> list[float | None]:+ return [+ 0.9 if any(clause in item and sentence in item for clause, sentence in self.explanations.items()) else 0.1+ for item in items+ ]+++class PickJev(FakeJev):+ def __init__(self, pick: JevPick | None) -> None:+ super().__init__([], {}, {})+ self.pick = pick++ def choice(self, items: list[str], question: str, labels: list[str]) -> list[JevPick | None]:+ return [self.pick for _ in items]diff --git a/products/today/backend/tests/test_api.py b/products/today/backend/tests/test_api.pyindex 6cec753f93a1..1ecbd608e5cc 100644--- a/products/today/backend/tests/test_api.py+++ b/products/today/backend/tests/test_api.py@@ -1,25 +1,43 @@+import json+from dataclasses import replacefrom datetime import UTC, datetimeimport time_machinefrom posthog.test.base import APIBaseTestfrom unittest.mock import AsyncMock, MagicMock, patch+from django.core.cache import cache+from parameterized import parameterizedfrom rest_framework import statusfrom posthog.constants import AvailableFeature+from posthog.llm.system_one import (+ ChoiceAnswer,+ Question,+ SystemOneNotConfigured,+ SystemOneRequestFailed,+ SystemOneResult,+)+from posthog.llm.system_one_client import GatewaySystemOneClientfrom posthog.models import PersonalAPIKey, Team, Userfrom posthog.models.personal_api_key import hash_key_valuefrom products.access_control.backend.models.access_control import AccessControl+from products.signals.backend.facade import api as signalsfrom products.signals.backend.models import SignalReportfrom products.today.backend.facade.enums import BriefingStatus, BriefingTriggerfrom products.today.backend.logic import briefings+from products.today.backend.logic.jev import JevPickfrom products.today.backend.models import DailyBriefingfrom products.today.backend.tests.conftest import TodayTeamScopedTestMixin-from products.today.backend.tests.factories import page_source+from products.today.backend.tests.factories import AGREEING, FakeJev, SameAnswerJev, page_source+from products.today.backend.tests.test_key_clauses import CART_TEXT, CAUSE, CAUSE_EXPLAINED, SUMMARYREPORT_ID = "01a10212-6f09-0000-0ed6-46b2df6f81ca"+FIGURE_LEAD = "🚨 The export failed for 212 users."+FIGURE_SOURCE = "On Monday 🚨 the export failed for 212 users."+WRITTEN_AT = datetime(2026, 10, 1, 9, 0, tzinfo=UTC)@patch("products.today.backend.logic.briefings.sync_connect")@@ -29,8 +47,13 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):self.organization.is_ai_data_processing_approved = Trueself.organization.save()- def _flag(self, enabled: bool):- return patch("products.today.backend.feature_flags.feature_enabled_or_false", return_value=enabled)+ def _flag(self, enabled: bool | frozenset[str]):+ if isinstance(enabled, bool):+ return patch("products.today.backend.feature_flags.feature_enabled_or_false", return_value=enabled)+ return patch(+ "products.today.backend.feature_flags.feature_enabled_or_false",+ side_effect=lambda flag, *args, **kwargs: flag in enabled,+ )@parameterized.expand([@@ -158,6 +181,174 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):assert DailyBriefing.objects.for_team(self.team.id).filter(user_id=other.id).count() == 1assert DailyBriefing.objects.for_team(self.team.id).count() == 2+ @parameterized.expand(+ [+ ("flag on", True, REPORT_ID, None, status.HTTP_200_OK),+ ("flag off", False, REPORT_ID, None, status.HTTP_404_NOT_FOUND),+ (+ "the jev flag without the new navigation",+ frozenset({"today-report-jev"}),+ REPORT_ID,+ None,+ status.HTTP_404_NOT_FOUND,+ ),+ ("not a report id", True, "report-1", None, status.HTTP_404_NOT_FOUND),+ ("no gateway", True, REPORT_ID, SystemOneNotConfigured("no gateway"), status.HTTP_503_SERVICE_UNAVAILABLE),+ (+ "the gateway refuses to bill",+ True,+ REPORT_ID,+ SystemOneRequestFailed("payment required", status_code=402),+ status.HTTP_503_SERVICE_UNAVAILABLE,+ ),+ ]+ )+ def test_key_clauses_answer_only_people_who_may_use_jev_even_without_ai_credits(+ self,+ _sync_connect: MagicMock,+ _name: str,+ flag: bool | frozenset[str],+ report_id: str,+ gateway_error: Exception | None,+ expected: int,+ ) -> None:+ jev = FakeJev([CART_TEXT], {CAUSE: JevPick(label="cause", probability=0.9)}, {CAUSE: CAUSE_EXPLAINED})+ page = replace(+ page_source(summary=SUMMARY),+ sections=signals.ReportSections(lead=CART_TEXT, impact=None, solution=None),+ )+ with (+ self._flag(flag),+ patch("products.today.backend.feature_flags.is_team_limited", return_value=True),+ patch("products.today.backend.facade.api.signals.report_page_source", return_value=page),+ patch("products.today.backend.facade.api.GatewayJev", return_value=jev, side_effect=gateway_error),+ ):+ response = self.client.get(f"/api/projects/{self.team.id}/today/reports/{report_id}/key_clauses/")++ assert response.status_code == expected+ if expected == status.HTTP_200_OK:+ found = response.json()+ assert (found["impact"], found["proposal"]) == ([], [])+ assert [+ (CART_TEXT[clause["start"] : clause["end"]], clause["role"], clause["expansion"])+ for clause in found["lead"]+ ] == [(CAUSE, "cause", [CAUSE_EXPLAINED])]++ @parameterized.expand(+ [+ ("a signal states the number", True, "signal", None, status.HTTP_200_OK),+ ("the agent's research states the number", True, "research", None, status.HTTP_200_OK),+ ("flag off", False, "signal", None, status.HTTP_404_NOT_FOUND),+ ("no gateway", True, "signal", SystemOneNotConfigured("no gateway"), status.HTTP_503_SERVICE_UNAVAILABLE),+ ]+ )+ def test_figure_marks_name_the_sentence_that_states_each_number(+ self,+ _sync_connect: MagicMock,+ _name: str,+ flag: bool,+ source_kind: str,+ gateway_error: Exception | None,+ expected: int,+ ) -> None:+ signal = signals.ReportSignal(+ signal_id="signal-1",+ content=FIGURE_SOURCE,+ source_product="error_tracking",+ source_type="issue",+ source_id="issue-1",+ timestamp=WRITTEN_AT,+ extra={},+ )+ finding = signals.ReportArtefactText(+ artefact_id="artefact-1",+ type="signal_finding",+ content=json.dumps({"data_queried": FIGURE_SOURCE}),+ created_at=WRITTEN_AT,+ )+ page = replace(+ page_source(),+ sections=signals.ReportSections(lead=FIGURE_LEAD, impact=None, solution=None),+ signals=[signal] if source_kind == "signal" else [],+ )+ with (+ self._flag(flag),+ patch("products.today.backend.facade.api.signals.report_page_source", return_value=page),+ patch(+ "products.today.backend.facade.api.signals.report_agent_texts",+ return_value=[finding] if source_kind == "research" else [],+ ),+ patch(+ "products.today.backend.facade.api.GatewayJev",+ return_value=SameAnswerJev(AGREEING),+ side_effect=gateway_error,+ ),+ ):+ response = self.client.get(f"/api/projects/{self.team.id}/today/reports/{REPORT_ID}/figure_marks/")++ assert response.status_code == expected+ if expected == status.HTTP_200_OK:+ marks = response.json()["marks"]+ quote_signal = marks[0]["quote"].pop("signal")+ assert (quote_signal or {}).get("signal_id") == ("signal-1" if source_kind == "signal" else None)+ assert marks == [+ {+ "text": "lead",+ "start": FIGURE_LEAD.index("212") + 1,+ "end": FIGURE_LEAD.index("212") + 4,+ "figure": "212",+ "quote": {+ "kind": source_kind,+ "at": "2026-10-01T09:00:00Z",+ "sentence": FIGURE_SOURCE,+ "start": FIGURE_SOURCE.index("212") + 1,+ "end": FIGURE_SOURCE.index("212") + 4,+ },+ }+ ]++ @parameterized.expand(+ [+ ("a sure pick", ChoiceAnswer(choice="2", confidence=0.9, probabilities={}), status.HTTP_200_OK, 1),+ ("an unsure pick", ChoiceAnswer(choice="2", confidence=0.3, probabilities={}), status.HTTP_200_OK, None),+ ("a failing gateway", SystemOneRequestFailed("bad gateway", status_code=502), 503, None),+ ("a gateway that refuses to bill", SystemOneRequestFailed("payment required", status_code=402), 503, None),+ ]+ )+ def test_excerpt_choice_asks_the_gateway_once_for_the_finding(+ self,+ _sync_connect: MagicMock,+ _name: str,+ outcome: ChoiceAnswer | Exception,+ expected: int,+ index: int | None,+ ) -> None:+ cache.clear()+ client = GatewaySystemOneClient(+ url="https://gateway.example.com", api_key="test-key", headers={}, model="jev", timeout=30+ )++ def adecide(state: dict[str, str], questions: dict[str, Question]) -> SystemOneResult:+ if isinstance(outcome, Exception):+ raise outcome+ return SystemOneResult(model="jev", answers=dict.fromkeys(questions, outcome), input_tokens=1)++ with (+ self._flag(True),+ patch("products.today.backend.logic.jev.build_system_one_client", return_value=client),+ patch.object(GatewaySystemOneClient, "adecide", AsyncMock(side_effect=adecide)) as decide,+ ):+ response = self.client.post(+ f"/api/projects/{self.team.id}/today/excerpt_choice/",+ {"finding": "The cart drops the token.", "excerpts": ["a = 1", "drop(token)"]},+ format="json",+ )++ assert response.status_code == expected+ assert decide.await_count == 1+ if expected == status.HTTP_200_OK:+ assert response.json() == {"index": index}+@parameterized.expand([("a report", True, REPORT_ID, status.HTTP_200_OK, "Lead."),@@ -181,12 +372,14 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):@parameterized.expand([- ("today only", ["today:read"], status.HTTP_403_FORBIDDEN),- ("today and signals", ["today:read", "task:read"], status.HTTP_200_OK),+ ("the page with only today", "get", "page", ["today:read"], status.HTTP_403_FORBIDDEN),+ ("the page with today and signals", "get", "page", ["today:read", "task:read"], status.HTTP_200_OK),+ ("key clauses with only today", "get", "key_clauses", ["today:read"], status.HTTP_403_FORBIDDEN),+ ("figure marks with only today", "get", "figure_marks", ["today:read"], status.HTTP_403_FORBIDDEN),])- def test_a_scoped_key_reads_the_report_page_only_with_the_signals_scope(- self, _sync_connect: MagicMock, _name: str, scopes: list[str], expected: int+ def test_a_scoped_key_reads_report_data_only_with_the_signals_scope(+ self, _sync_connect: MagicMock, _name: str, method: str, endpoint: str, scopes: list[str], expected: int) -> None:raw_key = "today_report_page_key"PersonalAPIKey.objects.create(@@ -197,20 +390,23 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):self._flag(True),patch("products.today.backend.logic.report_page.signals.report_page_source", return_value=page_source()),):- response = self.client.get(- f"/api/projects/{self.team.id}/today/reports/{REPORT_ID}/page/", HTTP_AUTHORIZATION=f"Bearer {raw_key}"+ response = getattr(self.client, method)(+ f"/api/projects/{self.team.id}/today/reports/{REPORT_ID}/{endpoint}/",+ HTTP_AUTHORIZATION=f"Bearer {raw_key}",)assert response.status_code == expected@parameterized.expand([- ("can read inbox reports", None, status.HTTP_200_OK),- ("may not read inbox reports", "none", status.HTTP_403_FORBIDDEN),+ ("the page, with access", "page", None, status.HTTP_200_OK),+ ("the page, without access", "page", "none", status.HTTP_403_FORBIDDEN),+ ("key clauses, without access", "key_clauses", "none", status.HTTP_403_FORBIDDEN),+ ("figure marks, without access", "figure_marks", "none", status.HTTP_403_FORBIDDEN),])- def test_a_member_reads_the_report_page_only_with_access_to_inbox_reports(- self, _sync_connect: MagicMock, _name: str, task_access: str | None, expected: int+ def test_a_member_reads_report_data_only_with_access_to_inbox_reports(+ self, _sync_connect: MagicMock, _name: str, endpoint: str, task_access: str | None, expected: int) -> None:self.organization.available_product_features = [{"key": AvailableFeature.ACCESS_CONTROL, "name": AvailableFeature.ACCESS_CONTROL}@@ -219,11 +415,12 @@ class TestTodayAPI(TodayTeamScopedTestMixin, APIBaseTest):if task_access is not None:AccessControl.objects.create(team=self.team, resource="task", resource_id=None, access_level=task_access)self.client.force_login(User.objects.create_and_join(self.organization, "[email protected]", "testtest"))+ url = f"/api/projects/{self.team.id}/today/reports/{REPORT_ID}/{endpoint}/"with (self._flag(True),patch("products.today.backend.logic.report_page.signals.report_page_source", return_value=page_source()),):- response = self.client.get(f"/api/projects/{self.team.id}/today/reports/{REPORT_ID}/page/")+ response = self.client.get(url)assert response.status_code == expecteddiff --git a/products/today/backend/tests/test_code_excerpts.py b/products/today/backend/tests/test_code_excerpts.pynew file mode 100644index 000000000000..46d57f0fa641--- /dev/null+++ b/products/today/backend/tests/test_code_excerpts.py@@ -0,0 +1,21 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from products.today.backend.logic.code_excerpts import which_excerpt+from products.today.backend.logic.jev import JevPick+from products.today.backend.tests.factories import PickJev+++class TestCodeExcerpts(SimpleTestCase):+ @parameterized.expand(+ [+ ("a sure pick", JevPick(label="2", probability=0.8), 1),+ ("an unsure pick", JevPick(label="2", probability=0.4), None),+ ("no pick", None, None),+ ]+ )+ def test_picks_the_excerpt_a_finding_describes(+ self, _name: str, pick: JevPick | None, expected: int | None+ ) -> None:+ assert which_excerpt("The cart drops the token.", ["a = 1", "drop(token)"], PickJev(pick)) == expecteddiff --git a/products/today/backend/tests/test_figure_sources.py b/products/today/backend/tests/test_figure_sources.pynew file mode 100644index 000000000000..853afebe3557--- /dev/null+++ b/products/today/backend/tests/test_figure_sources.py@@ -0,0 +1,96 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from products.today.backend.facade.enums import FigureText+from products.today.backend.logic.figure_sources import (+ KIND_LABELS,+ KIND_QUESTION,+ NAMED_LABELS,+ NAMED_QUESTION,+ RELATION_QUESTION,+ SOURCE_QUESTION,+ UNNAMED,+ match_figures,+)+from products.today.backend.logic.jev import JevPick+from products.today.backend.tests.factories import AGREEING, SURE, SameAnswerJev, signal++ALL_QUESTIONS = [KIND_QUESTION, SOURCE_QUESTION, RELATION_QUESTION, NAMED_QUESTION]+++class TestFigureSources(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "marks a measured number that one source states",+ "The export failed for 212 users.",+ ["On Monday the export failed for 212 users."],+ {},+ [("212", "On Monday the export failed for 212 users.")],+ ALL_QUESTIONS,+ ),+ (+ "never marks a zero",+ "The scanner saw 0 sessions.",+ ["The scanner saw 0 sessions."],+ {},+ [],+ [],+ ),+ (+ "never marks a scaled zero or a zero range",+ "The scanner saw 0K sessions and 0–0 errors.",+ ["The scanner saw 0K sessions and 0–0 errors."],+ {},+ [],+ [],+ ),+ (+ "drops the mark when Jev does not read the number as a measured result",+ "The export failed for 212 users.",+ ["On Monday the export failed for 212 users."],+ {KIND_QUESTION: JevPick(label=KIND_LABELS[1], probability=SURE)},+ [],+ [KIND_QUESTION],+ ),+ (+ "drops the mark when the option order changes the source Jev picks",+ "The export failed for 212 users.",+ ["On Monday the export failed for 212 users.", "We count 212 users in the EU."],+ {},+ [],+ [KIND_QUESTION, SOURCE_QUESTION],+ ),+ (+ "drops the mark when the source does not say what the number counts",+ "The export failed for 212 users.",+ ["Result: 212."],+ {NAMED_QUESTION: JevPick(label=UNNAMED, probability=SURE)},+ [],+ ALL_QUESTIONS,+ ),+ (+ "drops the mark when Jev is unsure the source says what the number counts",+ "The export failed for 212 users.",+ ["On Monday the export failed for 212 users."],+ {NAMED_QUESTION: JevPick(label=NAMED_LABELS[0], probability=0.6)},+ [],+ ALL_QUESTIONS,+ ),+ ]+ )+ def test_marks_only_proven_numbers_and_asks_only_what_the_next_step_needs(+ self,+ _name: str,+ lead: str,+ sources: list[str],+ answers: dict[str, JevPick],+ expected: list[tuple[str, str]],+ asked: list[str],+ ) -> None:+ signals = [signal(content=text, signal_id=f"signal-{index}") for index, text in enumerate(sources)]+ jev = SameAnswerJev({**AGREEING, **answers})+ matches = match_figures({FigureText.LEAD: lead}, signals, [], jev, {FigureText.LEAD: lead})+ assert [(match.claim.figure.text, match.source.source.sentence) for match in matches] == expected+ assert jev.asked == askeddiff --git a/products/today/backend/tests/test_figures.py b/products/today/backend/tests/test_figures.pynew file mode 100644index 000000000000..82c082ca87da--- /dev/null+++ b/products/today/backend/tests/test_figures.py@@ -0,0 +1,30 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from products.today.backend.logic.figures import numbers_in, same_amount+++class TestFigures(SimpleTestCase):+ @parameterized.expand(+ [+ ("keeps a scaled range as one number", "about 18.6K–21.4K signups", ["18.6K–21.4K"]),+ ("keeps a percent range as one number", "17–21% of loads", ["17–21%"]),+ ("keeps a range with a sign on both ends as one number", "17%–21% of loads", ["17%–21%"]),+ ("adds a duration word only to a bare count", "for 40 minutes, then 1.3% weeks", ["40 minutes", "1.3%"]),+ ("skips numbers joined to other characters", "v1.2 at 10:30 for #123", []),+ ]+ )+ def test_finds_numbers(self, _name: str, text: str, expected: list[str]) -> None:+ assert [number.text for number in numbers_in(text)] == expected++ @parameterized.expand(+ [+ ("a rounded count covers the exact value", "1.35K users", "1,348 users", True),+ ("a rounded count stops at its rounding edge", "1.35K users", "1,356 users", False),+ ("a percent never matches a count", "12% of runs", "12 runs", False),+ ("a range matches only the same range", "40–90 runs", "40 runs", False),+ ]+ )+ def test_compares_amounts(self, _name: str, claim: str, source: str, expected: bool) -> None:+ assert same_amount(numbers_in(claim)[0].amount, numbers_in(source)[0].amount) is expecteddiff --git a/products/today/backend/tests/test_jev.py b/products/today/backend/tests/test_jev.pynew file mode 100644index 000000000000..5b055baceaf5--- /dev/null+++ b/products/today/backend/tests/test_jev.py@@ -0,0 +1,85 @@+from types import SimpleNamespace++from unittest.mock import AsyncMock, patch++from django.core.cache import cache+from django.test import SimpleTestCase, override_settings++from posthog.llm.system_one import NoulAnswer, Question, SystemOneNotConfigured, SystemOneRequestFailed, SystemOneResult+from posthog.llm.system_one_client import GatewaySystemOneClient+from posthog.tasks.usage_report import POSTHOG_AI_PRODUCTS++from products.today.backend.facade.contracts import JevTimedOut+from products.today.backend.logic.jev import GatewayJev++LOCAL_CACHE = {"default": {"BACKEND": "django.core.cache.backends.locmem.LocMemCache"}}+CLIENT = GatewaySystemOneClient(+ url="https://gateway.example.com", api_key="test-key", headers={}, model="jev", timeout=30+)+++def answered(state: dict[str, str], questions: dict[str, Question]) -> SystemOneResult:+ return SystemOneResult(model="jev", answers={key: NoulAnswer(probability=0.8) for key in questions}, input_tokens=1)+++@override_settings(CACHES=LOCAL_CACHE)+class TestGatewayJev(SimpleTestCase):+ def setUp(self) -> None:+ cache.clear()++ def _ask(self, adecide: AsyncMock, items: list[str], team_id: int = 1) -> list[float | None]:+ with (+ patch("products.today.backend.logic.jev.build_system_one_client", return_value=CLIENT) as build,+ patch.object(GatewaySystemOneClient, "adecide", adecide),+ ):+ answers = GatewayJev(team_id=team_id, distinct_id="person").yes_probability(items, "Is it broken?")+ assert all(call.kwargs["ai_product"] not in POSTHOG_AI_PRODUCTS for call in build.call_args_list)+ return answers++ def test_asks_the_model_once_for_each_distinct_text(self) -> None:+ adecide = AsyncMock(side_effect=answered)++ first = self._ask(adecide, ["cart", "spinner", "cart"])+ second = self._ask(adecide, ["spinner", "cart"])+ other_team = self._ask(adecide, ["cart"], team_id=2)++ assert (first, second, other_team) == ([0.8, 0.8, 0.8], [0.8, 0.8], [0.8])+ assert [sorted(call.kwargs["state"].values()) for call in adecide.await_args_list] == [+ ["cart", "spinner"],+ ["cart"],+ ]++ def test_keeps_the_answers_of_batches_that_succeed_when_another_fails(self) -> None:+ items = [f"text {index}" for index in range(40)]++ def first_batch_fails(state: dict[str, str], questions: dict[str, Question]) -> SystemOneResult:+ if "text 0" in state.values():+ raise SystemOneRequestFailed("gateway down", status_code=500)+ return answered(state, questions)++ with self.assertRaises(SystemOneRequestFailed):+ self._ask(AsyncMock(side_effect=first_batch_fails), items)+ retry = AsyncMock(side_effect=answered)++ assert self._ask(retry, items) == [0.8] * 40+ assert [len(call.kwargs["state"]) for call in retry.await_args_list] == [32]++ def test_stops_asking_once_the_request_deadline_passes(self) -> None:+ clock = SimpleNamespace(now=0.0)+ with (+ patch("products.today.backend.logic.jev.build_system_one_client", return_value=CLIENT),+ patch.object(GatewaySystemOneClient, "adecide", AsyncMock(side_effect=answered)),+ patch("products.today.backend.logic.jev.time", SimpleNamespace(monotonic=lambda: clock.now)),+ ):+ jev = GatewayJev(team_id=1, distinct_id="person")+ jev.yes_probability(["cart"], "Is it broken?")+ clock.now = 60.0+ with self.assertRaises(JevTimedOut):+ jev.yes_probability(["spinner"], "Is it broken?")++ def test_answers_from_the_cache_without_a_gateway(self) -> None:+ self._ask(AsyncMock(side_effect=answered), ["cart"])+ with patch(+ "products.today.backend.logic.jev.build_system_one_client", side_effect=SystemOneNotConfigured("no gateway")+ ):+ assert GatewayJev(team_id=1, distinct_id="person").yes_probability(["cart"], "Is it broken?") == [0.8]diff --git a/products/today/backend/tests/test_key_clauses.py b/products/today/backend/tests/test_key_clauses.pynew file mode 100644index 000000000000..e5ac9cc21916--- /dev/null+++ b/products/today/backend/tests/test_key_clauses.py@@ -0,0 +1,150 @@+from django.test import SimpleTestCase++from parameterized import parameterized++from products.today.backend.facade.contracts import KeyClause+from products.today.backend.facade.enums import KeyClauseRole+from products.today.backend.logic.jev import JevPick+from products.today.backend.logic.key_clauses import KeyClauseRequest, find_key_clauses, text_clauses+from products.today.backend.tests.factories import FakeJev++CART_TEXT = "Shoppers see an empty cart, a frozen spinner, and a blank receipt because the cart service drops the session token."+FIX_TEXT = "Keep the token in a cookie so the cart survives the switch."+CART_EXPLAINED = "The cart page renders before the session loads and shows zero items."+SPINNER_EXPLAINED = "The spinner waits on a price request that never returns."+CAUSE_EXPLAINED = "The service drops the token when a shopper moves from the app to the browser."+FIX_EXPLAINED = "A cookie keeps the token across that move for one extra header."+SUMMARY = "\n\n".join([CART_TEXT, FIX_TEXT, CART_EXPLAINED, SPINNER_EXPLAINED, CAUSE_EXPLAINED, FIX_EXPLAINED])+EMPTY_CART = "Shoppers see an empty cart"+FROZEN_SPINNER = "a frozen spinner"+CAUSE = "because the cart service drops the session token"+FIX = "Keep the token in a cookie"+++def shown(requests: list[KeyClauseRequest], found: list[list[KeyClause]]) -> dict[str, list[tuple[str, list[str]]]]:+ return {+ request.text: [(request.text[clause.start : clause.end], clause.expansion) for clause in own]+ for request, own in zip(requests, found)+ }+++PROBLEM_AND_CAUSE = [KeyClauseRole.PROBLEM, KeyClauseRole.CAUSE]+++class TestKeyClauses(SimpleTestCase):+ @parameterized.expand(+ [+ (+ "punctuation and a word that opens a clause",+ "Shoppers on the mobile app see an empty cart, a frozen spinner, and a blank receipt because the cart service drops the session token.",+ [+ "Shoppers on the mobile app see an empty cart",+ "a frozen spinner",+ "and a blank receipt",+ "because the cart service drops the session token",+ ],+ ),+ (+ "file names and an uppercase OR kept whole",+ "The filter in orders_view.ts joins carts across an OR, so each query scans every row.",+ ["The filter in orders_view.ts joins carts across an OR", "so each query scans every row"],+ ),+ (+ "a dash between clauses but not inside a number range",+ "Checkout fails for 120–150 shoppers a week – the coupon step drops their cart.",+ ["Checkout fails for 120–150 shoppers a week", "the coupon step drops their cart"],+ ),+ (+ "one sentence across a period when the next word is lowercase",+ "The work is already in flight. #1192 shows the cart on narrow windows, and 1,204 shoppers use it.",+ ["The work is already in flight. #1192 shows the cart on narrow windows", "and 1,204 shoppers use it"],+ ),+ ]+ )+ def test_splits_text_into_clauses(self, _name: str, text: str, expected: list[str]) -> None:+ assert [clause.text for clause in text_clauses(text)] == expected++ @parameterized.expand(+ [+ (+ "the surest clause for each role",+ {+ EMPTY_CART: JevPick(label="problem", probability=0.8),+ FROZEN_SPINNER: JevPick(label="problem", probability=0.9),+ CAUSE: JevPick(label="cause", probability=0.85),+ },+ {EMPTY_CART: CART_EXPLAINED, FROZEN_SPINNER: SPINNER_EXPLAINED, CAUSE: CAUSE_EXPLAINED},+ [(FROZEN_SPINNER, [SPINNER_EXPLAINED]), (CAUSE, [CAUSE_EXPLAINED])],+ ),+ (+ "a less sure clause the report explains, over a surer one it does not",+ {+ FROZEN_SPINNER: JevPick(label="problem", probability=0.95),+ EMPTY_CART: JevPick(label="problem", probability=0.8),+ },+ {EMPTY_CART: CART_EXPLAINED},+ [(EMPTY_CART, [CART_EXPLAINED])],+ ),+ (+ "only a clause the report explains",+ {+ FROZEN_SPINNER: JevPick(label="problem", probability=0.95),+ CAUSE: JevPick(label="cause", probability=0.8),+ },+ {CAUSE: CAUSE_EXPLAINED},+ [(CAUSE, [CAUSE_EXPLAINED])],+ ),+ (+ "nothing for an unsure role",+ {+ FROZEN_SPINNER: JevPick(label="problem", probability=0.7),+ CAUSE: JevPick(label="cause", probability=0.7),+ },+ {FROZEN_SPINNER: SPINNER_EXPLAINED, CAUSE: CAUSE_EXPLAINED},+ [],+ ),+ ]+ )+ def test_shows(+ self,+ _name: str,+ roles: dict[str, JevPick],+ explanations: dict[str, str],+ expected: list[tuple[str, list[str]]],+ ) -> None:+ requests = [KeyClauseRequest(text=CART_TEXT, roles=PROBLEM_AND_CAUSE)]+ found = find_key_clauses(requests, SUMMARY, FakeJev([CART_TEXT], roles, explanations))+ assert shown(requests, found) == {CART_TEXT: expected}++ def test_gives_each_text_its_own_clauses_and_at_most_two_across_all_texts(self) -> None:+ requests = [+ KeyClauseRequest(text=CART_TEXT, roles=PROBLEM_AND_CAUSE),+ KeyClauseRequest(text=FIX_TEXT, roles=[KeyClauseRole.FIX]),+ ]+ found = find_key_clauses(+ requests,+ SUMMARY,+ FakeJev(+ [CART_TEXT, FIX_TEXT],+ {+ FROZEN_SPINNER: JevPick(label="problem", probability=0.95),+ CAUSE: JevPick(label="cause", probability=0.8),+ FIX: JevPick(label="fix", probability=0.9),+ },+ {FROZEN_SPINNER: SPINNER_EXPLAINED, CAUSE: CAUSE_EXPLAINED, FIX: FIX_EXPLAINED},+ ),+ )+ assert shown(requests, found) == {+ CART_TEXT: [(FROZEN_SPINNER, [SPINNER_EXPLAINED])],+ FIX_TEXT: [(FIX, [FIX_EXPLAINED])],+ }++ def test_places_clauses_by_the_offsets_the_browser_counts(self) -> None:+ text = f"🛒 {CART_TEXT}"+ [clauses] = find_key_clauses(+ [KeyClauseRequest(text=text, roles=[KeyClauseRole.CAUSE])],+ SUMMARY,+ FakeJev([text], {CAUSE: JevPick(label="cause", probability=0.9)}, {CAUSE: CAUSE_EXPLAINED}),+ )+ [clause] = clauses+ assert (clause.start, clause.end) == (text.index(CAUSE) + 1, text.index(CAUSE) + 1 + len(CAUSE))diff --git a/products/today/backend/tests/test_report_page.py b/products/today/backend/tests/test_report_page.pyindex 70a120ef7a68..1001aa532d65 100644--- a/products/today/backend/tests/test_report_page.py+++ b/products/today/backend/tests/test_report_page.py@@ -6,8 +6,8 @@ from parameterized import parameterizedfrom products.signals.backend.facade import api as signalsfrom products.today.backend.logic.prose import concise_text-from products.today.backend.logic.report_page import report_page-from products.today.backend.tests.factories import page_source+from products.today.backend.logic.report_page import figure_marks, report_page+from products.today.backend.tests.factories import AGREEING, SameAnswerJev, page_source, signalSOLUTION_PR = "Reuse draft https://github.com/example/web/pull/9."@@ -124,3 +124,13 @@ class TestReportPage(SimpleTestCase):def test_sees_a_bare_reference_without_a_repository(self) -> None:page = report_page(replace(page_source(solution="PR #5 already fixes this."), repo_slug=None))assert (page.named_pull_request, page.solution_names_pull_request) == (None, True)++ def test_marks_numbers_in_prose_but_not_in_code(self) -> None:+ source = signal(content="The export failed for 212 users.")+ page = replace(+ page_source(),+ sections=signals.ReportSections(lead="`limit=212` stops 212 users.", impact=None, solution=None),+ signals=[source],+ )+ marks = figure_marks(page, [], SameAnswerJev(AGREEING))+ assert [(mark.start, mark.figure) for mark in marks] == [(16, "212")]diff --git a/products/today/frontend/generated/api.schemas.ts b/products/today/frontend/generated/api.schemas.tsindex 28443b33c23c..bd448672d2fc 100644--- a/products/today/frontend/generated/api.schemas.ts+++ b/products/today/frontend/generated/api.schemas.ts@@ -359,13 +359,51 @@ export interface CandidateListApi {more_reports_count: number}-export interface PullRequestLinkApi {- /** The pull request on GitHub. */- url: string- /** The pull request number. */- number: number+export interface ExcerptChoiceRequestApi {+ /**+ * The finding the code excerpts should show.+ * @maxLength 6000+ */+ finding: string+ /**+ * Candidate code excerpts, best scored first.+ * @minItems 2+ * @maxItems 5+ * @items.maxLength 2000+ */+ excerpts: string[]+}++export interface ExcerptChoiceApi {+ /**+ * The excerpt that shows what the finding describes, or null when unsure.+ * @nullable+ */+ index: number | null}+/**+ * * `lead` - Lead+ * * `impact` - Impact+ */+export type FigureTextEnumApi = (typeof FigureTextEnumApi)[keyof typeof FigureTextEnumApi]++export const FigureTextEnumApi = {+ Lead: 'lead',+ Impact: 'impact',+} as const++/**+ * * `signal` - Signal+ * * `research` - Agent's research+ */+export type FigureSourceKindEnumApi = (typeof FigureSourceKindEnumApi)[keyof typeof FigureSourceKindEnumApi]++export const FigureSourceKindEnumApi = {+ Signal: 'signal',+ Research: 'research',+} as const+/*** * `code` - Code* * `slack` - Slack@@ -477,6 +515,89 @@ export interface SignalViewApi {preview: SignalPreviewApi | null}+export interface FigureQuoteApi {+ /** Where the number comes from: a signal or the agent's research.+ *+ * * `signal` - Signal+ * * `research` - Agent's research */+ kind: FigureSourceKindEnumApi+ /** The signal that states the number. Null when the agent's research states it. */+ signal: SignalViewApi | null+ /** When the source was written. */+ at: string+ /** The source sentence that states the number. */+ sentence: string+ /** Where the number starts in the sentence. */+ start: number+ /** Where the number ends in the sentence. */+ end: number+}++export interface FigureMarkApi {+ /** The page text the number is in: the lead or the impact sentence.+ *+ * * `lead` - Lead+ * * `impact` - Impact */+ text: FigureTextEnumApi+ /** Where the number starts in that text, as the reader sees it. */+ start: number+ /** Where the number ends in that text. */+ end: number+ /** The number as the page shows it. */+ figure: string+ /** The sentence that states the same result. */+ quote: FigureQuoteApi+}++export interface FigureMarksApi {+ /** The numbers to mark, at most 4, each with its source. */+ marks: FigureMarkApi[]+}++/**+ * * `problem` - Problem+ * * `cause` - Cause+ * * `fix` - Fix+ */+export type KeyClauseRoleEnumApi = (typeof KeyClauseRoleEnumApi)[keyof typeof KeyClauseRoleEnumApi]++export const KeyClauseRoleEnumApi = {+ Problem: 'problem',+ Cause: 'cause',+ Fix: 'fix',+} as const++export interface KeyClauseApi {+ /** Where the clause starts in its text, as the reader sees it. */+ start: number+ /** Where the clause ends in its text. */+ end: number+ /** What the clause tells the reader.+ *+ * * `problem` - Problem+ * * `cause` - Cause+ * * `fix` - Fix */+ role: KeyClauseRoleEnumApi+ /** Sentences from the report that explain the clause further. */+ expansion: string[]+}++export interface ReportKeyClausesApi {+ /** The clauses that state the problem or its cause in the lead. */+ lead: KeyClauseApi[]+ /** The clauses that state the problem or its cause in the impact sentence. */+ impact: KeyClauseApi[]+ /** The clause that states the fix in the proposal. */+ proposal: KeyClauseApi[]+}++export interface PullRequestLinkApi {+ /** The pull request on GitHub. */+ url: string+ /** The pull request number. */+ number: number+}+/*** * `tickets` - Support tickets* * `query-hours` - Database hours@@ -560,3 +681,10 @@ export type TodayCandidatesRetrieveParams = {*/timezone?: string}++export type TodayReportsKeyClausesRetrieveParams = {+ /**+ * Whether to mark the impact sentence. Pass false when the page shows an impact number instead.+ */+ include_impact?: boolean+}diff --git a/products/today/frontend/generated/api.ts b/products/today/frontend/generated/api.tsindex 4238f0aabbea..5587036f2b87 100644--- a/products/today/frontend/generated/api.ts+++ b/products/today/frontend/generated/api.ts@@ -11,10 +11,15 @@ import { apiMutator } from '../../../../frontend/src/lib/api-orval-mutator'import type {BriefingApi,CandidateListApi,+ ExcerptChoiceApi,+ ExcerptChoiceRequestApi,+ FigureMarksApi,+ ReportKeyClausesApi,ReportPageApi,TodayBriefingRefreshCreateParams,TodayBriefingRetrieveParams,TodayCandidatesRetrieveParams,+ TodayReportsKeyClausesRetrieveParams,} from './api.schemas'export const getTodayBriefingRetrieveUrl = (projectId: string, params?: TodayBriefingRetrieveParams) => {@@ -110,6 +115,82 @@ export const todayCandidatesRetrieve = async (})}+export const getTodayExcerptChoiceCreateUrl = (projectId: string) => {+ return `/api/projects/${projectId}/today/excerpt_choice/`+}++/**+ * Asks the decision model which of several code excerpts shows what a finding describes. Returns null when it is unsure. 404 when the person may not use Jev.+ * @summary Pick the code excerpt a finding describes+ */+export const todayExcerptChoiceCreate = async (+ projectId: string,+ excerptChoiceRequestApi: ExcerptChoiceRequestApi,+ options?: RequestInit+): Promise<ExcerptChoiceApi> => {+ return apiMutator<ExcerptChoiceApi>(getTodayExcerptChoiceCreateUrl(projectId), {+ ...options,+ method: 'POST',+ headers: { 'Content-Type': 'application/json', ...options?.headers },+ body: JSON.stringify(excerptChoiceRequestApi),+ })+}++export const getTodayReportsFigureMarksRetrieveUrl = (projectId: string, reportId: string) => {+ return `/api/projects/${projectId}/today/reports/${reportId}/figure_marks/`+}++/**+ * The numbers in the report's lead and impact sentence that a signal or the agent's research states, each with the sentence that states it. A number is marked only when the decision model is sure it is a measured result and that one source states the same result. 404 when the report is missing or the person may not use Jev.+ * @summary Mark the numbers of a report with their sources+ */+export const todayReportsFigureMarksRetrieve = async (+ projectId: string,+ reportId: string,+ options?: RequestInit+): Promise<FigureMarksApi> => {+ return apiMutator<FigureMarksApi>(getTodayReportsFigureMarksRetrieveUrl(projectId, reportId), {+ ...options,+ method: 'GET',+ })+}++export const getTodayReportsKeyClausesRetrieveUrl = (+ projectId: string,+ reportId: string,+ params?: TodayReportsKeyClausesRetrieveParams+) => {+ const normalizedParams = new URLSearchParams()++ Object.entries(params || {}).forEach(([key, value]) => {+ if (value !== undefined) {+ normalizedParams.append(key, value === null ? 'null' : String(value))+ }+ })++ const stringifiedParams = normalizedParams.toString()++ return stringifiedParams.length > 0+ ? `/api/projects/${projectId}/today/reports/${reportId}/key_clauses/?${stringifiedParams}`+ : `/api/projects/${projectId}/today/reports/${reportId}/key_clauses/`+}++/**+ * The clauses in the report page's lead, impact sentence and proposal that state the problem, its cause or the fix, each with sentences from the report that explain it. Only clauses the report explains further are returned, at most 2 across all texts. 404 when the report is missing or the person may not use Jev.+ * @summary Mark the key clauses of a report+ */+export const todayReportsKeyClausesRetrieve = async (+ projectId: string,+ reportId: string,+ params?: TodayReportsKeyClausesRetrieveParams,+ options?: RequestInit+): Promise<ReportKeyClausesApi> => {+ return apiMutator<ReportKeyClausesApi>(getTodayReportsKeyClausesRetrieveUrl(projectId, reportId, params), {+ ...options,+ method: 'GET',+ })+}+export const getTodayReportsPageRetrieveUrl = (projectId: string, reportId: string) => {return `/api/projects/${projectId}/today/reports/${reportId}/page/`}diff --git a/products/today/frontend/generated/api.zod.ts b/products/today/frontend/generated/api.zod.tsindex e8a15d4e1b52..68d003731d7f 100644--- a/products/today/frontend/generated/api.zod.ts+++ b/products/today/frontend/generated/api.zod.ts@@ -7,3 +7,27 @@* PostHog API - generated* OpenAPI spec version: 1.0.0*/+import * as zod from 'zod'++/**+ * Asks the decision model which of several code excerpts shows what a finding describes. Returns null when it is unsure. 404 when the person may not use Jev.+ * @summary Pick the code excerpt a finding describes+ */+export const todayExcerptChoiceCreateBodyFindingMax = 6000++export const todayExcerptChoiceCreateBodyExcerptsItemMax = 2000++export const todayExcerptChoiceCreateBodyExcerptsMin = 2+export const todayExcerptChoiceCreateBodyExcerptsMax = 5++export const TodayExcerptChoiceCreateBody = /* @__PURE__ */ zod.object({+ finding: zod+ .string()+ .max(todayExcerptChoiceCreateBodyFindingMax)+ .describe('The finding the code excerpts should show.'),+ excerpts: zod+ .array(zod.string().max(todayExcerptChoiceCreateBodyExcerptsItemMax))+ .min(todayExcerptChoiceCreateBodyExcerptsMin)+ .max(todayExcerptChoiceCreateBodyExcerptsMax)+ .describe('Candidate code excerpts, best scored first.'),+})diff --git a/products/today/mcp/tools.yaml b/products/today/mcp/tools.yamlindex cf47880605bf..ec39a09fa157 100644--- a/products/today/mcp/tools.yaml+++ b/products/today/mcp/tools.yaml@@ -50,6 +50,15 @@ tools:urgent first.feature_flag: today-rail-navfeature_flag_behavior: enable+ today-excerpt-choice-create:+ operation: today_excerpt_choice_create+ enabled: false+ today-reports-figure-marks-retrieve:+ operation: today_reports_figure_marks_retrieve+ enabled: false+ today-reports-key-clauses-retrieve:+ operation: today_reports_key_clauses_retrieve+ enabled: falsetoday-reports-page-retrieve:operation: today_reports_page_retrieveenabled: falsediff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex daf3bcf1bb30..c861ad6a1fa4 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -41816,6 +41816,29 @@ export namespace Schemas {readonly docs_url: string;}+ export interface ExcerptChoice {+ /**+ * The excerpt that shows what the finding describes, or null when unsure.+ * @nullable+ */+ index: number | null;+ }++ export interface ExcerptChoiceRequest {+ /**+ * The finding the code excerpts should show.+ * @maxLength 6000+ */+ finding: string;+ /**+ * Candidate code excerpts, best scored first.+ * @minItems 2+ * @maxItems 5+ * @items.maxLength 2000+ */+ excerpts: string[];+ }+export interface ExecuteTestClusterRequest {/*** ClickHouse SQL to run against the test cluster.@@ -50222,6 +50245,162 @@ export namespace Schemas {readonly created_by: UserBasic;}+ /**+ * * `lead` - Lead+ * * `impact` - Impact+ */+ export type FigureTextEnum = typeof FigureTextEnum[keyof typeof FigureTextEnum];+++ export const FigureTextEnum = {+ Lead: 'lead',+ Impact: 'impact',+ } as const;++ /**+ * * `signal` - Signal+ * * `research` - Agent's research+ */+ export type FigureSourceKindEnum = typeof FigureSourceKindEnum[keyof typeof FigureSourceKindEnum];+++ export const FigureSourceKindEnum = {+ Signal: 'signal',+ Research: 'research',+ } as const;++ export interface RecordingTarget {+ /** The recording's session id. */+ session_id: string;+ /**+ * Where the player starts, a few seconds before the finding.+ * @nullable+ */+ start_at: string | null;+ /**+ * The finding's time in the recording, as MM:SS.+ * @nullable+ */+ offset: string | null;+ /**+ * Where the player starts, in seconds from the recording start. Null without an offset.+ * @nullable+ */+ seek_seconds: number | null;+ }++ export interface PageLink {+ /** Where the link goes, outside PostHog. */+ url: string;+ /** The link text. */+ text: string;+ }++ export interface PreviewLine {+ /** One line of the preview block. */+ text: string;+ /** Whether the line is secondary, such as a stack frame. */+ quiet: boolean;+ }++ export interface SignalPreview {+ /** What expanding the signal shows, such as 'Show the stack trace'. */+ hint: string;+ /** Repository files to quote, the finding's own file first. */+ code: CodeFile[];+ /** A preformatted block, such as a stack trace or a query. */+ block: PreviewLine[];+ /** The finding's text beyond its first sentence. */+ text: string;+ /** Short facts about the source. */+ facts: string[];+ /** A link that replaces the signal's own destination. */+ link: PageLink | null;+ /**+ * A label that replaces the label of the signal's own destination.+ * @nullable+ */+ link_label: string | null;+ }++ /**+ * The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON.+ */+ export type SignalViewExtra = { [key: string]: unknown };++ export interface SignalView {+ /** The signal's id. */+ signal_id: string;+ /** The product that emitted the signal. */+ source_product: string;+ /** The kind of signal within its product. */+ source_type: string;+ /** The id of the source object, such as an issue or a ticket. */+ source_id: string;+ /** The signal's text as emitted. */+ content: string;+ /** When the signal happened. */+ timestamp: string;+ /** The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON. */+ extra: SignalViewExtra;+ /** The signal as one short line. */+ headline: string;+ /** The signal's first sentence. */+ lead: string;+ /** Identifiers such as a pull request or ticket number, joined by dots. */+ meta: string;+ /** What a scout finding cites: code or a Slack thread.+ *+ * * `code` - Code+ * * `slack` - Slack */+ cited: CitedSourceEnum | null;+ /** The recording the signal plays, if any. */+ recording: RecordingTarget | null;+ /** Where a scout finding links outside PostHog, if anywhere. */+ link: PageLink | null;+ /** What expanding the signal shows, if anything. */+ preview: SignalPreview | null;+ }++ export interface FigureQuote {+ /** Where the number comes from: a signal or the agent's research.+ *+ * * `signal` - Signal+ * * `research` - Agent's research */+ kind: FigureSourceKindEnum;+ /** The signal that states the number. Null when the agent's research states it. */+ signal: SignalView | null;+ /** When the source was written. */+ at: string;+ /** The source sentence that states the number. */+ sentence: string;+ /** Where the number starts in the sentence. */+ start: number;+ /** Where the number ends in the sentence. */+ end: number;+ }++ export interface FigureMark {+ /** The page text the number is in: the lead or the impact sentence.+ *+ * * `lead` - Lead+ * * `impact` - Impact */+ text: FigureTextEnum;+ /** Where the number starts in that text, as the reader sees it. */+ start: number;+ /** Where the number ends in that text. */+ end: number;+ /** The number as the page shows it. */+ figure: string;+ /** The sentence that states the same result. */+ quote: FigureQuote;+ }++ export interface FigureMarks {+ /** The numbers to mark, at most 4, each with its source. */+ marks: FigureMark[];+ }+/*** * `hogql` - hogql*/@@ -57045,99 +57224,6 @@ export namespace Schemas {QueryHours: 'query-hours',} as const;- export interface RecordingTarget {- /** The recording's session id. */- session_id: string;- /**- * Where the player starts, a few seconds before the finding.- * @nullable- */- start_at: string | null;- /**- * The finding's time in the recording, as MM:SS.- * @nullable- */- offset: string | null;- /**- * Where the player starts, in seconds from the recording start. Null without an offset.- * @nullable- */- seek_seconds: number | null;- }-- export interface PageLink {- /** Where the link goes, outside PostHog. */- url: string;- /** The link text. */- text: string;- }-- export interface PreviewLine {- /** One line of the preview block. */- text: string;- /** Whether the line is secondary, such as a stack frame. */- quiet: boolean;- }-- export interface SignalPreview {- /** What expanding the signal shows, such as 'Show the stack trace'. */- hint: string;- /** Repository files to quote, the finding's own file first. */- code: CodeFile[];- /** A preformatted block, such as a stack trace or a query. */- block: PreviewLine[];- /** The finding's text beyond its first sentence. */- text: string;- /** Short facts about the source. */- facts: string[];- /** A link that replaces the signal's own destination. */- link: PageLink | null;- /**- * A label that replaces the label of the signal's own destination.- * @nullable- */- link_label: string | null;- }-- /**- * The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON.- */- export type SignalViewExtra = { [key: string]: unknown };-- export interface SignalView {- /** The signal's id. */- signal_id: string;- /** The product that emitted the signal. */- source_product: string;- /** The kind of signal within its product. */- source_type: string;- /** The id of the source object, such as an issue or a ticket. */- source_id: string;- /** The signal's text as emitted. */- content: string;- /** When the signal happened. */- timestamp: string;- /** The emitter's extra fields as it sent them, used to link to the source object. Values are any JSON. */- extra: SignalViewExtra;- /** The signal as one short line. */- headline: string;- /** The signal's first sentence. */- lead: string;- /** Identifiers such as a pull request or ticket number, joined by dots. */- meta: string;- /** What a scout finding cites: code or a Slack thread.- *- * * `code` - Code- * * `slack` - Slack */- cited: CitedSourceEnum | null;- /** The recording the signal plays, if any. */- recording: RecordingTarget | null;- /** Where a scout finding links outside PostHog, if anywhere. */- link: PageLink | null;- /** What expanding the signal shows, if anything. */- preview: SignalPreview | null;- }-export interface ImpactWorking {/** How the number is worked out, such as '120 ms × 30,000 calls'. */expression: string;@@ -58157,6 +58243,35 @@ export namespace Schemas {created_at: string | null;}+ /**+ * * `problem` - Problem+ * * `cause` - Cause+ * * `fix` - Fix+ */+ export type KeyClauseRoleEnum = typeof KeyClauseRoleEnum[keyof typeof KeyClauseRoleEnum];+++ export const KeyClauseRoleEnum = {+ Problem: 'problem',+ Cause: 'cause',+ Fix: 'fix',+ } as const;++ export interface KeyClause {+ /** Where the clause starts in its text, as the reader sees it. */+ start: number;+ /** Where the clause ends in its text. */+ end: number;+ /** What the clause tells the reader.+ *+ * * `problem` - Problem+ * * `cause` - Cause+ * * `fix` - Fix */+ role: KeyClauseRoleEnum;+ /** Sentences from the report that explain the clause further. */+ expansion: string[];+ }+/*** One chunk in a drill-down window over a single knowledge document.*@@ -90505,6 +90620,15 @@ export namespace Schemas {readonly updated_at: string;}+ export interface ReportKeyClauses {+ /** The clauses that state the problem or its cause in the lead. */+ lead: KeyClause[];+ /** The clauses that state the problem or its cause in the impact sentence. */+ impact: KeyClause[];+ /** The clause that states the fix in the proposal. */+ proposal: KeyClause[];+ }+/*** One impact measurement shown on a report.*/@@ -124211,6 +124335,13 @@ export namespace Schemas {timezone?: string;};+ export type TodayReportsKeyClausesRetrieveParams = {+ /**+ * Whether to mark the impact sentence. Pass false when the page shows an impact number instead.+ */+ include_impact?: boolean;+ };+export type TracingRetentionRulesListParams = {/*** Number of results to return per page.