/** * The analysis behind the Research post on our CI getting 3× faster. It reads the committed raw data * (one row per CI run, the pull requests merged at night, and the per-day changelog) and computes every * number the post shows, apart from the measurements the changelog cites with their sources. * `reproduce.ts` runs it and writes `results.json`; the post reads only that file. */ import { longDate } from './format.ts'; import { bootstrapMedians, mannWhitneyU, median, quantile, type BootstrapOptions, type Interval } from './stats.ts'; /** The raw data files, by the names the post publishes them under. */ export const CI_DATA_FILES = ['ci-runs.jsonl', 'merges.jsonl', 'changelog.json'] as const; export type RunEvent = 'pull_request' | 'push'; export type RunConclusion = 'success' | 'failure' | 'cancelled'; export type RunnerKind = 'github-hosted' | 'self-hosted'; export interface CiJob { name: string; attempt: number; /** `github-hosted`, or `self-hosted-` for one of our own runners. */ runner: string; created_at: string; started_at: string; completed_at: string; } /** One run of the CI workflow, as GitHub's REST API reported it. Jobs are only those that got a runner. */ export interface CiRun { id: number; night: string; event: RunEvent; conclusion: RunConclusion; attempt: number; created_at: string; run_started_at: string; updated_at: string; /** Where the latest attempt's check-and-test job ran; null when it never got a runner. */ runner: RunnerKind | null; jobs: CiJob[]; } export interface Merge { number: number; /** When the pull request was opened. */ created_at: string; merged_at: string; } export interface Cited { value: number | [number, number]; unit?: string; source: string; } export type Builder = 'dev-loop' | 'agent' | 'other'; export interface ChangePr { number: number; by: Builder; what: string; measured?: string; } export interface Day { date: string; title: string; problem: string; evidence: string; change: string; effect: string; prs: ChangePr[]; } /** A moment the CI data cannot show, such as a change to the Dev Loop, cited with its source. */ export interface Moment { at: string; source: string; } export interface Changelog { fetchedAt: string; cited: Record; moments: Record; days: Day[]; } /** The check-and-test job's time limit in minutes, from the night `from` on. */ export interface JobLimit { from: string; minutes: number; } export type AlternativeBaseline = 'withoutLastNight' | 'selfHostedNights' | 'closestNight'; export interface CiDesign { nights: readonly string[]; baseline: readonly string[]; comparison: string; tailQuantile: number; bootstrap: BootstrapOptions; /** A job that ran this long was stopped by the limit: GitHub cancels it there. */ jobLimits: readonly JobLimit[]; /** Other baselines, to show how much the headline depends on the one we chose. */ alternatives: Readonly>; } /** The post's design, fixed before the analysis: see "What we measured" in the post. */ export const CI_DESIGN: CiDesign = { nights: ['2026-10-04', '2026-10-05', '2026-10-06', '2026-10-07', '2026-10-08', '2026-10-09', '2026-10-10', '2026-10-11'], baseline: ['2026-10-06', '2026-10-07', '2026-10-08', '2026-10-09', '2026-10-10'], comparison: '2026-10-11', tailQuantile: 0.9, bootstrap: { resamples: 20000, seed: 795, level: 0.95 }, // 15 minutes until pull requests #63 and #68 (merged on the morning of 6 October), then 25; from the night of // 11 October, 45 on our own runners (#640). The changelog cites the same limits with their sources. jobLimits: [{ from: '2026-10-04', minutes: 15 }, { from: '2026-10-06', minutes: 25 }, { from: '2026-10-11', minutes: 45 }], alternatives: { // The baseline without its worst night. withoutLastNight: ['2026-10-06', '2026-10-07', '2026-10-08', '2026-10-09'], // Only the nights CI ran on our own machine, as it did on the comparison night. selfHostedNights: ['2026-10-08', '2026-10-09', '2026-10-10'], // The night most like the comparison night: the same machine, four runners and two Dev Loop lanes. It is not // clean: the slower test selection of pull request #526 merged at 03:50 UTC, near its end (the changelog's // moment selection526), so the post also compares the runs before that moment. closestNight: ['2026-10-09'], }, }; export interface NightResult { night: string; runs: number; pullRequests: number; pushes: number; success: number; failure: number; cancelled: number; cancelledShare: number; /** The job time limit that night, in minutes. */ jobLimit: number; /** Cancelled runs whose latest attempt's job ran until the time limit stopped it. */ timedOutRuns: number; /** Job attempts, of any run, that ran until the time limit stopped them. */ timedOutJobs: number; /** Runs that were not cancelled: the ones the duration statistics use. */ completed: number; median: number | null; p90: number | null; min: number | null; max: number | null; prMedian: number | null; prP90: number | null; pushMedian: number | null; pushP90: number | null; runnerMinutes: number; merges: number; runnerMinutesPerMerge: number | null; hardware: RunnerKind | 'mixed' | 'none'; selfHostedRunners: number; /** When each of our runners started its first job of the night, earliest first. */ runnerStarts: string[]; /** Minutes from opening a pull request to merging it, median over the pull requests merged that night. */ leadTimeMedian: number | null; /** The same, for only the pull requests opened that night. */ leadTimeOpenedAtNight: number | null; /** Pull requests merged that night that were opened before it began. */ mergedOpenedByDay: number; } export interface GroupResult { nights: string[]; runs: number; cancelled: number; cancelledShare: number; completed: number; median: number; p90: number; prMedian: number | null; pushMedian: number | null; } /** The comparison night against another baseline. */ export interface AlternativeResult { nights: string[]; completed: number; median: number; p90: number; /** Baseline median over the comparison night's median, and the same for the tail. */ ratio: number; p90Ratio: number; } /** Part of one night's timed runs, measured as a night is, and against the comparison night as a baseline would be. */ export interface SplitPart { completed: number; median: number | null; p90: number | null; prMedian: number | null; pushMedian: number | null; /** This part's median over the comparison night's, and the same for the tail; null when the part is empty. */ ratio: number | null; p90Ratio: number | null; } /** The timed runs of one night, split at a cited moment by when each run was created. */ export interface SplitResult { night: string; at: string; before: SplitPart; after: SplitPart; } export interface CiResults { post: 'ci-3x-faster'; fetchedAt: string; method: { windowUtc: { start: string; end: string }; nights: string[]; baseline: string[]; comparison: string; tailQuantile: number; bootstrap: BootstrapOptions; jobLimits: JobLimit[]; totalRuns: number; }; headline: { ratio: number; p90Ratio: number }; nights: NightResult[]; baseline: GroupResult; comparison: GroupResult; test: { u: number; z: number; p: number; n1: number; n2: number; probabilityFaster: number }; bootstrap: { medianChange: Interval; medianRatio: Interval }; /** How the headline changes with the baseline. */ alternatives: Record; /** The baseline again, with each run the time limit stopped counted at the time it was stopped. */ countingTimeouts: { timedOut: number; completed: number; median: number; ratio: number }; merges: { baselineMedian: number; previousBest: number; comparison: number; isRecord: boolean; chanceOfRecordIfAlike: number }; /** Minutes from opening a pull request to merging it, over the nights' medians. */ leadTime: { comparison: number; baselineNight: number; baselineLowest: number; baselineHighest: number; comparisonOpenedByDay: number; comparisonMerged: number; comparisonOpenedAtNight: number; baselineNightOpenedAtNight: number; }; splits: Record; runs: { night: number; minutes: number; main: boolean; cancelled: boolean }[]; cited: Record; moments: Record; days: Day[]; } const WINDOW_START_HOUR = 21; const WINDOW_HOURS = 9; const HOUR = 3_600_000; /** The night (the date its 21:00 UTC start falls on) of a timestamp, or null outside 21:00 to 06:00 UTC. */ export function nightOf(iso: string): string | null { const shifted = new Date(Date.parse(iso) - WINDOW_START_HOUR * HOUR); if (Number.isNaN(shifted.getTime()) || shifted.getUTCHours() >= WINDOW_HOURS) return null; return shifted.toISOString().slice(0, 10); } const minutesBetween = (from: string, to: string) => (Date.parse(to) - Date.parse(from)) / 60_000; const round = (value: number, places = 3) => Math.round(value * 10 ** places) / 10 ** places; const roundOrNull = (value: number | null) => (value === null ? null : round(value)); const quantileOrNull = (values: number[], q: number) => (values.length ? quantile(values, q) : null); function duration(run: CiRun): number { return minutesBetween(run.run_started_at, run.updated_at); } /** The job time limit in force on a night. */ export function jobLimitOn(night: string, design: CiDesign): number { const limit = design.jobLimits.filter((entry) => entry.from <= night).at(-1); if (!limit) throw new RangeError(`no job time limit is given for the night of ${night}`); return limit.minutes; } const timedOut = (job: CiJob, limit: number) => minutesBetween(job.started_at, job.completed_at) >= limit; /** A cancelled run whose latest attempt's job ran until the time limit stopped it. */ function isTimedOutRun(run: CiRun, design: CiDesign): boolean { const limit = jobLimitOn(run.night, design); return run.conclusion === 'cancelled' && run.jobs.some((job) => job.attempt === run.attempt && timedOut(job, limit)); } const leadTime = (merge: Merge) => minutesBetween(merge.created_at, merge.merged_at); const medianOrNull = (values: number[]) => (values.length ? median(values) : null); function summarizeNight(night: string, runs: CiRun[], merged: Merge[], design: CiDesign): NightResult { const completed = runs.filter((run) => run.conclusion !== 'cancelled'); const times = completed.map(duration); const timesOf = (event: RunEvent) => completed.filter((run) => run.event === event).map(duration); const cancelled = runs.filter((run) => run.conclusion === 'cancelled'); const jobs = runs.flatMap((run) => run.jobs); const runnerMinutes = jobs.reduce((sum, job) => sum + minutesBetween(job.started_at, job.completed_at), 0); const kinds = new Set(jobs.map((job) => (job.runner === 'github-hosted' ? 'github-hosted' : 'self-hosted'))); const firstJob = new Map(); for (const job of jobs) { if (job.runner === 'github-hosted') continue; const first = firstJob.get(job.runner); if (first === undefined || job.started_at < first) firstJob.set(job.runner, job.started_at); } const limit = jobLimitOn(night, design); const nightStart = `${night}T${String(WINDOW_START_HOUR).padStart(2, '0')}:00:00Z`; const openedAtNight = merged.filter((merge) => merge.created_at >= nightStart); const merges = merged.length; return { night, runs: runs.length, pullRequests: runs.filter((run) => run.event === 'pull_request').length, pushes: runs.filter((run) => run.event === 'push').length, success: runs.filter((run) => run.conclusion === 'success').length, failure: runs.filter((run) => run.conclusion === 'failure').length, cancelled: cancelled.length, cancelledShare: runs.length ? round(cancelled.length / runs.length, 4) : 0, jobLimit: limit, timedOutRuns: cancelled.filter((run) => isTimedOutRun(run, design)).length, timedOutJobs: jobs.filter((job) => timedOut(job, limit)).length, completed: completed.length, median: roundOrNull(quantileOrNull(times, 0.5)), p90: roundOrNull(quantileOrNull(times, design.tailQuantile)), min: times.length ? round(Math.min(...times)) : null, max: times.length ? round(Math.max(...times)) : null, prMedian: roundOrNull(quantileOrNull(timesOf('pull_request'), 0.5)), prP90: roundOrNull(quantileOrNull(timesOf('pull_request'), design.tailQuantile)), pushMedian: roundOrNull(quantileOrNull(timesOf('push'), 0.5)), pushP90: roundOrNull(quantileOrNull(timesOf('push'), design.tailQuantile)), runnerMinutes: round(runnerMinutes, 2), merges, runnerMinutesPerMerge: merges ? round(runnerMinutes / merges) : null, hardware: kinds.size === 0 ? 'none' : kinds.size > 1 ? 'mixed' : [...kinds][0] as RunnerKind, selfHostedRunners: firstJob.size, runnerStarts: [...firstJob.values()].sort(), leadTimeMedian: roundOrNull(medianOrNull(merged.map(leadTime))), leadTimeOpenedAtNight: roundOrNull(medianOrNull(openedAtNight.map(leadTime))), mergedOpenedByDay: merges - openedAtNight.length, }; } function summarizeGroup(nights: readonly string[], runs: CiRun[], design: CiDesign): GroupResult { const included = runs.filter((run) => nights.includes(run.night)); const completed = included.filter((run) => run.conclusion !== 'cancelled'); const times = completed.map(duration); if (!times.length) throw new RangeError(`no completed runs in ${nights.join(', ')}`); const cancelled = included.length - completed.length; return { nights: [...nights], runs: included.length, cancelled, cancelledShare: round(cancelled / included.length, 4), completed: completed.length, median: round(median(times)), p90: round(quantile(times, design.tailQuantile)), prMedian: roundOrNull(quantileOrNull(completed.filter((run) => run.event === 'pull_request').map(duration), 0.5)), pushMedian: roundOrNull(quantileOrNull(completed.filter((run) => run.event === 'push').map(duration), 0.5)), }; } const fixed = (value: number | null, places: number) => { if (value === null) throw new RangeError('a token refers to a value the data does not have'); return value.toFixed(places); }; const percent = (share: number) => `${Math.round(share * 100)}%`; /** 2026-10-11T00:09:07Z as "00:09\u00a0UTC". */ export const clock = (iso: string) => `${iso.slice(11, 16)}\u00a0UTC`; const citedText = (cited: Cited) => { const value = Array.isArray(cited.value) ? `${cited.value[0]}–${cited.value[1]}` : String(cited.value); if (cited.unit === '%') return `${value}%`; return cited.unit ? `${value}\u00a0${cited.unit}` : value; }; /** Every value a changelog sentence may name, formatted as the post shows it. */ function tokenTable(results: Omit): Map { const tokens = new Map(); const minuteFields = ['median', 'p90', 'min', 'max', 'prMedian', 'prP90', 'pushMedian', 'pushP90'] as const; const countFields = ['runs', 'pullRequests', 'pushes', 'success', 'failure', 'cancelled', 'timedOutRuns', 'timedOutJobs', 'completed', 'merges', 'selfHostedRunners', 'mergedOpenedByDay'] as const; for (const night of results.nights) { tokens.set(`night.${night.night}.date`, longDate(night.night)); for (const field of minuteFields) if (night[field] !== null) tokens.set(`night.${night.night}.${field}`, fixed(night[field], 2)); for (const field of countFields) tokens.set(`night.${night.night}.${field}`, String(night[field])); tokens.set(`night.${night.night}.cancelledShare`, percent(night.cancelledShare)); tokens.set(`night.${night.night}.jobLimit`, `${night.jobLimit}\u00a0minutes`); if (night.runnerMinutesPerMerge !== null) tokens.set(`night.${night.night}.runnerMinutesPerMerge`, fixed(night.runnerMinutesPerMerge, 2)); night.runnerStarts.forEach((start, index) => tokens.set(`night.${night.night}.runnerStart.${index + 1}`, clock(start))); } for (const [name, group] of [['baseline', results.baseline], ['comparison', results.comparison]] as const) { for (const field of ['median', 'p90', 'prMedian', 'pushMedian'] as const) if (group[field] !== null) tokens.set(`${name}.${field}`, fixed(group[field], 2)); for (const field of ['runs', 'cancelled', 'completed'] as const) tokens.set(`${name}.${field}`, String(group[field])); tokens.set(`${name}.cancelledShare`, percent(group.cancelledShare)); } tokens.set('headline.ratio', fixed(results.headline.ratio, 1)); for (const [key, split] of Object.entries(results.splits)) { for (const [name, part] of [['before', split.before], ['after', split.after]] as const) { tokens.set(`split.${key}.${name}.completed`, String(part.completed)); for (const field of ['median', 'p90', 'prMedian', 'pushMedian'] as const) if (part[field] !== null) tokens.set(`split.${key}.${name}.${field}`, fixed(part[field], 2)); } } for (const [key, cited] of Object.entries(results.cited)) tokens.set(`cited.${key}`, citedText(cited)); for (const [key, moment] of Object.entries(results.moments)) tokens.set(`moment.${key}`, clock(moment.at)); return tokens; } function render(text: string, tokens: Map): string { return text.replace(/\{([^{}]+)\}/g, (_, token: string) => { const value = tokens.get(token); if (value === undefined) throw new RangeError(`unknown token ${token}`); return value; }); } export function analyzeCiSpeed(input: { runs: readonly CiRun[]; merges: readonly Merge[]; changelog: Changelog }, design: CiDesign = CI_DESIGN): CiResults { for (const run of input.runs) { const night = nightOf(run.created_at); if (night !== run.night) throw new RangeError(`run ${run.id} is labelled night ${run.night} but was created in night ${night ?? '(outside the window)'}`); } for (const merge of input.merges) { if (merge.created_at > merge.merged_at) throw new RangeError(`pull request ${merge.number} was merged before it was opened`); } const runs = input.runs.filter((run) => design.nights.includes(run.night)); const mergedOn = new Map(); for (const merge of input.merges) { const night = nightOf(merge.merged_at); if (night !== null) mergedOn.set(night, [...(mergedOn.get(night) ?? []), merge]); } const nights = design.nights.map((night) => summarizeNight(night, runs.filter((run) => run.night === night), mergedOn.get(night) ?? [], design)); const nightResult = (date: string) => nights.find((night) => night.night === date)!; const baseline = summarizeGroup(design.baseline, runs, design); const comparison = summarizeGroup([design.comparison], runs, design); const completedTimes = (group: readonly string[]) => runs.filter((run) => group.includes(run.night) && run.conclusion !== 'cancelled').map(duration); const after = completedTimes([design.comparison]); const before = completedTimes(design.baseline); const test = mannWhitneyU(after, before); const intervals = bootstrapMedians(after, before, design.bootstrap); const roundInterval = (interval: Interval): Interval => ({ estimate: round(interval.estimate), low: round(interval.low), high: round(interval.high) }); const alternative = (group: readonly string[]): AlternativeResult => { const times = completedTimes(group); if (!times.length) throw new RangeError(`no completed runs in ${group.join(', ')}`); return { nights: [...group], completed: times.length, median: round(median(times)), p90: round(quantile(times, design.tailQuantile)), ratio: round(median(times) / median(after)), p90Ratio: round(quantile(times, design.tailQuantile) / quantile(after, design.tailQuantile)), }; }; const stopped = runs.filter((run) => design.baseline.includes(run.night) && isTimedOutRun(run, design)).map(duration); const withTimeouts = [...before, ...stopped]; const mergeCount = (night: string) => mergedOn.get(night)?.length ?? 0; const comparisonIndex = design.nights.indexOf(design.comparison); const previousBest = Math.max(...design.nights.slice(0, comparisonIndex).map(mergeCount)); const baselineLeadTimes = design.baseline.map((night) => nightResult(night).leadTimeMedian).filter((value) => value !== null); const baselineOpenedAtNight = design.baseline.map((night) => nightResult(night).leadTimeOpenedAtNight).filter((value) => value !== null); const last = nightResult(design.comparison); if (last.leadTimeMedian === null || last.leadTimeOpenedAtNight === null || !baselineLeadTimes.length || !baselineOpenedAtNight.length) { throw new RangeError('the lead time needs pull requests merged on the comparison night and the baseline nights'); } const splits: Record = {}; for (const [key, moment] of Object.entries(input.changelog.moments)) { const night = nightOf(moment.at); if (night === null || !design.nights.includes(night)) throw new RangeError(`moment ${key} is not during a night the post studies`); const timed = runs.filter((run) => run.night === night && run.conclusion !== 'cancelled'); const part = (selected: CiRun[]): SplitPart => { const times = selected.map(duration); const of = (event: RunEvent) => selected.filter((run) => run.event === event).map(duration); return { completed: selected.length, median: roundOrNull(quantileOrNull(times, 0.5)), p90: roundOrNull(quantileOrNull(times, design.tailQuantile)), prMedian: roundOrNull(quantileOrNull(of('pull_request'), 0.5)), pushMedian: roundOrNull(quantileOrNull(of('push'), 0.5)), ratio: times.length ? round(median(times) / median(after)) : null, p90Ratio: times.length ? round(quantile(times, design.tailQuantile) / quantile(after, design.tailQuantile)) : null, }; }; splits[key] = { night, at: moment.at, before: part(timed.filter((run) => run.created_at < moment.at)), after: part(timed.filter((run) => run.created_at >= moment.at)) }; } const results: Omit = { post: 'ci-3x-faster', fetchedAt: input.changelog.fetchedAt, method: { windowUtc: { start: '21:00', end: '06:00' }, nights: [...design.nights], baseline: [...design.baseline], comparison: design.comparison, tailQuantile: design.tailQuantile, bootstrap: { ...design.bootstrap }, jobLimits: design.jobLimits.map((limit) => ({ ...limit })), totalRuns: runs.length, }, headline: { ratio: round(median(before) / median(after)), p90Ratio: round(quantile(before, design.tailQuantile) / quantile(after, design.tailQuantile)) }, nights, baseline, comparison, test: { u: test.u, z: round(test.z), p: Number(test.p.toPrecision(3)), n1: test.n1, n2: test.n2, probabilityFaster: round(test.probabilityFirstSmaller, 4) }, bootstrap: { medianChange: roundInterval(intervals.difference), medianRatio: roundInterval(intervals.ratio) }, alternatives: { withoutLastNight: alternative(design.alternatives.withoutLastNight), selfHostedNights: alternative(design.alternatives.selfHostedNights), closestNight: alternative(design.alternatives.closestNight), }, countingTimeouts: { timedOut: stopped.length, completed: withTimeouts.length, median: round(median(withTimeouts)), ratio: round(median(withTimeouts) / median(after)) }, merges: { baselineMedian: median(design.baseline.map(mergeCount)), previousBest, comparison: mergeCount(design.comparison), isRecord: mergeCount(design.comparison) > previousBest, chanceOfRecordIfAlike: round(1 / (design.baseline.length + 1)), }, leadTime: { comparison: last.leadTimeMedian, baselineNight: round(median(baselineLeadTimes)), baselineLowest: Math.min(...baselineLeadTimes), baselineHighest: Math.max(...baselineLeadTimes), comparisonOpenedByDay: last.mergedOpenedByDay, comparisonMerged: last.merges, comparisonOpenedAtNight: last.leadTimeOpenedAtNight, baselineNightOpenedAtNight: round(median(baselineOpenedAtNight)), }, splits, runs: runs.map((run) => ({ night: design.nights.indexOf(run.night), minutes: round(duration(run)), main: run.event === 'push', cancelled: run.conclusion === 'cancelled' })), cited: input.changelog.cited, moments: input.changelog.moments, }; const tokens = tokenTable(results); const days = input.changelog.days.map((day) => ({ ...day, title: render(day.title, tokens), problem: render(day.problem, tokens), evidence: render(day.evidence, tokens), change: render(day.change, tokens), effect: render(day.effect, tokens), prs: day.prs.map((pr) => ({ ...pr, what: render(pr.what, tokens), ...(pr.measured === undefined ? {} : { measured: render(pr.measured, tokens) }) })), })); return { ...results, days }; } const isObject = (value: unknown): value is Record => typeof value === 'object' && value !== null && !Array.isArray(value); const isTime = (value: unknown): value is string => typeof value === 'string' && /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\dZ$/.test(value); const isDate = (value: unknown): value is string => typeof value === 'string' && /^\d{4}-\d\d-\d\d$/.test(value); const isCount = (value: unknown): value is number => Number.isSafeInteger(value) && (value as number) > 0; function lines(text: string): unknown[] { return text.split('\n').filter((line) => line.trim() !== '').map((line, index) => { try { return JSON.parse(line) as unknown; } catch { throw new SyntaxError(`line ${index + 1} is not JSON`); } }); } function isJob(value: unknown): value is CiJob { return isObject(value) && typeof value.name === 'string' && isCount(value.attempt) && typeof value.runner === 'string' && /^(github-hosted|self-hosted-\d+)$/.test(value.runner) && isTime(value.created_at) && isTime(value.started_at) && isTime(value.completed_at); } function isRun(value: unknown): value is CiRun { return isObject(value) && isCount(value.id) && isDate(value.night) && (value.event === 'pull_request' || value.event === 'push') && (value.conclusion === 'success' || value.conclusion === 'failure' || value.conclusion === 'cancelled') && isCount(value.attempt) && isTime(value.created_at) && isTime(value.run_started_at) && isTime(value.updated_at) && (value.runner === null || value.runner === 'github-hosted' || value.runner === 'self-hosted') && Array.isArray(value.jobs) && value.jobs.every(isJob); } /** Parses `ci-runs.jsonl`: one CI run per line. */ export function parseRuns(text: string): CiRun[] { return lines(text).map((row, index) => { if (!isRun(row)) throw new TypeError(`line ${index + 1} is not a CI run`); return row; }); } /** Parses `merges.jsonl`: one pull request merged into main per line, with when it was opened. */ export function parseMerges(text: string): Merge[] { return lines(text).map((row, index) => { if (!isObject(row) || !isCount(row.number) || !isTime(row.created_at) || !isTime(row.merged_at)) throw new TypeError(`line ${index + 1} is not a merge`); return { number: row.number, created_at: row.created_at, merged_at: row.merged_at }; }); } function isCited(value: unknown): value is Cited { if (!isObject(value) || typeof value.source !== 'string' || (value.unit !== undefined && typeof value.unit !== 'string')) return false; const number = (item: unknown) => typeof item === 'number' && Number.isFinite(item); return number(value.value) || (Array.isArray(value.value) && value.value.length === 2 && value.value.every(number)); } function isDay(value: unknown): value is Day { return isObject(value) && isDate(value.date) && ['title', 'problem', 'evidence', 'change', 'effect'].every((field) => typeof value[field] === 'string') && Array.isArray(value.prs) && value.prs.every((pr: unknown) => isObject(pr) && isCount(pr.number) && (pr.by === 'dev-loop' || pr.by === 'agent' || pr.by === 'other') && typeof pr.what === 'string' && (pr.measured === undefined || typeof pr.measured === 'string')); } /** Parses `changelog.json`: what changed each day, and the measurements and moments it cites from elsewhere. */ export function parseChangelog(value: unknown): Changelog { if (!isObject(value) || !isTime(value.fetchedAt) || !isObject(value.cited) || !isObject(value.moments) || !Array.isArray(value.days)) { throw new TypeError('the changelog needs fetchedAt, cited, moments and days'); } for (const [key, cited] of Object.entries(value.cited)) if (!isCited(cited)) throw new TypeError(`cited.${key} needs a value and a source`); for (const [key, moment] of Object.entries(value.moments)) { if (!isObject(moment) || !isTime(moment.at) || typeof moment.source !== 'string') throw new TypeError(`moments.${key} needs a time and a source`); } value.days.forEach((day, index) => { if (!isDay(day)) throw new TypeError(`day ${index + 1} is incomplete`); }); return value as unknown as Changelog; }