: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(mcp): add the logic behind the explain-chart walkthrough (#122524)
Sam Pennington6071d01a6f3c
diff --git a/products/product_analytics/mcp/apps/explainChart/explainChartTypes.ts b/products/product_analytics/mcp/apps/explainChart/explainChartTypes.tsnew file mode 100644index 000000000000..1a17f099b9d7--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/explainChartTypes.ts@@ -0,0 +1,45 @@+export type StoryConfidence = 'high' | 'medium' | 'low'++export interface StoryEvidence {+ text: string+ url: string | null+ query?: Record<string, unknown> | null+}++export interface StoryChapter {+ title: string+ /** Inclusive indexes into the series' points. Null when the chapter's dates match no point on the chart. */+ range: [number, number] | null+ summary: string | null+ cause: string | null+ confidence: StoryConfidence | null+ confidenceReason: string | null+ evidence: StoryEvidence[]+}++export interface StorySeriesResult {+ label?: string+ data?: number[]+ days?: string[]+ action?: { name?: string }+}++export interface StoryTrendsQuery {+ kind: 'TrendsQuery'+ interval?: string+ trendsFilter?: Record<string, unknown>+ series?: Record<string, unknown>[]+ [key: string]: unknown+}++export interface ExplainChartData {+ query: StoryTrendsQuery+ results: StorySeriesResult[]+ seriesIndex: number+ insightName: string | null+ lastPointInProgress: boolean+ headline: string+ chapters: StoryChapter[]+ warnings?: unknown[]+ _posthogUrl?: string+}diff --git a/products/product_analytics/mcp/apps/explainChart/storyFacts.ts b/products/product_analytics/mcp/apps/explainChart/storyFacts.tsnew file mode 100644index 000000000000..664b84ab1370--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/storyFacts.ts@@ -0,0 +1,233 @@+import { mark } from './storyMarks'++export interface StoryFactsOptions {+ interval: string+ lastPointInProgress: boolean+ formatValue: (value: number) => string+}++interface Baseline {+ typical: number+ sparse: boolean+}++const MONTHS = [+ 'January',+ 'February',+ 'March',+ 'April',+ 'May',+ 'June',+ 'July',+ 'August',+ 'September',+ 'October',+ 'November',+ 'December',+]+/** A series with this share of zero points is compared by its non-zero points only. */+const SPARSE_SHARE = 0.3+const MIN_POINTS = 3++function mean(values: number[]): number {+ return values.length ? values.reduce((sum, value) => sum + value, 0) / values.length : 0+}++function median(values: number[]): number {+ if (!values.length) {+ return 0+ }+ const sorted = [...values].sort((a, b) => a - b)+ const middle = Math.floor(sorted.length / 2)+ return sorted.length % 2 ? sorted[middle]! : (sorted[middle - 1]! + sorted[middle]!) / 2+}++function baselineOf(values: number[]): Baseline {+ const active = values.filter((value) => value !== 0)+ const sparse = active.length > 0 && values.length - active.length >= values.length * SPARSE_SHARE+ return { typical: median(sparse ? active : values), sparse }+}++function unitOf(interval: string): string {+ return interval+}++// Parsed by hand: `new Date('2026-10-02')` is midnight UTC, which reads as October 1 west of Greenwich.+export function dateLabel(day: string, interval: string): string {+ const [, year, month, date, hour, minute, second] =+ /^(\d{4})-(\d{2})-(\d{2})(?:[ T](\d{2}):(\d{2})(?::(\d{2}))?)?/.exec(day) ?? []+ if (!year || !month || !date) {+ return day+ }+ const monthName = MONTHS[Number(month) - 1] ?? month+ switch (interval) {+ case 'second':+ return `${monthName.slice(0, 3)} ${Number(date)}, ${hour ?? '00'}:${minute ?? '00'}:${second ?? '00'}`+ case 'minute':+ case 'hour':+ return `${monthName.slice(0, 3)} ${Number(date)}, ${hour ?? '00'}:${minute ?? '00'}`+ case 'week':+ return `the week of ${monthName} ${Number(date)}`+ case 'month':+ return `${monthName} ${year}`+ case 'quarter':+ return `Q${Math.floor((Number(month) - 1) / 3) + 1} ${year}`+ case 'year':+ return year+ default:+ return `${monthName} ${Number(date)}`+ }+}++function times(ratio: number): string {+ return `${ratio >= 10 ? Math.round(ratio) : Math.round(ratio * 10) / 10} times`+}++// A typical level is a median, and its decimals say nothing a person can use. A value below 1+// keeps two significant digits, so a rate like 0.02 survives until the unit formatter runs.+function level(value: number): number {+ const size = Math.abs(value)+ if (size >= 10) {+ return Math.round(value)+ }+ if (size >= 1 || size === 0) {+ return Math.round(value * 10) / 10+ }+ const factor = 10 ** (Math.ceil(-Math.log10(size)) + 1)+ return Math.round(value * factor) / factor+}++function percent(share: number): string {+ return `${Math.round(Math.abs(share) * 100)}%`+}++function comparison(value: number, typical: number, against: string): string {+ const ratio = value / typical+ if (ratio >= 2) {+ return `${mark('value', times(ratio))} ${against}`+ }+ if (Math.abs(ratio - 1) <= 0.2) {+ return `in line with ${against}`+ }+ return `${mark('value', `${percent(ratio - 1)} ${ratio > 1 ? 'above' : 'below'}`)} ${against}`+}++function completeValues(data: number[], options: StoryFactsOptions): number[] {+ return options.lastPointInProgress ? data.slice(0, -1) : data+}++function baselineAround(data: number[], [start, end]: [number, number], options: StoryFactsOptions): Baseline | null {+ const outside = completeValues(data, options).filter((_, index) => index < start || index > end)+ return outside.length >= MIN_POINTS ? baselineOf(outside) : null+}++/** The point a chapter's marker sits on: the one furthest from the rest of the chart. */+export function anchorOf(data: number[], range: [number, number], options: StoryFactsOptions): number {+ const [start, end] = range+ // An unfinished last point reads low, so it takes the marker only when it is the whole chapter.+ const last = options.lastPointInProgress && end === data.length - 1 && end > start ? end - 1 : end+ const typical = baselineAround(data, range, options)?.typical ?? median(completeValues(data, options))+ let anchor = start+ for (let index = start; index <= last; index++) {+ if (Math.abs(data[index]! - typical) > Math.abs(data[anchor]! - typical)) {+ anchor = index+ }+ }+ return anchor+}++export function overviewFacts(data: number[], options: StoryFactsOptions): string {+ const values = completeValues(data, options)+ if (values.length < MIN_POINTS) {+ return ''+ }+ const { formatValue } = options+ const unit = unitOf(options.interval)+ const base = baselineOf(values)+ const sentences: string[] = []+ if (base.sparse) {+ const active = values.filter((value) => value !== 0).length+ sentences.push(+ `Only ${mark('value', `${active} of ${values.length} ${unit}s`)} are not zero. A typical non-zero ${unit} is ${mark('value', formatValue(level(base.typical)))}.`+ )+ } else {+ sentences.push(`A typical ${unit} is ${mark('value', formatValue(level(base.typical)))}.`)+ }+ let lowest = values[0]!+ let highest = values[0]!+ for (const value of values) {+ lowest = Math.min(lowest, value)+ highest = Math.max(highest, value)+ }+ sentences.push(`The range runs from ${formatValue(lowest)} to ${formatValue(highest)}.`)+ const third = Math.floor(values.length / 3)+ if (third >= 2 && !base.sparse) {+ const start = mean(values.slice(0, third))+ const end = mean(values.slice(-third))+ if (start > 0) {+ const change = end / start - 1+ sentences.push(+ Math.abs(change) < 0.1+ ? 'It ends at about the level it starts at.'+ : `It ends ${mark('value', `${percent(change)} ${change > 0 ? 'higher' : 'lower'}`)} than it starts.`+ )+ }+ }+ return sentences.join(' ')+}++function pointFacts(data: number[], days: string[], index: number, options: StoryFactsOptions): string {+ const unit = unitOf(options.interval)+ const label = dateLabel(days[index] ?? '', options.interval)+ const when = `${options.interval === 'day' ? 'on' : unit === 'minute' || unit === 'hour' ? 'at' : 'in'} ${mark('date', label)}`+ const value = mark('value', options.formatValue(data[index]!))+ if (options.lastPointInProgress && index === data.length - 1) {+ return `${value} so far ${when}. This ${unit} is not over yet, so the number can still change.`+ }+ const base = baselineAround(data, [index, index], options)+ const typicalUnit = `a typical ${base?.sparse ? 'non-zero ' : ''}${unit}`+ const compared =+ base && base.typical > 0+ ? comparison(data[index]!, base.typical, `${typicalUnit} (${options.formatValue(level(base.typical))})`)+ : ''+ return `${value} ${when}${compared ? `, ${compared}` : ''}.`+}++function stretchFacts(data: number[], days: string[], range: [number, number], options: StoryFactsOptions): string {+ const [start, end] = range+ const unit = unitOf(options.interval)+ const from = mark('date', dateLabel(days[start] ?? '', options.interval))+ const to = mark('date', dateLabel(days[end] ?? '', options.interval))+ const includesInProgress = options.lastPointInProgress && end === data.length - 1+ const values = data.slice(start, includesInProgress ? end : end + 1)+ const ongoing = includesInProgress ? ` This ${unit} is not over yet.` : ''+ if (!values.length) {+ return pointFacts(data, days, end, options)+ }+ if (data.slice(start, end + 1).every((value) => value === 0)) {+ return `From ${from} to ${to} every value is zero.${ongoing}`+ }+ const base = baselineAround(data, range, options)+ // A sparse chart is judged by its non-zero points, so the stretch leaves out its zeros as well.+ const nonZero = values.filter((value) => value !== 0)+ const typical = median(base?.sparse && nonZero.length ? nonZero : values)+ const typicalUnit = `a typical ${base?.sparse ? 'non-zero ' : ''}${unit}`+ const compared =+ base && base.typical > 0+ ? comparison(+ typical,+ base.typical,+ `the rest of the chart (${options.formatValue(level(base.typical))} on ${typicalUnit})`+ )+ : ''+ return `From ${from} to ${to}, ${typicalUnit} is ${mark('value', options.formatValue(level(typical)))}${compared ? `, ${compared}` : ''}.${ongoing}`+}++export function chapterFacts(+ data: number[],+ days: string[],+ range: [number, number],+ options: StoryFactsOptions+): string {+ return range[0] === range[1] ? pointFacts(data, days, range[0], options) : stretchFacts(data, days, range, options)+}diff --git a/products/product_analytics/mcp/apps/explainChart/storyMarkerPlacement.ts b/products/product_analytics/mcp/apps/explainChart/storyMarkerPlacement.tsnew file mode 100644index 000000000000..60f8932d35c9--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/storyMarkerPlacement.ts@@ -0,0 +1,137 @@+export interface Point {+ x: number+ y: number+}++export interface Rect {+ left: number+ top: number+ right: number+ bottom: number+}++export interface MarkerObstacles {+ /** Each drawn line as its points in pixels, ordered by x. */+ lines: Point[][]+ bars: Rect[]+}++export interface MarkerLayout {+ radius: number+ /** From the marked point to the badge's centre. */+ distance: number+ bounds: Rect+}++// Straight up first, then fanning out to either side, so a clear sky keeps every badge above its point.+const ANGLES = [-90, -60, -120, -30, -150, 0, 180, 30, 150, 60, 120, 90].map((degrees) => (degrees * Math.PI) / 180)+const RINGS = [1, 1.6]+const CLEARANCE = 4+const TAIL_HALF_WIDTH = 2.5++function distanceToSegment(point: Point, from: Point, to: Point): number {+ const dx = to.x - from.x+ const dy = to.y - from.y+ const lengthSquared = dx * dx + dy * dy+ const t =+ lengthSquared === 0+ ? 0+ : Math.max(0, Math.min(1, ((point.x - from.x) * dx + (point.y - from.y) * dy) / lengthSquared))+ return Math.hypot(point.x - (from.x + t * dx), point.y - (from.y + t * dy))+}++function distanceToRect(point: Point, rect: Rect): number {+ const dx = Math.max(rect.left - point.x, 0, point.x - rect.right)+ const dy = Math.max(rect.top - point.y, 0, point.y - rect.bottom)+ return Math.hypot(dx, dy)+}++function firstIndexFrom(line: Point[], x: number): number {+ let low = 0+ let high = line.length+ while (low < high) {+ const middle = (low + high) >> 1+ if (line[middle]!.x < x) {+ low = middle + 1+ } else {+ high = middle+ }+ }+ return low+}++function distanceToLines(point: Point, lines: Point[][], reach: number): number {+ let nearest = Infinity+ for (const line of lines) {+ const end = firstIndexFrom(line, point.x + reach)+ for (let index = Math.max(firstIndexFrom(line, point.x - reach) - 1, 0); index < end; index++) {+ const next = line[index + 1]+ nearest = Math.min(+ nearest,+ next+ ? distanceToSegment(point, line[index]!, next)+ : Math.hypot(point.x - line[index]!.x, point.y - line[index]!.y)+ )+ }+ }+ return nearest+}++export function placeMarkers(anchors: Point[], obstacles: MarkerObstacles, layout: MarkerLayout): Point[] {+ const { radius, distance, bounds } = layout+ const placed: Point[] = []+ const reach = distance * RINGS[RINGS.length - 1]! + radius * 2++ const clearanceAt = (center: Point, anchor: Point): number => {+ if (+ center.x - radius < bounds.left ||+ center.x + radius > bounds.right ||+ center.y - radius < bounds.top ||+ center.y + radius > bounds.bottom+ ) {+ return -Infinity+ }+ // The tail starts on the line, so its midpoint only has to stay off the line, not keep the badge's margin.+ const length = Math.hypot(center.x - anchor.x, center.y - anchor.y)+ const along = (length - radius) / 2 / length+ const tailMiddle = { x: anchor.x + (center.x - anchor.x) * along, y: anchor.y + (center.y - anchor.y) * along }+ let clearance = Math.min(+ distanceToLines(center, obstacles.lines, reach) - radius,+ distanceToLines(tailMiddle, obstacles.lines, reach) - TAIL_HALF_WIDTH + CLEARANCE+ )+ for (const bar of obstacles.bars) {+ clearance = Math.min(clearance, distanceToRect(center, bar) - radius)+ }+ for (const other of placed) {+ clearance = Math.min(clearance, Math.hypot(center.x - other.x, center.y - other.y) - radius * 2)+ }+ for (const other of anchors) {+ if (other !== anchor) {+ clearance = Math.min(clearance, Math.hypot(center.x - other.x, center.y - other.y) - radius)+ }+ }+ return clearance+ }++ for (const anchor of anchors) {+ let best: { center: Point; clearance: number } | null = null+ search: for (const ring of RINGS) {+ for (const angle of ANGLES) {+ const center = {+ x: anchor.x + Math.cos(angle) * distance * ring,+ y: anchor.y + Math.sin(angle) * distance * ring,+ }+ const clearance = clearanceAt(center, anchor)+ if (clearance >= CLEARANCE) {+ best = { center, clearance }+ break search+ }+ if (!best || clearance > best.clearance) {+ best = { center, clearance }+ }+ }+ }+ placed.push(best!.center)+ }+ return placed+}diff --git a/products/product_analytics/mcp/apps/explainChart/storyMarks.ts b/products/product_analytics/mcp/apps/explainChart/storyMarks.tsnew file mode 100644index 000000000000..8021cefaeeef--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/storyMarks.ts@@ -0,0 +1,57 @@+export type StoryMarkKind = 'value' | 'date' | 'name'++export interface StoryTextPart {+ text: string+ kind: StoryMarkKind | null+}++const OPEN = '⟦'+const CLOSE = '⟧'+const CODES: Record<string, StoryMarkKind> = { v: 'value', d: 'date', n: 'name' }+// A stretch that the page marked, or one that the model marked with double asterisks.+const MARKED = new RegExp(`${OPEN}([vdn]):([^${CLOSE}]*)${CLOSE}|\\*\\*([^*]+)\\*\\*`, 'g')+const MONTH = /\b(January|February|March|April|May|June|July|August|September|October|November|December)\b/++export function mark(kind: StoryMarkKind, text: string): string {+ return `${OPEN}${kind[0]}:${text.replaceAll(OPEN, '').replaceAll(CLOSE, '')}${CLOSE}`+}++// The model only says that a stretch matters, so what it is comes from how it reads.+function kindOf(text: string): StoryMarkKind {+ if (MONTH.test(text) && /\d/.test(text)) {+ return 'date'+ }+ return /^[^\p{L}]*\d/u.test(text) ? 'value' : 'name'+}++export function storyTextParts(text: string): StoryTextPart[] {+ const parts: StoryTextPart[] = []+ let from = 0+ for (const match of text.matchAll(MARKED)) {+ if (match.index > from) {+ parts.push({ text: text.slice(from, match.index), kind: null })+ }+ const [, code, pageText, modelText] = match+ parts.push(+ modelText !== undefined+ ? { text: modelText, kind: kindOf(modelText) }+ : { text: pageText ?? '', kind: (code && CODES[code]) || null }+ )+ from = match.index + match[0].length+ }+ if (from < text.length) {+ parts.push({ text: text.slice(from), kind: null })+ }+ return parts+}++export function markedNames(text: string): string[] {+ return storyTextParts(text).flatMap((part) => (part.kind === 'name' ? [part.text] : []))+}++/** The text without its marks, for a prompt or a label. A name gets quotes there, where no highlight sets it apart. */+export function plainStoryText(text: string): string {+ return storyTextParts(text)+ .map((part) => (part.kind === 'name' ? `"${part.text}"` : part.text))+ .join('')+}diff --git a/products/product_analytics/mcp/apps/explainChart/storyNamedSeries.ts b/products/product_analytics/mcp/apps/explainChart/storyNamedSeries.tsnew file mode 100644index 000000000000..49866d30b08d--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/storyNamedSeries.ts@@ -0,0 +1,20 @@+import { markedNames, storyTextParts } from './storyMarks'++function escapeRegExp(text: string): string {+ return text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')+}++export function isSeriesNamedIn(names: string[], text: string): boolean {+ const marked = new Set(markedNames(text).map((name) => name.trim().toLowerCase()))+ const plain = storyTextParts(text)+ .map((part) => part.text)+ .join('')+ return names+ .map((name) => name.trim())+ .filter(Boolean)+ .some(+ (name) =>+ marked.has(name.toLowerCase()) ||+ new RegExp(`(?<![\\p{L}\\p{N}_])${escapeRegExp(name)}(?![\\p{L}\\p{N}_])`, 'u').test(plain)+ )+}diff --git a/products/product_analytics/mcp/apps/explainChart/storyPages.ts b/products/product_analytics/mcp/apps/explainChart/storyPages.tsnew file mode 100644index 000000000000..9975ab361168--- /dev/null+++ b/products/product_analytics/mcp/apps/explainChart/storyPages.ts@@ -0,0 +1,53 @@+import type { ExplainChartData, StoryChapter } from './explainChartTypes'+import { anchorOf, chapterFacts, overviewFacts, type StoryFactsOptions } from './storyFacts'++export interface StoryPage {+ title: string+ range: [number, number] | null+ anchor: number | null+ /** What the chart itself says, worked out here so that no number comes from the agent's text. */+ facts: string+ /** The agent's chapter. Null for the summary that opens the story. */+ chapter: StoryChapter | null+}++export const SUMMARY_TITLE = 'The big picture'++function isPointRange(range: [number, number] | null, length: number): range is [number, number] {+ if (!range) {+ return false+ }+ const [start, end] = range+ return Number.isInteger(start) && Number.isInteger(end) && start >= 0 && start <= end && end < length+}++export function buildStoryPages(data: ExplainChartData, formatValue: StoryFactsOptions['formatValue']): StoryPage[] {+ const series = data.results[data.seriesIndex]+ const values = series?.data ?? []+ const days = series?.days ?? []+ const options: StoryFactsOptions = {+ interval: data.query.interval ?? 'day',+ lastPointInProgress: data.lastPointInProgress,+ formatValue,+ }+ const summary: StoryPage = {+ title: SUMMARY_TITLE,+ range: null,+ anchor: null,+ facts: overviewFacts(values, options),+ chapter: null,+ }+ const chapters = data.chapters.map((chapter): StoryPage => {+ const range = isPointRange(chapter.range, values.length) ? chapter.range : null+ return {+ title: chapter.title,+ range,+ anchor: range ? anchorOf(values, range, options) : null,+ facts: range ? chapterFacts(values, days, range, options) : '',+ chapter,+ }+ })+ // Numbered in date order, so the markers read left to right. A chapter with no point comes last.+ const startOf = (page: StoryPage): number => page.range?.[0] ?? values.length+ return [summary, ...chapters.sort((a, b) => startOf(a) - startOf(b))]+}diff --git a/services/mcp/tests/unit/explain-chart-walkthrough.test.ts b/services/mcp/tests/unit/explain-chart-walkthrough.test.tsnew file mode 100644index 000000000000..cacf31f344e9--- /dev/null+++ b/services/mcp/tests/unit/explain-chart-walkthrough.test.ts@@ -0,0 +1,233 @@+import { describe, expect, it } from 'vitest'++import type { ExplainChartData } from 'products/product_analytics/mcp/apps/explainChart/explainChartTypes'+import {+ anchorOf,+ chapterFacts,+ dateLabel,+ overviewFacts,+} from 'products/product_analytics/mcp/apps/explainChart/storyFacts'+import { placeMarkers } from 'products/product_analytics/mcp/apps/explainChart/storyMarkerPlacement'+import { isSeriesNamedIn } from 'products/product_analytics/mcp/apps/explainChart/storyNamedSeries'+import { buildStoryPages } from 'products/product_analytics/mcp/apps/explainChart/storyPages'++const DAYS = ['2026-10-01', '2026-10-02', '2026-10-03', '2026-10-04', '2026-10-05']+const MARKER_LAYOUT = { radius: 10, distance: 22, bounds: { left: 0, top: 0, right: 400, bottom: 300 } }++describe('explain chart walkthrough', () => {+ it('keeps a small rate from rounding to zero', () => {+ const facts = chapterFacts([0.02, 0.02, 0.02, 0.02, 0.02], DAYS, [1, 3], {+ interval: 'day',+ lastPointInProgress: false,+ formatValue: (value) => `${value * 100}%`,+ })++ expect(facts).toContain('2%')+ expect(facts).not.toContain('0%')+ })++ it('describes a series with more points than a function call can take', () => {+ const values = Array.from({ length: 200_000 }, (_, index) => index % 7)++ expect(+ overviewFacts(values, { interval: 'minute', lastPointInProgress: false, formatValue: String })+ ).toContain('The range runs from 0 to 6.')+ })++ it('counts a negative bucket as activity', () => {+ const facts = overviewFacts([1, -1, -1, 2, 3, -1], {+ interval: 'day',+ lastPointInProgress: false,+ formatValue: String,+ })++ expect(facts).not.toContain('Only')+ })++ it('keeps a per-second chart in seconds', () => {+ const seconds = ['2026-10-01 10:00:00', '2026-10-01 10:00:01', '2026-10-01 10:00:02', '2026-10-01 10:00:03']+ const facts = chapterFacts([1, 2, 3, 4], seconds, [1, 2], {+ interval: 'second',+ lastPointInProgress: false,+ formatValue: String,+ })++ expect(facts).toContain('typical second')+ expect(facts).toContain('10:00:01')+ })++ it('does not call a stretch empty when only its unfinished last point has activity', () => {+ const facts = chapterFacts([0, 0, 20], DAYS.slice(0, 3), [0, 2], {+ interval: 'day',+ lastPointInProgress: true,+ formatValue: String,+ })++ expect(facts).not.toContain('every value is zero')+ })++ it.each([+ ['a start below zero', [-1e20, 0]],+ ['a fractional index', [0.5, 1]],+ ['an end past the last point', [1, 3]],+ ])('shows a chapter with %s as one without a point', (_, range) => {+ const data = {+ query: { kind: 'TrendsQuery', interval: 'day', series: [] },+ results: [{ label: 'signed_up', data: [1, 2, 3], days: DAYS.slice(0, 3) }],+ seriesIndex: 0,+ insightName: 'Sign-ups',+ lastPointInProgress: false,+ headline: 'A headline.',+ chapters: [+ {+ title: 'A chapter',+ range,+ summary: null,+ cause: null,+ confidence: null,+ confidenceReason: null,+ evidence: [],+ },+ ],+ } as unknown as ExplainChartData++ const [, chapter] = buildStoryPages(data, String)++ expect(chapter?.range).toBeNull()+ expect(chapter?.anchor).toBeNull()+ })++ it('does not compare a period that has not ended with complete ones', () => {+ const facts = chapterFacts([60, 62, 58, 61, 9], DAYS, [4, 4], {+ interval: 'day',+ lastPointInProgress: true,+ formatValue: String,+ })++ expect(facts).not.toContain('below')+ expect(facts).toContain('not over yet')+ })++ it('puts a chart marker straight above a peak', () => {+ const peak = [+ { x: 100, y: 200 },+ { x: 120, y: 50 },+ { x: 140, y: 200 },+ ]++ const [center] = placeMarkers([{ x: 120, y: 50 }], { lines: [peak], bars: [] }, MARKER_LAYOUT)++ expect(center?.x).toBeCloseTo(120)+ expect(center?.y).toBeCloseTo(28)+ })++ it.each([+ {+ name: 'a line that falls into the last point at the right edge',+ line: [+ { x: 320, y: 120 },+ { x: 360, y: 160 },+ { x: 400, y: 200 },+ ],+ anchors: [{ x: 400, y: 200 }],+ },+ {+ name: 'a spike that reaches the top of the chart',+ line: [+ { x: 100, y: 200 },+ { x: 120, y: 8 },+ { x: 140, y: 200 },+ ],+ anchors: [{ x: 120, y: 8 }],+ },+ {+ name: 'two marked points next to each other',+ line: [+ { x: 80, y: 150 },+ { x: 160, y: 150 },+ ],+ anchors: [+ { x: 110, y: 150 },+ { x: 120, y: 150 },+ ],+ },+ ])('keeps chart markers off the line, apart and inside the chart for $name', ({ line, anchors }) => {+ const centers = placeMarkers(anchors, { lines: [line], bars: [] }, MARKER_LAYOUT)+ const { radius, bounds } = MARKER_LAYOUT++ for (const [index, center] of centers.entries()) {+ expect(center.x - radius).toBeGreaterThanOrEqual(bounds.left)+ expect(center.x + radius).toBeLessThanOrEqual(bounds.right)+ expect(center.y - radius).toBeGreaterThanOrEqual(bounds.top)+ expect(center.y + radius).toBeLessThanOrEqual(bounds.bottom)+ for (const [from, to] of line.slice(1).map((point, i) => [line[i]!, point] as const)) {+ for (let t = 0; t <= 1; t += 0.02) {+ const onLine = { x: from.x + (to.x - from.x) * t, y: from.y + (to.y - from.y) * t }+ expect(Math.hypot(center.x - onLine.x, center.y - onLine.y)).toBeGreaterThanOrEqual(radius)+ }+ }+ for (const other of centers.slice(index + 1)) {+ expect(Math.hypot(center.x - other.x, center.y - other.y)).toBeGreaterThanOrEqual(radius * 2)+ }+ }+ })+ it.each<[string, string[], string, boolean]>([+ ['a marked name in another case', ['Germany'], 'Sign-ups from **germany** rose.', true],+ ['a name written out without marks', ['United Kingdom'], 'United States and United Kingdom held steady.', true],+ [+ 'one value of a multi-breakdown series',+ ['Germany::Chrome', 'Germany', 'Chrome'],+ 'Most of it came from Chrome.',+ true,+ ],+ ['a referrer with a symbol', ['$direct'], '$direct went from 80 to 160.', true],+ ['a marked name with a number, in another case', ['Windows 11'], 'Sign-ups from **windows 11** rose.', true],+ [+ 'a marked value that holds a dash',+ ['signup - US - East', 'US - East'],+ 'Most of it came from **us - east**.',+ true,+ ],+ [+ 'another value that ends the same way',+ ['signup - US - East', 'US - East'],+ 'It came from **Europe - East**.',+ false,+ ],+ ['a short value inside an ordinary word', ['US'], 'Let us look at the step up.', false],+ ['a short value inside an identifier', ['US'], 'US_East increased.', false],+ ['a value in another case that is not marked', ['Other'], 'Every other country stayed flat.', false],+ ['a value inside a longer name', ['India'], 'Indiana stayed flat.', false],+ ])('matches a series to the evidence that names it, for %s', (_, names, text, expected) => {+ expect(isSeriesNamedIn(names, text)).toBe(expected)+ })++ it('compares a stretch of a sparse chart by its non-zero points, as it does the rest of the chart', () => {+ const days = Array.from({ length: 8 }, (_, index) => `2026-10-0${index + 1}`)++ const facts = chapterFacts([0, 0, 100, 100, 0, 0, 100, 100], days, [0, 3], {+ interval: 'day',+ lastPointInProgress: false,+ formatValue: String,+ })++ expect(facts).toContain('in line with')+ })++ it('keeps the marker off an unfinished last point when the chapter has complete ones', () => {+ const anchor = anchorOf([100, 100, 100, 100, 150, 150, 150, 1], [4, 7], {+ interval: 'day',+ lastPointInProgress: true,+ formatValue: String,+ })++ expect(anchor).toBe(4)+ })++ it.each([+ ['quarter', '2026-04-01', 'Q2 2026'],+ ['year', '2024-01-01', '2024'],+ ])('names a %s by its period, with the year', (interval, day, expected) => {+ expect(dateLabel(day, interval)).toBe(expected)+ })+})