Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

ci: nightly-watch keeps one agent-actionable issue per red scheduled workflow

garrytanc2b058c42529
diff --git a/.github/nightly-known-red.tsv b/.github/nightly-known-red.tsv
new file mode 100644
index 0000000000..c99f277bab
--- /dev/null
+++ b/.github/nightly-known-red.tsv
@@ -0,0 +1,14 @@
+# Known-red and known-skipped nightly cells (GBRA-47 V-5). nightly-watch (scripts/nightly-issue.ts) keeps the
+# workflow's incident open with the known-red label while a row matches, and comments only when the failing set
+# changes or a review-by date passes. At most 3 rows: fix one before adding another. Docs: docs/RELEASING.md#nightly-red-issues
+#
+# Columns (tab-separated): workflow, job, signature, kind, todo, review_by
+# workflow the workflow name: (e.g. Scale tier)
+# job the job name exactly as GitHub shows it, matrix values expanded
+# signature known-red: text in the failing step name or one of the job's error annotations
+# known-skipped: the name of the step that ends skipped
+# kind known-red | known-skipped
+# todo the TODOS.md entry title that owns the fix (must appear in TODOS.md)
+# review_by YYYY-MM-DD; after it the incident asks for a fix or a re-justified date
+Scale tier scale pglite 20000 phase watchdog: vectors known-red PGLite bulk-embedding cliff at ~20k chunks 2026-10-25
+Heavy Tests Hermes door e2e (credentialed, real binary, loud-fail) Run hermes door tests known-skipped Set the ANTHROPIC_API_KEY and OPENAI_API_KEY repo secrets 2026-10-18
diff --git a/.github/workflows/nightly-watch.yml b/.github/workflows/nightly-watch.yml
new file mode 100644
index 0000000000..5a6087c279
--- /dev/null
+++ b/.github/workflows/nightly-watch.yml
@@ -0,0 +1,78 @@
+name: Nightly watch
+
+# Keeps one `nightly-red` issue per scheduled workflow (scripts/nightly-issue.ts;
+# owner and 24-hour response: docs/RELEASING.md#nightly-red-issues). Opens it on
+# a red scheduled run, updates it while red, reopens it on a flap, and closes
+# it only when a later scheduled run is green and every previously failing job
+# executed. Cells listed in .github/nightly-known-red.tsv keep the issue open
+# with the `known-red` label instead of counting as green.
+#
+# Security: runs only for scheduled runs of this repository, checks out the
+# default branch (never the triggering run's code), passes every event field
+# through env (no expression interpolation inside run:), and holds only
+# issues: write, actions: read and checks: read (for error annotations).
+#
+# Every workflow with a schedule trigger must be listed below
+# (test/scripts/nightly-issue.test.ts enforces it). A new workflow file can
+# only be dispatched from the default branch, so `run_id` dispatch is for
+# post-merge checks: gh workflow run nightly-watch.yml -f run_id=<scheduled run id>
+
+on:
+ workflow_run:
+ workflows:
+ - Test
+ - E2E Tests
+ - Heavy Tests
+ - Scale tier
+ - macOS 26 validation
+ - Semgrep
+ - OSV-Scanner
+ - CI health
+ types: [completed]
+ workflow_dispatch:
+ inputs:
+ run_id:
+ description: Scheduled run id to evaluate
+ required: true
+ type: string
+ dry_run:
+ description: Print the issue it would write instead of writing it
+ type: boolean
+ default: false
+
+permissions: {}
+
+# One group per watched workflow, queued (never cancelled), so two runs of the
+# same workflow cannot race on its issue.
+concurrency:
+ group: nightly-watch-${{ github.event.workflow_run.workflow_id || inputs.run_id }}
+ cancel-in-progress: false
+
+jobs:
+ watch:
+ if: github.event_name == 'workflow_dispatch' || (github.event.workflow_run.event == 'schedule' && github.event.workflow_run.head_repository.full_name == github.repository)
+ runs-on: ubicloud-standard-2-ubuntu-2404
+ timeout-minutes: 10
+ permissions:
+ issues: write
+ actions: read
+ checks: read
+ steps:
+ - uses: actions/checkout@11d5960a326750d5838078e36cf38b85af677262 # v4
+ with:
+ persist-credentials: false
+ sparse-checkout: |
+ scripts
+ .github/nightly-known-red.tsv
+ TODOS.md
+ - uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2
+ with:
+ bun-version: 1.4.2
+ - name: Upsert the nightly-red issue
+ env:
+ GH_TOKEN: ${{ github.token }}
+ RUN_ID: ${{ github.event.workflow_run.id || inputs.run_id }}
+ DRY_RUN: ${{ inputs.dry_run && '--dry-run' || '' }}
+ run: |
+ # shellcheck disable=SC2086 # DRY_RUN is empty or one flag
+ bun scripts/nightly-issue.ts --run-id "$RUN_ID" --repo "$GITHUB_REPOSITORY" $DRY_RUN
diff --git a/.github/workflows/scale-tier.yml b/.github/workflows/scale-tier.yml
index 220eafa245..0744a7cb02 100644
--- a/.github/workflows/scale-tier.yml
+++ b/.github/workflows/scale-tier.yml
@@ -183,6 +183,8 @@ jobs:
if [ ! -f "$REPORT" ]; then
WATCHDOG="${REPORT%.json}.watchdog.txt"
if [ -f "$WATCHDOG" ]; then
+ # The annotation is the signature nightly-watch matches against .github/nightly-known-red.tsv.
+ echo "::error title=Scale phase watchdog::$(head -1 "$WATCHDOG")"
{ echo "### Phase watchdog killed the harness"; echo '```'; cat "$WATCHDOG"; echo '```'; } >> "$GITHUB_STEP_SUMMARY"
else
echo "No report: the harness crashed before writing one; see the step log." >> "$GITHUB_STEP_SUMMARY"
diff --git a/TODOS.md b/TODOS.md
index 47d9c605e6..5cd559afdc 100644
--- a/TODOS.md
+++ b/TODOS.md
@@ -1,5 +1,14 @@
# TODOS
+## Test, eval and CI fix wave follow-ups (filed 2026-10-04, GBRA-47)
+
+Context: `.github/nightly-known-red.tsv` rows point here; nightly-watch keeps their incidents open until the row is deleted.
+
+- [ ] **P1 — PGLite bulk-embedding cliff at ~20k chunks.**
+ **What:** the scale tier's PGLite 20k cell stalled in the `vectors` phase (batched `UPDATE content_chunks SET embedding`) for 36+ minutes on nightly run 37196223708, while Postgres finished the same phase in 42 s. **Why:** a default PGLite brain that embeds ~20k chunks at once may hit the same wall. **Fix:** measure through the shipped `gbrain embed` path and the per-batch `vectors` progress lines (batch time, RSS, dimension) on the next 20k runs, then decide the engine fix (HNSW maintenance around bulk updates, PGLite memory settings). The phase watchdog names the stall meanwhile. **Effort:** M. **Priority:** P1.
+- [ ] **P1 — Set the ANTHROPIC_API_KEY and OPENAI_API_KEY repo secrets.**
+ **What:** the Hermes door's paid leg and the real-agent Claude/Codex doors skip visibly every night because both secrets are empty (approved, decision D-1). **Why:** only the repo owner can set secrets. **Fix:** `gh secret set ANTHROPIC_API_KEY` and `gh secret set OPENAI_API_KEY`, then delete the Heavy Tests row from `.github/nightly-known-red.tsv`. **Effort:** S. **Priority:** P1.
+
## Held files follow-ups (filed 2026-10-04, follow-up from v0.60.47.0)
Context: `docs/guides/repair.md#held-files`, `docs/guides/write-refusals.md#held-files-and-content-refusals`.
diff --git a/scripts/lib/gh-issue.ts b/scripts/lib/gh-issue.ts
new file mode 100644
index 0000000000..8fd092f3fc
--- /dev/null
+++ b/scripts/lib/gh-issue.ts
@@ -0,0 +1,140 @@
+/**
+ * Shared GitHub issue helpers for the CI watchers (scripts/nightly-issue.ts,
+ * scripts/ci-health-report.ts).
+ *
+ * - `inert()` makes a run-derived string (job, step and test names, error
+ * text) safe to show an agent: control characters stripped, length capped,
+ * backticks and pipes replaced, `@` mentions and links neutralised, so the
+ * text renders as data and never pings, links or breaks out of a fence.
+ * - `GitHubClient` is the one seam both scripts call; tests pass a recorded
+ * fake, production uses `restClient()` (fetch + GH_TOKEN/GITHUB_TOKEN in
+ * Actions, or the authenticated `gh api` CLI for local dry runs).
+ * - `findIssueByTitle` looks an issue up through the list API by label and
+ * exact title (open first, else the most recently updated closed one, so a
+ * flapping workflow reopens its own issue).
+ */
+
+export interface GitHubClient {
+ request<T = unknown>(method: 'GET' | 'POST' | 'PATCH', path: string, body?: unknown): Promise<T>;
+}
+
+export interface Issue {
+ number: number;
+ title: string;
+ state: 'open' | 'closed';
+ body?: string | null;
+ labels?: Array<{ name: string } | string>;
+ updated_at?: string;
+ pull_request?: unknown;
+}
+
+const ZWSP = '\u200b';
+
+export function inert(value: unknown, max = 200): string {
+ let s = String(value ?? '')
+ .replace(/[\u0000-\u0008\u000b-\u001f\u007f]/g, '')
+ .replace(/\r?\n/g, ' ')
+ .replace(/`/g, "'")
+ .replace(/\|/g, '/')
+ .replace(/@/g, `@${ZWSP}`)
+ .replace(/:\/\//g, `:${ZWSP}//`)
+ .replace(/\bwww\./gi, m => `${m.slice(0, 3)}${ZWSP}.`)
+ .replace(/[<>]/g, c => (c === '<' ? '‹' : '›'))
+ .trim();
+ if (s.length > max) s = `${s.slice(0, max - 1)}…`;
+ return s;
+}
+
+/** Multi-line run-derived text for a `~~~text` fence: same neutralisation, newlines kept, fences broken. */
+export function inertBlock(value: unknown, max = 1500): string {
+ const lines = String(value ?? '').split(/\r?\n/).map(line => inert(line, 400).replace(/~{3,}/g, '~ ~ ~'));
+ let s = lines.join('\n');
+ if (s.length > max) s = `${s.slice(0, max - 1)}…`;
+ return s;
+}
+
+/** Production client: REST with GH_TOKEN/GITHUB_TOKEN (Actions), else the authenticated `gh api` CLI (local dry runs). */
+export function restClient(repo: string, token = process.env.GH_TOKEN || process.env.GITHUB_TOKEN): GitHubClient {
+ const resolve = (path: string) => path.replace('{repo}', repo).replace(/^\//, '');
+ if (!token) return ghCliClient(resolve);
+ return {
+ async request<T>(method: 'GET' | 'POST' | 'PATCH', path: string, body?: unknown): Promise<T> {
+ const url = `https://api.github.com/${resolve(path)}`;
+ const res = await fetch(url, {
+ method,
+ headers: {
+ authorization: `Bearer ${token}`,
+ accept: 'application/vnd.github+json',
+ 'x-github-api-version': '2022-11-28',
+ ...(body === undefined ? {} : { 'content-type': 'application/json' }),
+ },
+ body: body === undefined ? undefined : JSON.stringify(body),
+ });
+ if (!res.ok) {
+ const text = await res.text().catch(() => '');
+ throw Object.assign(new Error(`GitHub API ${method} ${url} -> ${res.status}: ${text.slice(0, 300)}`), { status: res.status });
+ }
+ return (res.status === 204 ? undefined : await res.json()) as T;
+ },
+ };
+}
+
+function ghCliClient(resolve: (path: string) => string): GitHubClient {
+ return {
+ async request<T>(method: 'GET' | 'POST' | 'PATCH', path: string, body?: unknown): Promise<T> {
+ const args = ['gh', 'api', '-X', method, resolve(path), ...(body === undefined ? [] : ['--input', '-'])];
+ const r = Bun.spawnSync(args, { stdin: body === undefined ? 'ignore' : Buffer.from(JSON.stringify(body)), stdout: 'pipe', stderr: 'pipe' });
+ if (r.exitCode !== 0) {
+ const err = `${r.stderr.toString()} ${r.stdout.toString()}`.trim();
+ const status = Number(/HTTP (\d{3})/.exec(err)?.[1]) || undefined;
+ throw Object.assign(new Error(`gh api ${method} ${resolve(path)} failed: ${err.slice(0, 300)}. Fix: gh auth login, or export GH_TOKEN.`), { status });
+ }
+ const out = r.stdout.toString().trim();
+ return (out ? JSON.parse(out) : undefined) as T;
+ },
+ };
+}
+
+/** Create a label unless it exists (422 = already there). */
+export async function ensureLabel(client: GitHubClient, name: string, color: string, description: string): Promise<void> {
+ try {
+ await client.request('POST', 'repos/{repo}/labels', { name, color, description });
+ } catch (e) {
+ if ((e as { status?: number }).status !== 422) throw e;
+ }
+}
+
+export async function findIssueByTitle(client: GitHubClient, label: string, title: string, maxPages = 3): Promise<Issue | undefined> {
+ const matches: Issue[] = [];
+ for (let page = 1; page <= maxPages; page++) {
+ const batch = await client.request<Issue[]>('GET', `repos/{repo}/issues?labels=${encodeURIComponent(label)}&state=all&sort=updated&direction=desc&per_page=100&page=${page}`);
+ matches.push(...batch.filter(i => !i.pull_request && i.title === title));
+ if (batch.length < 100) break;
+ }
+ return matches.find(i => i.state === 'open') ?? matches[0];
+}
+
+export const labelNames = (issue: Issue): string[] => (issue.labels ?? []).map(l => (typeof l === 'string' ? l : l.name));
+
+export async function createIssue(client: GitHubClient, title: string, body: string, labels: string[]): Promise<Issue> {
+ return client.request<Issue>('POST', 'repos/{repo}/issues', { title, body, labels });
+}
+
+export async function updateIssue(client: GitHubClient, number: number, patch: { body?: string; state?: 'open' | 'closed'; labels?: string[] }): Promise<Issue> {
+ return client.request<Issue>('PATCH', `repos/{repo}/issues/${number}`, patch);
+}
+
+export async function commentIssue(client: GitHubClient, number: number, body: string): Promise<void> {
+ await client.request('POST', `repos/{repo}/issues/${number}/comments`, { body });
+}
+
+/** Extract the fenced JSON block a watcher wrote between its markers; undefined when absent or not valid JSON. */
+export function readJsonBlock<T>(body: string | null | undefined, marker: string): T | undefined {
+ const m = new RegExp(`<!-- ${marker} -->\\s*\`\`\`json\\n([\\s\\S]*?)\\n\`\`\``).exec(body ?? '');
+ if (!m) return undefined;
+ try { return JSON.parse(m[1]!) as T; } catch { return undefined; }
+}
+
+export function jsonBlock(marker: string, value: unknown): string {
+ return `<!-- ${marker} -->\n\`\`\`json\n${JSON.stringify(value, null, 2)}\n\`\`\``;
+}
diff --git a/scripts/nightly-issue.ts b/scripts/nightly-issue.ts
new file mode 100644
index 0000000000..b21286e83b
--- /dev/null
+++ b/scripts/nightly-issue.ts
@@ -0,0 +1,377 @@
+#!/usr/bin/env bun
+/**
+ * Nightly-red incident upkeep (GBRA-47 A1; X1, V-5, DX-15, ENG-14, ENG-15).
+ *
+ * bun scripts/nightly-issue.ts --run-id <id> [--repo owner/name] [--dry-run]
+ *
+ * Reads one completed scheduled workflow run (run, jobs, the failing jobs'
+ * check-run annotations, the workflow's last green scheduled run) and keeps
+ * one GitHub issue per workflow titled `Nightly red: <workflow>` (label
+ * `nightly-red`): opens it on a red run, updates it while red, reopens it on
+ * a flap (recording the run attempt), and closes it only when a later
+ * scheduled run is green AND every previously failing job executed and
+ * passed (a skipped job never closes an incident).
+ *
+ * `.github/nightly-known-red.tsv` (at most 3 rows) lists known-red and
+ * known-skipped cells. A run whose only problems match rows keeps the issue
+ * open with the `known-red` label and comments only when the failing set
+ * changes or a row's review-by date passes. A new failure inside a listed job
+ * (different step or error text) is a new incident.
+ *
+ * Everything that comes from the run (job, step and test names, error text)
+ * passes through inert(): no mentions, no links, no fence breaks. The issue
+ * body ends with a fenced JSON block for agents; the next step names who
+ * acts (owner_action vs code_fix).
+ *
+ * --dry-run reads only and prints the action and the issue body it would
+ * write. Exit 0 on any verdict; 1 when the run or the TSV cannot be read
+ * (the error says why and how to fix it); 2 usage error.
+ */
+import { readFileSync } from 'node:fs';
+import { basename, join, resolve } from 'node:path';
+import {
+ commentIssue, createIssue, ensureLabel, findIssueByTitle, inert, inertBlock, jsonBlock, labelNames, readJsonBlock, restClient, updateIssue,
+ type GitHubClient, type Issue,
+} from './lib/gh-issue.ts';
+
+const REPO_ROOT = resolve(import.meta.dir, '..');
+export const KNOWN_RED_FILE = '.github/nightly-known-red.tsv';
+export const KNOWN_RED_MAX = 3;
+export const LABEL = 'nightly-red';
+export const KNOWN_LABEL = 'known-red';
+export const JSON_MARKER = 'nightly-watch:json';
+export const DOCS = 'docs/RELEASING.md#nightly-red-issues';
+
+export interface RunInfo {
+ id: number;
+ name: string;
+ event: string;
+ conclusion: string | null;
+ run_attempt: number;
+ path: string;
+ workflow_id: number;
+ head_branch: string;
+ head_sha: string;
+ html_url: string;
+ head_repository?: { full_name: string };
+ repository?: { full_name: string };
+}
+export interface JobInfo {
+ id: number;
+ name: string;
+ conclusion: string | null;
+ html_url?: string;
+ steps?: Array<{ number: number; name: string; conclusion: string | null }>;
+}
+export interface Annotation { annotation_level: string; title?: string | null; message: string }
+export interface KnownRow { workflow: string; job: string; signature: string; kind: 'known-red' | 'known-skipped'; todo: string; review_by: string }
+export interface Failure { job: string; job_id: number; job_url?: string; conclusion: string; step: string; errors: string[] }
+export interface Assessment {
+ state: 'green' | 'red' | 'known-red' | 'known-skipped';
+ failures: Failure[];
+ unmatched: Failure[];
+ matched: Array<{ row: KnownRow; failure?: Failure }>;
+ stale: KnownRow[];
+ reviewPassed: KnownRow[];
+}
+export interface IncidentRecord {
+ workflow: string;
+ workflow_file: string;
+ state: Assessment['state'];
+ run_id: number;
+ run_attempt: number;
+ run_url: string;
+ head_sha: string;
+ failing: Array<{ job: string; job_id: number; step: string; errors: string[] }>;
+ known: Array<{ job: string; signature: string; kind: string; todo: string; review_by: string }>;
+ first_red: { run_id: number; sha: string };
+ last_green_sha: string | null;
+ dispatch_argv: string[];
+ next_step: 'code_fix' | 'owner_action' | 'known_red_wait' | 'review_by_passed' | 'none';
+ review_by_notified?: string[];
+}
+export interface Plan {
+ action: 'create' | 'update' | 'reopen' | 'close' | 'none';
+ title: string;
+ labels: string[];
+ body?: string;
+ comment?: string;
+ issue?: number;
+ record?: IncidentRecord;
+ reason: string;
+}
+
+const FAILING = new Set(['failure', 'timed_out', 'cancelled', 'startup_failure']);
+const GENERIC_ERROR = /^Process completed with exit code \d+\.?$/;
+const OWNER_SIGNAL = /gh secret set|secret is empty|secrets? (?:is |are )?(?:empty|missing|not configured)/i;
+
+export function parseKnownRed(text: string): { rows: KnownRow[]; problems: string[] } {
+ const rows: KnownRow[] = [];
+ const problems: string[] = [];
+ text.split('\n').forEach((line, i) => {
+ if (!line.trim() || line.startsWith('#')) return;
+ const cols = line.split('\t');
+ if (cols.length !== 6 || cols.some(c => !c.trim())) {
+ problems.push(`line ${i + 1}: expected 6 non-empty tab-separated columns (workflow, job, signature, kind, todo, review_by), got ${cols.length}`);
+ return;
+ }
+ const [workflow, job, signature, kind, todo, review_by] = cols.map(c => c.trim()) as [string, string, string, string, string, string];
+ if (kind !== 'known-red' && kind !== 'known-skipped') problems.push(`line ${i + 1}: kind must be known-red or known-skipped, got '${kind}'`);
+ if (!/^\d{4}-\d{2}-\d{2}$/.test(review_by) || Number.isNaN(Date.parse(`${review_by}T00:00:00Z`))) problems.push(`line ${i + 1}: review_by must be an ISO date (YYYY-MM-DD), got '${review_by}'`);
+ rows.push({ workflow, job, signature, kind: kind as KnownRow['kind'], todo, review_by });
+ });
+ if (rows.length > KNOWN_RED_MAX) problems.push(`${rows.length} rows; at most ${KNOWN_RED_MAX} cells may be known-red at once (fix one before adding another)`);
+ return { rows, problems };
+}
+
+/** Problems that make the TSV invalid; each says how to fix it. */
+export function validateKnownRed(text: string, todosText: string): string[] {
+ const { rows, problems } = parseKnownRed(text);
+ for (const row of rows) {
+ if (!todosText.includes(row.todo)) problems.push(`row '${row.job}': todo '${row.todo}' is not in TODOS.md; every known-red row needs the TODO that owns its fix`);
+ }
+ return problems.map(p => `${KNOWN_RED_FILE}: ${p}. Fix: edit the row, then run bun test test/scripts/nightly-issue.test.ts. Docs: ${DOCS}`);
+}
+
+export function assessRun(run: RunInfo, jobs: JobInfo[], annotations: Record<number, Annotation[]>, rows: KnownRow[], today: string): Assessment {
+ const failures: Failure[] = jobs.filter(j => FAILING.has(j.conclusion ?? '')).map(j => {
+ const step = j.steps?.find(s => FAILING.has(s.conclusion ?? ''));
+ const errors = (annotations[j.id] ?? []).filter(a => a.annotation_level === 'failure' && !GENERIC_ERROR.test(a.message.trim()))
+ .map(a => [a.title, a.message].filter(Boolean).join(': '));
+ return { job: j.name, job_id: j.id, job_url: j.html_url, conclusion: j.conclusion!, step: step?.name ?? '(job-level)', errors };
+ });
+ const mine = rows.filter(r => r.workflow === run.name);
+ const matched: Assessment['matched'] = [];
+ const stale: KnownRow[] = [];
+ const unmatched = failures.filter(f => {
+ const row = mine.find(r => r.kind === 'known-red' && r.job === f.job && (f.step.includes(r.signature) || f.errors.some(e => e.includes(r.signature))));
+ if (row) matched.push({ row, failure: f });
+ return !row;
+ });
+ for (const row of mine) {
+ const job = jobs.find(j => j.name === row.job);
+ if (row.kind === 'known-skipped') {
+ const step = job?.steps?.find(s => s.name === row.signature);
+ if (step?.conclusion === 'skipped') matched.push({ row });
+ else if (job && step) stale.push(row);
+ } else if (!matched.some(m => m.row === row) && job?.conclusion === 'success') {
+ stale.push(row);
+ }
+ }
+ const reviewPassed = matched.map(m => m.row).filter(r => r.review_by < today);
+ const state: Assessment['state'] = unmatched.length ? 'red'
+ : matched.some(m => m.row.kind === 'known-red') ? 'known-red'
+ : matched.length ? 'known-skipped' : 'green';
+ return { state, failures, unmatched, matched, stale, reviewPassed };
+}
+
+export function dispatchArgv(run: RunInfo, failures: Failure[]): string[] {
+ const argv = ['gh', 'workflow', 'run', basename(run.path), '--ref', run.head_branch];
+ if (basename(run.path) === 'scale-tier.yml') {
+ const pages = failures.map(f => /\b(\d{4,})$/.exec(f.job)?.[1]).find(Boolean);
+ if (pages) argv.push('-f', `pages=${pages}`);
+ }
+ return argv;
+}
+
+const failingKey = (rec: Pick<IncidentRecord, 'failing'> | undefined) => (rec?.failing ?? []).map(f => `${f.job} > ${f.step} > ${f.errors.join(' / ')}`).sort().join('\n');
+
+function nextStepText(rec: IncidentRecord, assessment: Assessment): string {
+ const dispatch = `\`${rec.dispatch_argv.join(' ')}\``;
+ switch (rec.next_step) {
+ case 'owner_action':
+ return `**Owner action (not a code fix).** A repository setting only the owner can change is missing (see the errors above, e.g. an empty secret). `
+ + `Ask the repo owner to apply the named fix (\`gh secret set <NAME>\`), then re-check with ${dispatch}. Do not open a code PR for this.`;
+ case 'known_red_wait':
+ return `**Known red, tracked.** The failing cells match \`${KNOWN_RED_FILE}\` rows owned by TODOS.md entries (listed above). `
+ + `No action until the review-by date; a new failure in the same job opens a new incident.`;
+ case 'review_by_passed':
+ return `**Review-by date passed** for: ${assessment.reviewPassed.map(r => `\`${inert(r.job)}\` (${r.review_by}, TODO: ${inert(r.todo)})`).join('; ')}. `
+ + `Fix the cell and delete its row, or re-justify the row with a new date in a reviewed PR. Docs: ${DOCS}`;
+ case 'code_fix': {
+ const owner = assessment.unmatched.filter(f => OWNER_SIGNAL.test(f.errors.join(' ')));
+ return `**Code fix.** Read the failing step log (\`gh run view ${rec.run_id} --log-failed\`), reproduce it locally with the owning workflow's command, `
+ + `then within 24 hours open a repair PR or add a \`${KNOWN_RED_FILE}\` row (at most ${KNOWN_RED_MAX}) with a P1 TODO. Re-check with ${dispatch}. Docs: ${DOCS}`
+ + (owner.length ? `\n\nAlso an **owner action** (not a code fix) for ${owner.map(f => `\`${inert(f.job)}\``).join(', ')}: ask the repo owner to apply the fix its error names.` : '');
+ }
+ default:
+ return 'None.';
+ }
+}
+
+export function renderBody(rec: IncidentRecord, assessment: Assessment): string {
+ const lines = [
+ `Workflow **${inert(rec.workflow)}** (\`${rec.workflow_file}\`) — state: **${rec.state}**.`,
+ '',
+ `- Latest scheduled run: ${rec.run_url} (attempt ${rec.run_attempt}, \`${rec.head_sha.slice(0, 12)}\`)`,
+ `- First red run of this incident: https://github.com/{repo}/actions/runs/${rec.first_red.run_id} (\`${rec.first_red.sha.slice(0, 12)}\`)`,
+ `- Last green scheduled run SHA: ${rec.last_green_sha ? `\`${rec.last_green_sha.slice(0, 12)}\`; commits since: https://github.com/{repo}/compare/${rec.last_green_sha}...${rec.head_sha}` : 'none found'}`,
+ `- Re-check: \`${rec.dispatch_argv.join(' ')}\``,
+ `- Owner: the agent on release duty (Garry escalates); respond within 24 hours with a repair PR or a known-red row. Docs: ${DOCS}`,
+ '',
+ ];
+ if (assessment.failures.length) {
+ lines.push('| job | step | result | tracked |', '|---|---|---|---|');
+ for (const f of assessment.failures) {
+ const row = assessment.matched.find(m => m.failure === f)?.row;
+ lines.push(`| \`${inert(f.job)}\` | \`${inert(f.step)}\` | ${inert(f.conclusion, 20)} | ${row ? `known-red (TODO: ${inert(row.todo)}, review by ${row.review_by})` : 'no'} |`);
+ }
+ lines.push('');
+ for (const f of assessment.failures.filter(x => x.errors.length)) {
+ lines.push(`Errors in \`${inert(f.job)}\`:`, '~~~text', inertBlock(f.errors.slice(0, 3).join('\n')), '~~~', '');
+ }
+ }
+ for (const m of assessment.matched.filter(x => x.row.kind === 'known-skipped')) {
+ lines.push(`- Known-skipped: \`${inert(m.row.job)}\` step \`${inert(m.row.signature)}\` did not run (TODO: ${inert(m.row.todo)}, review by ${m.row.review_by}). This run is not green coverage.`);
+ }
+ for (const r of assessment.stale) {
+ lines.push(`- Stale row: \`${inert(r.job)}\` / \`${inert(r.signature)}\` no longer matches (the cell ran). Delete it from \`${KNOWN_RED_FILE}\`.`);
+ }
+ lines.push('', '### Next step for the agent', '', nextStepText(rec, assessment), '', jsonBlock(JSON_MARKER, rec), '');
+ return lines.join('\n');
+}
+
+export function planIncident(run: RunInfo, assessment: Assessment, existing: Issue | undefined, lastGreenSha: string | null, repo: string, succeededJobs: string[]): Plan {
+ const title = `Nightly red: ${inert(run.name, 100)}`;
+ const previous = existing ? readJsonBlock<IncidentRecord>(existing.body, JSON_MARKER) : undefined;
+ const keepLabels = existing ? labelNames(existing).filter(l => l !== KNOWN_LABEL && l !== LABEL) : [];
+ const runUrl = `https://github.com/${repo}/actions/runs/${run.id}`;
+
+ if (assessment.state === 'green') {
+ if (!existing || existing.state === 'closed') return { action: 'none', title, labels: [], reason: 'green and no open incident' };
+ const prevJobs = [...new Set((previous?.failing ?? []).map(f => f.job))];
+ const notRun = prevJobs.filter(job => !succeededJobs.some(s => inert(s) === job));
+ if (notRun.length) {
+ return {
+ action: 'none', title, labels: [], issue: existing.number,
+ comment: `Run ${runUrl} is green, but previously failing job(s) did not execute and pass: ${notRun.map(j => `\`${inert(j)}\``).join(', ')}. `
+ + 'Keeping this incident open; a skipped job is not a fix.',
+ reason: 'green but previously failing jobs did not run',
+ };
+ }
+ return {
+ action: 'close', title, labels: [], issue: existing.number,
+ comment: `Green: scheduled run ${runUrl} (attempt ${run.run_attempt}) passed and every previously failing job executed. Closing.`,
+ reason: 'green and previously failing jobs passed',
+ };
+ }
+
+ const reopening = existing?.state === 'closed';
+ const continuing = existing?.state === 'open' && previous;
+ const notified = continuing ? previous!.review_by_notified ?? [] : [];
+ const newlyPassed = assessment.reviewPassed.filter(r => !notified.includes(`${r.job}|${r.review_by}`));
+ const record: IncidentRecord = {
+ workflow: inert(run.name, 100),
+ workflow_file: run.path,
+ state: assessment.state,
+ run_id: run.id,
+ run_attempt: run.run_attempt,
+ run_url: runUrl,
+ head_sha: run.head_sha,
+ failing: assessment.failures.map(f => ({ job: inert(f.job), job_id: f.job_id, step: inert(f.step), errors: f.errors.slice(0, 3).map(e => inert(e, 400)) })),
+ known: assessment.matched.map(m => ({ job: inert(m.row.job), signature: inert(m.row.signature), kind: m.row.kind, todo: inert(m.row.todo), review_by: m.row.review_by })),
+ first_red: continuing ? previous!.first_red : { run_id: run.id, sha: run.head_sha },
+ last_green_sha: lastGreenSha,
+ dispatch_argv: dispatchArgv(run, assessment.failures),
+ next_step: assessment.state === 'red'
+ ? (assessment.unmatched.every(f => OWNER_SIGNAL.test(f.errors.join(' '))) ? 'owner_action' : 'code_fix')
+ : assessment.reviewPassed.length ? 'review_by_passed'
+ : assessment.state === 'known-skipped' ? 'owner_action' : 'known_red_wait',
+ review_by_notified: [...notified, ...newlyPassed.map(r => `${r.job}|${r.review_by}`)],
+ };
+ const body = renderBody(record, assessment).replaceAll('{repo}', repo);
+ const labels = [LABEL, ...(assessment.state === 'red' ? [] : [KNOWN_LABEL]), ...keepLabels];
+
+ if (!existing) return { action: 'create', title, labels, body, record, reason: `new ${assessment.state} incident` };
+ if (reopening) {
+ return {
+ action: 'reopen', title, labels, body, record, issue: existing.number,
+ comment: `Red again (flap): scheduled run ${runUrl}, attempt ${run.run_attempt}, state ${assessment.state}. Reopening; the body has the failing jobs and the next step.`,
+ reason: 'closed incident is red again',
+ };
+ }
+ const changed = failingKey(previous) !== failingKey(record) || previous?.state !== record.state;
+ const comment = changed
+ ? `Failing set changed in scheduled run ${runUrl} (attempt ${run.run_attempt}); state ${record.state}. See the updated body.`
+ : newlyPassed.length
+ ? `Review-by date passed for ${newlyPassed.map(r => `\`${inert(r.job)}\``).join(', ')}: fix the cell or re-justify its row with a new date.`
+ : undefined;
+ return { action: 'update', title, labels, body, record, issue: existing.number, comment, reason: changed ? 'failing set changed' : 'same failing set' };
+}
+
+async function pagedJobs(client: GitHubClient, run: RunInfo): Promise<JobInfo[]> {
+ const jobs: JobInfo[] = [];
+ for (let page = 1; page <= 5; page++) {
+ const r = await client.request<{ jobs: JobInfo[]; total_count: number }>('GET', `repos/{repo}/actions/runs/${run.id}/attempts/${run.run_attempt}/jobs?per_page=100&page=${page}`);
+ jobs.push(...r.jobs);
+ if (jobs.length >= r.total_count || r.jobs.length < 100) break;
+ }
+ return jobs;
+}
+
+export interface WatchResult { plan: Plan; assessment: Assessment; run: RunInfo }
+
+export async function watchRun(opts: { client: GitHubClient; repo: string; runId: number; rows: KnownRow[]; today: string; dryRun: boolean }): Promise<WatchResult> {
+ const { client, repo } = opts;
+ const run = await client.request<RunInfo>('GET', `repos/{repo}/actions/runs/${opts.runId}`);
+ if (run.head_repository?.full_name && run.repository?.full_name && run.head_repository.full_name !== run.repository.full_name) {
+ throw new Error(`run ${run.id} comes from fork ${run.head_repository.full_name}; nightly-watch never reads fork runs.`);
+ }
+ if (run.event !== 'schedule' && !opts.dryRun) {
+ throw new Error(`run ${run.id} is a ${run.event} run; nightly-watch only tracks scheduled runs. Fix: pass a scheduled run id, or add --dry-run to preview.`);
+ }
+ const jobs = await pagedJobs(client, run);
+ const annotations: Record<number, Annotation[]> = {};
+ for (const job of jobs.filter(j => FAILING.has(j.conclusion ?? ''))) {
+ annotations[job.id] = await client.request<Annotation[]>('GET', `repos/{repo}/check-runs/${job.id}/annotations?per_page=50`).catch(() => []);
+ }
+ const assessment = assessRun(run, jobs, annotations, opts.rows, opts.today);
+ const greens = await client.request<{ workflow_runs: Array<{ head_sha: string }> }>('GET',
+ `repos/{repo}/actions/workflows/${run.workflow_id}/runs?event=schedule&status=success&per_page=1`).catch(() => ({ workflow_runs: [] }));
+ const existing = await findIssueByTitle(client, LABEL, `Nightly red: ${inert(run.name, 100)}`);
+ const succeeded = jobs.filter(j => j.conclusion === 'success').map(j => j.name);
+ const plan = planIncident(run, assessment, existing, greens.workflow_runs[0]?.head_sha ?? null, repo, succeeded);
+ if (opts.dryRun) return { plan, assessment, run };
+
+ if (plan.action === 'create' || plan.action === 'reopen' || plan.action === 'update') {
+ await ensureLabel(client, LABEL, 'b60205', 'A scheduled workflow is red (nightly-watch)');
+ if (plan.labels.includes(KNOWN_LABEL)) await ensureLabel(client, KNOWN_LABEL, 'fbca04', 'Red or skipped on a tracked .github/nightly-known-red.tsv row');
+ }
+ if (plan.action === 'create') {
+ plan.issue = (await createIssue(client, plan.title, plan.body!, plan.labels)).number;
+ } else if (plan.action === 'reopen' || plan.action === 'update') {
+ await updateIssue(client, plan.issue!, { body: plan.body, labels: plan.labels, ...(plan.action === 'reopen' ? { state: 'open' as const } : {}) });
+ }
+ if (plan.comment && plan.issue) await commentIssue(client, plan.issue, plan.comment);
+ if (plan.action === 'close') await updateIssue(client, plan.issue!, { state: 'closed' });
+ return { plan, assessment, run };
+}
+
+if (import.meta.main) {
+ const flag = (name: string) => { const i = process.argv.indexOf(name); return i >= 0 ? process.argv[i + 1] : undefined; };
+ const runId = Number(flag('--run-id'));
+ const repo = flag('--repo') ?? process.env.GITHUB_REPOSITORY ?? 'garrytan/gbrain';
+ const dryRun = process.argv.includes('--dry-run');
+ if (!Number.isInteger(runId) || runId <= 0) {
+ console.log('Usage: bun scripts/nightly-issue.ts --run-id <id> [--repo owner/name] [--dry-run]');
+ process.exit(2);
+ }
+ try {
+ const tsv = readFileSync(join(REPO_ROOT, KNOWN_RED_FILE), 'utf8');
+ const problems = validateKnownRed(tsv, readFileSync(join(REPO_ROOT, 'TODOS.md'), 'utf8'));
+ for (const p of problems) console.log(`::warning::${p}`);
+ const { rows } = parseKnownRed(tsv);
+ const today = new Date().toISOString().slice(0, 10);
+ const { plan, assessment, run } = await watchRun({ client: restClient(repo), repo, runId, rows, today, dryRun });
+ console.log(`[nightly-watch] ${run.name} run ${run.id} attempt ${run.run_attempt}: ${assessment.state}; action ${plan.action}${plan.issue ? ` #${plan.issue}` : ''} (${plan.reason})${dryRun ? ' [dry run]' : ''}`);
+ if (dryRun) {
+ console.log(`--- title: ${plan.title}\n--- labels: ${plan.labels.join(', ') || '(none)'}`);
+ if (plan.comment) console.log(`--- comment:\n${plan.comment}`);
+ if (plan.body) console.log(`--- body:\n${plan.body}`);
+ }
+ } catch (e) {
+ console.log(`[nightly-watch] FAIL: ${e instanceof Error ? e.message : String(e)}`);
+ console.log(`[nightly-watch] Fix: check the run id and the token's actions:read / issues:write scopes, then rerun: bun scripts/nightly-issue.ts --run-id ${runId} --dry-run. Docs: ${DOCS}`);
+ process.exit(1);
+ }
+}
diff --git a/test/fixtures/nightly-watch/annotations-111415376248.json b/test/fixtures/nightly-watch/annotations-111415376248.json
new file mode 100644
index 0000000000..d3949ab208
--- /dev/null
+++ b/test/fixtures/nightly-watch/annotations-111415376248.json
@@ -0,0 +1,12 @@
+[
+ {
+ "annotation_level": "warning",
+ "title": "",
+ "message": "Node.js 20 is deprecated. The following actions target Node.js 20 but are being forced to run on Node.js 24: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684, actions/checkout@11d5960a326750d5838078e36cf38b85af677262, actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02. For more information see: https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-ac"
+ },
+ {
+ "annotation_level": "failure",
+ "title": "",
+ "message": "Process completed with exit code 1."
+ }
+]
diff --git a/test/fixtures/nightly-watch/annotations-111415376292.json b/test/fixtures/nightly-watch/annotations-111415376292.json
new file mode 100644
index 0000000000..a57573348d
--- /dev/null
+++ b/test/fixtures/nightly-watch/annotations-111415376292.json
@@ -0,0 +1,17 @@
+[
+ {
+ "annotation_level": "warning",
+ "title": "",
+ "message": "Node.js 20 is deprecated. The following actions target Node.js 20 but are being forced to run on Node.js 24: actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684, actions/checkout@11d5960a326750d5838078e36cf38b85af677262, actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02. For more information see: https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-ac"
+ },
+ {
+ "annotation_level": "failure",
+ "title": "",
+ "message": "Process completed with exit code 1."
+ },
+ {
+ "annotation_level": "failure",
+ "title": "",
+ "message": "ANTHROPIC_API_KEY secret is empty — this scheduled/dispatched run cannot cover the hermes door without it (owner-only fix: gh secret set ANTHROPIC_API_KEY)"
+ }
+]
diff --git a/test/fixtures/nightly-watch/annotations-111415376359.json b/test/fixtures/nightly-watch/annotations-111415376359.json
new file mode 100644
index 0000000000..a9cb7331e9
--- /dev/null
+++ b/test/fixtures/nightly-watch/annotations-111415376359.json
@@ -0,0 +1,17 @@
+[
+ {
+ "annotation_level": "warning",
+ "title": "",
+ "message": "Node.js 20 is deprecated. The following actions target Node.js 20 but are being forced to run on Node.js 24: actions/checkout@11d5960a326750d5838078e36cf38b85af677262. For more information see: https://github.blog/changelog/2025-09-19-deprecation-of-node-20-on-github-actions-runners/"
+ },
+ {
+ "annotation_level": "failure",
+ "title": "",
+ "message": "Process completed with exit code 1."
+ },
+ {
+ "annotation_level": "failure",
+ "title": "error: expect(received).toEqual(expected)",
+ "message": " [\n \"add_timeline_entry\",\n \"cancel_job\",\n \"cancel_write_request\",\n \"capture\",\n \"context_pack\",\n- \"delete_skill\",\n \"delta\",\n \"edit_page\",\n \"entity\",\n \"find_anomalies\",\n \"forget\",\n \"get_agent_job\",\n \"get_backlinks\",\n \"get_ingest_log\",\n \"get_page\",\n \"get_recent_salience\",\n \"get_skill\",\n \"get_skill_asset\",\n \"get_write_request\",\n- \"join_brain\","
+ }
+]
diff --git a/test/fixtures/nightly-watch/jobs-heavy.json b/test/fixtures/nightly-watch/jobs-heavy.json
new file mode 100644
index 0000000000..ba3df9c6ec
--- /dev/null
+++ b/test/fixtures/nightly-watch/jobs-heavy.json
@@ -0,0 +1,517 @@
+{
+ "total_count": 7,
+ "jobs": [
+ {
+ "id": 111415376143,
+ "name": "opencode door e2e (keyless)",
+ "status": "completed",
+ "conclusion": "success",
+ "html_url": "https://github.com/garrytan/gbrain/actions/runs/37195155240/job/111415376143",
+ "steps": [
+ {
+ "number": 1,
+ "name": "Set up job",
+ "conclusion": "success"
+ },
+ {
+ "number": 2,
+ "name": "Set up runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 3,
+ "name": "Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 4,
+ "name": "Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 5,
+ "name": "Run bun install --frozen-lockfile",
+ "conclusion": "success"
+ },
+ {
+ "number": 6,
+ "name": "Prepare evidence dir",
+ "conclusion": "success"
+ },
+ {
+ "number": 7,
+ "name": "Build gbrain (compile once per lane)",
+ "conclusion": "success"
+ },
+ {
+ "number": 8,
+ "name": "Install opencode (pinned npm package, pack-verify-install)",
+ "conclusion": "success"
+ },
+ {
+ "number": 9,
+ "name": "Run opencode door tests (keyless tier — SMOKE included)",
+ "conclusion": "success"
+ },
+ {
+ "number": 10,
+ "name": "Report credentialed coverage not run in keyless lane",
+ "conclusion": "success"
+ },
+ {
+ "number": 11,
+ "name": "Preconditions (credentialed lane requires secret)",
+ "conclusion": "skipped"
+ },
+ {
+ "number": 12,
+ "name": "Run opencode door tests (credentialed tier only)",
+ "conclusion": "skipped"
+ },
+ {
+ "number": 13,
+ "name": "Version re-check (mid-job drift tripwire)",
+ "conclusion": "success"
+ },
+ {
+ "number": 14,
+ "name": "Scrub credentials from evidence (defensive)",
+ "conclusion": "skipped"
+ },
+ {
+ "number": 15,
+ "name": "Upload opencode door evidence",
+ "conclusion": "skipped"
+ },
+ {
+ "number": 16,
+ "name": "Remove opencode credentials (unconditional)",
+ "conclusion": "success"
+ },
+ {
+ "number": 30,
+ "name": "Post Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 31,
+ "name": "Post Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 32,
+ "name": "Complete runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 33,
+ "name": "Complete job",
+ "conclusion": "success"
+ }
+ ]
+ },
+ {
+ "id": 111415376248,
+ "name": "Heavy tests",
+ "status": "completed",
+ "conclusion": "failure",
+ "html_url": "https://github.com/garrytan/gbrain/actions/runs/37195155240/job/111415376248",
+ "steps": [
+ {
+ "number": 1,
+ "name": "Set up job",
+ "conclusion": "success"
+ },
+ {
+ "number": 2,
+ "name": "Set up runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 3,
+ "name": "Initialize containers",
+ "conclusion": "success"
+ },
+ {
+ "number": 4,
+ "name": "Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 5,
+ "name": "Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 6,
+ "name": "Run actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684",
+ "conclusion": "success"
+ },
+ {
+ "number": 7,
+ "name": "Run bun install --frozen-lockfile",
+ "conclusion": "success"
+ },
+ {
+ "number": 8,
+ "name": "Run heavy tests",
+ "conclusion": "success"
+ },
+ {
+ "number": 9,
+ "name": "Bootstrap offline Docker e2e (placeholder)",
+ "conclusion": "failure"
+ },
+ {
+ "number": 10,
+ "name": "Stage heavy-test logs into workspace",
+ "conclusion": "success"
+ },
+ {
+ "number": 11,
+ "name": "Upload heavy-test artifacts",
+ "conclusion": "success"
+ },
+ {
+ "number": 19,
+ "name": "Post Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "skipped"
+ },
+ {
+ "number": 20,
+ "name": "Post Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 21,
+ "name": "Stop containers",
+ "conclusion": "success"
+ },
+ {
+ "number": 22,
+ "name": "Complete runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 23,
+ "name": "Complete job",
+ "conclusion": "success"
+ }
+ ]
+ },
+ {
+ "id": 111415376262,
+ "name": "Real-agent door e2e (skips without authed binaries)",
+ "status": "completed",
+ "conclusion": "success",
+ "html_url": "https://github.com/garrytan/gbrain/actions/runs/37195155240/job/111415376262",
+ "steps": [
+ {
+ "number": 1,
+ "name": "Set up job",
+ "conclusion": "success"
+ },
+ {
+ "number": 2,
+ "name": "Set up runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 3,
+ "name": "Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 4,
+ "name": "Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 5,
+ "name": "Run actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684",
+ "conclusion": "success"
+ },
+ {
+ "number": 6,
+ "name": "Run bun install --frozen-lockfile",
+ "conclusion": "success"
+ },
+ {
+ "number": 7,
+ "name": "Run real-agent door tests",
+ "conclusion": "success"
+ },
+ {
+ "number": 12,
+ "name": "Post Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 13,
+ "name": "Post Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 14,
+ "name": "Complete runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 15,
+ "name": "Complete job",
+ "conclusion": "success"
+ }
+ ]
+ },
+ {
+ "id": 111415376292,
+ "name": "Hermes door e2e (credentialed, real binary, loud-fail)",
+ "status": "completed",
+ "conclusion": "failure",
+ "html_url": "https://github.com/garrytan/gbrain/actions/runs/37195155240/job/111415376292",
+ "steps": [
+ {
+ "number": 1,
+ "name": "Set up job",
+ "conclusion": "success"
+ },
+ {
+ "number": 2,
+ "name": "Set up runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 3,
+ "name": "Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 4,
+ "name": "Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 5,
+ "name": "Run actions/cache/restore@5a3ec84eff668545956fd18022155c47e93e2684",
+ "conclusion": "success"
+ },
+ {
+ "number": 6,
+ "name": "Run bun install --frozen-lockfile",
+ "conclusion": "success"
+ },
+ {
+ "number": 7,
+ "name": "Prepare evidence dir",
+ "conclusion": "success"
+ },
+ {
+ "number": 8,
+ "name": "Install hermes (pinned installer digest)",
+ "conclusion": "success"
+ },
+ {
+ "number": 9,
+ "name": "Preconditions (binary, secret, version pin)",
+ "conclusion": "failure"
+ },
+ {
+ "number": 10,
+ "name": "Configure hermes (auth + model pin)",
+ "conclusion": "skipped"
+ },
+ {
+ "number": 11,
+ "name": "Run hermes door tests",
+ "conclusion": "skipped"
+ },
+ {
+ "number": 12,
+ "name": "Scrub credentials from evidence (defensive)",
+ "conclusion": "success"
+ },
+ {
+ "number": 13,
+ "name": "Upload hermes door evidence",
+ "conclusion": "success"
+ },
+ {
+ "number": 14,
+ "name": "Remove hermes credentials (unconditional)",
+ "conclusion": "success"
+ },
+ {
+ "number": 26,
+ "name": "Post Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "skipped"
+ },
+ {
+ "number": 27,
+ "name": "Post Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 28,
+ "name": "Complete runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 29,
+ "name": "Complete job",
+ "conclusion": "success"
+ }
+ ]
+ },
+ {
+ "id": 111415376295,
+ "name": "opencode door canary (latest, keyless, non-gating)",
+ "status": "completed",
+ "conclusion": "success",
+ "html_url": "https://github.com/garrytan/gbrain/actions/runs/37195155240/job/111415376295",
+ "steps": [
+ {
+ "number": 1,
+ "name": "Set up job",
+ "conclusion": "success"
+ },
+ {
+ "number": 2,
+ "name": "Set up runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 3,
+ "name": "Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 4,
+ "name": "Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 5,
+ "name": "Run bun install --frozen-lockfile",
+ "conclusion": "success"
+ },
+ {
+ "number": 6,
+ "name": "Build gbrain",
+ "conclusion": "success"
+ },
+ {
+ "number": 7,
+ "name": "Install opencode@latest (unpinned — the whole point)",
+ "conclusion": "success"
+ },
+ {
+ "number": 8,
+ "name": "Run opencode door tests (keyless tier against latest)",
+ "conclusion": "success"
+ },
+ {
+ "number": 14,
+ "name": "Post Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 15,
+ "name": "Post Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 16,
+ "name": "Complete runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 17,
+ "name": "Complete job",
+ "conclusion": "success"
+ }
+ ]
+ },
+ {
+ "id": 111415376359,
+ "name": "Plugin doors (codex + claude, install tier)",
+ "status": "completed",
+ "conclusion": "failure",
+ "html_url": "https://github.com/garrytan/gbrain/actions/runs/37195155240/job/111415376359",
+ "steps": [
+ {
+ "number": 1,
+ "name": "Set up job",
+ "conclusion": "success"
+ },
+ {
+ "number": 2,
+ "name": "Set up runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 3,
+ "name": "Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 4,
+ "name": "Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 5,
+ "name": "Run bun install --frozen-lockfile",
+ "conclusion": "success"
+ },
+ {
+ "number": 6,
+ "name": "Build gbrain (compile once for the doors)",
+ "conclusion": "success"
+ },
+ {
+ "number": 7,
+ "name": "Install codex + claude (pinned npm versions, refuse on drift)",
+ "conclusion": "success"
+ },
+ {
+ "number": 8,
+ "name": "Codex plugin door (install tier — expected shape enforced)",
+ "conclusion": "failure"
+ },
+ {
+ "number": 9,
+ "name": "Claude plugin door (install tier — expected shape enforced)",
+ "conclusion": "skipped"
+ },
+ {
+ "number": 16,
+ "name": "Post Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "skipped"
+ },
+ {
+ "number": 17,
+ "name": "Post Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 18,
+ "name": "Complete runner",
+ "conclusion": "success"
+ },
+ {
+ "number": 19,
+ "name": "Complete job",
+ "conclusion": "success"
+ }
+ ]
+ },
+ {
+ "id": 111415376784,
+ "name": "Grok door e2e (real binary, keyless-first)",
+ "status": "completed",
+ "conclusion": "skipped",
+ "html_url": "https://github.com/garrytan/gbrain/actions/runs/37195155240/job/111415376784",
+ "steps": []
+ }
+ ]
+}
diff --git a/test/fixtures/nightly-watch/jobs-macos-green.json b/test/fixtures/nightly-watch/jobs-macos-green.json
new file mode 100644
index 0000000000..ef47066823
--- /dev/null
+++ b/test/fixtures/nightly-watch/jobs-macos-green.json
@@ -0,0 +1,79 @@
+{
+ "total_count": 1,
+ "jobs": [
+ {
+ "id": 111423193214,
+ "name": "macOS 26 validation",
+ "status": "completed",
+ "conclusion": "success",
+ "html_url": "https://github.com/garrytan/gbrain/actions/runs/37197810506/job/111423193214",
+ "steps": [
+ {
+ "number": 1,
+ "name": "Set up job",
+ "conclusion": "success"
+ },
+ {
+ "number": 2,
+ "name": "Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 3,
+ "name": "Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 4,
+ "name": "Run bun install --frozen-lockfile --ignore-scripts",
+ "conclusion": "success"
+ },
+ {
+ "number": 5,
+ "name": "Runner identity",
+ "conclusion": "success"
+ },
+ {
+ "number": 6,
+ "name": "#5604 device-identity re-stamp on real APFS",
+ "conclusion": "success"
+ },
+ {
+ "number": 7,
+ "name": "#5449 PGLite checkpoint harness on a >= 2 GiB store",
+ "conclusion": "success"
+ },
+ {
+ "number": 8,
+ "name": "#5449 harness result",
+ "conclusion": "success"
+ },
+ {
+ "number": 9,
+ "name": "#5286 published signed release binary",
+ "conclusion": "success"
+ },
+ {
+ "number": 10,
+ "name": "#5810 shell scripts and bun run verify under /bin/bash 3.2",
+ "conclusion": "success"
+ },
+ {
+ "number": 19,
+ "name": "Post Run oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6",
+ "conclusion": "success"
+ },
+ {
+ "number": 20,
+ "name": "Post Run actions/checkout@11d5960a326750d5838078e36cf38b85af677262",
+ "conclusion": "success"
+ },
+ {
+ "number": 21,
+ "name": "Complete job",
+ "conclusion": "success"
+ }
+ ]
+ }
+ ]
+}
diff --git a/test/fixtures/nightly-watch/run-heavy.json b/test/fixtures/nightly-watch/run-heavy.json
new file mode 100644
index 0000000000..16a108a240
--- /dev/null
+++ b/test/fixtures/nightly-watch/run-heavy.json
@@ -0,0 +1,19 @@
+{
+ "id": 37195155240,
+ "name": "Heavy Tests",
+ "event": "schedule",
+ "status": "completed",
+ "conclusion": "failure",
+ "run_attempt": 1,
+ "path": ".github/workflows/heavy-tests.yml",
+ "workflow_id": 280280559,
+ "head_branch": "master",
+ "head_sha": "8b5ed04c6c061031acd953fccd5590357e8bfe8e",
+ "html_url": "https://github.com/garrytan/gbrain/actions/runs/37195155240",
+ "head_repository": {
+ "full_name": "garrytan/gbrain"
+ },
+ "repository": {
+ "full_name": "garrytan/gbrain"
+ }
+}
diff --git a/test/fixtures/nightly-watch/run-macos-green.json b/test/fixtures/nightly-watch/run-macos-green.json
new file mode 100644
index 0000000000..4534c2f79f
--- /dev/null
+++ b/test/fixtures/nightly-watch/run-macos-green.json
@@ -0,0 +1,19 @@
+{
+ "id": 37197810506,
+ "name": "macOS 26 validation",
+ "event": "schedule",
+ "status": "completed",
+ "conclusion": "success",
+ "run_attempt": 1,
+ "path": ".github/workflows/macos-validation.yml",
+ "workflow_id": 370626310,
+ "head_branch": "master",
+ "head_sha": "8b5ed04c6c061031acd953fccd5590357e8bfe8e",
+ "html_url": "https://github.com/garrytan/gbrain/actions/runs/37197810506",
+ "head_repository": {
+ "full_name": "garrytan/gbrain"
+ },
+ "repository": {
+ "full_name": "garrytan/gbrain"
+ }
+}
diff --git a/test/scripts/nightly-issue.test.ts b/test/scripts/nightly-issue.test.ts
new file mode 100644
index 0000000000..5b3098cd6d
--- /dev/null
+++ b/test/scripts/nightly-issue.test.ts
@@ -0,0 +1,233 @@
+/**
+ * scripts/nightly-issue.ts + scripts/lib/gh-issue.ts over recorded GitHub API
+ * JSON (Heavy Tests scheduled run 37195155240, red; macOS 26 validation
+ * scheduled run 37197810506, green): open, update, flap-reopen, skip-green
+ * stays open, close, known-red signatures, review-by, injection, TSV
+ * validation and the "every scheduled workflow is watched" ratchet.
+ */
+import { describe, expect, test } from 'bun:test';
+import { readdirSync, readFileSync } from 'node:fs';
+import { join } from 'node:path';
+import { safeLoad } from 'js-yaml';
+import { inert, readJsonBlock, type GitHubClient, type Issue } from '../../scripts/lib/gh-issue.ts';
+import {
+ JSON_MARKER, parseKnownRed, validateKnownRed, watchRun, type IncidentRecord, type JobInfo, type KnownRow, type RunInfo,
+} from '../../scripts/nightly-issue.ts';
+
+const ROOT = join(import.meta.dir, '../..');
+const FIX = join(ROOT, 'test/fixtures/nightly-watch');
+const load = <T>(name: string): T => JSON.parse(readFileSync(join(FIX, name), 'utf8')) as T;
+const REPO = 'garrytan/gbrain';
+const TODAY = '2026-10-05';
+
+interface Call { method: string; path: string; body?: Record<string, unknown> }
+
+function fakeClient(opts: { run: RunInfo; jobs: { jobs: JobInfo[]; total_count: number }; annotations?: Record<number, unknown[]>; issues?: Issue[] }) {
+ const calls: Call[] = [];
+ const client: GitHubClient = {
+ async request<T>(method: 'GET' | 'POST' | 'PATCH', path: string, body?: unknown): Promise<T> {
+ calls.push({ method, path, body: body as Record<string, unknown> });
+ if (method !== 'GET') {
+ if (path === 'repos/{repo}/issues') return { number: 101, title: (body as { title: string }).title, state: 'open' } as T;
+ return {} as T;
+ }
+ if (/actions\/runs\/\d+$/.test(path)) return opts.run as T;
+ if (path.includes('/jobs?')) return opts.jobs as T;
+ const ann = /check-runs\/(\d+)\/annotations/.exec(path);
+ if (ann) return (opts.annotations?.[Number(ann[1])] ?? []) as T;
+ if (path.includes('/runs?event=schedule&status=success')) return { workflow_runs: [{ head_sha: 'a'.repeat(40) }] } as T;
+ if (path.includes('/issues?labels=')) return (opts.issues ?? []) as T;
+ throw new Error(`unexpected GET ${path}`);
+ },
+ };
+ return { client, calls };
+}
+
+const heavy = () => ({
+ run: load<RunInfo>('run-heavy.json'),
+ jobs: load<{ jobs: JobInfo[]; total_count: number }>('jobs-heavy.json'),
+ annotations: Object.fromEntries([111415376248, 111415376292, 111415376359].map(id => [id, load<unknown[]>(`annotations-${id}.json`)])),
+});
+const realRows = parseKnownRed(readFileSync(join(ROOT, '.github/nightly-known-red.tsv'), 'utf8')).rows;
+const recordOf = (body: unknown) => readJsonBlock<IncidentRecord>(String(body), JSON_MARKER)!;
+const issueWith = (state: 'open' | 'closed', record: Partial<IncidentRecord>, labels = ['nightly-red']): Issue => ({
+ number: 7, title: 'Nightly red: Heavy Tests', state, labels: labels.map(name => ({ name })),
+ body: `old\n<!-- ${JSON_MARKER} -->\n\`\`\`json\n${JSON.stringify(record)}\n\`\`\``,
+});
+
+describe('nightly-watch incidents', () => {
+ test('a red scheduled run with no issue opens one with job/step pairs, the next step and a JSON block', async () => {
+ const { client, calls } = fakeClient(heavy());
+ const { plan, assessment } = await watchRun({ client, repo: REPO, runId: 37195155240, rows: realRows, today: TODAY, dryRun: false });
+ expect(assessment.state).toBe('red');
+ expect(plan.action).toBe('create');
+ const create = calls.find(c => c.method === 'POST' && c.path === 'repos/{repo}/issues')!;
+ expect(create.body!.title).toBe('Nightly red: Heavy Tests');
+ expect(create.body!.labels).toEqual(['nightly-red']);
+ const body = String(create.body!.body);
+ expect(body).toContain('| `Heavy tests` | `Bootstrap offline Docker e2e (placeholder)` | failure | no |');
+ expect(body).toContain('### Next step for the agent');
+ expect(body).toContain('owner action');
+ expect(body).toContain('https://github.com/garrytan/gbrain/compare/');
+ const record = recordOf(body);
+ expect(record.failing.map(f => f.job).sort()).toEqual(['Heavy tests', 'Hermes door e2e (credentialed, real binary, loud-fail)', 'Plugin doors (codex + claude, install tier)']);
+ expect(record.first_red).toEqual({ run_id: 37195155240, sha: record.head_sha });
+ expect(record.dispatch_argv).toEqual(['gh', 'workflow', 'run', 'heavy-tests.yml', '--ref', 'master']);
+ expect(record.next_step).toBe('code_fix');
+ expect(calls.filter(c => c.path === 'repos/{repo}/labels').map(c => c.body!.name)).toEqual(['nightly-red']);
+ });
+
+ test('an open incident with the same failing set is updated without a comment; a changed set comments; first red is kept', async () => {
+ const first = fakeClient(heavy());
+ const created = await watchRun({ client: first.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: true });
+ const same = issueWith('open', { ...created.plan.record!, first_red: { run_id: 42, sha: 'f'.repeat(40) } });
+ const again = fakeClient({ ...heavy(), issues: [same] });
+ const updated = await watchRun({ client: again.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false });
+ expect(updated.plan.action).toBe('update');
+ expect(again.calls.some(c => c.path.endsWith('/comments'))).toBe(false);
+ const patch = again.calls.find(c => c.method === 'PATCH')!;
+ expect(recordOf(patch.body!.body).first_red.run_id).toBe(42);
+
+ const changed = fakeClient({ ...heavy(), issues: [issueWith('open', { ...created.plan.record!, failing: [] })] });
+ await watchRun({ client: changed.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false });
+ expect(String(changed.calls.find(c => c.path.endsWith('/comments'))!.body!.body)).toContain('Failing set changed');
+ });
+
+ test('a closed incident that goes red again reopens with the run attempt (flap)', async () => {
+ const { client, calls } = fakeClient({ ...heavy(), issues: [issueWith('closed', { failing: [] })] });
+ const { plan } = await watchRun({ client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false });
+ expect(plan.action).toBe('reopen');
+ expect(calls.find(c => c.method === 'PATCH')!.body!.state).toBe('open');
+ const comment = String(calls.find(c => c.path.endsWith('/comments'))!.body!.body);
+ expect(comment).toContain('flap');
+ expect(comment).toContain('attempt 1');
+ expect(recordOf(calls.find(c => c.method === 'PATCH')!.body!.body).first_red.run_id).toBe(37195155240);
+ });
+
+ test('a green run closes only when the previously failing jobs executed; a skipped job keeps it open', async () => {
+ const green = { run: load<RunInfo>('run-macos-green.json'), jobs: load<{ jobs: JobInfo[]; total_count: number }>('jobs-macos-green.json') };
+ const fixed = fakeClient({ ...green, issues: [{ ...issueWith('open', { failing: [{ job: 'macOS 26 validation', job_id: 1, step: 's', errors: [] }] }), title: 'Nightly red: macOS 26 validation' }] });
+ const closed = await watchRun({ client: fixed.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false });
+ expect(closed.plan.action).toBe('close');
+ expect(fixed.calls.find(c => c.method === 'PATCH')!.body!.state).toBe('closed');
+
+ const skipped = fakeClient({ ...green, issues: [{ ...issueWith('open', { failing: [{ job: 'macOS codesign', job_id: 1, step: 's', errors: [] }] }), title: 'Nightly red: macOS 26 validation' }] });
+ const kept = await watchRun({ client: skipped.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false });
+ expect(kept.plan.action).toBe('none');
+ expect(skipped.calls.some(c => c.method === 'PATCH')).toBe(false);
+ expect(String(skipped.calls.find(c => c.path.endsWith('/comments'))!.body!.body)).toContain('did not execute and pass');
+ });
+
+ const scaleRun = (message: string) => ({
+ run: { ...load<RunInfo>('run-heavy.json'), name: 'Scale tier', path: '.github/workflows/scale-tier.yml' },
+ jobs: { total_count: 2, jobs: [
+ { id: 1, name: 'scale pglite 20000', conclusion: 'failure', steps: [{ number: 7, name: 'Scale tier (pglite, 20000 pages, enforce)', conclusion: 'failure' }] },
+ { id: 2, name: 'scale postgres 20000', conclusion: 'success', steps: [] },
+ ] },
+ annotations: { 1: [{ annotation_level: 'failure', title: 'Scale phase watchdog', message }] },
+ });
+
+ test('a failure matching a known-red row is tracked (known-red label, no comment when unchanged); new error text in the same job is a new incident', async () => {
+ const watchdog = '[scale] FAIL phase watchdog: vectors ran 676 s, limit 675 s; the harness was killed (exit 1).';
+ const first = fakeClient(scaleRun(watchdog));
+ const known = await watchRun({ client: first.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false });
+ expect(known.assessment.state).toBe('known-red');
+ expect(known.plan.labels).toEqual(['nightly-red', 'known-red']);
+ expect(known.plan.record!.next_step).toBe('known_red_wait');
+ expect(known.plan.record!.dispatch_argv).toEqual(['gh', 'workflow', 'run', 'scale-tier.yml', '--ref', 'master', '-f', 'pages=20000']);
+
+ const unchanged = fakeClient({ ...scaleRun(watchdog), issues: [{ ...issueWith('open', known.plan.record!, ['nightly-red', 'known-red']), title: 'Nightly red: Scale tier' }] });
+ await watchRun({ client: unchanged.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false });
+ expect(unchanged.calls.some(c => c.path.endsWith('/comments'))).toBe(false);
+
+ const other = fakeClient(scaleRun('[scale] FAIL find_orphans: an island page is missing'));
+ const fresh = await watchRun({ client: other.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false });
+ expect(fresh.assessment.state).toBe('red');
+ expect(fresh.plan.labels).toEqual(['nightly-red']);
+ });
+
+ test('a passed review-by date asks for a fix once, then stays quiet', async () => {
+ const watchdog = '[scale] FAIL phase watchdog: vectors ran 676 s';
+ const late = '2026-11-01';
+ const first = fakeClient(scaleRun(watchdog));
+ const created = await watchRun({ client: first.client, repo: REPO, runId: 1, rows: realRows, today: late, dryRun: false });
+ expect(created.plan.record!.next_step).toBe('review_by_passed');
+ const before = { ...created.plan.record!, review_by_notified: [] };
+ const open = fakeClient({ ...scaleRun(watchdog), issues: [{ ...issueWith('open', before, ['nightly-red', 'known-red']), title: 'Nightly red: Scale tier' }] });
+ const notified = await watchRun({ client: open.client, repo: REPO, runId: 1, rows: realRows, today: late, dryRun: false });
+ expect(String(open.calls.find(c => c.path.endsWith('/comments'))!.body!.body)).toContain('Review-by date passed');
+ const quiet = fakeClient({ ...scaleRun(watchdog), issues: [{ ...issueWith('open', notified.plan.record!, ['nightly-red', 'known-red']), title: 'Nightly red: Scale tier' }] });
+ await watchRun({ client: quiet.client, repo: REPO, runId: 1, rows: realRows, today: late, dryRun: false });
+ expect(quiet.calls.some(c => c.path.endsWith('/comments'))).toBe(false);
+ });
+
+ test('the keyless Hermes leg is known-skipped: the run is not green and the issue stays open with an owner action', async () => {
+ const h = heavy();
+ const jobs = h.jobs.jobs.map(j => j.name.startsWith('Hermes') ? { ...j, conclusion: 'success', steps: j.steps!.map(s => ({ ...s, conclusion: s.name === 'Run hermes door tests' ? 'skipped' : 'success' })) }
+ : { ...j, conclusion: j.conclusion === 'failure' ? 'success' : j.conclusion });
+ const { client } = fakeClient({ ...h, jobs: { ...h.jobs, jobs } });
+ const { assessment, plan } = await watchRun({ client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: true });
+ expect(assessment.state).toBe('known-skipped');
+ expect(plan.action).toBe('create');
+ expect(plan.record!.next_step).toBe('owner_action');
+ expect(plan.body).toContain('This run is not green coverage.');
+ });
+
+ test('run-derived text is inert: no mention, no link, no fence break', async () => {
+ const hostile = 'shard @attacker see https://evil.example/x ```\n</details> | `rm -rf ~`';
+ const h = heavy();
+ const jobs = h.jobs.jobs.map(j => (j.id === 111415376248 ? { ...j, name: hostile } : j));
+ const annotations = { ...h.annotations, 111415376248: [{ annotation_level: 'failure', message: `boom @maintainer [click](https://evil.example)\n~~~\n\`\`\`` }] };
+ const { client } = fakeClient({ ...h, jobs: { ...h.jobs, jobs }, annotations });
+ const { plan } = await watchRun({ client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: true });
+ const body = plan.body!;
+ expect(body).not.toMatch(/@attacker|@maintainer/);
+ expect(body).not.toContain('https://evil');
+ expect(body).not.toContain('`rm -rf ~`');
+ expect(body).not.toContain('</details>');
+ expect((body.match(/^~~~/gm) ?? []).length % 2).toBe(0);
+ expect((body.match(/^```/gm) ?? []).length).toBe(2);
+ expect(recordOf(body).failing.some(f => f.job.includes(`@\u200battacker`))).toBe(true);
+ expect(inert('a'.repeat(500), 50)).toHaveLength(50);
+ });
+
+ test('fork runs are never read; non-scheduled runs are refused unless previewed', async () => {
+ const forked = fakeClient({ ...heavy(), run: { ...load<RunInfo>('run-heavy.json'), head_repository: { full_name: 'someone/fork' } } });
+ await expect(watchRun({ client: forked.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: true })).rejects.toThrow('fork');
+ const pushed = fakeClient({ ...heavy(), run: { ...load<RunInfo>('run-heavy.json'), event: 'push' } });
+ await expect(watchRun({ client: pushed.client, repo: REPO, runId: 1, rows: realRows, today: TODAY, dryRun: false })).rejects.toThrow('only tracks scheduled runs');
+ });
+});
+
+describe('.github/nightly-known-red.tsv', () => {
+ const todos = readFileSync(join(ROOT, 'TODOS.md'), 'utf8');
+ const header = '# Columns: workflow, job, signature, kind, todo, review_by\n';
+ const row = (r: Partial<KnownRow> = {}) => [r.workflow ?? 'W', r.job ?? 'j', r.signature ?? 's', r.kind ?? 'known-red', r.todo ?? 'PGLite bulk-embedding cliff at ~20k chunks', r.review_by ?? '2026-10-25'].join('\t');
+
+ test('the committed file is valid: at most 3 rows, ISO review-by dates, each TODO present in TODOS.md', () => {
+ expect(validateKnownRed(readFileSync(join(ROOT, '.github/nightly-known-red.tsv'), 'utf8'), todos)).toEqual([]);
+ });
+
+ test('a fourth row, a bad date, an unknown kind or a missing TODO is refused with the fix', () => {
+ const four = header + [row(), row({ job: 'a' }), row({ job: 'b' }), row({ job: 'c' })].join('\n');
+ expect(validateKnownRed(four, todos).join('\n')).toContain('at most 3 cells');
+ expect(validateKnownRed(header + row({ review_by: '10/25/2026' }), todos).join('\n')).toContain('ISO date');
+ expect(validateKnownRed(header + row({ kind: 'flaky' as KnownRow['kind'] }), todos).join('\n')).toContain('known-red or known-skipped');
+ const missing = validateKnownRed(header + row({ todo: 'No such TODO' }), todos);
+ expect(missing.join('\n')).toContain('is not in TODOS.md');
+ expect(missing[0]).toContain('Fix: ');
+ expect(missing[0]).toContain('Docs: docs/RELEASING.md#nightly-red-issues');
+ });
+});
+
+describe('nightly-watch coverage ratchet', () => {
+ test('every workflow with a schedule trigger is watched', () => {
+ const dir = join(ROOT, '.github/workflows');
+ const watch = safeLoad(readFileSync(join(dir, 'nightly-watch.yml'), 'utf8')) as { on: { workflow_run: { workflows: string[] } } };
+ const scheduled = readdirSync(dir).filter(f => f.endsWith('.yml')).map(f => safeLoad(readFileSync(join(dir, f), 'utf8')) as { name: string; on?: { schedule?: unknown } })
+ .filter(w => w.on && typeof w.on === 'object' && 'schedule' in w.on).map(w => w.name);
+ expect(scheduled.length).toBeGreaterThan(5);
+ const missing = scheduled.filter(name => !watch.on.workflow_run.workflows.includes(name));
+ expect(missing, `Add ${missing.join(', ')} to .github/workflows/nightly-watch.yml on.workflow_run.workflows`).toEqual([]);
+ });
+});