Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 5 additions & 1 deletion core/lib/ledger.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,11 @@ export function buildLedger({ datasets, health = null, replies = [], generatedAt
workflow: w.id, lastSuccess: w.lastSuccess ?? null, lastRun: w.lastRun ?? null, enabled: w.enabled ?? null,
intervalHours: w.intervalHours, thresholdHours: w.thresholdHours, events: w.events ?? [],
}));
const dead = (health?.links ?? []).filter((l) => l.state === 'broken').map((l) => ({ url: l.url, status: l.status, lastOk: l.lastOk ?? null, usedBy: l.usedBy ?? [], archive: l.archive ?? null }));
// Only a link that answered the same way twice running: one bad check is usually the
// network, and naming a live citation dead on this page is the worse mistake. A record
// written before the check recorded `confirmed` is taken as it stands.
const dead = (health?.links ?? []).filter((l) => l.state === 'broken' && l.confirmed !== false)
.map((l) => ({ url: l.url, status: l.status, lastOk: l.lastOk ?? null, usedBy: l.usedBy ?? [], archive: l.archive ?? null }));
return {
generatedAt, license: 'CC BY 4.0', contact,
counts: { tracked: rows.length, current: count('current'), due: count('due'), late: count('late'), discontinued: count('discontinued') },
Expand Down
61 changes: 55 additions & 6 deletions pipeline/link-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import REGULATORS from '../data/curated/regulators.mjs';
import QF from '../data/curated/qf-checklist.mjs';
import LARGE_LOAD from '../data/curated/large-load-tariffs/_index.mjs';
import PROGRAM_LINKS from '../data/curated/program-links.mjs';
import { recordRun } from './lib/health.mjs';
import { readHealth, recordRun } from './lib/health.mjs';
import { github } from './lib/github.mjs';
import { ROOT } from './run.mjs';

Expand Down Expand Up @@ -47,6 +47,40 @@ export async function outboundLinks(root = ROOT) {
return links;
}

/**
* Hosts that answer an automated check with a wall of their own instead of the
* page asked for. eCFR and the Federal Register send one to unblock.federalregister.gov;
* Minnesota's PUC sends one to a ShieldSquare challenge. The redirect is an
* interception, not a move: following it would store a URL that cites nothing.
*/
const INTERSTITIALS = new Set(['unblock.federalregister.gov', 'validate.perfdrive.com']);

/**
* Resolvers whose whole job is to redirect. A DOI is the stable name of a dataset
* or a paper; where it points is the publisher's business and may change again.
* Storing what it resolved to today would replace a permanent citation with a
* perishable one, so a DOI that resolves is simply working.
*/
const RESOLVERS = new Set(['doi.org', 'dx.doi.org']);

const hostOf = (u) => { try { return new URL(u).host; } catch { return ''; } };
/** Two addresses for comparison: the fragment is ours, not the server's, and `fetch` drops it. */
const same = (a, b) => a.replace(/#.*$/, '').replace(/\/$/, '') === b.replace(/#.*$/, '').replace(/\/$/, '');

/**
* What one answer means. A 403 or 429 is "blocked": some state sites refuse
* automated checks, so a person checks those by hand, and a redirect onto an
* interstitial is the same refusal wearing a 200.
* @param {{url: string, status: number, finalUrl: string}} r
*/
export function classify({ url, status, finalUrl }) {
if (status === 403 || status === 429) return 'blocked';
if (status === 0 || status >= 400) return 'broken';
if (INTERSTITIALS.has(hostOf(finalUrl)) && hostOf(finalUrl) !== hostOf(url)) return 'blocked';
if (RESOLVERS.has(hostOf(url))) return 'ok';
return same(finalUrl, url) ? 'ok' : 'moved';
}

/**
* @param {{fetch?: typeof fetch, host?: any, root?: string, now?: () => Date}} [o]
*/
Expand All @@ -56,6 +90,8 @@ export async function linkCheck(o = {}) {
const now = o.now ?? (() => new Date());
const host = o.host ?? github();
const started = now().toISOString();
// What each link answered last time, so this run can tell a lasting change from a blip.
const previous = new Map((readHealth(root).links ?? []).map((l) => [l.url, l]));
const results = [];
for (const [url, usedBy] of await outboundLinks(root)) {
let status = 0;
Expand All @@ -73,14 +109,27 @@ export async function linkCheck(o = {}) {
if (effective) finalUrl = effective;
} else status = 0;
}
const state = status === 403 || status === 429 ? 'blocked' : status === 0 || status >= 400 ? 'broken' : finalUrl.replace(/\/$/, '') !== url.replace(/\/$/, '') ? 'moved' : 'ok';
results.push({ url, state, status, ...(state === 'moved' ? { finalUrl } : {}), usedBy });
const state = classify({ url, status, finalUrl });
// Since when this link has been answering this way. One bad check is usually the
// network or a moment's load, and a site that hands out a fresh session URL every
// visit (Wyoming's and Montana's dockets) "moves" every week; both look the same
// twice running only when something really changed. Publishing a live citation as
// a dead one is the worse mistake, so a result counts only once it is confirmed.
const was = previous.get(url);
const sameAnswer = Boolean(was && was.state === state && (state !== 'moved' || same(was.finalUrl ?? '', finalUrl)));
results.push({ url, state, status, ...(state === 'moved' ? { finalUrl } : {}), held: sameAnswer && was.since ? was.since : null, usedBy });
}
const finished = now().toISOString();
for (const r of results) {
r.since = r.state === 'ok' ? null : r.held ?? finished;
r.confirmed = r.state !== 'ok' && r.since !== finished;
delete r.held;
}
const bad = results.filter((r) => r.state !== 'ok');
const bad = results.filter((r) => r.confirmed);
if (bad.length && host.available) {
try { await host.openIssue('Link check: broken or moved links', bad.map((b) => `- ${b.state}: ${b.url}${b.finalUrl ? ` → ${b.finalUrl}` : ''} (HTTP ${b.status}), used by ${b.usedBy.join(', ')}`).join('\n')); } catch { /* recorded below either way */ }
try { await host.openIssue('Link check: broken or moved links', bad.map((b) => `- ${b.state}: ${b.url}${b.finalUrl ? ` → ${b.finalUrl}` : ''} (HTTP ${b.status}), unchanged since ${b.since}, used by ${b.usedBy.join(', ')}`).join('\n')); } catch { /* recorded below either way */ }
}
recordRun(root, { workflow: 'link-check', started, finished: now().toISOString(), ok: true, links: results, notes: bad.length ? [`${bad.length} broken or moved links`] : [] });
recordRun(root, { workflow: 'link-check', started, finished, ok: true, links: results, notes: bad.length ? [`${bad.length} broken or moved links`] : [] });
return results;
}

Expand Down
92 changes: 90 additions & 2 deletions verify/tests/pipeline/automation.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,9 @@ import assert from 'node:assert/strict';
import { mkdirSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { scheduledRun } from '../../../pipeline/scheduled.mjs';
import { linkCheck, outboundLinks } from '../../../pipeline/link-check.mjs';
import { classify, linkCheck, outboundLinks } from '../../../pipeline/link-check.mjs';
import { readHealth } from '../../../pipeline/lib/health.mjs';
import { buildLedger } from '../../../core/lib/ledger.mjs';
import { stalled, WORKFLOWS } from '../../../pipeline/workflows.mjs';
import { checkWorkflows } from '../../gates/workflows.mjs';
import entry from '../../../pipeline/registry/eia-861.mjs';
Expand Down Expand Up @@ -144,10 +145,97 @@ test('link check: a moved handoff is recorded with its new target and every page
const ri = results.find((x) => x.url === 'https://ripuc.ri.gov/');
assert.equal(ri.state, 'blocked', 'a site that refuses automated checks is blocked, not broken');
assert.deepEqual(ri.usedBy, ['RI regulator home']);
assert.equal(host.issues.length, 1);
assert.equal(host.issues.length, 0, 'the first sighting is held back: one bad check is usually the network');
// The health record keeps each result, with when it was checked and when it last worked.
assert.deepEqual(readHealth(r).links.map(({ checked, lastOk, ...l }) => l), results);
assert.ok(readHealth(r).links.every((l) => l.checked && (l.state === 'ok' ? l.lastOk === l.checked : l.lastOk === null)));

// The same answer a week later confirms it, and the issue says since when.
const again = await linkCheck({ fetch: f, host, root: r, now: at('2026-11-10T07:23:00Z') });
assert.equal(again.find((x) => x.url === moved).since, '2026-11-03T07:23:00.000Z');
assert.ok(again.find((x) => x.url === moved).confirmed);
assert.equal(host.issues.length, 1);
assert.match(host.issues[0].body, /moved: .*energy-conversion-calculators\.php .*unchanged since 2026-11-03T07:23:00\.000Z/);
});

test('link check: a link that fails once and works again is never called broken in public', async () => {
const r = root();
const nist = (status) => async (url) => {
const res = new Response('ok', { status: url.includes('nist.gov') ? status : 200 });
Object.defineProperty(res, 'url', { value: url });
return res;
};
const host = fakeHost();
const one = await linkCheck({ fetch: nist(500), host, root: r, now: at('2026-11-03T07:23:00Z') });
const first = one.find((x) => x.url.includes('nist.gov'));
assert.equal(first.state, 'broken', 'the record is honest about what this check saw');
assert.equal(first.confirmed, false);
assert.deepEqual(buildLedger({ datasets: [], health: readHealth(r), generatedAt: '2026-11-03T08:00:00Z', contact: 'x@y' }).deadLinks, [],
'an unconfirmed failure is not published as a dead citation on the limits page');

const two = await linkCheck({ fetch: nist(200), host, root: r, now: at('2026-11-10T07:23:00Z') });
assert.equal(two.find((x) => x.url.includes('nist.gov')).state, 'ok');
assert.equal(host.issues.length, 0, 'nothing was ever reported');
});

test('link check: a page that stays broken is confirmed, reported, and published as a dead citation', async () => {
const r = root();
const f = async (url) => {
const res = new Response('ok', { status: url.includes('nist.gov') ? 404 : 200 });
Object.defineProperty(res, 'url', { value: url });
return res;
};
const host = fakeHost();
await linkCheck({ fetch: f, host, root: r, now: at('2026-11-03T07:23:00Z') });
const two = await linkCheck({ fetch: f, host, root: r, now: at('2026-11-10T07:23:00Z') });
const dead = two.find((x) => x.url.includes('nist.gov'));
assert.equal(dead.confirmed, true);
assert.equal(dead.since, '2026-11-03T07:23:00.000Z');
assert.equal(host.issues.length, 1);
assert.deepEqual(buildLedger({ datasets: [], health: readHealth(r), generatedAt: '2026-11-10T08:00:00Z', contact: 'x@y' }).deadLinks.map((l) => l.status), [404]);
});

test('link check: a docket that hands out a fresh session URL every visit has not moved', async () => {
const r = root();
const docket = 'https://dms.wyo.gov/external/publicusers.aspx';
assert.ok((await outboundLinks()).has(docket));
let visit = 0;
const f = async (url) => {
const res = new Response('ok', { status: 200 });
Object.defineProperty(res, 'url', { value: url === docket ? `https://dms.wyo.gov/(S(session${visit++}))/external/publicusers.aspx` : url });
return res;
};
const host = fakeHost();
await linkCheck({ fetch: f, host, root: r, now: at('2026-11-03T07:23:00Z') });
const two = await linkCheck({ fetch: f, host, root: r, now: at('2026-11-10T07:23:00Z') });
const w = two.find((x) => x.url === docket);
assert.equal(w.state, 'moved', 'this check really was redirected');
assert.equal(w.confirmed, false, 'but to somewhere new each time, so there is nothing to update');
assert.equal(host.issues.length, 0);
});

test('classify: an interstitial is the refusal of an automated check, not a move', () => {
const ecfr = 'https://www.ecfr.gov/current/title-18/section-292.203';
assert.equal(classify({ url: ecfr, status: 200, finalUrl: 'https://unblock.federalregister.gov/' }), 'blocked');
assert.equal(classify({ url: 'https://mn.gov/puc/get-involved/public-comments/', status: 200, finalUrl: 'https://validate.perfdrive.com/abc?ssa=1' }), 'blocked');
// A redirect to another host is ordinarily a real move.
assert.equal(classify({ url: 'https://www.epa.gov/egrid/egrid-questions-and-answers', status: 200, finalUrl: 'https://www.epa.gov/egrid/frequent-questions-about-egrid' }), 'moved');
assert.equal(classify({ url: ecfr, status: 403, finalUrl: ecfr }), 'blocked');
assert.equal(classify({ url: ecfr, status: 404, finalUrl: ecfr }), 'broken');
});

test('classify: a DOI that resolves is working, not moved', () => {
// Following it would swap a permanent citation for today's address.
assert.equal(classify({ url: 'https://doi.org/10.7289/V5D21VHZ', status: 200, finalUrl: 'https://www.ncei.noaa.gov/metadata/geoportal/x/html' }), 'ok');
assert.equal(classify({ url: 'https://doi.org/10.6084/m9.figshare.24237376.v4', status: 202, finalUrl: 'https://figshare.com/articles/dataset/x/24237376/4' }), 'ok');
assert.equal(classify({ url: 'https://doi.org/10.0000/gone', status: 404, finalUrl: 'https://doi.org/10.0000/gone' }), 'broken', 'a DOI that resolves to nothing is still broken');
});

test('classify: the fragment is ours, not the server\'s, so dropping it is not a move', () => {
const readme = 'https://github.com/catalyst-cooperative/pudl/blob/main/README.rst#licensing';
assert.equal(classify({ url: readme, status: 200, finalUrl: 'https://github.com/catalyst-cooperative/pudl/blob/main/README.rst' }), 'ok');
assert.equal(classify({ url: 'https://example.gov/a', status: 200, finalUrl: 'https://example.gov/a/' }), 'ok', 'nor is a trailing slash');
assert.equal(classify({ url: readme, status: 200, finalUrl: 'https://github.com/catalyst-cooperative/pudl/blob/main/docs.rst' }), 'moved');
});

test('CI policy: a marketplace action, an unpinned action, pull_request_target, event text in a shell line, and a floating runner all fail', () => {
Expand Down