Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(fleet-console): classify probe failures and harden the views
nirholasd069a254e667
diff --git a/services/fleet-console/src/extract-urls.js b/services/fleet-console/src/extract-urls.jsindex 67b7ca6e1..56e5b7c34 100644--- a/services/fleet-console/src/extract-urls.js+++ b/services/fleet-console/src/extract-urls.js@@ -67,16 +67,27 @@ const DEPLOYMENT_HOST_SUFFIXES = ['.firebaseapp.com'];-/** Link text that promises the link is a running thing. */-const LIVE_LABEL = /\b(live|demo|try\s*it|playground|deployed|hosted|website|homepage|docs?\s*site|dashboard|app|preview|open\s*in)\b/i;+/**+ * Link text that promises the link is a running thing.+ *+ * Deliberately strict. An earlier version accepted a bare "live", which+ * classified a link labelled "Debian live-build" as one of our own deployments+ * and then reported that third party's downtime as our defect.+ */+const LIVE_LABEL = /(live\s+(demo|site|app|version|instance|url)|\bdemo\b|try\s*it|playground|deployed\s+at|hosted\s+at|open\s+the\s+app|docs?\s+site|\bwebsite\b|\bhomepage\b|\bdashboard\b|\bpreview\b)/i;const normalise = (raw) => {let value = String(raw || '').trim();if (!value) return '';- // Markdown regularly leaves trailing punctuation glued to a bare URL.- value = value.replace(/[).,;:'"\]}>]+$/, '');+ // Markdown regularly leaves trailing punctuation, emphasis markers and code+ // fences glued to a bare URL. Strip them before parsing, or the URL+ // constructor percent-encodes the garbage into the path and the probe 404s+ // on a URL that never existed.+ value = value.replace(/[).,;:'"\]}>`*_~]+$/, '');if (value.startsWith('www.')) value = `https://${value}`;if (!/^https?:\/\//i.test(value)) return '';+ // A glob or a template placeholder is documentation, not an address.+ if (/[*{}<>\s]|\$\{/.test(value)) return '';try {const url = new URL(value);if (url.protocol !== 'http:' && url.protocol !== 'https:') return '';@@ -143,23 +154,41 @@ export function extractReadmeLinks(markdown) {return out.filter((link) => !isIgnoredHost(link.url));}+const originOf = (url) => {+ try {+ return new URL(url).origin;+ } catch {+ return '';+ }+};+/*** Decide which URLs this repository is promising are live.*+ * Claims are grouped by origin, because "is the deployment up?" is a question+ * about a site, not about every page a README happens to link on it. A README+ * that lists ninety paths on one host is making one deployment claim, not+ * ninety, and probing all ninety both wastes the scan and lets a single stale+ * subpage drag the score down as if the site were half dead. The origin root is+ * always probed, plus a small sample of the deeper paths, which is what catches+ * a host that serves its landing page and 404s everything else.+ ** @param {object} input* @param {string} input.repoName* @param {string} input.homepage repo.homepage from the GitHub record* @param {string} input.pagesUrl published GitHub Pages URL, when enabled* @param {string} input.manifestHomepage package.json "homepage"* @param {{url:string,label:string,source:string}[]} input.links extracted README links+ * @param {number} [input.perOrigin] paths probed per origin, including the root+ * @param {number} [input.maxCandidates] hard cap across all origins* @returns {{ url: string, why: string }[]}*/-export function deploymentCandidates({ repoName, homepage, pagesUrl, manifestHomepage, links }) {- const found = new Map();+export function deploymentCandidates({ repoName, homepage, pagesUrl, manifestHomepage, links, perOrigin = 3, maxCandidates = 8 }) {+ const claims = new Map();const add = (raw, why) => {const url = normalise(raw);if (!url || isIgnoredHost(url)) return;- if (!found.has(url)) found.set(url, why);+ if (!claims.has(url)) claims.set(url, why);};add(homepage, 'repository homepage field');@@ -167,23 +196,47 @@ export function deploymentCandidates({ repoName, homepage, pagesUrl, manifestHomadd(manifestHomepage, 'package.json homepage');const slug = String(repoName || '').toLowerCase().replace(/[^a-z0-9]+/g, '');+ const ownHosts = new Set([homepage, manifestHomepage, pagesUrl].map(hostOf).filter(Boolean));+for (const link of links) {const host = hostOf(link.url);if (looksLikeDeploymentHost(link.url)) {add(link.url, 'known hosting provider');continue;}- if (LIVE_LABEL.test(link.label)) {- add(link.url, `linked as "${link.label.slice(0, 40)}"`);+ const nameMatch = slug.length >= 4 && host.replace(/[^a-z0-9]+/g, '').includes(slug);+ if (nameMatch) {+ add(link.url, 'host matches the repository name');continue;}- // A host that spells out the repository name is that repository's own site.- if (slug.length >= 4 && host.replace(/[^a-z0-9]+/g, '').includes(slug)) {- add(link.url, 'host matches the repository name');+ // A "live demo" label only counts on a host this repository already owns.+ // Otherwise a link labelled "live" on somebody else's site becomes our outage.+ if (LIVE_LABEL.test(link.label) && (ownHosts.has(host) || ownHosts.size === 0)) {+ add(link.url, `linked as "${link.label.slice(0, 40)}"`);}}- return [...found].map(([url, why]) => ({ url, why }));+ // Group by origin. The shortest claimed path on an origin is that site's base+ // and is always probed; a sample of the deeper paths comes along to catch a+ // host that serves its landing page and 404s everything beneath it. The base+ // is never synthesized: on a project Pages site the origin root belongs to a+ // different repository, and probing it would report somebody else's page as+ // this one's deployment.+ const byOrigin = new Map();+ for (const [url, why] of claims) {+ const origin = originOf(url);+ if (!origin) continue;+ if (!byOrigin.has(origin)) byOrigin.set(origin, []);+ byOrigin.get(origin).push({ url, why });+ }++ const out = [];+ for (const group of byOrigin.values()) {+ const ordered = [...group].sort((a, b) => a.url.length - b.url.length || a.url.localeCompare(b.url));+ out.push(...ordered.slice(0, perOrigin));+ if (out.length >= maxCandidates) break;+ }+ return out.slice(0, maxCandidates);}-export const __testables = { normalise, hostOf, looksLikeDeploymentHost, stripCodeFences };+export const __testables = { normalise, hostOf, originOf, looksLikeDeploymentHost, stripCodeFences, LIVE_LABEL };diff --git a/services/fleet-console/src/github.js b/services/fleet-console/src/github.jsindex 80150c5c8..dc53465d1 100644--- a/services/fleet-console/src/github.js+++ b/services/fleet-console/src/github.js@@ -88,15 +88,29 @@ export async function ghGet(path, { accept, attempts = 3 } = {}) {return { status: 0, data: null, notModified: false, error: String(lastError?.message || lastError) };}-/** Every non-fork, non-archived repository owned by `owner`, newest API page first. */+/**+ * Every non-fork, non-archived repository owned by `owner`, highest star count first.+ *+ * Enumeration failures are thrown rather than swallowed. An expired token+ * returning 401 would otherwise produce an empty fleet, and an empty fleet+ * renders as "everything is fine" instead of "the console cannot see anything".+ */export async function listRepos(owner) {const out = [];for (let page = 1; page <= 10; page++) {- const { status, data } = await ghGet(`/users/${encodeURIComponent(owner)}/repos?per_page=100&page=${page}&sort=updated`);- if (status !== 200 || !Array.isArray(data) || data.length === 0) break;+ const { status, data, error } = await ghGet(`/users/${encodeURIComponent(owner)}/repos?per_page=100&page=${page}&sort=updated`);+ if (status === 401) throw new Error('GitHub rejected the credentials (401). GITHUB_TOKEN is missing, expired or revoked.');+ if (status === 404) throw new Error(`GitHub has no user or organisation called "${owner}" (404). Check FLEET_OWNER.`);+ if (status === 403 || status === 429) {+ throw new Error(`GitHub rate limit reached${rateLimit.resetAt ? `, resets at ${rateLimit.resetAt}` : ''}. Set GITHUB_TOKEN to raise the budget from 60 to 5000 requests an hour.`);+ }+ if (status === 0) throw new Error(`Could not reach the GitHub API: ${error || 'network failure'}`);+ if (status !== 200) throw new Error(`GitHub responded ${status} while listing repositories for "${owner}".`);+ if (!Array.isArray(data) || data.length === 0) break;out.push(...data);if (data.length < 100) break;}+ if (out.length === 0) throw new Error(`"${owner}" has no public repositories the console can see.`);return out.filter((repo) => (config.includeForks ? true : !repo.fork)).filter((repo) => (config.includeArchived ? true : !repo.archived))diff --git a/services/fleet-console/src/probe.js b/services/fleet-console/src/probe.jsindex c4e0486b9..efc87989a 100644--- a/services/fleet-console/src/probe.js+++ b/services/fleet-console/src/probe.js@@ -28,7 +28,7 @@ export const PROBE_STATES = {const classifyError = (error) => {const code = error?.cause?.code || error?.code || '';const message = String(error?.message || error || '').toLowerCase();- if (error?.name === 'AbortError' || message.includes('timeout') || code === 'UND_ERR_HEADERS_TIMEOUT') return 'timeout';+ if (error?.name === 'AbortError' || message.includes('timeout') || code === 'ETIMEDOUT' || code === 'UND_ERR_HEADERS_TIMEOUT' || code === 'UND_ERR_CONNECT_TIMEOUT') return 'timeout';if (code === 'ENOTFOUND' || code === 'EAI_AGAIN' || message.includes('getaddrinfo')) return 'dns_failure';if (code === 'ECONNREFUSED') return 'refused';if (code === 'ECONNRESET' || code === 'EPIPE') return 'unreachable';diff --git a/services/fleet-console/src/registry.js b/services/fleet-console/src/registry.jsindex 94aa4ea9b..bcfcea576 100644--- a/services/fleet-console/src/registry.js+++ b/services/fleet-console/src/registry.js@@ -46,6 +46,8 @@ export function advertisedPackages(markdown) {if (raw.includes('/') && !raw.startsWith('@')) continue;if (raw.startsWith('.') || raw.includes(':') || raw.endsWith('.tgz')) continue;const name = stripVersionRange(raw);+ // A bare number on an install line is a port or a count, never a package.+ if (/^\d+$/.test(name)) continue;if (PACKAGE_NAME.test(name)) names.add(name);}}diff --git a/services/fleet-console/src/views/dashboard.js b/services/fleet-console/src/views/dashboard.jsindex b387871d0..42e20e7e3 100644--- a/services/fleet-console/src/views/dashboard.js+++ b/services/fleet-console/src/views/dashboard.js@@ -35,12 +35,15 @@ function statTiles(summary, history) {}];- const trend = history.length- ? `<div class="stat"><div class="k">Median trend</div><div style="margin-top:6px">${sparkline(- history.map((entry) => ({ at: entry.at, score: entry.medianScore })),- { width: 150, height: 40 }- )}</div><div class="s">${history.length} scan${history.length === 1 ? '' : 's'} recorded</div></div>`- : '';+ // A sparkline needs at least two points to be a line. Below that the tile+ // would show a sentence where every neighbouring tile shows a number.+ const trend =+ history.length >= 2+ ? `<div class="stat"><div class="k">Median trend</div><div style="margin-top:6px">${sparkline(+ history.map((entry) => ({ at: entry.at, score: entry.medianScore })),+ { width: 150, height: 40 }+ )}</div><div class="s">${history.length} scans recorded</div></div>`+ : '';return `<section class="stats" aria-label="Fleet summary">${tiles.map((tile) => `<div class="stat ${tile.cls || ''}"><div class="k">${esc(tile.k)}</div><div class="v">${esc(tile.v)}</div><div class="s">${esc(tile.s)}</div></div>`).join('\n')}@@ -125,11 +128,22 @@ ${rows/** The scanning / never-scanned state. It polls for progress rather than spinning. */export function scanningPage({ owner, progress, authenticated }) {const pct = progress.total ? Math.round((progress.done / progress.total) * 100) : 0;+ const failed = progress.phase === 'failed' && progress.error;const body = `<section class="hero">- <h1>${progress.running ? 'Scanning the fleet' : 'No scan has run yet'}</h1>+ <h1>${failed ? 'The scan could not run' : progress.running ? 'Scanning the fleet' : 'No scan has run yet'}</h1><p class="lede">Fleet Console enumerates every public repository owned by <strong>${esc(owner)}</strong>, extracts the URLs andpackages each one advertises, and checks them against the live internet. The first pass takes a few minutes.</p></section>+${+ failed+ ? `<section class="panel"><h2>What went wrong</h2><div class="pad">+ <p class="mono" style="margin-top:0;color:var(--bad)">${esc(progress.error)}</p>+ <p style="color:var(--muted);margin-bottom:0">The console reports this rather than showing an empty fleet, because an empty+ fleet reads as "nothing is broken" when the truth is "nothing could be seen". Fix the cause and the next scheduled scan+ recovers on its own.</p>+</div></section>`+ : ''+}${authenticated ? '' : '<div class="note"><strong>Running unauthenticated.</strong> GitHub allows 60 requests an hour without a token, which covers only a handful of repositories. Set <code>GITHUB_TOKEN</code> for a full scan.</div>'}<section class="panel"><div class="pad"><div class="bar" role="progressbar" aria-valuenow="${pct}" aria-valuemin="0" aria-valuemax="100" aria-label="Scan progress"><span style="width:${pct}%"></span></div>diff --git a/services/fleet-console/src/views/repo.js b/services/fleet-console/src/views/repo.jsindex b95bb9510..8758c3213 100644--- a/services/fleet-console/src/views/repo.js+++ b/services/fleet-console/src/views/repo.js@@ -52,6 +52,29 @@ ${rows</tbody></table></div>`;}+/**+ * One button per live site, not one per probed path. Several probes on the same+ * origin are the same site checked twice, and rendering both produced two+ * identical "Open live site" buttons side by side.+ */+function liveSiteButtons(repo) {+ const seen = new Map();+ for (const entry of repo.deployments || []) {+ if (entry.state !== 'live' && entry.state !== 'redirected') continue;+ let host = '';+ try {+ host = new URL(entry.url).host;+ } catch {+ continue;+ }+ if (!seen.has(host)) seen.set(host, entry.url);+ }+ return [...seen]+ .slice(0, 3)+ .map(([host, url]) => `<a class="btn" href="${attr(url)}" rel="noopener" target="_blank">Open ${esc(host)}</a>`)+ .join('');+}+export function repoPage({ repo, owner, history }) {const checks = repo.checks || [];const passed = checks.filter((entry) => entry.status === 'pass').length;@@ -73,7 +96,7 @@ export function repoPage({ repo, owner, history }) {</div><div class="chips" style="margin-top:12px"><a class="btn" href="${attr(repo.htmlUrl)}" rel="noopener" target="_blank">Source on GitHub</a>- ${(repo.deployments || []).filter((entry) => entry.state === 'live' || entry.state === 'redirected').slice(0, 2).map((entry) => `<a class="btn" href="${attr(entry.url)}" rel="noopener" target="_blank">Open live site</a>`).join('')}+ ${liveSiteButtons(repo)}<a class="btn" href="/api/repo/${encodeURIComponent(repo.name)}">JSON</a><a class="btn" href="/badge/${encodeURIComponent(repo.name)}.svg">Badge</a></div>diff --git a/tests/fleet-console.test.js b/tests/fleet-console.test.jsnew file mode 100644index 000000000..cd7118f9e--- /dev/null+++ b/tests/fleet-console.test.js@@ -0,0 +1,439 @@+/**+ * Unit tests for the fleet console engine (services/fleet-console).+ *+ * Everything here is pure: URL extraction, probe classification, the scoring+ * model, registry name parsing, badge rendering and the attention ranking. The+ * network-facing parts are covered by running a real scan, which cannot live in+ * a unit test suite.+ */++import { describe, it, expect } from 'vitest';++import { extractReadmeLinks, deploymentCandidates, isIgnoredHost } from '../services/fleet-console/src/extract-urls.js';+import { __testables as probeInternals, isHealthyState, PROBE_STATES } from '../services/fleet-console/src/probe.js';+import { scoreRepo, summarise, gradeFor } from '../services/fleet-console/src/score.js';+import { advertisedPackages, __testables as registryInternals } from '../services/fleet-console/src/registry.js';+import { badgeSvg, repoBadge, deploymentBadge, fleetBadge } from '../services/fleet-console/src/badge.js';+import { esc, ago } from '../services/fleet-console/src/views/html.js';+import { attention, slim } from '../services/fleet-console/src/server.js';+import { mapPool } from '../services/fleet-console/src/pool.js';++const probe = (url, state, extra = {}) => ({ url, state, status: state === 'live' ? 200 : 404, ms: 12, finalUrl: url, redirected: false, detail: '', ...extra });++const baseRepo = {+ name: 'widget',+ description: 'A widget',+ stars: 10,+ topics: ['a', 'b', 'c'],+ license: 'MIT',+ pushedAt: new Date(Date.now() - 5 * 86400000).toISOString(),+ readmeBytes: 4000,+ hasDocsDir: true,+ deployments: [],+ links: [],+ packages: { checked: [], missing: [] }+};++describe('README link extraction', () => {+ it('pulls markdown, reference, HTML and bare links while skipping images', () => {+ const readme = `+# Widget+[Live demo](https://widget.example.dev/) and +<a href="https://docs.widget.dev">Docs site</a>+See https://spec.example.org/v1 for the format.++[ref]: https://ref.example.net/page+`;+ const urls = extractReadmeLinks(readme).map((link) => link.url);+ expect(urls).toContain('https://widget.example.dev/');+ expect(urls).toContain('https://docs.widget.dev/');+ expect(urls).toContain('https://spec.example.org/v1');+ expect(urls).toContain('https://ref.example.net/page');+ expect(urls.some((url) => url.includes('shields.io'))).toBe(false);+ });++ it('ignores URLs inside fenced code blocks', () => {+ const readme = ['```bash', 'curl https://api.internal-only.test/v1/thing', '```', '[real](https://real.example.dev)'].join('\n');+ const urls = extractReadmeLinks(readme).map((link) => link.url);+ expect(urls).toEqual(['https://real.example.dev/']);+ });++ it('strips trailing punctuation from bare URLs', () => {+ const urls = extractReadmeLinks('Visit https://example.dev/page, then leave.').map((link) => link.url);+ expect(urls).toEqual(['https://example.dev/page']);+ });++ it('treats github, npm and badge hosts as not worth checking', () => {+ expect(isIgnoredHost('https://github.com/a/b')).toBe(true);+ expect(isIgnoredHost('https://www.npmjs.com/package/x')).toBe(true);+ expect(isIgnoredHost('https://img.shields.io/badge.svg')).toBe(true);+ expect(isIgnoredHost('https://widget.example.dev')).toBe(false);+ });++ it('rejects non-http schemes and unparseable values', () => {+ const urls = extractReadmeLinks('[mail](mailto:[email protected]) [js](javascript:alert(1)) [ok](https://ok.example.dev)').map((link) => link.url);+ expect(urls).toEqual(['https://ok.example.dev/']);+ });+});++describe('deployment claim detection', () => {+ const call = (overrides) =>+ deploymentCandidates({ repoName: 'widget', homepage: '', pagesUrl: '', manifestHomepage: '', links: [], ...overrides }).map((entry) => entry.url);++ it('counts the homepage field, Pages URL and manifest homepage', () => {+ const urls = call({ homepage: 'https://widget.dev', pagesUrl: 'https://owner.github.io/widget/', manifestHomepage: 'https://manifest.example.dev' });+ expect(urls.sort()).toEqual(['https://manifest.example.dev/', 'https://owner.github.io/widget/', 'https://widget.dev/']);+ });++ it('counts known hosting providers found in the README', () => {+ const urls = call({ links: [{ url: 'https://thing-abc.a.run.app/', label: 'API', source: 'markdown' }] });+ expect(urls).toEqual(['https://thing-abc.a.run.app/']);+ });++ it('counts a link labelled as live but not an ordinary reference', () => {+ const urls = call({+ links: [+ { url: 'https://try.example.dev/', label: 'Live demo', source: 'markdown' },+ { url: 'https://spec.example.org/', label: 'the specification', source: 'markdown' }+ ]+ });+ expect(urls).toEqual(['https://try.example.dev/']);+ });++ it('does not claim a third party site because its link text contains the word live', () => {+ // A README linking "Debian live-build" is not promising to run debian.org.+ const urls = call({+ homepage: 'https://widget.dev',+ links: [{ url: 'https://live-team.pages.debian.net/live-manual/', label: 'Debian live-build', source: 'markdown' }]+ });+ expect(urls).toEqual(['https://widget.dev/']);+ });++ it('collapses many paths on one host into a small sample of that one site', () => {+ const links = Array.from({ length: 40 }, (unused, index) => ({ url: `https://widget.dev/page-${index}`, label: '', source: 'markdown' }));+ const urls = call({ homepage: 'https://widget.dev', links });+ // One site, one deployment claim, plus a couple of deeper paths as a spot check.+ expect(urls.length).toBe(3);+ expect(urls[0]).toBe('https://widget.dev/');+ });++ it('caps the total number of probes even across many hosts', () => {+ const links = Array.from({ length: 30 }, (unused, index) => ({ url: `https://host-${index}.pages.dev/`, label: '', source: 'markdown' }));+ expect(call({ links }).length).toBeLessThanOrEqual(8);+ });++ it('never invents an origin root that was not claimed', () => {+ // On a project Pages site the origin root is a different repository's page.+ const urls = call({ pagesUrl: 'https://owner.github.io/widget/' });+ expect(urls).toEqual(['https://owner.github.io/widget/']);+ });++ it('recovers a real URL from trailing markdown noise instead of probing the noise', () => {+ const urls = call({ links: [{ url: 'https://owner.github.io/widget/**', label: '', source: 'bare' }] });+ expect(urls).toEqual(['https://owner.github.io/widget/']);+ });++ it('drops template placeholders and interior globs rather than probing them', () => {+ const urls = call({+ links: [+ { url: 'https://api.example.dev/${version}/thing', label: 'Live demo', source: 'markdown' },+ { url: 'https://cdn.example.dev/*/asset.js', label: 'Live demo', source: 'markdown' },+ { url: 'https://widget.dev/real', label: 'Live demo', source: 'markdown' }+ ]+ });+ expect(urls).toEqual(['https://widget.dev/real']);+ });++ it('counts a host that spells out the repository name', () => {+ const urls = call({ links: [{ url: 'https://widget.example.io/', label: '', source: 'bare' }] });+ expect(urls).toEqual(['https://widget.example.io/']);+ });++ it('does not double count the same URL reached two ways', () => {+ const urls = call({ homepage: 'https://widget.dev', links: [{ url: 'https://widget.dev', label: 'Live', source: 'markdown' }] });+ expect(urls).toEqual(['https://widget.dev/']);+ });+});++describe('probe classification', () => {+ const { classifyStatus, classifyError } = probeInternals;++ it('separates the ways a request can fail to return a page', () => {+ expect(classifyStatus(200, false)).toBe('live');+ expect(classifyStatus(200, true)).toBe('redirected');+ expect(classifyStatus(402, false)).toBe('payment_required');+ expect(classifyStatus(401, false)).toBe('auth_required');+ expect(classifyStatus(403, false)).toBe('auth_required');+ expect(classifyStatus(429, false)).toBe('rate_limited');+ expect(classifyStatus(404, false)).toBe('not_found');+ expect(classifyStatus(410, false)).toBe('not_found');+ expect(classifyStatus(503, false)).toBe('server_error');+ });++ it('maps transport failures to their cause', () => {+ expect(classifyError({ cause: { code: 'ENOTFOUND' } })).toBe('dns_failure');+ expect(classifyError({ cause: { code: 'ECONNREFUSED' } })).toBe('refused');+ expect(classifyError({ cause: { code: 'CERT_HAS_EXPIRED' } })).toBe('tls_failure');+ expect(classifyError({ name: 'AbortError', message: 'aborted' })).toBe('timeout');+ expect(classifyError(new Error('something else'))).toBe('unreachable');+ });++ it('treats only live and redirected as healthy', () => {+ expect(isHealthyState('live')).toBe(true);+ expect(isHealthyState('redirected')).toBe(true);+ expect(isHealthyState('payment_required')).toBe(false);+ });++ it('has a label and tone for every state the classifiers can produce', () => {+ for (const state of ['live', 'redirected', 'payment_required', 'auth_required', 'rate_limited', 'not_found', 'server_error', 'dns_failure', 'refused', 'tls_failure', 'timeout', 'unreachable']) {+ expect(PROBE_STATES[state], state).toBeTruthy();+ }+ });+});++describe('scoring', () => {+ it('gives a fully healthy repository a top grade', () => {+ const { score, grade } = scoreRepo({+ ...baseRepo,+ deployments: [probe('https://widget.dev/', 'live')],+ links: [probe('https://spec.example.org/', 'live')],+ packages: { checked: [{ name: 'widget', published: true, latest: '1.2.0', deprecated: false, role: 'manifest' }], missing: [], ownPackage: { name: 'widget', published: true, latest: '1.2.0' } },+ packageVersion: '1.2.0'+ });+ expect(score).toBe(100);+ expect(grade.grade).toBe('A');+ });++ it('does not punish a library for having nothing deployed', () => {+ const withoutDeployment = scoreRepo(baseRepo);+ const deploymentCheck = withoutDeployment.checks.find((check) => check.id === 'deployment');+ expect(deploymentCheck.status).toBe('skip');+ // A skipped check leaves the denominator entirely, so the rest still scores full marks.+ expect(withoutDeployment.score).toBe(100);+ });++ it('fails a repository whose only advertised deployment is down', () => {+ const { score, checks } = scoreRepo({ ...baseRepo, deployments: [probe('https://gone.example.dev/', 'payment_required')] });+ expect(checks.find((check) => check.id === 'deployment').status).toBe('fail');+ expect(score).toBeLessThan(100);+ });++ it('warns when some but not all deployments respond', () => {+ const { checks } = scoreRepo({ ...baseRepo, deployments: [probe('https://a.example.dev/', 'live'), probe('https://b.example.dev/', 'not_found')] });+ expect(checks.find((check) => check.id === 'deployment').status).toBe('warn');+ });++ it('fails a repository advertising a package that was never published', () => {+ const { checks } = scoreRepo({+ ...baseRepo,+ packages: { checked: [{ name: 'ghost-package', published: false, latest: '', deprecated: false, role: 'readme' }], missing: ['ghost-package'] }+ });+ const check = checks.find((entry) => entry.id === 'packages');+ expect(check.status).toBe('fail');+ expect(check.evidence).toContain('ghost-package');+ expect(check.fix).toBeTruthy();+ });++ it('does not count an auth wall or a rate limit as a dead link', () => {+ const { checks } = scoreRepo({ ...baseRepo, links: [probe('https://private.example.dev/', 'auth_required'), probe('https://slow.example.dev/', 'rate_limited')] });+ expect(checks.find((check) => check.id === 'links').status).toBe('pass');+ });++ it('warns when the published version has drifted from the manifest', () => {+ const { checks } = scoreRepo({+ ...baseRepo,+ packages: { checked: [{ name: 'widget', published: true, latest: '1.0.0', deprecated: false, role: 'manifest' }], missing: [], ownPackage: { name: 'widget', published: true, latest: '1.0.0' } },+ packageVersion: '2.0.0'+ });+ const check = checks.find((entry) => entry.id === 'release-sync');+ expect(check.status).toBe('warn');+ expect(check.evidence).toContain('2.0.0');+ });++ it('degrades a stale, undocumented, unlicensed repository', () => {+ const { score, grade } = scoreRepo({+ ...baseRepo,+ description: '',+ license: '',+ topics: [],+ readmeBytes: 0,+ hasDocsDir: false,+ pushedAt: new Date(Date.now() - 900 * 86400000).toISOString()+ });+ expect(score).toBeLessThan(40);+ expect(grade.grade).toBe('F');+ });++ it('maps scores onto grade bands at the boundaries', () => {+ expect(gradeFor(100).grade).toBe('A');+ expect(gradeFor(90).grade).toBe('A');+ expect(gradeFor(89).grade).toBe('B');+ expect(gradeFor(75).grade).toBe('B');+ expect(gradeFor(60).grade).toBe('C');+ expect(gradeFor(40).grade).toBe('D');+ expect(gradeFor(0).grade).toBe('F');+ });++ it('never returns a score outside 0..100', () => {+ for (const repo of [baseRepo, { ...baseRepo, description: '', license: '', topics: [], readmeBytes: 0, hasDocsDir: false }]) {+ const { score } = scoreRepo(repo);+ expect(score).toBeGreaterThanOrEqual(0);+ expect(score).toBeLessThanOrEqual(100);+ }+ });+});++describe('fleet summary', () => {+ it('rolls up scores, deployments, links and missing packages', () => {+ const repos = [+ { ...baseRepo, name: 'a', score: 100, grade: gradeFor(100), stars: 5, deployments: [probe('https://a.dev/', 'live')], links: [], packages: { checked: [], missing: [] } },+ { ...baseRepo, name: 'b', score: 50, grade: gradeFor(50), stars: 3, deployments: [probe('https://b.dev/', 'not_found')], links: [probe('https://x.dev/', 'dns_failure')], packages: { checked: [], missing: ['ghost'] } }+ ];+ const summary = summarise(repos);+ expect(summary.repos).toBe(2);+ expect(summary.stars).toBe(8);+ expect(summary.medianScore).toBe(75);+ expect(summary.deployments).toMatchObject({ total: 2, healthy: 1 });+ expect(summary.links).toMatchObject({ total: 1, dead: 1 });+ expect(summary.missingPackages).toEqual([{ repo: 'b', name: 'ghost' }]);+ expect(summary.byGrade.A).toBe(1);+ });++ it('handles an empty fleet without dividing by zero', () => {+ const summary = summarise([]);+ expect(summary.medianScore).toBe(0);+ expect(summary.averageScore).toBe(0);+ expect(summary.repos).toBe(0);+ });+});++describe('npm registry parsing', () => {+ it('finds package names across npm, yarn, pnpm and bun install lines', () => {+ const readme = `+\`npm install @scope/thing\`+yarn add other-thing@^2.0.0+pnpm add -D dev-thing+bun add third-thing+`;+ expect(advertisedPackages(readme).sort()).toEqual(['@scope/thing', 'dev-thing', 'other-thing', 'third-thing']);+ });++ it('skips flags, local paths, tarballs and git specifiers', () => {+ const names = advertisedPackages('npm install -g ./local-dir ../other https://x.test/a.tgz github:owner/repo real-package');+ expect(names).toEqual(['real-package']);+ });++ it('does not mistake a port number on an install line for a package', () => {+ expect(advertisedPackages('npm install serve 3001')).toEqual(['serve']);+ });++ it('strips a version range without eating a scope', () => {+ expect(registryInternals.stripVersionRange('@scope/[email protected]')).toBe('@scope/thing');+ expect(registryInternals.stripVersionRange('thing@^1.0.0')).toBe('thing');+ expect(registryInternals.stripVersionRange('@scope/thing')).toBe('@scope/thing');+ });++ it('rejects names the registry could never hold', () => {+ expect(registryInternals.PACKAGE_NAME.test('Valid-Name')).toBe(false);+ expect(registryInternals.PACKAGE_NAME.test('valid-name')).toBe(true);+ expect(registryInternals.PACKAGE_NAME.test('@scope/valid')).toBe(true);+ });+});++describe('badges', () => {+ it('renders valid, self-describing SVG', () => {+ const svg = badgeSvg({ label: 'fleet health', message: '92/100 A', tone: 'good' });+ expect(svg.startsWith('<svg')).toBe(true);+ expect(svg).toContain('role="img"');+ expect(svg).toContain('aria-label="fleet health: 92/100 A"');+ expect(svg.trim().endsWith('</svg>')).toBe(true);+ });++ it('escapes text so a repository name can never break the markup', () => {+ expect(badgeSvg({ label: 'a<b>', message: '"x"&y', tone: 'bad' })).toContain('a<b>');+ });++ it('reports an unknown repository rather than inventing a score', () => {+ expect(repoBadge(null)).toContain('unknown');+ expect(fleetBadge(null)).toContain('not scanned');+ });++ it('summarises deployment health', () => {+ expect(deploymentBadge({ deployments: [probe('https://a.dev/', 'live'), probe('https://b.dev/', 'not_found')] })).toContain('1/2 live');+ expect(deploymentBadge({ deployments: [] })).toContain('none advertised');+ });++ it('scales the badge width with its text', () => {+ const narrow = badgeSvg({ label: 'a', message: 'b', tone: 'good' });+ const wide = badgeSvg({ label: 'a much longer label', message: 'and a longer message', tone: 'good' });+ const width = (svg) => Number(svg.match(/width="(\d+)"/)[1]);+ expect(width(wide)).toBeGreaterThan(width(narrow));+ });+});++describe('attention feed', () => {+ const snapshot = {+ owner: 'someone',+ generatedAt: '2026-01-01T00:00:00.000Z',+ repos: [+ {+ ...baseRepo,+ name: 'alpha',+ htmlUrl: 'https://github.com/someone/alpha',+ deployments: [probe('https://alpha.dev/', 'payment_required')],+ links: [probe('https://dead.example.dev/', 'dns_failure')],+ packages: { checked: [], missing: ['ghost-pkg'] },+ checks: [{ id: 'license', title: 'Declares a license', weight: 6, status: 'fail', evidence: 'none', fix: 'Add a LICENSE file.' }]+ }+ ]+ };++ it('ranks broken deployments and unpublished packages above dead links', () => {+ const report = attention(snapshot);+ expect(report.count).toBe(4);+ expect(report.items[0].severity).toBe('high');+ expect(report.items.at(-1).kind).toBe('dead_link');+ expect(report.items.map((item) => item.kind)).toContain('package_unpublished');+ expect(report.items.map((item) => item.kind)).toContain('check_failed:license');+ });++ it('slims a repository down to what a list view needs', () => {+ const record = slim(snapshot.repos[0]);+ expect(record).toMatchObject({ name: 'alpha', unpublishedPackages: ['ghost-pkg'] });+ expect(record.broken).toEqual([{ url: 'https://alpha.dev/', state: 'payment_required' }]);+ expect(record.live).toEqual([]);+ });+});++describe('view helpers', () => {+ it('escapes every character that could close a tag or an attribute', () => {+ expect(esc('<script>"x"&\'y\'</script>')).toBe('<script>"x"&'y'</script>');+ });++ it('renders relative times in plain language', () => {+ expect(ago(new Date(Date.now() - 30 * 1000).toISOString())).toMatch(/second/);+ expect(ago(new Date(Date.now() - 3 * 86400000).toISOString())).toBe('3 days ago');+ expect(ago('')).toBe('never');+ expect(ago('not a date')).toBe('never');+ });+});++describe('bounded concurrency', () => {+ it('preserves input order and never exceeds the limit', async () => {+ let active = 0;+ let peak = 0;+ const result = await mapPool([1, 2, 3, 4, 5, 6, 7, 8], 3, async (value) => {+ active += 1;+ peak = Math.max(peak, active);+ await new Promise((resolve) => setTimeout(resolve, 5));+ active -= 1;+ return value * 2;+ });+ expect(result).toEqual([2, 4, 6, 8, 10, 12, 14, 16]);+ expect(peak).toBeLessThanOrEqual(3);+ });++ it('handles an empty list', async () => {+ expect(await mapPool([], 4, async () => 1)).toEqual([]);+ });+});