diff --git a/.github/workflows/ci-evidence-report.yml b/.github/workflows/ci-evidence-report.yml new file mode 100644 index 0000000000..14b72d9b40 --- /dev/null +++ b/.github/workflows/ci-evidence-report.yml @@ -0,0 +1,63 @@ +# The daily digest and the weekly evidence report, generated from the +# measurement data ref (docs/decisions/ci-evidence.md). Measurement only: never +# a proof/merge gate. Executes trusted default-branch tooling with no +# dependency install, reads the archive and main's history, and writes nothing +# but its own artifacts and job summary. +name: ci-evidence-report + +on: + workflow_dispatch: + inputs: + weekly: + description: Also generate the weekly report, whatever the day + type: boolean + default: false + schedule: + # An hour after the 02:17 UTC archive compaction, which has a 60-minute limit. + - cron: "37 3 * * *" + +permissions: {} + +concurrency: + group: ci-evidence-report + cancel-in-progress: false + +jobs: + report: + runs-on: ubuntu-24.04 + timeout-minutes: 30 + permissions: + contents: read # the data ref and main's history; reports write nothing + steps: + - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7 + with: + ref: ${{ github.event.repository.default_branch }} + persist-credentials: false + # Proof-policy epochs classify main's first-parent squashes locally. + fetch-depth: 0 + - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: "1.4.2" + - name: Generate the daily digest, and the weekly report on Mondays + env: + REPORT_REPO: ${{ github.repository }} + REPORT_WEEKLY: ${{ inputs.weekly && 'true' || 'false' }} + run: | + bun scripts/ci-evidence-report.ts --cadence daily --repo "$REPORT_REPO" --from-archive origin --out tmp/ci-evidence + if [ "$REPORT_WEEKLY" = true ] || [ "$(date -u +%u)" = 1 ]; then + bun scripts/ci-evidence-report.ts --cadence weekly --repo "$REPORT_REPO" --from-archive origin --out tmp/ci-evidence + fi + - name: Write the reports to the job summary + if: always() + run: | + for report in tmp/ci-evidence/weekly.md tmp/ci-evidence/digest.md; do + if [ -s "$report" ]; then cat "$report" >> "$GITHUB_STEP_SUMMARY"; fi + done + - name: Retain the reports + if: always() + uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9 # v7 + with: + name: ci-evidence-report + path: tmp/ci-evidence/ + if-no-files-found: error + retention-days: 90 diff --git a/docs/process/ci-evidence.md b/docs/process/ci-evidence.md index 68136938e2..a12344fa79 100644 --- a/docs/process/ci-evidence.md +++ b/docs/process/ci-evidence.md @@ -33,7 +33,8 @@ are refused; future schemas append rather than rewrite history. | `collection` (`collection.json`, `collections//collection.json`) v1 | Collection ID, requested window, discovered attempts, errors, budget and seed observations. | Every collect invocation, including partial acquisition. | API responses transient; manifests in hourly artifacts request 90 days. | | `enrichment` (`enrichment.json`) v1 | `LifecycleAcquisition`, repository, timestamp, expected PRs and acquisition errors. | Every lifecycle enrichment. | API responses transient; artifacts request 90 days. | | `source` (archive only) v1 | `ArchiveSource`, repository/artifact; collector run, artifact creation time, SHA-256 digest, archived and refused record counts. | Daily archive compaction, one per retained artifact. | Written to the data ref; the artifact it names expires after 90 days. | -| `summary` (`summary.json`) v1 | `summarize` and report joins: derived timings, throughput, epochs, red-main and coverage sections. Markdown is a rendering, not another schema. | Local `report` and hourly collect; scheduled archive-based daily/weekly report planned in #2956. | Derived from retained inputs; artifacts request 90 days. | +| `summary` (`summary.json`) v1 | `summarize` and report joins: derived timings, throughput, epochs, red-main and coverage sections. Markdown is a rendering, not another schema. | Local `report` and hourly collect. | Derived from retained inputs; artifacts request 90 days. | +| `evidence report` (`digest.json`, `weekly.json`) v1 | `evidenceReport` (`scripts/ci-evidence-report.ts`): gate, throughput headline, epochs, red-main, families, runner wait, contention, activity and coverage for one window, read from the data ref. Markdown is a rendering. | Daily digest, weekly report on Mondays ([scheduled reports](ci-timings.md#scheduled-evidence-reports)). | Derived from the data ref; the `ci-evidence-report` artifact requests 90 days. | Schema anchors: (`TimingSnapshot`, `scripts/ci-timings.ts:40-52`), (`PullObservation`, `scripts/ci-throughput.ts:7-13`), @@ -90,13 +91,13 @@ cost. Durations report sample counts and median/p90; unknowns stay separate. | Metric | Definition and source / producing file or task | Kind/version → report field | Status | | --- | --- | --- | --- | | First-main failing categories | Failed primary job categories per first-main attempt; `ci-throughput.ts`. | R + P → S `reliability.firstMainFailedJobCategories` | collected | -| Failure families and attribution | Evidence-linked product/test/infrastructure/stale-candidate/intentional-feedback annotations, optionally job-specific; annotation presence is not complete causal attribution. | E + R → S `reliability.classificationRecords`; #2956 ranks families | collected locally; hosted publication planned #2954 | +| Failure families and attribution | Evidence-linked product/test/infrastructure/stale-candidate/intentional-feedback annotations, optionally job-specific; annotation presence is not complete causal attribution. | E + R → S `reliability.classificationRecords`; report `families` ranks them | collected locally; hosted publication planned #2954 | | Red-main incidents | Opening run, first bad SHA/refinements, test/category/reasons, incident issue, declared/expedited fixes and clearance; #2942 producer, #2953 collector (`ci-red-main.ts`). | M → S `redMain.incidents` | collected hourly | | Time to green | Record opened → cleared using server time; open incidents have unknown duration. | M → S `redMain.timeToGreenSeconds`, `openIncidents` | collected hourly | -| Suspected flakes, verdicts and reruns | Per-test suspicions, probe outcomes, linked issues and repeated-suspicion/probe-reproduced escalations; rerun attempts retained separately. | M + R → S `redMain.flakes`; ranked report #2956 | collected hourly | +| Suspected flakes, verdicts and reruns | Per-test suspicions, probe outcomes, linked issues and repeated-suspicion/probe-reproduced escalations; rerun attempts retained separately. | M + R → S `redMain.flakes`; report `families.suspectedFlaky` | collected hourly | | Cancelled/refused proof while red | Coordinator cancellation IDs and hosted gate refusal steps, observed consumed seconds and estimated saved seconds versus median successful PR attempt; missing snapshots/reference remain unknown. | C + M + R → S `redMain.cancellations`, `refusals`, `savingReference` | collected hourly | | Merges during red | Reported non-fix squashes matched to exact PR identity; unresolved PR counted separately. | M + P → S `redMain.mergesDuringRed` | collected hourly | -| Explicit incidents/reverts/expedited fixes | Supplied public evidence with affected/repair PR; overall product incident rate remains unknown without surveillance. | E → S reliability records | collected locally; publication #2954, archive/report #2955/#2956 | +| Explicit incidents/reverts/expedited fixes | Supplied public evidence with affected/repair PR; overall product incident rate remains unknown without surveillance. | E → S reliability records | collected locally; publication #2954, archived and reported | | Worker activity and work lifetime | Paired opaque worker/task work boundaries; overlapping tasks do not double count a worker. No instrumentation means unknown, not zero active agents. | E → S `parallelism.recordedWorkers`, `completedWorkIntervals` | collected only when orchestrator records; hosted publication planned #2954 | | Caller wait and conflict effort | Paired waits by reservation/CI/review/conflict/other reason; elapsed wait is not CPU effort. | E → S `parallelism.waits` | collected locally when emitted; publication planned #2954 | | Local host-slot admission wait | #2943 `host-admission.mjs` automatically emits wait pairs, reason `other`, task `admission-`. | E → S `parallelism.waits.other` | collected locally; publication planned #2954 | @@ -106,18 +107,18 @@ cost. Durations report sample counts and median/p90; unknowns stay separate. | Escape classes | #2937 historical public issue-comment audit: bypassed-confirmation, selection-miss, harness-change, confirmed-then-flaked, inherited-red, unknown. Issue comments have no configured collector expiry; failure classifications alone do not supply escape classes. | No normalized kind/version | gap #4043 | | Reservation requests | Request → admission/refusal demand, including unsuccessful callers, beyond acquired leases. Live command outcomes are not an archived event stream; no raw retention guarantee. | No kind/version | gap #4044 | | Reconfirmation reasons | Distinguish base advance, head change and other reproof causes; current leases/ready times cannot establish them. No retained structured source. | No kind/version | gap #4044 | -| Coverage gaps | Missing attempts, incomplete snapshots, lifecycle errors, budget/seed stops, failed reservation/red-main scopes and unknown coordinator logs; `ci-timings.ts` acquisition/report joins. | collection + enrichment v1, R/L/M/C → S coverage/acquisition | collected; missing hours/expired sources and archive-wide self-check planned #2956; collection recovery #3853 | +| Coverage gaps | Missing attempts, incomplete snapshots, lifecycle errors, budget/seed stops, failed reservation/red-main scopes and unknown coordinator logs; `ci-timings.ts` acquisition/report joins. | collection + enrichment v1, R/L/M/C → S coverage/acquisition → report `coverage` (missing hours, expired sources, failed acquisitions, unknowns) | collected; collection recovery #3853 | ## Phase B gate and scheduled report | Metric | Definition and source / producing file or task | Kind/version | Status | | --- | --- | --- | --- | -| Seven consecutive days | One proof-policy epoch, opening at a classified proof-system squash; unknown/unbounded history cannot prove stability. `ci-epochs.ts` classifies first-parent Git history using the parent's path set (#3270). Git history has no configured TTL; derived on every report, hourly checkout fetches full history. | R + P + Git → S `throughput.epochs.current.days` | collected input; gate evaluation planned #2956 | -| At least 80% first-main green | Green / known first-main outcomes in that same epoch, carrying denominator, unknown outcomes and coverage limits. | R + P → S `throughput.epochs.current.firstMainGreen` | collected input; gate evaluation planned #2956 | -| Every red incident attributed | Requires evidence for every red incident in the epoch. Current `incidentAttribution` counts failed first-main attempts with any annotation; it cannot establish complete attribution of all failures or incidents. | E + R + P → S `throughput.epochs.current.incidentAttribution`; M supplies incident coverage | planned #2956 for complete gate assessment; current input collected with this limitation | -| Phase B gate state/change | All three requirements qualified together; no mixed epoch or incomplete attribution promoted to met. Measurement only, no rollout authorization. | No implemented gate kind/version; future report schema owned by #2956 | planned #2956 | -| Daily digest / weekly report | Archive-derived cohorts, first-main per epoch, red incidents/recovery, failing/flaky families, escape classes, runner wait, local contention and coverage. | Current S v1 is local/hourly; scheduled schema owned by #2956 | planned #2955/#2956 | -| Delivery/change triggers | Weekly always; daily newly observed incident (no duration threshold), gate change or collection gap; unchanged incident is not new. Artifacts daily, comments on one pinned issue. | No implemented delivery record/version; #2957 owns delivery state | planned #2956/#2957 | +| Seven consecutive days | One proof-policy epoch, opening at a classified proof-system squash; unknown/unbounded history cannot prove stability. `ci-epochs.ts` classifies first-parent Git history using the parent's path set (#3270). Git history has no configured TTL; derived on every report, hourly checkout fetches full history. | R + P + Git → S `throughput.epochs.current.days` → report `gate.conditions.epoch` | collected, evaluated | +| At least 80% first-main green | Green / known first-main outcomes in that same epoch, carrying denominator, unknown outcomes and coverage limits. | R + P → S `throughput.epochs.current.firstMainGreen` → report `gate.conditions.firstMainGreen` | collected, evaluated | +| Every red incident attributed | Every red-main incident open in the gate's seven days has a `failure-classified` event naming its opening run; missing red-main history is unknown. `incidentAttribution` separately counts failed first-main attempts with any annotation. | M + E → report `gate.conditions.incidentsAttributed` | collected, evaluated; annotation is not complete causal attribution | +| Phase B gate state/change | All three requirements qualified together; no mixed epoch or incomplete attribution promoted to met. Measurement only, no rollout authorization. | Report `gate`, `previousGate`, `triggers.gateChanged` | evaluated daily | +| Daily digest / weekly report | Archive-derived cohorts, first-main per epoch, red incidents/recovery, failing/flaky families, escape classes, runner wait, local contention and coverage. | `evidence report` v1 | generated daily and weekly | +| Delivery/change triggers | Weekly always; daily newly observed incident (no duration threshold), gate change or collection gap; unchanged incident is not new. Artifacts daily, comments on one pinned issue. | Report `changed` and `triggers`; #2957 owns delivery state | triggers computed; delivery planned #2957 | ## Trace a reported value diff --git a/docs/process/ci-throughput.md b/docs/process/ci-throughput.md index d302c4d325..1b7494a112 100644 --- a/docs/process/ci-throughput.md +++ b/docs/process/ci-throughput.md @@ -113,8 +113,9 @@ hourly collector checks out full history for this reason. | `epochs.current` | The epoch holding the newest squash before the window end: `days` since its boundary and `firstMainGreen`, the two numeric inputs of the #2934 Phase B gate, plus `incidentAttribution`. | | `epochs.current.incidentAttribution` | Failed first-main attempts in the epoch and how many carry a `failure-classified` record. `unknown` when none do, `partial` when some do, `recorded` when all do. No record is unknown, not unattributed; incidents outside first-main runs are not observed. | -The report states these inputs; it does not decide whether the gate is met. -An `unknown` boundary on the current epoch means its days are counted from a +This report states these inputs; it does not decide whether the gate is met. +The [scheduled evidence reports](ci-timings.md#scheduled-evidence-reports) +evaluate the gate from them every day. An `unknown` boundary on the current epoch means its days are counted from a squash that may not have changed policy, so they are not evidence of a stable epoch. diff --git a/docs/process/ci-timings.md b/docs/process/ci-timings.md index d59ff65a28..415cb68126 100644 --- a/docs/process/ci-timings.md +++ b/docs/process/ci-timings.md @@ -210,8 +210,7 @@ is merged. A refused record is excluded, named with its kind, artifact path and reason in the JSON output and job summary, and makes the command exit 1 after publishing the rest. Each artifact gets a `source` record with its ID, collector run, creation time, SHA-256 digest and record/refusal counts. -#2956 uses those to report missing collection hours and expired sources. An -unreadable artifact is refused as a source and retried next time. +An unreadable artifact is refused as a source and retried next time. Each commit is parented by the inspected remote head and pushed with exact `--force-with-lease`, using an isolated index; the caller's checkout and index @@ -241,6 +240,76 @@ Readers refuse an unknown kind, an unknown schema version, another repository's record and a record outside its month partition. The archive is measurement only and never an input to proof, selection or merging. +## Scheduled evidence reports + +`.github/workflows/ci-evidence-report.yml` runs daily at 03:37 UTC, an hour +after the archive compaction, and on manual dispatch. It reads the data ref and +main's full first-parent history, with a read-only token, and writes the daily +digest. On Mondays, or when dispatched with `weekly`, it also writes the weekly +report. Both go to the job summary and the `ci-evidence-report` artifact, kept +for 90 days, whether or not anything is delivered: + +```sh +bun scripts/ci-evidence-report.ts --cadence daily --repo odysseus/chronicle \ + --from-archive origin --out tmp/ci-evidence [--until 2026-07-13T00:00:00Z] [--history origin/main] +``` + +The digest covers the UTC day before `--until`, and the weekly report the seven +days before it. `--until` defaults to the start of the current UTC day and must +fall on a whole hour. The command writes `digest.json` and `digest.md`, or +`weekly.json` and `weekly.md`. Each Markdown report opens with a `## Summary` +section that ends at the next heading, so it can be posted on its own and link +the full artifact. The JSON is `version: 1`. + +Each report has these sections, all computed from the archive for its window: + +| Section | Content | +| --- | --- | +| `gate` | The #2934 Phase B gate over the seven days before `--until`, and `previousGate` a day earlier. See below. | +| `throughput` | The [throughput](ci-throughput.md#what-the-report-measures) cohort headline: merges, first-main green, first-pass greens/day, latencies, size cohorts, merge paths and reservation occupancy. The weekly report also carries the full summary under `detail`. | +| `epochs` | First-main green per [proof-policy epoch](ci-throughput.md#proof-policy-epochs) the window touches. | +| `redMain` | Red-main incidents open at any time in the window, with time to green, those still open at its end, and the ones first observed in it. | +| `families` | The ten failing test families most often named by those incidents, the ten most-suspected flaky families with probe outcomes, first-main failed job categories and failure classifications. | +| `escapeClasses` | Always `null` until an archived source exists ([#4043](https://github.com/schlessera/brain-kit/issues/4043)). | +| `runnerSlotWait` | [Runner-slot wait](ci-throughput.md#runner-slot-wait) over the attempts created in the window. | +| `localContention` | Published work and wait events in the window; `null` when none were published. | +| `activity` | Run attempts and merges per UTC day. A day with a missing collection hour reports `null` counts and the observed numbers as `observedRunAttempts` and `observedMerges`. | +| `coverage` | Missing collection hours, expired sources, failed acquisitions, missing run attempts and named unknowns. | + +**Coverage.** An hour of the window is missing when no collection manifest's +creation window covered it. No activity is known for a missing hour, so it is +never read as zero. An hour covered only by partial collections is listed in +`partialOnly`, because its runs may be incomplete, but it is not a gap. A missing +hour or failed acquisition more than 90 days old is also counted under +`expiredSources`: GitHub no longer holds its raw source, so the gap is permanent. +Failed acquisitions list partial collections, lifecycle errors, failed +reservation and red-main histories, partial coordinator scopes and coordinator +logs that could not say what they cancelled. + +**Phase B gate.** The gate is `met` only when all three conditions are met for +the seven days before `--until`; otherwise it is `not met` and `failing` names +each condition that is not met or is unknown: + +- `epoch`: the current proof-policy epoch opened at a classified proof-system + squash at least seven days before `--until`. An unreadable history, an + unbounded epoch or an unknown boundary leaves it unknown. +- `firstMainGreen`: at least 80% of the epoch's known first-main outcomes in + those days are green. No known outcome, or any missing collection hour in + those days, leaves it unknown. +- `incidentsAttributed`: every red-main incident open in those days has a + `failure-classified` event naming its opening run. No red-main history + collected in those days, or a failed red-main acquisition, leaves it unknown. + +**Delivery trigger.** `changed` is true when a red-main incident is first +observed in the window (its earliest archived red-main record falls in it), the +gate's status differs from `previousGate`, or the window has a missing +collection hour. `triggers` names which. An incident observed again unchanged +does not trigger, and no duration threshold applies +([decision](../decisions/ci-evidence.md#reports-cadence-and-delivery)). The +weekly report is delivered whatever its flag. Posting the reports is +[#2957](https://github.com/schlessera/brain-kit/issues/2957)'s; this workflow +holds no write permission. + ## Refresh reviewed unit weights Use the separate explicit refresh command after choosing a successful exhaustive diff --git a/scripts/check-ci-workflows.ts b/scripts/check-ci-workflows.ts index b3c83ce0b8..98ce4dfc5e 100644 --- a/scripts/check-ci-workflows.ts +++ b/scripts/check-ci-workflows.ts @@ -145,7 +145,8 @@ export function checkCIWorkflows(root: string): string[] { if (files.includes("ci-timings.yml")) expected.push("ci-timings.yml"); if (files.includes("heavy-feedback.yml")) expected.push("heavy-feedback.yml"); if (files.includes("ci-evidence-archive.yml")) expected.push("ci-evidence-archive.yml"); - if (JSON.stringify(files) !== JSON.stringify(expected.sort())) problems.push("GitHub must contain only authoritative CI, contract, project-sync, red-main coordination and optional Pages/timing/archive/heavy-feedback workflows"); + if (files.includes("ci-evidence-report.yml")) expected.push("ci-evidence-report.yml"); + if (JSON.stringify(files) !== JSON.stringify(expected.sort())) problems.push("GitHub must contain only authoritative CI, contract, project-sync, red-main coordination and optional Pages/timing/archive/report/heavy-feedback workflows"); // Every workflow, authoritative or not, runs only reviewed action commits (#4111). for (const file of files.filter(file => /\.ya?ml$/.test(file))) problems.push(...actionPinProblems(readFileSync(join(directory, file), "utf8"), file)); const depot = join(root, ".depot/workflows"); @@ -163,6 +164,8 @@ export function checkCIWorkflows(root: string): string[] { if (existsSync(timings)) problems.push(...timingWorkflowProblems(readFileSync(timings, "utf8"))); const archive = join(directory, "ci-evidence-archive.yml"); if (existsSync(archive)) problems.push(...archiveWorkflowProblems(readFileSync(archive, "utf8"))); + const report = join(directory, "ci-evidence-report.yml"); + if (existsSync(report)) problems.push(...reportWorkflowProblems(readFileSync(report, "utf8"))); return problems; } @@ -195,6 +198,37 @@ export function archiveWorkflowProblems(text: string): string[] { return errors; } +/** + * The scheduled evidence reports (#2956) read the data ref and main's history + * and write only their own artifacts: no write authority at all, trusted + * default-branch code, and an always-uploaded 90-day artifact + * (docs/decisions/ci-evidence.md). Posting them is a separate job's grant. + */ +export function reportWorkflowProblems(text: string): string[] { + const errors: string[] = [], fail = (message: string) => errors.push(`ci-evidence-report.yml: ${message}`); + let workflow: Workflow; + try { workflow = Bun.YAML.parse(text) as Workflow; } + catch { return ["ci-evidence-report.yml: invalid YAML"]; } + if (!workflow || typeof workflow !== "object") return ["ci-evidence-report.yml: workflow must be a mapping"]; + if (JSON.stringify(Object.keys(workflow.on ?? {}).sort()) !== JSON.stringify(["schedule", "workflow_dispatch"]) || + /\bsecrets\.|\bpull_request(?:_target)?\b|\bworkflow_run\b/.test(text)) fail("reports must use scheduled/manual trusted execution only"); + const schedule = workflow.on?.schedule as { cron?: string }[] | undefined; + if (!Array.isArray(schedule) || schedule.length !== 1 || !/^\d{1,2} \d{1,2} \* \* \*$/.test(schedule[0]?.cron ?? "")) fail("reports must run once a day"); + if (JSON.stringify(workflow.permissions) !== "{}") fail("workflow token must grant nothing"); + if (JSON.stringify(Object.keys(workflow.jobs ?? {})) !== JSON.stringify(["report"])) fail("report workflow must contain only the report job"); + const job = workflow.jobs?.report; + if (JSON.stringify(job?.permissions) !== JSON.stringify({ contents: "read" })) fail("the report job may only read contents"); + const steps = job?.steps ?? [], checkouts = steps.filter(s => s.uses?.startsWith("actions/checkout@")); + if (checkouts.length !== 1 || checkouts[0]?.with?.ref !== "${{ github.event.repository.default_branch }}" || checkouts[0]?.with?.repository !== undefined || + checkouts[0]?.with?.["fetch-depth"] !== 0 || checkouts[0]?.with?.["persist-credentials"] !== false) fail("reports must check out trusted default-branch code with full history"); + if (!steps.some(s => s.run?.includes("bun scripts/ci-evidence-report.ts --cadence daily")) || !steps.some(s => s.run?.includes("bun scripts/ci-evidence-report.ts --cadence weekly"))) + fail("reports must generate the daily digest and the weekly report"); + if (!steps.some(s => s.uses === pinned("actions/upload-artifact@v7") && s.if === "always()" && s.with?.["retention-days"] === 90 && s.with?.path === "tmp/ci-evidence/")) + fail("the report artifacts must always be uploaded for 90 days"); + for (const step of steps) if ((step.run ?? "").includes("${{") || /bun install/.test(step.run ?? "")) fail("report scripts must not interpolate events or install dependencies"); + return errors; +} + /** Draft heavy feedback (#3272): ci.yml's own category jobs, per-PR cancellation, never `proof`. */ export function heavyFeedbackWorkflowProblems(text: string, ciText: string): string[] { const errors: string[] = [], fail = (message: string) => errors.push(`heavy-feedback.yml: ${message}`); diff --git a/scripts/ci-evidence-report.ts b/scripts/ci-evidence-report.ts new file mode 100644 index 0000000000..112de432ec --- /dev/null +++ b/scripts/ci-evidence-report.ts @@ -0,0 +1,395 @@ +/** + * The scheduled CI evidence reports (#2956): a daily digest and a weekly full + * report, both generated from the durable data ref (docs/decisions/ci-evidence.md). + * Measurement only: nothing here is an input to proof, selection or merging. + * Every section states its own coverage, and absent data is unknown, never zero. + */ +import { resolve, join } from "node:path"; +import { mkdir } from "node:fs/promises"; +import { percentage, stats } from "./ci-timing-stats"; +import { mergeIntervals, summarizeThroughput, type PullObservation, type WorkEvent } from "./ci-throughput"; +import { mergeRedMainArchives, summarizeRedMain, type CoordinatorObservation, type RedMainArchive } from "./ci-red-main"; +import { gitEpochSource, type EpochSource } from "./ci-epochs"; +import { failureKey } from "./red-main"; +import { archiveInputs, deduplicate, lifecycleCoverage, reservationCoverage, summarize, type ReportInputs, type TimingSnapshot } from "./ci-timings"; + +export const EVIDENCE_REPORT_VERSION = 1; +export type Cadence = "daily" | "weekly"; +/** The artifact base name each cadence writes: `.json` and `.md`. */ +export const REPORT_NAMES: Record = { daily: "digest", weekly: "weekly" }; +/** GitHub's retention cap for a public repository's artifacts, logs and runs. */ +export const RETENTION_DAYS = 90; +/** The #2934 Phase B gate, ruled on #2938. */ +export const GATE = { days: 7, firstMainGreenPercent: 80 } as const; +const HOUR = 3_600_000, DAY = 86_400_000, TOP = 10; +/** The throughput report's default sensitivity scenario (`writeReport`). */ +const SCENARIO = { failedPRFraction: .3, additionalPushes: 2, failedRunCostFraction: 1 }; +const iso = (ms: number) => new Date(ms).toISOString(); +const stamp = (value: unknown): value is string => typeof value === "string" && Number.isFinite(Date.parse(value)); + +export interface EvidenceOptions { + cadence: Cadence; + /** Exclusive end of the reported window, on a whole UTC hour. */ + until: string; + /** Generation time; decides which gaps have outlived GitHub's retention. */ + now: string; + /** Main's first-parent history for proof-policy epochs; absent means every epoch is unknown. */ + epochSource?: EpochSource; + archiveHead?: string | null; +} +type Status = "met" | "not met" | "unknown"; +export interface GateCondition { status: Status; reason: string } +export interface GateResult { + status: "met" | "not met"; window: { since: string; until: string }; + failing: ("epoch" | "firstMainGreen" | "incidentsAttributed")[]; + conditions: { epoch: GateCondition & { epoch: string | null; days: number | null }; + firstMainGreen: GateCondition & ReturnType; + incidentsAttributed: GateCondition & { incidents: number[]; unattributed: number[] } }; +} + +/** The window a cadence reports: the UTC day, or the seven days, before `until`. */ +export function reportWindow(cadence: Cadence, until: string): { since: string; until: string } { + const end = Date.parse(until); + if (!Number.isFinite(end) || end % HOUR) throw new Error("A report window ends on a whole UTC hour"); + return { since: iso(end - (cadence === "daily" ? DAY : GATE.days * DAY)), until: iso(end) }; +} + +/** Months a report needs from the archive: the gate's trailing week and the day before it. */ +export const archiveSince = (until: string) => iso(Date.parse(until) - (GATE.days + 1) * DAY); + +/** Memoizes commit classification, which spawns git, across the report's several throughput passes. */ +function memo(source: EpochSource | undefined): EpochSource | undefined { + if (!source || "error" in source) return source; + const cache = new Map>(); + return { ...source, classify(commit) { + if (!cache.has(commit.sha)) cache.set(commit.sha, source.classify(commit)); + return cache.get(commit.sha)!; + } }; +} + +/** + * Which hours of the window some collection's creation window covered. An hour + * no collection covered is missing; one covered only by partial collections is + * listed, because its runs may be incomplete, but it is not a gap. + */ +export function collectionHours(collections: { since?: unknown; until?: unknown; status?: unknown }[], window: { since: string; until: string }) { + const union = (rows: typeof collections) => mergeIntervals(rows.filter(c => stamp(c.since) && stamp(c.until)) + .map(c => ({ start: Date.parse(c.since as string), end: Date.parse(c.until as string) }))); + const any = union(collections), complete = union(collections.filter(c => c.status === "completed")); + const covered = (list: { start: number; end: number }[], start: number) => list.some(i => i.start <= start && i.end >= start + HOUR); + const missing: string[] = [], partialOnly: string[] = []; + let expected = 0; + for (let hour = Date.parse(window.since); hour < Date.parse(window.until); hour += HOUR) { + expected++; + if (!covered(any, hour)) missing.push(iso(hour)); + else if (!covered(complete, hour)) partialOnly.push(iso(hour)); + } + return { expected, covered: expected - missing.length, missing, partialOnly }; +} + +interface Loaded { + snapshots: TimingSnapshot[]; collections: any[]; pulls: PullObservation[]; events: WorkEvent[]; + redMain: RedMainArchive[]; coordinator: CoordinatorObservation[]; leases: ReturnType; + fullRun: { runnerSeconds: number | null; elapsedSeconds: number | null; samples: number }; +} + +function throughputFor(data: Loaded, window: { since: string; until: string }, epochSource: EpochSource | undefined) { + return summarizeThroughput(data.snapshots, data.pulls, data.events, { ...window, source: "scheduled evidence report window" }, + data.fullRun, SCENARIO, data.leases?.complete ? data.leases.leases : undefined, epochSource); +} + +/** Red-main incidents that were open at any time in the window. */ +function incidentsIn(redMain: NonNullable>, since: number, until: number) { + return redMain.incidents.filter(i => i.opened < until && (!i.cleared || i.cleared.at >= since)); +} + +/** + * The #2934 Phase B gate over the trailing seven days ending at `until`: one + * proof-policy epoch for all seven, first-main green at or above 80% of known + * outcomes, and every red-main incident open in those days attributed. An + * incident is attributed when a `failure-classified` event records its opening + * run. Missing evidence makes a condition unknown, and unknown is not met. + */ +export function phaseBGate(data: Loaded, until: string, epochSource: EpochSource | undefined): GateResult { + const window = { since: iso(Date.parse(until) - GATE.days * DAY), until }; + const throughput = throughputFor(data, window, epochSource), epochs = throughput.epochs, current = epochs?.current ?? null; + const epoch: GateResult["conditions"]["epoch"] = { status: "unknown", reason: "", epoch: current?.id ?? null, days: current?.days ?? null }; + if (!epochs) epoch.reason = "no proof-policy history was supplied"; + else if (epochs.status !== "derived") epoch.reason = `proof-policy history unavailable: ${epochs.error}`; + else if (!current) epoch.reason = "no main squash precedes the window end"; + else if (!current.start) epoch.reason = "no epoch boundary within the history lookback; an unbounded epoch cannot prove stability"; + else if (current.start.kind !== "proof-system") epoch.reason = "the current epoch opens at a squash whose classification is unknown"; + else if (current.days! >= GATE.days) Object.assign(epoch, { status: "met", reason: `${current.days!.toFixed(2)} days in epoch ${current.id}` }); + else Object.assign(epoch, { status: "not met", reason: `${current.days!.toFixed(2)} days in epoch ${current.id}, fewer than ${GATE.days}` }); + + const green = current?.firstMainGreen ?? percentage(0, 0), hours = collectionHours(data.collections, window); + const firstMainGreen: GateResult["conditions"]["firstMainGreen"] = { ...green, status: "unknown", reason: "" }; + if (!current) firstMainGreen.reason = "no current epoch"; + else if (hours.missing.length) firstMainGreen.reason = `${hours.missing.length} collection hours are missing, so deliveries may be uncounted`; + else if (!green.denominator) firstMainGreen.reason = "no known first-main outcome in the epoch"; + else Object.assign(firstMainGreen, { status: green.percent! >= GATE.firstMainGreenPercent ? "met" : "not met", + reason: `${green.numerator}/${green.denominator} first-main green (${green.percent!.toFixed(1)}%)` }); + + const since = Date.parse(window.since), end = Date.parse(until); + const red = summarizeRedMain({ archives: data.redMain, coordinator: data.coordinator, snapshots: data.snapshots, pulls: data.pulls }); + const scopes = data.redMain.filter(a => Date.parse(a.collectedAt) >= since && Date.parse(a.collectedAt) < end); + const open = red ? incidentsIn(red, since, end).map(i => i.run) : []; + const classified = new Set(data.events.filter(e => e.kind === "failure-classified").map(e => e.run)); + const unattributed = open.filter(run => !classified.has(run)); + const incidentsAttributed: GateResult["conditions"]["incidentsAttributed"] = { status: "unknown", reason: "", incidents: open, unattributed }; + if (!scopes.some(a => a.error === undefined)) incidentsAttributed.reason = "no red-main history was collected in the window"; + else if (scopes.some(a => a.error !== undefined)) incidentsAttributed.reason = `${scopes.filter(a => a.error !== undefined).length} red-main acquisitions failed in the window`; + else Object.assign(incidentsAttributed, unattributed.length + ? { status: "not met", reason: `${unattributed.length} of ${open.length} red-main incidents have no failure classification` } + : { status: "met", reason: `${open.length} red-main incidents, all attributed` }); + + const conditions = { epoch, firstMainGreen, incidentsAttributed }; + const failing = (Object.keys(conditions) as GateResult["failing"]).filter(k => conditions[k].status !== "met"); + return { status: failing.length ? "not met" : "met", window, failing, conditions }; +} + +/** One report from loaded archive inputs. Deterministic for the same inputs and options. */ +export function evidenceReport(inputs: ReportInputs, options: EvidenceOptions) { + const window = reportWindow(options.cadence, options.until), since = Date.parse(window.since), until = Date.parse(window.until); + const now = Date.parse(options.now), epochSource = memo(options.epochSource); + if (!Number.isFinite(now)) throw new Error("Invalid report generation time"); + const all = deduplicate(inputs.snapshots), op = inputs.operational, leases = reservationCoverage(op.reservations); + const collections = [...new Map(inputs.collections.map(c => [c.id ?? JSON.stringify(c), c])).values()]; + const baseline = summarize(all).baseline; + const data: Loaded = { snapshots: all, collections, pulls: op.pulls, events: op.events, redMain: op.redMain, coordinator: op.coordinator, leases, + fullRun: { runnerSeconds: baseline.runnerSeconds.median, elapsedSeconds: baseline.elapsedSeconds.median, samples: baseline.samples.length } }; + const inWindow = (at: unknown) => stamp(at) && Date.parse(at) >= since && Date.parse(at) < until; + + const throughput = throughputFor(data, window, epochSource); + const gate = phaseBGate(data, window.until, epochSource), previousGate = phaseBGate(data, iso(until - DAY), epochSource); + + // Red-main incidents: those open in the window, and those first observed in it. + const red = summarizeRedMain({ archives: op.redMain, coordinator: op.coordinator, snapshots: all, pulls: op.pulls }); + const firstSeen = new Map(); + for (const archive of op.redMain) if (archive.error === undefined) for (const i of archive.incidents) + firstSeen.set(i.run, Math.min(firstSeen.get(i.run) ?? Infinity, Date.parse(archive.collectedAt))); + const incidents = red ? incidentsIn(red, since, until) : []; + const newIncidents = incidents.filter(i => inWindow(iso(firstSeen.get(i.run) ?? NaN))).map(i => i.run); + const cleared = incidents.filter(i => i.cleared && i.cleared.at < until); + const redMain = red && { + incidents: incidents.map(i => ({ run: i.run, incident: i.incident, firstBad: i.firstBad, openedAt: i.openedAt, clearedAt: i.clearedAt, + timeToGreenSeconds: i.timeToGreenSeconds, categories: i.categories, fixes: i.fixes, newlyObserved: newIncidents.includes(i.run) })), + newlyObserved: newIncidents, + openAtEnd: incidents.filter(i => !i.cleared || i.cleared.at >= until).length, + timeToGreenSeconds: stats(cleared.map(i => i.timeToGreenSeconds!)), + mergesDuringRed: red.mergesDuringRed.rows.filter(m => incidents.some(i => i.run === m.incidentRun)).length, + }; + + // Failing and suspected-flaky test families, ranked by how many incidents and suspicions name them. + const families = new Map; runs: Set }>(); + for (const i of incidents) for (const f of i.failures) { + const key = failureKey(f), row = families.get(key) ?? { family: key, category: f.category, incidents: new Set(), runs: new Set() }; + row.incidents.add(i.run); row.runs.add(f.run); families.set(key, row); + } + const failing = [...families.values()].map(f => ({ family: f.family, category: f.category, incidents: f.incidents.size, runs: f.runs.size })) + .sort((a, b) => b.incidents - a.incidents || b.runs - a.runs || (a.family < b.family ? -1 : 1)); + const suspects = op.redMain.length ? mergeRedMainArchives(op.redMain).flakes.filter(f => inWindow(iso(f.at))) : []; + const realKeys = new Set(incidents.flatMap(i => i.failures.filter(f => f.escalated).map(failureKey))); + const flaky = [...new Set(suspects.map(s => s.test))].map(test => { + const rows = suspects.filter(s => s.test === test); + return { family: test, category: rows[0]!.category, suspicions: rows.length, + probes: Object.fromEntries(["passed", "failed", "pending", "unavailable"].map(p => [p, rows.filter(r => r.probe === p).length])), + issues: [...new Set(rows.flatMap(r => r.issue === null ? [] : [r.issue]))].sort((a, b) => a - b), + verdict: realKeys.has(test) ? "real" : "suspected-flake" }; + }).sort((a, b) => b.suspicions - a.suspicions || (a.family < b.family ? -1 : 1)); + const classifications = op.events.filter(e => e.kind === "failure-classified" && inWindow(e.at)); + + // Runner-slot wait and local contention, over what the window itself observed. + const windowSnapshots = all.filter(s => inWindow(s.run.createdAt)); + const wait = windowSnapshots.length ? summarize(windowSnapshots).runnerSlotWait : null; + const contention = op.events.filter(e => /^(work|wait)-/.test(e.kind) && inWindow(e.at)); + + // Coverage: missing hours, expired sources, failed acquisitions and unknowns. + const hours = collectionHours(collections, window); + const expired = (at: number) => at + RETENTION_DAYS * DAY < now; + const overlapping = collections.filter(c => stamp(c.since) && stamp(c.until) && Date.parse(c.since) < until && Date.parse(c.until) > since); + const observed = new Set(all.map(s => `${s.repository}/${s.run.id}/${s.run.attempt}`)); + const missingAttempts = [...new Set(overlapping.flatMap(c => (c.expected ?? []).flatMap((r: { run: number; attempts: number }) => + Array.from({ length: r.attempts }, (_, n) => `${c.repository}/${r.run}/${n + 1}`)).filter((k: string) => !observed.has(k))))].sort(); + const failed: { source: string; at: string; reason: string; expired: boolean }[] = []; + for (const c of overlapping.filter(c => c.status !== "completed").sort((a, b) => a.collectedAt < b.collectedAt ? -1 : 1)) + failed.push({ source: `collection ${c.id}`, at: c.collectedAt, expired: expired(Date.parse(c.until)), + reason: [c.requestBudget?.stopped ? `budget stop: ${c.requestBudget.stopped}` : "", c.seed?.error ? `seed: ${c.seed.error}` : "", + ...(c.errors ?? []).slice(0, 3).map((e: { error: string }) => e.error)].filter(Boolean).join("; ") || `status ${c.status}` }); + const lifecycle = lifecycleCoverage(op.acquisitions.filter(a => inWindow(a.collectedAt)), op.pulls); + for (const e of lifecycle?.errors ?? []) failed.push({ source: e.pr ? `lifecycle PR ${e.pr}` : "lifecycle discovery", at: lifecycle!.collectedAt, reason: e.problem, expired: false }); + for (const r of op.reservations.filter(r => inWindow(r.collectedAt) && r.error !== undefined)) + failed.push({ source: "reservation history", at: r.collectedAt, reason: r.error!, expired: expired(Date.parse(r.collectedAt)) }); + for (const r of op.redMain.filter(r => inWindow(r.collectedAt))) + if (r.error !== undefined || r.coordinatorScope?.status === "partial") + failed.push({ source: r.error !== undefined ? "red-main history" : "red-main coordinator logs", at: r.collectedAt, + reason: r.error ?? r.coordinatorScope!.error ?? "partial", expired: expired(Date.parse(r.collectedAt)) }); + for (const c of op.coordinator.filter(c => inWindow(c.createdAt) && c.cancelled === null)) + failed.push({ source: `coordinator run ${c.run} attempt ${c.attempt}`, at: c.createdAt, reason: c.problem ?? "cancellations unknown", expired: expired(Date.parse(c.createdAt)) }); + + const unknowns: { field: string; reason: string }[] = [ + { field: "escapeClasses", reason: "no archived escape-class source; acquisition is #4043" }, + { field: "reservationDemand", reason: "reservation requests and reconfirmation reasons are not archived; acquisition is #4044" }, + ]; + if (!red) unknowns.push({ field: "redMain", reason: "no red-main history in the archive" }); + if (!throughput.epochs || throughput.epochs.status !== "derived") unknowns.push({ field: "epochs", reason: throughput.epochs?.error ?? "no proof-policy history was supplied" }); + if (throughput.coverage.firstMainUnknown) unknowns.push({ field: "firstMainOutcomes", reason: `${throughput.coverage.firstMainUnknown} merged PRs have no known first-main outcome` }); + if (!contention.length) unknowns.push({ field: "localContention", reason: "no work or wait events were published in the window" }); + if (!wait) unknowns.push({ field: "runnerSlotWait", reason: "no run attempt was archived for the window" }); + else if (wait.overall.unknown) unknowns.push({ field: "runnerSlotWait", reason: `${wait.overall.unknown} jobs have no creation-to-start interval` }); + if (!leases?.complete) unknowns.push({ field: "reservation", reason: leases ? "reservation history acquisition was incomplete" : "no reservation history in the archive" }); + + // Activity per UTC day; a day with a missing hour reports what was observed as a lower bound, not a count. + const activity = []; + for (let day = since; day < until; day += DAY) { + const within = (at: unknown) => stamp(at) && Date.parse(at) >= day && Date.parse(at) < day + DAY; + const missing = hours.missing.filter(h => within(h)).length; + const runs = windowSnapshots.filter(s => within(s.run.createdAt)).length; + const merges = op.pulls.filter(p => p.baseBranch === "main" && within(p.mergedAt)).length; + activity.push({ day: iso(day).slice(0, 10), missingHours: missing, complete: missing === 0, + runAttempts: missing ? null : runs, merges: missing ? null : merges, observedRunAttempts: runs, observedMerges: merges }); + } + + const gateChanged = previousGate.status !== gate.status ? { from: previousGate.status, to: gate.status } : null; + const v = throughput.velocity, epochs = throughput.epochs; + return { + version: EVIDENCE_REPORT_VERSION, cadence: options.cadence, window, generatedAt: iso(now), archive: { head: options.archiveHead ?? null }, + /** Whether the daily digest is due for delivery (docs/decisions/ci-evidence.md); the weekly report is always delivered. */ + changed: newIncidents.length > 0 || gateChanged !== null || hours.missing.length > 0, + triggers: { newIncidents, gateChanged, collectionGap: hours.missing.length > 0 }, + gate, previousGate: { status: previousGate.status, until: previousGate.window.until, failing: previousGate.failing }, + throughput: { mergedInWindow: throughput.coverage.mergedInWindow, mergedPerDay: v.mergedPerDay, firstPassGreenPerDay: v.firstPassGreenPerDay, + firstPassGreen: v.firstPassGreen, firstMainUnknown: throughput.coverage.firstMainUnknown, firstMainOutcomes: throughput.reliability.firstMainOutcomes, + sameCommitObservedGreen: v.sameCommitObservedGreen, runnerMinutesPerObservedGreenIntegration: v.runnerMinutesPerObservedGreenIntegration, + createToMergeSeconds: v.createToMergeSeconds, createToGreenSeconds: v.createToGreenSeconds, mergeToGreenSeconds: v.mergeToGreenSeconds, + sameSourceRecoveries: throughput.reliability.sameSourceRecoveries, mergePaths: throughput.reliability.mergePaths, sizeCohorts: throughput.sizeCohorts, + reservationOccupancy: throughput.reservation?.occupiedWindow ?? null }, + epochs: epochs && epochs.status === "derived" ? epochs.epochs.map(e => ({ id: e.id, start: e.start?.at ?? null, kind: e.start?.kind ?? null, + end: e.end, current: e.current, merges: e.merges, firstMainGreen: e.firstMainGreen })) : null, + redMain, + families: { failing: failing.slice(0, TOP), suspectedFlaky: flaky.slice(0, TOP), + firstMainFailedJobCategories: throughput.reliability.firstMainFailedJobCategories, + classifications: Object.fromEntries([...new Set(classifications.map(e => e.classification!))].sort().map(k => [k, classifications.filter(e => e.classification === k).length])) }, + escapeClasses: null, + runnerSlotWait: wait, + localContention: contention.length ? { events: contention.length, recordedWorkers: throughput.coverage.recordedWorkers, + completedWorkIntervals: throughput.parallelism.completedWorkIntervals, waits: throughput.parallelism.waits, + unmatchedEvents: throughput.coverage.unmatchedCoordinationEvents } : null, + activity, + coverage: { complete: hours.missing.length === 0 && failed.length === 0 && missingAttempts.length === 0, + collectionHours: hours, + expiredSources: { hours: hours.missing.filter(h => expired(Date.parse(h) + HOUR)), acquisitions: failed.filter(f => f.expired).length, + note: `Gaps older than ${RETENTION_DAYS} days can no longer be recollected from GitHub.` }, + failedAcquisitions: failed, missingAttempts, unknowns }, + /** The weekly report also carries the full throughput summary it was computed from. */ + detail: options.cadence === "weekly" ? { throughput } : null, + }; +} +export type EvidenceReport = ReturnType; + +/** Consecutive whole hours as compact ranges, so a long gap reads as one line. */ +export function hourRanges(hours: string[]): string[] { + const out: string[] = []; + let start: number | null = null, last = 0; + const flush = () => { if (start !== null) out.push(start === last ? iso(start).slice(0, 13) + ":00Z" : `${iso(start).slice(0, 13)}:00Z–${iso(last + HOUR).slice(0, 13)}:00Z`); }; + for (const hour of hours.map(Date.parse).sort((a, b) => a - b)) { + if (start !== null && hour === last + HOUR) { last = hour; continue; } + flush(); start = last = hour; + } + flush(); + return out; +} + +const pct = (p: { numerator: number; denominator: number; percent: number | null }) => p.percent === null ? `unknown (0 known)` : `${p.numerator}/${p.denominator} (${p.percent.toFixed(1)}%)`; +const minutes = (n: number | null) => n === null ? "unknown" : (n / 60).toFixed(1); +const cell = (s: string) => s.replaceAll("|", "\\|"); + +/** + * The report as Markdown. `## Summary` comes first and ends at the next heading, + * so delivery (#2957) can post it alone and link the full artifact. + */ +export function evidenceMarkdown(r: EvidenceReport): string { + const title = r.cadence === "daily" ? `# CI evidence digest, ${r.window.since.slice(0, 10)}` : `# CI evidence weekly report, ${r.window.since.slice(0, 10)} to ${r.window.until.slice(0, 10)}`; + const t = r.throughput, c = r.coverage, g = r.gate; + const lines = [title, "", `Window ${r.window.since} to ${r.window.until} (UTC, end exclusive). Archive ${r.archive.head ?? "unknown"}. Generated ${r.generatedAt}.`, "", + "## Summary", "", + ...(c.complete ? [] : [`- **Coverage is incomplete**: ${c.collectionHours.missing.length} missing collection hours, ${c.failedAcquisitions.length} failed acquisitions, ${c.missingAttempts.length} missing run attempts. Counts below are lower bounds.`]), + `- Phase B gate: **${g.status}**${g.failing.length ? ` (failing: ${g.failing.join(", ")})` : ""}${r.triggers.gateChanged ? `, changed from ${r.triggers.gateChanged.from}` : ""}.`, + `- Merged PRs: ${t.mergedInWindow}; first-main green ${pct(t.firstPassGreen)}; first-pass greens/day ${t.firstPassGreenPerDay.toFixed(2)}.`, + `- Red-main incidents open: ${r.redMain ? r.redMain.incidents.length : "unknown"}; newly observed: ${r.redMain ? r.redMain.newlyObserved.length : "unknown"}; median time to green ${minutes(r.redMain?.timeToGreenSeconds.median ?? null)} min.`, + `- Runner-slot wait median ${minutes(r.runnerSlotWait?.overall.median ?? null)} min, p90 ${minutes(r.runnerSlotWait?.overall.p90 ?? null)} min.`, + `- Delivery due: ${r.cadence === "weekly" ? "yes (weekly)" : r.changed ? `yes (${[r.triggers.newIncidents.length ? "new incident" : "", r.triggers.gateChanged ? "gate change" : "", r.triggers.collectionGap ? "collection gap" : ""].filter(Boolean).join(", ")})` : "no"}.`, "", + "## Phase B gate", "", + `Trailing ${GATE.days} days ${g.window.since} to ${g.window.until}. Previous (to ${r.previousGate.until}): ${r.previousGate.status}.`, "", + "| Condition | Status | Evidence |", "| --- | --- | --- |", + `| ${GATE.days} days in one proof-policy epoch | ${g.conditions.epoch.status} | ${cell(g.conditions.epoch.reason)} |`, + `| First-main green at or above ${GATE.firstMainGreenPercent}% | ${g.conditions.firstMainGreen.status} | ${cell(g.conditions.firstMainGreen.reason)} |`, + `| Every red-main incident attributed | ${g.conditions.incidentsAttributed.status} | ${cell(g.conditions.incidentsAttributed.reason)} |`, "", + "## Throughput", "", + `Merged ${t.mergedInWindow} (${t.mergedPerDay.toFixed(2)}/day); first-main outcomes ${JSON.stringify(t.firstMainOutcomes)}; same-commit observed green ${pct(t.sameCommitObservedGreen)}.`, + `Runner-minutes per observed-green integration: ${t.runnerMinutesPerObservedGreenIntegration?.toFixed(1) ?? "unknown"}. Create to merge median ${minutes(t.createToMergeSeconds.median)} min, p90 ${minutes(t.createToMergeSeconds.p90)} min (n=${t.createToMergeSeconds.n}). Create to green median ${minutes(t.createToGreenSeconds.median)} min (n=${t.createToGreenSeconds.n}).`, + `Merge paths: ${JSON.stringify(t.mergePaths)}. Reservation occupancy: ${t.reservationOccupancy ? pct(t.reservationOccupancy) : "unknown"}.`, "", + "| Size cohort | PRs | First-main green |", "| --- | ---: | --- |", + ...Object.entries(t.sizeCohorts).map(([k, v]) => `| ${k} | ${v.prs} | ${pct(v.firstMainGreen)} |`), "", + "## First-main green per proof-policy epoch", "", + ...(r.epochs ? ["| Epoch | Starts | Boundary | Merges | First-main green |", "| --- | --- | --- | ---: | --- |", + ...r.epochs.map(e => `| ${e.id.slice(0, 12)}${e.current ? " (current)" : ""} | ${e.start ?? "before lookback"} | ${e.kind ?? "unbounded"} | ${e.merges} | ${pct(e.firstMainGreen)} |`)] + : ["Proof-policy epochs are unknown: no main history was readable."]), "", + "## Red-main incidents", "", + ...(!r.redMain ? ["Unknown: no red-main history in the archive."] : r.redMain.incidents.length ? [ + "| Opening run | Opened | Cleared | Time to green min | Categories | New |", "| --- | --- | --- | ---: | --- | --- |", + ...r.redMain.incidents.map(i => `| ${i.run} | ${i.openedAt} | ${i.clearedAt ?? "open"} | ${minutes(i.timeToGreenSeconds)} | ${i.categories.join(", ")} | ${i.newlyObserved ? "yes" : "no"} |`), "", + `Open at window end: ${r.redMain.openAtEnd}. Merges while red: ${r.redMain.mergesDuringRed}.`] : ["No red-main incident was open in the window."]), "", + "## Top failing test families", "", + ...(r.families.failing.length ? ["| Family | Category | Incidents | Runs |", "| --- | --- | ---: | ---: |", + ...r.families.failing.map(f => `| ${cell(f.family)} | ${f.category} | ${f.incidents} | ${f.runs} |`)] : [r.redMain ? "No failing test in a red-main incident." : "Unknown."]), "", + `First-main failed job categories: ${JSON.stringify(r.families.firstMainFailedJobCategories)}. Failure classifications: ${JSON.stringify(r.families.classifications)}.`, "", + "## Suspected-flaky test families", "", + ...(r.families.suspectedFlaky.length ? ["| Family | Category | Suspicions | Probes passed / failed / pending / unavailable | Verdict |", "| --- | --- | ---: | --- | --- |", + ...r.families.suspectedFlaky.map(f => `| ${cell(f.family)} | ${f.category} | ${f.suspicions} | ${f.probes.passed} / ${f.probes.failed} / ${f.probes.pending} / ${f.probes.unavailable} | ${f.verdict} |`)] + : [r.redMain ? "No suspected flake in the window." : "Unknown."]), "", + "## Escape classes", "", "Unknown: no archived escape-class source yet (#4043).", "", + "## Runner-slot wait", "", + ...(r.runnerSlotWait ? ["| Cohort | Known jobs | Unknown | Median min | p90 min | Max min | >5 min |", "| --- | ---: | ---: | ---: | ---: | ---: | --- |", + ...[["overall", r.runnerSlotWait.overall] as const, ...Object.entries(r.runnerSlotWait.byEvent).map(([k, v]) => [`event/${k}`, v] as const)].map(([k, v]) => + `| ${k} | ${v.n} | ${v.unknown} | ${minutes(v.median)} | ${minutes(v.p90)} | ${minutes(v.max)} | ${pct(v.overFiveMinutes)} |`)] : ["Unknown: no run attempt was archived for the window."]), "", + "## Local contention", "", + ...(r.localContention ? [`Events ${r.localContention.events}; workers ${r.localContention.recordedWorkers}; completed work intervals ${r.localContention.completedWorkIntervals}; unmatched ${r.localContention.unmatchedEvents}.`, + ...Object.entries(r.localContention.waits).map(([k, v]) => `- wait ${k}: n=${v.n}, median ${minutes(v.median)} min, p90 ${minutes(v.p90)} min`)] + : ["Unknown: no work or wait events were published in the window."]), "", + "## Activity by day", "", "| Day | Run attempts | Merges | Missing hours |", "| --- | ---: | ---: | ---: |", + ...r.activity.map(d => `| ${d.day} | ${d.runAttempts ?? `unknown (${d.observedRunAttempts} observed)`} | ${d.merges ?? `unknown (${d.observedMerges} observed)`} | ${d.missingHours} |`), "", + "## Coverage", "", + `Collection hours covered: ${c.collectionHours.covered}/${c.collectionHours.expected}; covered only by partial collections: ${c.collectionHours.partialOnly.length}.`, + ...(c.collectionHours.missing.length ? ["", "Missing collection hours (no activity is known for them):", ...hourRanges(c.collectionHours.missing).map(h => `- ${h}`)] : []), + "", `Expired sources: ${c.expiredSources.hours.length} missing hours and ${c.expiredSources.acquisitions} failed acquisitions are past retention. ${c.expiredSources.note}`, + "", `Failed acquisitions: ${c.failedAcquisitions.length}.`, ...c.failedAcquisitions.slice(0, 20).map(f => `- ${f.source} at ${f.at}: ${cell(f.reason)}${f.expired ? " (expired)" : ""}`), + ...(c.failedAcquisitions.length > 20 ? [`- ${c.failedAcquisitions.length - 20} more in the JSON report`] : []), + "", `Missing run attempts: ${c.missingAttempts.length}.`, "", "Unknown:", ...c.unknowns.map(u => `- ${u.field}: ${u.reason}`), ""]; + return lines.join("\n"); +} + +if (import.meta.main) { + try { + const args = process.argv.slice(2), options = new Map(); + while (args.length) { + const flag = args.shift()!; + if (!["--cadence", "--from-archive", "--until", "--repo", "--history", "--out"].includes(flag) || !args.length || options.has(flag)) throw new Error(`Invalid option ${flag}`); + options.set(flag, args.shift()!); + } + const cadence = options.get("--cadence") as Cadence; + if (!(cadence in REPORT_NAMES) || !options.has("--from-archive")) throw new Error("usage: bun scripts/ci-evidence-report.ts --cadence daily|weekly --from-archive REMOTE [--until ISO] [--history REF] [--repo owner/repo] [--out DIR]"); + const repository = options.get("--repo") ?? "schlessera/brain-kit"; + if (!/^[\w.-]+\/[\w.-]+$/.test(repository)) throw new Error("Invalid repository"); + const now = new Date().toISOString(), until = options.get("--until") ?? iso(Math.floor(Date.parse(now) / DAY) * DAY); + reportWindow(cadence, until); + const inputs = await archiveInputs(options.get("--from-archive")!, repository, archiveSince(until), until); + const report = evidenceReport(inputs, { cadence, until, now, archiveHead: inputs.head, + epochSource: gitEpochSource(process.cwd(), options.get("--history") ?? "origin/main") }); + const dir = resolve(options.get("--out") ?? "tmp/ci-evidence"), name = REPORT_NAMES[cadence]; + await mkdir(dir, { recursive: true }); + await Bun.write(join(dir, `${name}.json`), JSON.stringify(report, null, 2) + "\n"); + await Bun.write(join(dir, `${name}.md`), evidenceMarkdown(report)); + console.log(JSON.stringify({ report: join(dir, `${name}.json`), cadence, window: report.window, changed: report.changed, gate: report.gate.status, coverageComplete: report.coverage.complete })); + } catch (error) { console.error(error); process.exitCode = 1; } +} diff --git a/scripts/ci-timings.ts b/scripts/ci-timings.ts index bc77372249..c01e4ffb05 100644 --- a/scripts/ci-timings.ts +++ b/scripts/ci-timings.ts @@ -436,11 +436,11 @@ function newestPulls(pulls: PullObservation[]): PullObservation[] { * window, months from one before `since` through one after `until` are read, so * a cohort's earlier PR attempts and later main proof stay in view. */ -async function archiveInputs(remote: string, repository: string, since?: string, until?: string): Promise { +export async function archiveInputs(remote: string, repository: string, since?: string, until?: string, root = process.cwd()): Promise { const { GitArchiveStore, readArchive } = await import("./ci-archive"); const shift = (at: string, months: number) => { const d = new Date(at); d.setUTCDate(1); d.setUTCMonth(d.getUTCMonth() + months); return d.toISOString().slice(0, 7); }; const range = since && until ? [shift(since, -1), shift(until, 1)] as const : null; - const { head, rows } = await readArchive(new GitArchiveStore(process.cwd(), remote), repository, range ? m => m >= range[0] && m <= range[1] : undefined); + const { head, rows } = await readArchive(new GitArchiveStore(root, remote), repository, range ? m => m >= range[0] && m <= range[1] : undefined); if (!head) throw new Error("The archive ref does not exist on that remote"); return { head, snapshots: rows.run as TimingSnapshot[], collections: rows.collection, operational: { pulls: newestPulls(rows.pull as PullObservation[]), events: rows.event as WorkEvent[], acquisitions: rows.enrichment as LifecycleAcquisition[], @@ -448,7 +448,7 @@ async function archiveInputs(remote: string, repository: string, since?: string, } const COORDINATOR_FILE = /^coordinator-\d+-attempt-\d+\.json$/; -function lifecycleCoverage(input: LifecycleAcquisition[], pulls: PullObservation[]) { +export function lifecycleCoverage(input: LifecycleAcquisition[], pulls: PullObservation[]) { if (!input.length) return null; const scopes = [...new Map(input.map(s => [JSON.stringify(s), s])).values()] .sort((a, b) => Date.parse(a.collectedAt) - Date.parse(b.collectedAt)); @@ -471,7 +471,7 @@ function lifecycleCoverage(input: LifecycleAcquisition[], pulls: PullObservation missingPRs: expectedPRs.filter(pr => !pulls.some(p => p.number === pr)), scopes }; } -function reservationCoverage(input: ReservationArchive[]) { +export function reservationCoverage(input: ReservationArchive[]) { if (!input.length) return null; const archives = [...new Map(input.map(s => [JSON.stringify(s), s])).values()] .sort((a, b) => Date.parse(a.collectedAt) - Date.parse(b.collectedAt)); diff --git a/tests/ci-evidence-report.test.ts b/tests/ci-evidence-report.test.ts new file mode 100644 index 0000000000..fcbc272b50 --- /dev/null +++ b/tests/ci-evidence-report.test.ts @@ -0,0 +1,253 @@ +import { afterEach, expect, test } from "bun:test"; +import { mkdirSync, mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join, resolve } from "node:path"; +import { GitArchiveStore, publishBatch, type ArchiveKind } from "../scripts/ci-archive"; +import { archiveSince, evidenceMarkdown, evidenceReport, hourRanges, type Cadence } from "../scripts/ci-evidence-report"; +import { reportWorkflowProblems } from "../scripts/check-ci-workflows"; +import { archiveInputs, type ReportInputs } from "../scripts/ci-timings"; +import type { EpochSource } from "../scripts/ci-epochs"; + +const repository = "odysseus/chronicle"; +const HOUR = 3_600_000, DAY = 86_400_000; +const ms = (at: string) => Date.parse(at), iso = (at: number) => new Date(at).toISOString(); +const sha = (n: number) => n.toString(16).padStart(40, "0"); +const UNTIL = "2026-07-13T00:00:00.000Z", NOW = "2026-07-13T03:40:00.000Z"; +const dirs: string[] = []; +afterEach(() => { for (const dir of dirs.splice(0)) rmSync(dir, { recursive: true, force: true }); }); + +interface Delivery { number: number; merged: string; outcome: "success" | "failure"; lines: number } +/** Five deliveries in the week before the pinned date; the last one's first main run fails. */ +const PRS: readonly Delivery[] = [ + { number: 41, merged: "2026-07-07T09:00:00.000Z", outcome: "success", lines: 20 }, + { number: 42, merged: "2026-07-08T09:00:00.000Z", outcome: "success", lines: 120 }, + { number: 43, merged: "2026-07-09T09:00:00.000Z", outcome: "success", lines: 30 }, + { number: 44, merged: "2026-07-10T09:00:00.000Z", outcome: "success", lines: 700 }, + { number: 45, merged: "2026-07-11T09:00:00.000Z", outcome: "failure", lines: 40 }, +]; +/** Creation to start for every job, by event: the runner-slot wait the report must recompute. */ +const WAIT = { pull_request: 60, push: 600 } as const; +const INCIDENT = 9001, INCIDENT_OPENED = "2026-07-10T10:00:00.000Z", INCIDENT_CLEARED = "2026-07-10T11:30:00.000Z"; + +function run(id: number, event: "pull_request" | "push", head: string, pr: number, created: string, conclusion: string) { + const start = iso(ms(created) + WAIT[event] * 1000), end = iso(ms(start) + 20 * 60000); + return { version: 2, repository, collectedAt: iso(ms(created) + 2 * HOUR), run: { id, attempt: 1, workflow: "CI", path: ".github/workflows/ci.yml", event, head, + branch: event === "push" ? "main" : `ithaca-${pr}`, headRepository: repository, createdAt: created, startedAt: created, status: "completed", conclusion, + prs: [pr], attribution: event === "push" ? "exact merged squash SHA" : "run payload" }, + jobs: [{ id: id * 10, name: "proof", category: "proof", conclusion, labels: [], execution: "observed", createdAt: created, startedAt: start, completedAt: end, + seconds: 1200, steps: [], resource: null, resourceProblem: null }], problems: [] }; +} +const pull = (p: Delivery) => ({ version: 1, repository, number: p.number, collectedAt: iso(ms(p.merged) + HOUR), createdAt: iso(ms(p.merged) - 5 * HOUR), + mergedAt: p.merged, closedAt: p.merged, head: sha(p.number), merge: sha(p.number + 1000), baseBranch: "main", changedFiles: 2, additions: p.lines, deletions: 0, + timeline: [{ event: "ready_for_review", at: iso(ms(p.merged) - 3 * HOUR) }], problems: [] }); +const collection = (id: string, since: string, until: string, expected: { run: number; attempts: number }[], status = "completed") => ({ + version: 1, id, repository, collectedAt: until, status, since, until, requestedRun: null, expected, resourcesRequested: false, errors: [], + requestBudget: { limit: 200, reserve: 500, requests: 4, remaining: 900, stopped: null }, seed: null }); +const failure = (test: string) => ({ test, category: "unit", reasons: ["in-affected-closure"], run: INCIDENT, sha: sha(44 + 1000), escalated: null, priorSuspectRun: null }); +const redMain = (collected: string, incidents: object[], flakes: object[] = []) => ({ version: 1, repository, collectedAt: collected, + sourceRef: "refs/heads/brain-integration-reservation", sourceHead: sha(7), since: iso(ms(collected) - 2 * DAY), incidents, flakes }); +const incident = (cleared: string | null) => ({ run: INCIDENT, opened: ms(INCIDENT_OPENED), firstBad: sha(1044), firstBadHistory: [{ sha: sha(1044), at: ms(INCIDENT_OPENED) }], + failures: [failure("tests/ithaca-loom.test.ts")], incident: 610, fixes: [46], expedited: [], reported: [], + cleared: cleared ? { at: ms(cleared), run: 9003 } : null, sources: [sha(7)] }); +const flake = { test: "tests/sirens-call.test.ts", category: "browser", run: 9002, sha: sha(1043), at: ms("2026-07-09T08:00:00.000Z"), probe: "passed", issue: null, sources: [sha(7)] }; +const classified = { version: 1, id: "classified-9001", repository, kind: "failure-classified", at: "2026-07-10T12:00:00.000Z", run: INCIDENT, attempt: 1, + classification: "test", evidence: `https://github.com/${repository}/actions/runs/${INCIDENT}` }; +const wait = (id: string, kind: string, at: string) => ({ version: 1, id, repository, kind, at, worker: "worker-1", task: "ithaca-loom", reason: "ci" }); + +interface Fixture { prs?: readonly Delivery[]; gap?: string; boundary?: string; events?: object[]; red?: object[] | null } +/** The archive's records for one world, by kind. */ +function world(f: Fixture = {}) { + const prs = f.prs ?? PRS; + const runs = prs.flatMap(p => [run(p.number * 10 + 1, "pull_request", sha(p.number), p.number, iso(ms(p.merged) - 2 * HOUR), "success"), + run(p.number * 10 + 2, "push", sha(p.number + 1000), p.number, iso(ms(p.merged) + 60000), p.outcome)]); + const expected = runs.map(r => ({ run: r.run.id, attempts: 1 })), start = iso(ms(UNTIL) - 10 * DAY); + const collections = f.gap ? [collection("before-gap", start, f.gap, expected), collection("after-gap", iso(ms(f.gap) + HOUR), UNTIL, [])] + : [collection("hourly", start, UNTIL, expected)]; + const red = f.red !== undefined ? f.red : [redMain("2026-07-05T00:00:00.000Z", []), redMain("2026-07-10T12:00:00.000Z", [incident(INCIDENT_CLEARED)], [flake])]; + const events = f.events ?? [classified, wait("wait-a", "wait-started", "2026-07-09T10:00:00.000Z"), wait("wait-b", "wait-finished", "2026-07-09T10:30:00.000Z")]; + return { runs, collections, pulls: prs.map(pull), red: red ?? [], events, enrichment: [{ version: 1, repository, collectedAt: "2026-07-11T12:00:00.000Z", expectedPRs: prs.map(p => p.number), errors: [] }] }; +} +const inputs = (w: ReturnType): ReportInputs => ({ snapshots: w.runs as never, collections: w.collections, operational: { + pulls: w.pulls as never, events: w.events as never, acquisitions: w.enrichment as never, reservations: [], redMain: w.red as never, coordinator: [] } }); + +/** Main's first-parent history: each delivery's squash and one proof-system boundary, newest first. */ +function history(prs: readonly Delivery[], boundary = iso(ms(UNTIL) - 10 * DAY)): EpochSource { + const commits = [...prs.map(p => ({ sha: sha(p.number + 1000), at: p.merged })), { sha: sha(1), at: boundary }, { sha: sha(2), at: iso(ms(boundary) - DAY) }] + .sort((a, b) => ms(b.at) - ms(a.at)); + return { ref: "main", history: commits.map((c, i) => ({ ...c, parents: commits[i + 1] ? [commits[i + 1]!.sha] : [] })), + classify: c => ({ proofSystem: c.sha === sha(1) }) }; +} +const report = (cadence: Cadence, until: string, f: Fixture = {}) => + evidenceReport(inputs(world(f)), { cadence, until, now: NOW, epochSource: history(f.prs ?? PRS, f.boundary) }); + +function git(root: string, ...args: string[]) { + const p = Bun.spawnSync(["git", ...args], { cwd: root, stdout: "pipe", stderr: "pipe" }); + expect(p.exitCode, new TextDecoder().decode(p.stderr)).toBe(0); + return new TextDecoder().decode(p.stdout).trim(); +} +/** Publishes the world through the archive writer to a bare remote, returning a clone that reads it. */ +async function archived(w: ReturnType) { + const root = mkdtempSync(join(tmpdir(), "odysseus-evidence-")); dirs.push(root); + const remote = join(root, "remote.git"), clone = join(root, "clone"); + git(root, "init", "-q", "--bare", remote); mkdirSync(clone); git(clone, "init", "-q"); git(clone, "remote", "add", "origin", remote); + const records = ([["run", w.runs], ["collection", w.collections], ["pull", w.pulls], ["red-main", w.red], ["event", w.events], ["enrichment", w.enrichment]] as const) + .flatMap(([kind, rows]) => (rows as object[]).map(row => ({ kind: kind as ArchiveKind, row: row as Record }))); + const published = await publishBatch(new GitArchiveStore(clone), repository, { records, refused: [], sources: [] }); + expect(published.refused).toEqual([]); + return { root, clone }; +} + +test("the weekly report's numbers match a manual recomputation of the same window from the archive", async () => { + const w = world(), { clone } = await archived(w); + const loaded = await archiveInputs("origin", repository, archiveSince(UNTIL), UNTIL, clone); + const r = evidenceReport(loaded, { cadence: "weekly", until: UNTIL, now: NOW, epochSource: history(PRS), archiveHead: loaded.head }); + const since = ms(UNTIL) - 7 * DAY, inWeek = (at: string) => ms(at) >= since && ms(at) < ms(UNTIL); + + // Recomputed by hand from the fixture's own definitions. + const merged = PRS.filter(p => inWeek(p.merged)), green = merged.filter(p => p.outcome === "success"); + expect(r.window, "WEEKLY_WINDOW").toEqual({ since: iso(since), until: UNTIL }); + expect(r.throughput.mergedInWindow, "MERGED").toBe(merged.length); + expect(r.throughput.firstPassGreen, "FIRST_MAIN_GREEN").toEqual({ numerator: green.length, denominator: merged.length, percent: 100 * green.length / merged.length }); + expect(r.throughput.mergedPerDay).toBeCloseTo(merged.length / 7, 10); + expect(r.throughput.firstPassGreenPerDay).toBeCloseTo(green.length / 7, 10); + expect(r.throughput.createToMergeSeconds, "CREATE_TO_MERGE").toEqual({ n: 5, mean: 5 * 3600, median: 5 * 3600, p90: 5 * 3600 }); + expect(Object.fromEntries(Object.entries(r.throughput.sizeCohorts).map(([k, v]) => [k, v.prs]))) + .toEqual({ "0-50 changed lines": 3, "51-500 changed lines": 1, "501+ changed lines": 1 }); + + const waits = w.runs.filter(s => inWeek(s.run.createdAt)).map(s => WAIT[s.run.event as keyof typeof WAIT]).sort((a, b) => a - b); + expect(r.runnerSlotWait!.overall, "RUNNER_SLOT_WAIT").toEqual({ n: waits.length, mean: waits.reduce((a, b) => a + b, 0) / waits.length, + median: (waits[4]! + waits[5]!) / 2, p90: waits[8]!, max: 600, unknown: 0, + overFiveMinutes: { numerator: waits.filter(s => s > 300).length, denominator: waits.length, percent: 50 } }); + + expect(r.redMain!.incidents.map(i => [i.run, i.timeToGreenSeconds, i.newlyObserved]), "INCIDENT_TIME_TO_GREEN") + .toEqual([[INCIDENT, (ms(INCIDENT_CLEARED) - ms(INCIDENT_OPENED)) / 1000, true]]); + expect(r.redMain!.timeToGreenSeconds.median).toBe(5400); + expect(r.families.failing, "FAILING_FAMILIES").toEqual([{ family: "tests/ithaca-loom.test.ts", category: "unit", incidents: 1, runs: 1 }]); + expect(r.families.suspectedFlaky.map(f => [f.family, f.suspicions, f.probes.passed, f.verdict])).toEqual([["tests/sirens-call.test.ts", 1, 1, "suspected-flake"]]); + expect(r.families.firstMainFailedJobCategories).toEqual({ proof: 1 }); + expect(r.families.classifications).toEqual({ test: 1 }); + expect(r.localContention!.waits.ci, "LOCAL_CONTENTION").toEqual({ n: 1, mean: 1800, median: 1800, p90: 1800 }); + expect(r.epochs!.map(e => [e.id, e.kind, e.merges, e.firstMainGreen.percent])).toEqual([[sha(1), "proof-system", 5, 80]]); + + const perDay = Array.from({ length: 7 }, (_, n) => iso(since + n * DAY).slice(0, 10)).map(day => ({ day, + runs: w.runs.filter(s => s.run.createdAt.startsWith(day)).length, merges: PRS.filter(p => p.merged.startsWith(day)).length })); + expect(r.activity.map(d => ({ day: d.day, runs: d.runAttempts, merges: d.merges })), "ACTIVITY_BY_DAY").toEqual(perDay); + expect(r.coverage, "COMPLETE_COVERAGE").toMatchObject({ complete: true, collectionHours: { expected: 168, covered: 168, missing: [], partialOnly: [] }, + failedAcquisitions: [], missingAttempts: [] }); + expect(r.coverage.unknowns.map(u => u.field)).toEqual(["escapeClasses", "reservationDemand", "reservation"]); + expect(r.gate.status).toBe("met"); + expect(r.detail!.throughput.prs.map(p => p.number)).toEqual(merged.map(p => p.number)); + expect(r.archive.head).toBe(git(clone, "ls-remote", "origin", "refs/heads/brain-ci-metrics").split(/\s/)[0]!); +}); + +test("a missing collection hour is listed under coverage and never reads as zero activity", () => { + const gap = "2026-07-10T05:00:00.000Z", r = report("daily", "2026-07-11T00:00:00.000Z", { gap }); + expect(r.coverage.collectionHours, "MISSING_HOUR_LISTED").toEqual({ expected: 24, covered: 23, missing: [gap], partialOnly: [] }); + expect(r.coverage.complete).toBe(false); + expect(r.activity, "MISSING_HOUR_NOT_ZERO").toEqual([{ day: "2026-07-10", missingHours: 1, complete: false, runAttempts: null, merges: null, + observedRunAttempts: 2, observedMerges: 1 }]); + expect(r.gate.conditions.firstMainGreen, "GAP_LEAVES_GATE_UNKNOWN").toMatchObject({ status: "unknown" }); + const md = evidenceMarkdown(r); + expect(md).toContain("- 2026-07-10T05:00Z"); + expect(md).toContain("| 2026-07-10 | unknown (2 observed) | unknown (1 observed) | 1 |"); + expect(md).toContain("**Coverage is incomplete**"); + expect(md).not.toMatch(/\| 2026-07-10 \| 0 \|/); + expect(hourRanges([gap, "2026-07-10T06:00:00.000Z", "2026-07-10T09:00:00.000Z"])).toEqual(["2026-07-10T05:00Z–2026-07-10T07:00Z", "2026-07-10T09:00Z"]); +}); + +test("an hour covered only by a partial collection is listed but is not a gap", () => { + const w = world(), r = evidenceReport({ ...inputs(w), collections: [{ ...w.collections[0]!, status: "partial", errors: [{ run: 0, attempt: 0, error: "budget" }] }] }, + { cadence: "daily", until: "2026-07-11T00:00:00.000Z", now: NOW, epochSource: history(PRS) }); + expect(r.coverage.collectionHours.missing).toEqual([]); + expect(r.coverage.collectionHours.partialOnly).toHaveLength(24); + expect(r.coverage.failedAcquisitions.map(f => f.source)).toEqual(["collection hourly"]); + expect(r.triggers.collectionGap).toBe(false); +}); + +test("the gate is met exactly when all three conditions hold, and names each failing condition", () => { + const met = report("weekly", UNTIL); + expect(met.gate, "GATE_MET").toMatchObject({ status: "met", failing: [] }); + expect(met.gate.conditions.firstMainGreen, "EIGHTY_PERCENT_IS_MET").toMatchObject({ status: "met", numerator: 4, denominator: 5 }); + + // All green, so only the epoch's age can fail. + const young = report("weekly", UNTIL, { boundary: iso(ms(UNTIL) - 3 * DAY), prs: PRS.map(p => ({ ...p, outcome: "success" })) }); + expect(young.gate, "EPOCH_TOO_YOUNG").toMatchObject({ status: "not met", failing: ["epoch"] }); + expect(young.gate.conditions.epoch.reason).toBe(`3.00 days in epoch ${sha(1)}, fewer than 7`); + + const red = report("weekly", UNTIL, { prs: PRS.map((p, n) => n < 2 ? { ...p, outcome: "failure" } : p) }); + expect(red.gate, "FIRST_MAIN_BELOW_EIGHTY").toMatchObject({ status: "not met", failing: ["firstMainGreen"] }); + expect(red.gate.conditions.firstMainGreen.reason).toBe("2/5 first-main green (40.0%)"); + + const unattributed = report("weekly", UNTIL, { events: [] }); + expect(unattributed.gate, "INCIDENT_UNATTRIBUTED").toMatchObject({ status: "not met", failing: ["incidentsAttributed"] }); + expect(unattributed.gate.conditions.incidentsAttributed).toMatchObject({ status: "not met", incidents: [INCIDENT], unattributed: [INCIDENT] }); + + const unknown = report("weekly", UNTIL, { red: null }); + expect(unknown.gate, "NO_RED_MAIN_HISTORY_IS_NOT_MET").toMatchObject({ status: "not met", failing: ["incidentsAttributed"] }); + expect(unknown.gate.conditions.incidentsAttributed.status).toBe("unknown"); + + const noHistory = evidenceReport(inputs(world()), { cadence: "weekly", until: UNTIL, now: NOW }); + expect(noHistory.gate.failing, "NO_HISTORY_IS_NOT_MET").toEqual(["epoch", "firstMainGreen"]); + expect(noHistory.gate.conditions.epoch).toMatchObject({ status: "unknown", reason: "no proof-policy history was supplied" }); +}); + +test("the digest's changed flag is true for each trigger and false otherwise", () => { + const quiet = report("daily", "2026-07-13T00:00:00.000Z"); + expect([quiet.changed, quiet.triggers], "UNCHANGED_DAY").toEqual([false, { newIncidents: [], gateChanged: null, collectionGap: false }]); + + const incidentDay = report("daily", "2026-07-11T00:00:00.000Z"); + expect([incidentDay.changed, incidentDay.triggers], "NEW_INCIDENT").toEqual([true, { newIncidents: [INCIDENT], gateChanged: null, collectionGap: false }]); + + // The same incident, still open and observed again the next day, is not new. + const again = [redMain("2026-07-05T00:00:00.000Z", []), redMain("2026-07-10T12:00:00.000Z", [incident(null)]), redMain("2026-07-11T12:00:00.000Z", [incident(null)])]; + const reobserved = report("daily", "2026-07-12T00:00:00.000Z", { red: again }); + expect(reobserved.redMain!.incidents.map(i => [i.run, i.newlyObserved]), "REOBSERVED_NOT_NEW").toEqual([[INCIDENT, false]]); + expect([reobserved.changed, reobserved.triggers], "REOBSERVED_INCIDENT_UNCHANGED").toEqual([false, { newIncidents: [], gateChanged: null, collectionGap: false }]); + + const matured = report("daily", "2026-07-12T00:00:00.000Z", { boundary: "2026-07-04T12:00:00.000Z" }); + expect([matured.changed, matured.triggers], "GATE_CHANGE").toEqual([true, { newIncidents: [], gateChanged: { from: "not met", to: "met" }, collectionGap: false }]); + + // Without main's history the gate is not met on either day, so the gap is the only trigger. + const gap = evidenceReport(inputs(world({ gap: "2026-07-12T20:00:00.000Z" })), { cadence: "daily", until: "2026-07-13T00:00:00.000Z", now: NOW }); + expect([gap.changed, gap.triggers], "COLLECTION_GAP").toEqual([true, { newIncidents: [], gateChanged: null, collectionGap: true }]); +}); + +test("the CLI writes the stable digest files from the archive and refuses a window off the hour", async () => { + const { root, clone } = await archived(world()); + const script = resolve(import.meta.dir, "../scripts/ci-evidence-report.ts"), out = join(root, "out"); + const cli = (...args: string[]) => { + const child = Bun.spawnSync([process.execPath, script, "--repo", repository, "--from-archive", "origin", "--out", out, ...args], { cwd: clone, stdout: "pipe", stderr: "pipe" }); + return { code: child.exitCode, out: new TextDecoder().decode(child.stdout), err: new TextDecoder().decode(child.stderr) }; + }; + const daily = cli("--cadence", "daily", "--until", "2026-07-11T00:00:00Z", "--history", "main"); + expect(daily.code, daily.err).toBe(0); + expect(JSON.parse(daily.out)).toMatchObject({ cadence: "daily", changed: true, gate: "not met" }); + const digest = JSON.parse(readFileSync(join(out, "digest.json"), "utf8")); + expect(digest.triggers.newIncidents, "CLI_READS_ARCHIVE").toEqual([INCIDENT]); + expect(digest.gate.conditions.epoch.status, "UNREADABLE_HISTORY_UNKNOWN").toBe("unknown"); + expect(readFileSync(join(out, "digest.md"), "utf8")).toStartWith("# CI evidence digest, 2026-07-10\n"); + const off = cli("--cadence", "weekly", "--until", "2026-07-11T00:30:00Z"); + expect(off.code, "OFF_HOUR_REFUSED").toBe(1); + expect(off.err).toContain("A report window ends on a whole UTC hour"); +}); + +test("only trusted read-only scheduled execution generates the reports", () => { + const workflow = readFileSync(resolve(import.meta.dir, "../.github/workflows/ci-evidence-report.yml"), "utf8"); + expect(reportWorkflowProblems(workflow)).toEqual([]); + const problem = (text: string) => reportWorkflowProblems(text); + expect(problem(workflow.replace(" contents: read", " contents: write")), "REPORT_JOB_READ_ONLY") + .toContain("ci-evidence-report.yml: the report job may only read contents"); + expect(problem(workflow.replace(" contents: read", " contents: read\n issues: write"))) + .toContain("ci-evidence-report.yml: the report job may only read contents"); + expect(problem(workflow.replace("permissions: {}", "permissions:\n contents: read"))) + .toContain("ci-evidence-report.yml: workflow token must grant nothing"); + expect(problem(workflow.replace(" schedule:", " pull_request:\n schedule:"))) + .toContain("ci-evidence-report.yml: reports must use scheduled/manual trusted execution only"); + expect(problem(workflow.replace("fetch-depth: 0", "fetch-depth: 1"))) + .toContain("ci-evidence-report.yml: reports must check out trusted default-branch code with full history"); + expect(problem(workflow.replace("retention-days: 90", "retention-days: 30"))) + .toContain("ci-evidence-report.yml: the report artifacts must always be uploaded for 90 days"); + expect(problem(workflow.replace('"37 3 * * *"', '"37 * * * *"'))).toContain("ci-evidence-report.yml: reports must run once a day"); + expect(problem(workflow.replace("--from-archive origin --out tmp/ci-evidence\n if", "--from-archive origin --out tmp/ci-evidence\n bun install\n if"))) + .toContain("ci-evidence-report.yml: report scripts must not interpolate events or install dependencies"); +});