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): repo fleet monitoring service
nirholas3179fc268d38
diff --git a/services/fleet-console/package.json b/services/fleet-console/package.jsonnew file mode 100644index 000000000..bbe2f11c1--- /dev/null+++ b/services/fleet-console/package.json@@ -0,0 +1,21 @@+{+ "name": "@three-ws/fleet-console",+ "version": "1.0.0",+ "private": true,+ "type": "module",+ "description": "Live health console for an open-source fleet: enumerates every repository of a GitHub owner, resolves the URLs each one claims to be deployed at, probes them, verifies advertised npm packages actually exist, and scores the result.",+ "main": "src/server.js",+ "scripts": {+ "start": "node src/server.js",+ "dev": "node --watch src/server.js",+ "scan": "node src/cli.js scan",+ "mcp": "node src/mcp.js"+ },+ "bin": {+ "fleet-console": "src/cli.js",+ "fleet-console-mcp": "src/mcp.js"+ },+ "engines": {+ "node": ">=20"+ }+}diff --git a/services/fleet-console/src/badge.js b/services/fleet-console/src/badge.jsnew file mode 100644index 000000000..d713595d3--- /dev/null+++ b/services/fleet-console/src/badge.js@@ -0,0 +1,78 @@+/**+ * Live SVG health badges.+ *+ * The point of the badge is that it is not self-reported. A build badge says+ * the tests passed on some commit; this one says the URLs that repository+ * advertises answered a request a few hours ago. Drop it in a README and the+ * README stops being able to lie about being deployed.+ */++const COLORS = { good: '#3fb950', warn: '#d29922', bad: '#e5534b', mute: '#6e7681' };++/** Approximate advance width for the 11px sans stack shields use. */+const textWidth = (text) => {+ let width = 0;+ for (const char of String(text)) {+ if ('ilj|!.,:;\'`'.includes(char)) width += 3.2;+ else if ('Iftr()[]{}/\\ '.includes(char)) width += 4.4;+ else if ('mwMW@'.includes(char)) width += 9.6;+ else if (char >= 'A' && char <= 'Z') width += 7.6;+ else width += 6.6;+ }+ return Math.ceil(width);+};++const escapeXml = (value) =>+ String(value).replace(/[&<>"']/g, (char) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' })[char]);++/**+ * Render a two-part badge.+ * @param {{label:string, message:string, tone:'good'|'warn'|'bad'|'mute'}} input+ */+export function badgeSvg({ label, message, tone = 'mute' }) {+ const color = COLORS[tone] || COLORS.mute;+ const leftWidth = textWidth(label) + 20;+ const rightWidth = textWidth(message) + 20;+ const total = leftWidth + rightWidth;+ const title = `${label}: ${message}`;++ return `<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="${total}" height="20" role="img" aria-label="${escapeXml(title)}">+<title>${escapeXml(title)}</title>+<linearGradient id="s" x2="0" y2="100%"><stop offset="0" stop-color="#bbb" stop-opacity=".1"/><stop offset="1" stop-opacity=".1"/></linearGradient>+<clipPath id="r"><rect width="${total}" height="20" rx="3" fill="#fff"/></clipPath>+<g clip-path="url(#r)">+ <rect width="${leftWidth}" height="20" fill="#33383d"/>+ <rect x="${leftWidth}" width="${rightWidth}" height="20" fill="${color}"/>+ <rect width="${total}" height="20" fill="url(#s)"/>+</g>+<g fill="#fff" text-anchor="middle" font-family="Verdana,Geneva,DejaVu Sans,sans-serif" font-size="11">+ <text x="${leftWidth / 2}" y="15" fill="#010101" fill-opacity=".3">${escapeXml(label)}</text>+ <text x="${leftWidth / 2}" y="14">${escapeXml(label)}</text>+ <text x="${leftWidth + rightWidth / 2}" y="15" fill="#010101" fill-opacity=".3">${escapeXml(message)}</text>+ <text x="${leftWidth + rightWidth / 2}" y="14">${escapeXml(message)}</text>+</g>+</svg>`;+}++/** Badge for one repository. */+export function repoBadge(repo) {+ if (!repo || typeof repo.score !== 'number') return badgeSvg({ label: 'fleet health', message: 'unknown', tone: 'mute' });+ return badgeSvg({ label: 'fleet health', message: `${repo.score}/100 ${repo.grade?.grade || ''}`.trim(), tone: repo.grade?.tone || 'mute' });+}++/** Badge for a repository's advertised deployments only. */+export function deploymentBadge(repo) {+ const deployments = repo?.deployments || [];+ if (!deployments.length) return badgeSvg({ label: 'deployment', message: 'none advertised', tone: 'mute' });+ const healthy = deployments.filter((entry) => entry.state === 'live' || entry.state === 'redirected').length;+ const tone = healthy === deployments.length ? 'good' : healthy > 0 ? 'warn' : 'bad';+ return badgeSvg({ label: 'deployment', message: `${healthy}/${deployments.length} live`, tone });+}++/** Fleet-wide badge. */+export function fleetBadge(snapshot) {+ if (!snapshot) return badgeSvg({ label: 'fleet', message: 'not scanned', tone: 'mute' });+ const median = snapshot.summary.medianScore;+ const tone = median >= 75 ? 'good' : median >= 55 ? 'warn' : 'bad';+ return badgeSvg({ label: `fleet (${snapshot.summary.repos} repos)`, message: `median ${median}/100`, tone });+}diff --git a/services/fleet-console/src/cli.js b/services/fleet-console/src/cli.jsnew file mode 100644index 000000000..3fe947113--- /dev/null+++ b/services/fleet-console/src/cli.js@@ -0,0 +1,80 @@+#!/usr/bin/env node+/**+ * Command line entry point. Runs one scan and prints the result, so the engine+ * can be used in a terminal or a cron job without the HTTP server.+ *+ * node src/cli.js scan human-readable report+ * node src/cli.js scan --json the raw snapshot+ * node src/cli.js scan --attention only what is broken, exit 1 if anything is+ */++import { config } from './config.js';+import { runScan } from './scan.js';+import * as store from './store.js';+import { attention } from './server.js';++const args = process.argv.slice(2);+const command = args[0] || 'scan';+const flag = (name) => args.includes(`--${name}`);+const value = (name, fallback) => {+ const index = args.indexOf(`--${name}`);+ return index > -1 && args[index + 1] ? args[index + 1] : fallback;+};++const tty = process.stdout.isTTY && !process.env.NO_COLOR;+const ansi = (code) => (tty ? `\u001b[${code}m` : '');+const BOLD = ansi(1);+const DIM = ansi(2);+const RESET = ansi(0);+const RED = ansi(31);+const YELLOW = ansi(33);+const GREEN = ansi(32);++const colorFor = (score) => (score >= 75 ? GREEN : score >= 55 ? YELLOW : RED);++function printReport(snapshot) {+ const { summary } = snapshot;+ process.stdout.write(`\n${BOLD}${snapshot.owner}${RESET} ${summary.repos} repositories, ${summary.stars.toLocaleString()} stars\n`);+ process.stdout.write(`${DIM}scanned in ${(snapshot.durationMs / 1000).toFixed(1)}s${snapshot.partial ? ', partial (rate limit)' : ''}${RESET}\n\n`);+ process.stdout.write(` median health ${colorFor(summary.medianScore)}${summary.medianScore}/100${RESET}\n`);+ process.stdout.write(` live deployments ${summary.deployments.healthy}/${summary.deployments.total}\n`);+ process.stdout.write(` dead README links ${summary.links.dead}/${summary.links.total}\n`);+ process.stdout.write(` unpublished pkgs ${summary.missingPackages.length}\n\n`);++ const worst = snapshot.repos.filter((repo) => typeof repo.score === 'number').sort((a, b) => a.score - b.score).slice(0, Number(value('top', 20)));+ const width = Math.max(...worst.map((repo) => repo.name.length), 4);+ process.stdout.write(`${BOLD}Lowest scoring${RESET}\n`);+ for (const repo of worst) {+ const failed = (repo.checks || []).filter((check) => check.status === 'fail').map((check) => check.id);+ process.stdout.write(` ${colorFor(repo.score)}${String(repo.score).padStart(3)}${RESET} ${repo.name.padEnd(width)} ${DIM}${failed.join(', ') || 'no failing checks'}${RESET}\n`);+ }+ process.stdout.write('\n');+}++async function main() {+ if (command !== 'scan') {+ process.stderr.write('usage: fleet-console scan [--json] [--attention] [--top N] [--owner NAME]\n');+ process.exit(2);+ }++ const owner = value('owner', config.owner);+ await store.load();+ const snapshot = await runScan({ owner });+ await store.save(snapshot);++ if (flag('json')) {+ process.stdout.write(`${JSON.stringify(snapshot, null, 2)}\n`);+ return;+ }+ if (flag('attention')) {+ const report = attention(snapshot);+ process.stdout.write(`${JSON.stringify(report, null, 2)}\n`);+ process.exit(report.count > 0 ? 1 : 0);+ }+ printReport(snapshot);+}++main().catch((error) => {+ process.stderr.write(`fleet-console: ${error?.message || error}\n`);+ process.exit(1);+});diff --git a/services/fleet-console/src/config.js b/services/fleet-console/src/config.jsnew file mode 100644index 000000000..257a5f12e--- /dev/null+++ b/services/fleet-console/src/config.js@@ -0,0 +1,56 @@+/**+ * Runtime configuration for the fleet console.+ *+ * Every value is read from the environment so the service is owner-agnostic:+ * point FLEET_OWNER at any GitHub user or organisation and the console+ * discovers that fleet at runtime. Nothing about a specific fleet is compiled+ * into this service.+ */++const int = (raw, fallback) => {+ const n = Number.parseInt(raw ?? '', 10);+ return Number.isFinite(n) && n > 0 ? n : fallback;+};++const bool = (raw, fallback) => {+ if (raw === undefined || raw === '') return fallback;+ return raw === '1' || raw.toLowerCase() === 'true';+};++export const config = {+ /** GitHub user or organisation whose repositories make up the fleet. */+ owner: process.env.FLEET_OWNER || 'nirholas',+ /** Optional token. Without one GitHub allows 60 requests/hour, which limits a scan to a handful of repositories. */+ githubToken: process.env.GITHUB_TOKEN || process.env.GH_TOKEN || '',+ /** Where snapshots are written. Ephemeral on Cloud Run unless a volume is mounted. */+ dataDir: process.env.FLEET_DATA_DIR || '/tmp/fleet-console',+ port: int(process.env.PORT, 8080),++ /** Repositories per scan, highest star count first. */+ maxRepos: int(process.env.FLEET_MAX_REPOS, 400),+ /** Skip forks, which are somebody else's code and score meaninglessly. */+ includeForks: bool(process.env.FLEET_INCLUDE_FORKS, false),+ /** Skip archived repositories, which are deliberately frozen. */+ includeArchived: bool(process.env.FLEET_INCLUDE_ARCHIVED, false),++ /** Concurrent GitHub requests. GitHub tolerates far more, but this keeps secondary rate limits away. */+ githubConcurrency: int(process.env.FLEET_GITHUB_CONCURRENCY, 6),+ /** Concurrent outbound HTTP probes against third-party hosts. */+ probeConcurrency: int(process.env.FLEET_PROBE_CONCURRENCY, 12),+ probeTimeoutMs: int(process.env.FLEET_PROBE_TIMEOUT_MS, 10000),+ /** External links checked per repository. READMEs occasionally carry hundreds. */+ maxLinksPerRepo: int(process.env.FLEET_MAX_LINKS_PER_REPO, 12),++ /** Automatic rescan cadence. Set to 0 to disable and drive scans over the API. */+ scanIntervalMs: int(process.env.FLEET_SCAN_INTERVAL_MS, 6 * 60 * 60 * 1000),+ /** Run a scan as soon as the process boots. */+ scanOnBoot: bool(process.env.FLEET_SCAN_ON_BOOT, true),+ /** Shared secret required by POST /api/scan. Empty means the endpoint is disabled. */+ scanToken: process.env.FLEET_SCAN_TOKEN || '',+ /** Snapshots retained for trend lines. */+ historyLimit: int(process.env.FLEET_HISTORY_LIMIT, 60),++ userAgent: 'fleet-console (+https://github.com/nirholas/three.ws)'+};++export default config;diff --git a/services/fleet-console/src/extract-urls.js b/services/fleet-console/src/extract-urls.jsnew file mode 100644index 000000000..67b7ca6e1--- /dev/null+++ b/services/fleet-console/src/extract-urls.js@@ -0,0 +1,189 @@+/**+ * Pull the URLs a repository claims out of its own README and manifest.+ *+ * The distinction that matters here is between a *deployment claim* and an+ * ordinary outbound link. A README that links to a specification is not+ * promising that link is its own running service; a README with a "Live demo"+ * button is. Grading both the same way produces a fleet report where every+ * repository looks broken because MDN moved a page.+ */++/** Hosts that are never a deployment and never worth link-checking. */+const IGNORED_HOSTS = new Set([+ 'github.com',+ 'www.github.com',+ 'gist.github.com',+ 'raw.githubusercontent.com',+ 'user-images.githubusercontent.com',+ 'avatars.githubusercontent.com',+ 'objects.githubusercontent.com',+ 'camo.githubusercontent.com',+ 'shields.io',+ 'img.shields.io',+ 'badge.fury.io',+ 'badgen.net',+ 'codecov.io',+ 'app.codecov.io',+ 'npmjs.com',+ 'www.npmjs.com',+ 'registry.npmjs.org',+ 'pypi.org',+ 'crates.io',+ 'opensource.org',+ 'choosealicense.com',+ 'spdx.org',+ 'localhost',+ '127.0.0.1',+ '0.0.0.0',+ 'example.com',+ 'www.example.com',+ 'twitter.com',+ 'x.com',+ 'discord.gg',+ 'discord.com',+ 't.me',+ 'linkedin.com',+ 'www.linkedin.com'+]);++/** Hosts that only ever appear because something was deployed there. */+const DEPLOYMENT_HOST_SUFFIXES = [+ '.run.app',+ '.a.run.app',+ '.pages.dev',+ '.workers.dev',+ '.vercel.app',+ '.netlify.app',+ '.github.io',+ '.fly.dev',+ '.onrender.com',+ '.herokuapp.com',+ '.railway.app',+ '.streamlit.app',+ '.hf.space',+ '.surge.sh',+ '.appspot.com',+ '.web.app',+ '.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;++const normalise = (raw) => {+ let value = String(raw || '').trim();+ if (!value) return '';+ // Markdown regularly leaves trailing punctuation glued to a bare URL.+ value = value.replace(/[).,;:'"\]}>]+$/, '');+ if (value.startsWith('www.')) value = `https://${value}`;+ if (!/^https?:\/\//i.test(value)) return '';+ try {+ const url = new URL(value);+ if (url.protocol !== 'http:' && url.protocol !== 'https:') return '';+ url.hash = '';+ return url.toString();+ } catch {+ return '';+ }+};++const hostOf = (url) => {+ try {+ return new URL(url).hostname.toLowerCase();+ } catch {+ return '';+ }+};++export const isIgnoredHost = (url) => {+ const host = hostOf(url);+ if (!host) return true;+ if (IGNORED_HOSTS.has(host)) return true;+ if (host.endsWith('.local') || host.endsWith('.internal')) return true;+ return false;+};++const looksLikeDeploymentHost = (url) => {+ const host = hostOf(url);+ return DEPLOYMENT_HOST_SUFFIXES.some((suffix) => host.endsWith(suffix));+};++/** Strip fenced code blocks so a curl example is not read as a deployment claim. */+const stripCodeFences = (markdown) => markdown.replace(/```[\s\S]*?```/g, '\n').replace(/^ {4,}\S.*$/gm, '');++/**+ * @returns {{ url: string, label: string, source: string }[]} unique links in document order.+ */+export function extractReadmeLinks(markdown) {+ const text = stripCodeFences(String(markdown || ''));+ const seen = new Set();+ const out = [];++ const push = (rawUrl, label, source) => {+ const url = normalise(rawUrl);+ if (!url || seen.has(url)) return;+ seen.add(url);+ out.push({ url, label: String(label || '').replace(/[*`_]/g, '').trim(), source });+ };++ // Inline markdown links, skipping images (a leading '!').+ for (const match of text.matchAll(/(!)?\[([^\]]*)\]\((\s*<?)([^)\s>]+)>?[^)]*\)/g)) {+ if (match[1]) continue;+ push(match[4], match[2], 'markdown');+ }+ // Reference definitions.+ for (const match of text.matchAll(/^\s*\[[^\]]+\]:\s*(\S+)/gm)) push(match[1], '', 'reference');+ // HTML anchors, which READMEs use for centred hero buttons.+ for (const match of text.matchAll(/<a\b[^>]*href=["']([^"']+)["'][^>]*>([\s\S]*?)<\/a>/gi)) {+ push(match[1], match[2].replace(/<[^>]+>/g, ' '), 'html');+ }+ // Bare URLs.+ for (const match of text.matchAll(/(?<![("<\]])\bhttps?:\/\/[^\s<>"')\]]+/g)) push(match[0], '', 'bare');++ return out.filter((link) => !isIgnoredHost(link.url));+}++/**+ * Decide which URLs this repository is promising are live.+ *+ * @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+ * @returns {{ url: string, why: string }[]}+ */+export function deploymentCandidates({ repoName, homepage, pagesUrl, manifestHomepage, links }) {+ const found = new Map();+ const add = (raw, why) => {+ const url = normalise(raw);+ if (!url || isIgnoredHost(url)) return;+ if (!found.has(url)) found.set(url, why);+ };++ add(homepage, 'repository homepage field');+ add(pagesUrl, 'GitHub Pages');+ add(manifestHomepage, 'package.json homepage');++ const slug = String(repoName || '').toLowerCase().replace(/[^a-z0-9]+/g, '');+ 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)}"`);+ 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');+ }+ }++ return [...found].map(([url, why]) => ({ url, why }));+}++export const __testables = { normalise, hostOf, looksLikeDeploymentHost, stripCodeFences };diff --git a/services/fleet-console/src/github.js b/services/fleet-console/src/github.jsnew file mode 100644index 000000000..80150c5c8--- /dev/null+++ b/services/fleet-console/src/github.js@@ -0,0 +1,162 @@+/**+ * Minimal GitHub REST client.+ *+ * Two things it does that a generic client does not:+ * 1. It caches by ETag, so a rescan of an unchanged repository costs a 304+ * and does not consume rate-limit budget.+ * 2. It surfaces the rate-limit state to the caller, so the console can tell+ * the user "this scan is partial because the budget ran out" instead of+ * silently reporting a repository as broken.+ */++import { config } from './config.js';+import { sleep } from './pool.js';++const API = 'https://api.github.com';++const etagCache = new Map();++export const rateLimit = {+ limit: null,+ remaining: null,+ resetAt: null,+ exhausted: false+};++const readRateLimit = (headers) => {+ const limit = Number.parseInt(headers.get('x-ratelimit-limit') ?? '', 10);+ const remaining = Number.parseInt(headers.get('x-ratelimit-remaining') ?? '', 10);+ const reset = Number.parseInt(headers.get('x-ratelimit-reset') ?? '', 10);+ if (Number.isFinite(limit)) rateLimit.limit = limit;+ if (Number.isFinite(remaining)) {+ rateLimit.remaining = remaining;+ rateLimit.exhausted = remaining <= 0;+ }+ if (Number.isFinite(reset)) rateLimit.resetAt = new Date(reset * 1000).toISOString();+};++const headers = (extra = {}) => {+ const base = {+ accept: 'application/vnd.github+json',+ 'x-github-api-version': '2022-11-28',+ 'user-agent': config.userAgent,+ ...extra+ };+ if (config.githubToken) base.authorization = `Bearer ${config.githubToken}`;+ return base;+};++/**+ * GET a GitHub API path. Returns `{ status, data, notModified }`.+ * Never throws for an expected HTTP status: a 404 is data, not an exception.+ */+export async function ghGet(path, { accept, attempts = 3 } = {}) {+ const url = path.startsWith('http') ? path : `${API}${path}`;+ const cached = etagCache.get(url);+ const extra = {};+ if (accept) extra.accept = accept;+ if (cached?.etag) extra['if-none-match'] = cached.etag;++ let lastError = null;+ for (let attempt = 1; attempt <= attempts; attempt++) {+ try {+ const res = await fetch(url, { headers: headers(extra), redirect: 'follow' });+ readRateLimit(res.headers);++ if (res.status === 304 && cached) return { status: 200, data: cached.data, notModified: true };++ // Secondary rate limits and 5xx are worth one more try after a pause.+ if ((res.status === 403 && rateLimit.exhausted) || res.status === 429) {+ return { status: res.status, data: null, notModified: false, rateLimited: true };+ }+ if (res.status >= 500 && attempt < attempts) {+ await sleep(400 * attempt);+ continue;+ }+ if (!res.ok) return { status: res.status, data: null, notModified: false };++ const isJson = (res.headers.get('content-type') || '').includes('json');+ const data = isJson ? await res.json() : await res.text();+ const etag = res.headers.get('etag');+ if (etag) etagCache.set(url, { etag, data });+ return { status: res.status, data, notModified: false };+ } catch (error) {+ lastError = error;+ if (attempt < attempts) await sleep(400 * attempt);+ }+ }+ 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. */+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;+ out.push(...data);+ if (data.length < 100) break;+ }+ return out+ .filter((repo) => (config.includeForks ? true : !repo.fork))+ .filter((repo) => (config.includeArchived ? true : !repo.archived))+ .map((repo) => ({+ name: repo.name,+ fullName: repo.full_name,+ description: repo.description || '',+ homepage: (repo.homepage || '').trim(),+ stars: repo.stargazers_count || 0,+ forks: repo.forks_count || 0,+ openIssues: repo.open_issues_count || 0,+ language: repo.language || '',+ topics: Array.isArray(repo.topics) ? repo.topics : [],+ license: repo.license?.spdx_id && repo.license.spdx_id !== 'NOASSERTION' ? repo.license.spdx_id : '',+ private: Boolean(repo.private),+ hasPages: Boolean(repo.has_pages),+ defaultBranch: repo.default_branch || 'main',+ pushedAt: repo.pushed_at || null,+ createdAt: repo.created_at || null,+ sizeKb: repo.size || 0,+ htmlUrl: repo.html_url+ }))+ .sort((a, b) => b.stars - a.stars || a.name.localeCompare(b.name));+}++/** Raw README text, or '' when the repository has none. */+export async function fetchReadme(fullName) {+ const { status, data } = await ghGet(`/repos/${fullName}/readme`, { accept: 'application/vnd.github.raw' });+ return status === 200 && typeof data === 'string' ? data : '';+}++/** Parsed root package.json, or null. */+export async function fetchPackageJson(fullName, branch) {+ const url = `https://raw.githubusercontent.com/${fullName}/${branch}/package.json`;+ try {+ const res = await fetch(url, { headers: { 'user-agent': config.userAgent } });+ if (!res.ok) return null;+ return JSON.parse(await res.text());+ } catch {+ return null;+ }+}++/** The published GitHub Pages URL, or '' when Pages is not enabled. */+export async function fetchPagesUrl(fullName) {+ const { status, data } = await ghGet(`/repos/${fullName}/pages`);+ if (status !== 200 || !data?.html_url) return '';+ return data.html_url;+}++/** Top-level entry names, used to tell a repository with docs from one without. */+export async function fetchRootEntries(fullName, branch) {+ const { status, data } = await ghGet(`/repos/${fullName}/contents/?ref=${encodeURIComponent(branch)}`);+ if (status !== 200 || !Array.isArray(data)) return [];+ return data.map((entry) => ({ name: entry.name, type: entry.type }));+}++/** The most recent release tag, or ''. */+export async function fetchLatestRelease(fullName) {+ const { status, data } = await ghGet(`/repos/${fullName}/releases/latest`);+ if (status !== 200 || !data?.tag_name) return '';+ return data.tag_name;+}diff --git a/services/fleet-console/src/mcp.js b/services/fleet-console/src/mcp.jsnew file mode 100644index 000000000..6be9af2e3--- /dev/null+++ b/services/fleet-console/src/mcp.js@@ -0,0 +1,192 @@+#!/usr/bin/env node+/**+ * Model Context Protocol server over stdio.+ *+ * The dashboard answers "what is broken?" for a person. This answers it for an+ * agent, which is the more useful half: an agent that can read the fleet's+ * measured state can be told to go fix the worst of it without a human first+ * pasting a list of URLs into the prompt.+ *+ * It reads the same snapshot the HTTP service writes, either from a running+ * console (FLEET_CONSOLE_URL) or straight from disk (FLEET_DATA_DIR).+ *+ * Register it with any MCP client:+ * { "mcpServers": { "fleet": { "command": "node", "args": ["src/mcp.js"],+ * "env": { "FLEET_CONSOLE_URL": "https://fleet-console.example.com" } } } }+ */++import { createInterface } from 'node:readline';+import { config } from './config.js';+import * as store from './store.js';+import { attention } from './server.js';++const PROTOCOL_VERSION = '2024-11-05';+const consoleUrl = (process.env.FLEET_CONSOLE_URL || '').replace(/\/+$/, '');++/** Snapshot source: a running console if one is configured, otherwise the local store. */+async function loadSnapshot() {+ if (consoleUrl) {+ const res = await fetch(`${consoleUrl}/api/fleet?full=1`, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`fleet console responded ${res.status}`);+ return res.json();+ }+ await store.load();+ const snapshot = store.getSnapshot();+ if (!snapshot) throw new Error(`no snapshot in ${config.dataDir}. Run "npm run scan" first, or set FLEET_CONSOLE_URL.`);+ return snapshot;+}++const TOOLS = [+ {+ name: 'fleet_summary',+ description:+ 'Fleet-wide health rollup for the configured GitHub owner: repository count, median and mean health score, how many advertised deployment URLs actually respond, dead README links, and npm packages that are advertised for install but were never published.',+ inputSchema: { type: 'object', properties: {}, additionalProperties: false },+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }+ },+ {+ name: 'fleet_attention',+ description:+ 'Everything measurably broken across the fleet, ranked worst first: down deployments, unpublished packages, dead links and failing checks. Use this to pick what to fix next.',+ inputSchema: {+ type: 'object',+ properties: {+ severity: { type: 'string', enum: ['high', 'medium', 'low'], description: 'Only return items at this severity.' },+ limit: { type: 'integer', minimum: 1, maximum: 500, description: 'Maximum items to return. Defaults to 50.' }+ },+ additionalProperties: false+ },+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }+ },+ {+ name: 'fleet_repo',+ description:+ 'Full measured detail for one repository: its score, every health check with the evidence behind it, every probed URL with status and latency, and its npm registry verification.',+ inputSchema: {+ type: 'object',+ properties: { name: { type: 'string', description: 'Repository name, without the owner prefix.' } },+ required: ['name'],+ additionalProperties: false+ },+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }+ },+ {+ name: 'fleet_search',+ description: 'Find repositories by name, description, language or topic, returning each one with its current health score and any broken deployment.',+ inputSchema: {+ type: 'object',+ properties: {+ query: { type: 'string', description: 'Free text matched against name, description, language and topics.' },+ max_score: { type: 'integer', minimum: 0, maximum: 100, description: 'Only return repositories scoring at or below this.' },+ limit: { type: 'integer', minimum: 1, maximum: 200, description: 'Maximum results. Defaults to 25.' }+ },+ additionalProperties: false+ },+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true }+ }+];++const textResult = (value) => ({ content: [{ type: 'text', text: typeof value === 'string' ? value : JSON.stringify(value, null, 2) }] });++const slimRepo = (repo) => ({+ name: repo.name,+ description: repo.description,+ url: repo.htmlUrl,+ stars: repo.stars,+ language: repo.language,+ score: repo.score,+ grade: repo.grade?.grade || null,+ failingChecks: (repo.checks || []).filter((check) => check.status === 'fail').map((check) => ({ id: check.id, evidence: check.evidence, fix: check.fix })),+ brokenDeployments: (repo.deployments || []).filter((entry) => entry.state !== 'live' && entry.state !== 'redirected').map((entry) => ({ url: entry.url, state: entry.state })),+ unpublishedPackages: repo.packages?.missing || []+});++async function callTool(name, args = {}) {+ const snapshot = await loadSnapshot();++ if (name === 'fleet_summary') {+ return textResult({+ owner: snapshot.owner,+ generatedAt: snapshot.generatedAt,+ partial: snapshot.partial,+ ...snapshot.summary+ });+ }++ if (name === 'fleet_attention') {+ const report = attention(snapshot);+ let items = report.items;+ if (args.severity) items = items.filter((item) => item.severity === args.severity);+ const limit = Math.min(args.limit || 50, 500);+ return textResult({ owner: snapshot.owner, generatedAt: snapshot.generatedAt, total: items.length, returned: Math.min(items.length, limit), items: items.slice(0, limit) });+ }++ if (name === 'fleet_repo') {+ const target = String(args.name || '').toLowerCase();+ const repo = snapshot.repos.find((entry) => entry.name.toLowerCase() === target);+ if (!repo) {+ const near = snapshot.repos.filter((entry) => entry.name.toLowerCase().includes(target)).slice(0, 8).map((entry) => entry.name);+ throw new Error(`no repository "${args.name}" in the snapshot${near.length ? `. Did you mean: ${near.join(', ')}` : ''}`);+ }+ return textResult(repo);+ }++ if (name === 'fleet_search') {+ const query = String(args.query || '').toLowerCase();+ const limit = Math.min(args.limit || 25, 200);+ const matches = snapshot.repos+ .filter((repo) => {+ if (typeof args.max_score === 'number' && !(typeof repo.score === 'number' && repo.score <= args.max_score)) return false;+ if (!query) return true;+ return [repo.name, repo.description, repo.language, ...(repo.topics || [])].join(' ').toLowerCase().includes(query);+ })+ .sort((a, b) => (a.score ?? 101) - (b.score ?? 101));+ return textResult({ total: matches.length, returned: Math.min(matches.length, limit), repos: matches.slice(0, limit).map(slimRepo) });+ }++ throw new Error(`unknown tool: ${name}`);+}++const respond = (id, result) => process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id, result })}\n`);+const fail = (id, code, message) => process.stdout.write(`${JSON.stringify({ jsonrpc: '2.0', id, error: { code, message } })}\n`);++async function handleMessage(message) {+ const { id, method, params } = message;++ if (method === 'initialize') {+ return respond(id, {+ protocolVersion: PROTOCOL_VERSION,+ capabilities: { tools: {} },+ serverInfo: { name: 'fleet-console', version: '1.0.0' }+ });+ }+ if (method === 'notifications/initialized' || method === 'notifications/cancelled') return;+ if (method === 'ping') return respond(id, {});+ if (method === 'tools/list') return respond(id, { tools: TOOLS });+ if (method === 'tools/call') {+ try {+ return respond(id, await callTool(params?.name, params?.arguments || {}));+ } catch (error) {+ return respond(id, { content: [{ type: 'text', text: `Error: ${error?.message || error}` }], isError: true });+ }+ }+ if (id !== undefined) fail(id, -32601, `method not found: ${method}`);+}++const rl = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY });+rl.on('line', (line) => {+ const trimmed = line.trim();+ if (!trimmed) return;+ let message;+ try {+ message = JSON.parse(trimmed);+ } catch {+ return fail(null, -32700, 'parse error');+ }+ handleMessage(message).catch((error) => {+ if (message?.id !== undefined) fail(message.id, -32603, String(error?.message || error));+ });+});+rl.on('close', () => process.exit(0));++export { TOOLS, callTool };diff --git a/services/fleet-console/src/pool.js b/services/fleet-console/src/pool.jsnew file mode 100644index 000000000..55819ebc4--- /dev/null+++ b/services/fleet-console/src/pool.js@@ -0,0 +1,24 @@+/**+ * Bounded-concurrency map. Third-party hosts punish a fleet-wide fan-out, and+ * an unbounded Promise.all over 300 repositories is exactly that fan-out.+ */+export async function mapPool(items, limit, worker) {+ const list = [...items];+ const results = new Array(list.length);+ const width = Math.max(1, Math.min(limit, list.length));+ let cursor = 0;++ const run = async () => {+ for (;;) {+ const index = cursor++;+ if (index >= list.length) return;+ results[index] = await worker(list[index], index);+ }+ };++ await Promise.all(Array.from({ length: width }, run));+ return results;+}++/** Resolve after `ms`, used only for backoff between retries. */+export const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));diff --git a/services/fleet-console/src/probe.js b/services/fleet-console/src/probe.jsnew file mode 100644index 000000000..c4e0486b9--- /dev/null+++ b/services/fleet-console/src/probe.js@@ -0,0 +1,105 @@+/**+ * HTTP prober.+ *+ * "Is it up?" is not a boolean. A suspended hosting account, an expired+ * certificate, a domain that no longer resolves, and a login wall all present+ * as "not 200", and each needs a different fix. This classifies them so the+ * console reports a cause rather than a symptom.+ */++import { config } from './config.js';++/** Every state a probe can end in. The dashboard renders one chip per state. */+export const PROBE_STATES = {+ live: { label: 'Live', tone: 'good' },+ redirected: { label: 'Redirected', tone: 'good' },+ auth_required: { label: 'Auth required', tone: 'warn' },+ payment_required: { label: 'Payment required', tone: 'bad' },+ rate_limited: { label: 'Rate limited', tone: 'warn' },+ not_found: { label: 'Not found', tone: 'bad' },+ server_error: { label: 'Server error', tone: 'bad' },+ dns_failure: { label: 'DNS failure', tone: 'bad' },+ tls_failure: { label: 'TLS failure', tone: 'bad' },+ refused: { label: 'Connection refused', tone: 'bad' },+ timeout: { label: 'Timeout', tone: 'bad' },+ unreachable: { label: 'Unreachable', tone: 'bad' }+};++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 (code === 'ENOTFOUND' || code === 'EAI_AGAIN' || message.includes('getaddrinfo')) return 'dns_failure';+ if (code === 'ECONNREFUSED') return 'refused';+ if (code === 'ECONNRESET' || code === 'EPIPE') return 'unreachable';+ if (code?.startsWith?.('ERR_TLS') || code === 'CERT_HAS_EXPIRED' || code === 'DEPTH_ZERO_SELF_SIGNED_CERT' || message.includes('certificate')) {+ return 'tls_failure';+ }+ return 'unreachable';+};++const classifyStatus = (status, redirected) => {+ if (status === 402) return 'payment_required';+ if (status === 401 || status === 403) return 'auth_required';+ if (status === 429) return 'rate_limited';+ if (status === 404 || status === 410) return 'not_found';+ if (status >= 500) return 'server_error';+ if (status >= 200 && status < 400) return redirected ? 'redirected' : 'live';+ return 'unreachable';+};++/**+ * Probe one URL. Never throws.+ * @returns {Promise<{url:string,state:string,status:number|null,ms:number,finalUrl:string,redirected:boolean,detail:string}>}+ */+export async function probeUrl(url, { timeoutMs = config.probeTimeoutMs } = {}) {+ const started = Date.now();+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(), timeoutMs);++ const attempt = async (method) =>+ fetch(url, {+ method,+ redirect: 'follow',+ signal: controller.signal,+ headers: {+ 'user-agent': config.userAgent,+ accept: 'text/html,application/json,*/*'+ }+ });++ try {+ let res = await attempt('HEAD');+ // Plenty of static hosts answer HEAD with 403 or 405 while GET is fine.+ if (res.status === 405 || res.status === 501 || res.status === 403) {+ res = await attempt('GET');+ }+ const ms = Date.now() - started;+ const finalUrl = res.url || url;+ const redirected = Boolean(res.redirected) || (finalUrl && finalUrl !== url);+ return {+ url,+ state: classifyStatus(res.status, redirected),+ status: res.status,+ ms,+ finalUrl,+ redirected,+ detail: redirected && finalUrl !== url ? `redirects to ${finalUrl}` : ''+ };+ } catch (error) {+ return {+ url,+ state: classifyError(error),+ status: null,+ ms: Date.now() - started,+ finalUrl: url,+ redirected: false,+ detail: String(error?.cause?.code || error?.message || error).slice(0, 160)+ };+ } finally {+ clearTimeout(timer);+ }+}++export const isHealthyState = (state) => state === 'live' || state === 'redirected';+export const __testables = { classifyStatus, classifyError };diff --git a/services/fleet-console/src/registry.js b/services/fleet-console/src/registry.jsnew file mode 100644index 000000000..94aa4ea9b--- /dev/null+++ b/services/fleet-console/src/registry.js@@ -0,0 +1,130 @@+/**+ * npm registry verification.+ *+ * A README that says `npm install @scope/thing` when `@scope/thing` was never+ * published is worse than no install instructions: the reader concludes the+ * project is broken, and the maintainer never finds out because the build is+ * green and the tests pass. Nothing in a normal CI pipeline catches it, because+ * the failure lives in prose.+ *+ * This resolves every package name a repository advertises (its own manifest+ * name plus every `npm i`/`npm install`/`pnpm add`/`yarn add` line in the+ * README) against the real registry, and reports the ones that do not exist.+ */++import { config } from './config.js';+import { mapPool } from './pool.js';++const REGISTRY = 'https://registry.npmjs.org';++const PACKAGE_NAME = /^(?:@[a-z0-9-*~][a-z0-9-*._~]*\/)?[a-z0-9-~][a-z0-9-._~]*$/;++/** Flags and non-package arguments that appear on an install line. */+const NOT_A_PACKAGE = new Set(['-g', '--global', '-D', '--save-dev', '--save', '-S', '--save-exact', '-E', 'npm', 'yarn', 'pnpm', 'bun', 'npx', 'install', 'add', 'i']);++const stripVersionRange = (spec) => {+ if (spec.startsWith('@')) {+ const at = spec.indexOf('@', 1);+ return at === -1 ? spec : spec.slice(0, at);+ }+ const at = spec.indexOf('@');+ return at === -1 ? spec : spec.slice(0, at);+};++/**+ * Package names a README tells the reader to install.+ * @returns {string[]}+ */+export function advertisedPackages(markdown) {+ const names = new Set();+ const text = String(markdown || '');+ for (const match of text.matchAll(/\b(?:npm\s+(?:i|install)|yarn\s+add|pnpm\s+(?:i|install|add)|bun\s+add)\s+([^\n`|]+)/gi)) {+ for (const token of match[1].split(/\s+/)) {+ const raw = token.trim().replace(/^["']|["'],?$/g, '');+ if (!raw || raw.startsWith('-') || NOT_A_PACKAGE.has(raw)) continue;+ // Local paths, tarballs and git specifiers are not registry lookups.+ if (raw.includes('/') && !raw.startsWith('@')) continue;+ if (raw.startsWith('.') || raw.includes(':') || raw.endsWith('.tgz')) continue;+ const name = stripVersionRange(raw);+ if (PACKAGE_NAME.test(name)) names.add(name);+ }+ }+ return [...names];+}++const cache = new Map();++/**+ * Look one package up in the registry.+ * @returns {Promise<{name:string, published:boolean, latest:string, deprecated:boolean, modified:string, error:string}>}+ */+export async function lookupPackage(name) {+ if (cache.has(name)) return cache.get(name);+ const result = { name, published: false, latest: '', deprecated: false, modified: '', error: '' };+ try {+ const res = await fetch(`${REGISTRY}/${name.replace('/', '%2F')}`, {+ headers: { accept: 'application/vnd.npm.install-v1+json', 'user-agent': config.userAgent }+ });+ if (res.status === 404) {+ cache.set(name, result);+ return result;+ }+ if (!res.ok) {+ result.error = `registry responded ${res.status}`;+ return result;+ }+ const body = await res.json();+ const latest = body?.['dist-tags']?.latest || '';+ result.published = Boolean(latest);+ result.latest = latest;+ result.modified = body?.modified || '';+ result.deprecated = Boolean(latest && body?.versions?.[latest]?.deprecated);+ } catch (error) {+ result.error = String(error?.message || error).slice(0, 160);+ }+ cache.set(name, result);+ return result;+}++/**+ * Verify everything a repository claims is installable.+ *+ * @param {object} input+ * @param {object|null} input.manifest parsed package.json+ * @param {string} input.readme+ * @returns {Promise<{checked:{name:string,published:boolean,latest:string,deprecated:boolean,role:string}[], missing:string[], ownPackage:object|null}>}+ */+export async function verifyPackages({ manifest, readme }) {+ const names = new Map();+ const own = manifest && !manifest.private && typeof manifest.name === 'string' && PACKAGE_NAME.test(manifest.name) ? manifest.name : '';+ if (own) names.set(own, 'manifest');+ for (const name of advertisedPackages(readme)) {+ // Only judge packages this owner could plausibly publish plus the repo's own+ // name. Third-party dependencies in an install line are not this repo's problem.+ if (!names.has(name)) names.set(name, 'readme');+ }++ const entries = [...names];+ const looked = await mapPool(entries, 5, async ([name, role]) => {+ const info = await lookupPackage(name);+ return { ...info, role };+ });++ const checked = looked.map((info) => ({+ name: info.name,+ published: info.published,+ latest: info.latest,+ deprecated: info.deprecated,+ role: info.role,+ error: info.error+ }));++ return {+ checked,+ missing: checked.filter((entry) => !entry.published && !entry.error).map((entry) => entry.name),+ ownPackage: own ? checked.find((entry) => entry.name === own) || null : null,+ ownVersion: own && manifest?.version ? String(manifest.version) : ''+ };+}++export const __testables = { stripVersionRange, PACKAGE_NAME };diff --git a/services/fleet-console/src/scan.js b/services/fleet-console/src/scan.jsnew file mode 100644index 000000000..0417da125--- /dev/null+++ b/services/fleet-console/src/scan.js@@ -0,0 +1,139 @@+/**+ * The scan orchestrator.+ *+ * One pass: enumerate the fleet, gather each repository's own claims, probe+ * those claims against the live internet, verify its packages against the npm+ * registry, and score the result. Progress is observable while it runs, because+ * a full fleet scan takes minutes and a spinner with no numbers is not a+ * loading state.+ */++import { config } from './config.js';+import { mapPool } from './pool.js';+import { listRepos, fetchReadme, fetchPackageJson, fetchPagesUrl, fetchRootEntries, rateLimit } from './github.js';+import { extractReadmeLinks, deploymentCandidates } from './extract-urls.js';+import { probeUrl } from './probe.js';+import { verifyPackages } from './registry.js';+import { scoreRepo, summarise } from './score.js';++/** Live progress for the dashboard's scanning state. */+export const progress = {+ running: false,+ startedAt: null,+ finishedAt: null,+ total: 0,+ done: 0,+ current: '',+ phase: 'idle',+ error: '',+ lastDurationMs: 0+};++const DOC_DIRS = new Set(['docs', 'doc', 'documentation', 'website', 'site']);++async function gatherRepo(repo) {+ const [readme, manifest, entries, pagesUrl] = await Promise.all([+ fetchReadme(repo.fullName),+ fetchPackageJson(repo.fullName, repo.defaultBranch),+ fetchRootEntries(repo.fullName, repo.defaultBranch),+ repo.hasPages ? fetchPagesUrl(repo.fullName) : Promise.resolve('')+ ]);++ const links = extractReadmeLinks(readme);+ const candidates = deploymentCandidates({+ repoName: repo.name,+ homepage: repo.homepage,+ pagesUrl,+ manifestHomepage: typeof manifest?.homepage === 'string' ? manifest.homepage : '',+ links+ });++ const candidateUrls = new Set(candidates.map((entry) => entry.url));+ // Check links that are not already covered by a deployment probe.+ const linkTargets = links+ .map((link) => link.url)+ .filter((url) => !candidateUrls.has(url))+ .slice(0, config.maxLinksPerRepo);++ const [deployments, linkResults, packages] = await Promise.all([+ mapPool(candidates, 4, async (candidate) => ({ ...(await probeUrl(candidate.url)), why: candidate.why })),+ mapPool(linkTargets, 4, (url) => probeUrl(url)),+ verifyPackages({ manifest, readme })+ ]);++ return {+ ...repo,+ pagesUrl,+ readmeBytes: Buffer.byteLength(readme, 'utf8'),+ hasDocsDir: entries.some((entry) => entry.type === 'dir' && DOC_DIRS.has(entry.name.toLowerCase())),+ packageName: manifest?.name || '',+ packageVersion: manifest?.version ? String(manifest.version) : '',+ deployments,+ links: linkResults,+ packages+ };+}++/**+ * Run one full fleet scan.+ * @returns {Promise<object>} the snapshot+ */+export async function runScan({ owner = config.owner, limit = config.maxRepos } = {}) {+ if (progress.running) throw new Error('a scan is already running');++ const startedAt = Date.now();+ Object.assign(progress, {+ running: true,+ startedAt: new Date(startedAt).toISOString(),+ finishedAt: null,+ total: 0,+ done: 0,+ current: '',+ phase: 'enumerating',+ error: ''+ });++ try {+ const all = await listRepos(owner);+ const selected = all.slice(0, limit);+ progress.total = selected.length;+ progress.phase = 'scanning';++ const scanned = await mapPool(selected, config.githubConcurrency, async (repo) => {+ progress.current = repo.name;+ try {+ const gathered = await gatherRepo(repo);+ const { score, grade, checks } = scoreRepo(gathered);+ return { ...gathered, score, grade, checks };+ } catch (error) {+ return { ...repo, score: null, grade: null, checks: [], scanError: String(error?.message || error).slice(0, 200) };+ } finally {+ progress.done += 1;+ }+ });++ const snapshot = {+ owner,+ generatedAt: new Date().toISOString(),+ durationMs: Date.now() - startedAt,+ partial: Boolean(rateLimit.exhausted) || selected.length < all.length,+ totalOwned: all.length,+ authenticated: Boolean(config.githubToken),+ rateLimit: { limit: rateLimit.limit, remaining: rateLimit.remaining, resetAt: rateLimit.resetAt },+ summary: summarise(scanned),+ repos: scanned+ };++ progress.lastDurationMs = snapshot.durationMs;+ progress.phase = 'idle';+ return snapshot;+ } catch (error) {+ progress.error = String(error?.message || error);+ progress.phase = 'failed';+ throw error;+ } finally {+ progress.running = false;+ progress.finishedAt = new Date().toISOString();+ progress.current = '';+ }+}diff --git a/services/fleet-console/src/score.js b/services/fleet-console/src/score.jsnew file mode 100644index 000000000..9251265ee--- /dev/null+++ b/services/fleet-console/src/score.js@@ -0,0 +1,196 @@+/**+ * The scoring model.+ *+ * Every check carries a weight and returns one of pass / warn / fail / skip,+ * together with the evidence that produced it. Skipped checks leave the+ * denominator, so a library with nothing deployed is not punished for having+ * nothing deployed, and a repository that publishes no package is not punished+ * for that either. The score answers one question: "of the promises this+ * repository makes, how many does it keep?"+ */++import { isHealthyState } from './probe.js';++export const GRADES = [+ { min: 90, grade: 'A', tone: 'good', label: 'Healthy' },+ { min: 75, grade: 'B', tone: 'good', label: 'Solid' },+ { min: 60, grade: 'C', tone: 'warn', label: 'Needs work' },+ { min: 40, grade: 'D', tone: 'warn', label: 'Degraded' },+ { min: 0, grade: 'F', tone: 'bad', label: 'Broken' }+];++export const gradeFor = (score) => GRADES.find((entry) => score >= entry.min) || GRADES[GRADES.length - 1];++const VALUE = { pass: 1, warn: 0.5, fail: 0, skip: null };++const DAY = 24 * 60 * 60 * 1000;++const check = (id, title, weight, status, evidence, fix = '') => ({ id, title, weight, status, evidence, fix });++/**+ * @param {object} repo repository facts gathered by the scanner+ * @returns {{score:number, grade:object, checks:object[]}}+ */+export function scoreRepo(repo) {+ const checks = [];++ checks.push(+ repo.description+ ? check('description', 'Has a description', 4, 'pass', repo.description)+ : check('description', 'Has a description', 4, 'fail', 'The repository has no description', 'Set the About description on GitHub.')+ );++ const readmeBytes = repo.readmeBytes || 0;+ checks.push(+ readmeBytes >= 600+ ? check('readme', 'Has a real README', 8, 'pass', `${readmeBytes.toLocaleString()} bytes`)+ : readmeBytes > 0+ ? check('readme', 'Has a real README', 8, 'warn', `Only ${readmeBytes} bytes, which is a stub`, 'Explain what it does, how to install it, and one runnable example.')+ : check('readme', 'Has a real README', 8, 'fail', 'No README found', 'Add a README.md.')+ );++ checks.push(+ repo.license+ ? check('license', 'Declares a license', 6, 'pass', repo.license)+ : check('license', 'Declares a license', 6, 'fail', 'GitHub detects no license', 'Add a LICENSE file GitHub can classify.')+ );++ checks.push(+ repo.hasDocsDir+ ? check('docs', 'Ships documentation beyond the README', 8, 'pass', 'A docs/ directory is present')+ : readmeBytes >= 3000+ ? check('docs', 'Ships documentation beyond the README', 8, 'warn', 'No docs/ directory, but the README is substantial')+ : check('docs', 'Ships documentation beyond the README', 8, 'fail', 'No docs/ directory and a thin README', 'Add docs/ with a getting-started page and examples.')+ );++ // Deployment. Skipped entirely when the repository never claims to be running.+ const deployments = repo.deployments || [];+ if (deployments.length === 0) {+ checks.push(check('deployment', 'Claimed deployments respond', 20, 'skip', 'This repository does not advertise a deployment'));+ } else {+ const healthy = deployments.filter((entry) => isHealthyState(entry.state));+ const ratio = healthy.length / deployments.length;+ const summary = `${healthy.length}/${deployments.length} responding`;+ const broken = deployments.filter((entry) => !isHealthyState(entry.state));+ const detail = broken.length ? `${summary}. Failing: ${broken.map((entry) => `${entry.url} (${entry.state})`).join(', ')}` : summary;+ checks.push(+ ratio === 1+ ? check('deployment', 'Claimed deployments respond', 20, 'pass', detail)+ : ratio > 0+ ? check('deployment', 'Claimed deployments respond', 20, 'warn', detail, 'Repoint or remove the URLs that no longer serve.')+ : check('deployment', 'Claimed deployments respond', 20, 'fail', detail, 'Every advertised URL is down. Redeploy or delete the claim.')+ );+ }++ // README link rot.+ const links = repo.links || [];+ if (links.length === 0) {+ checks.push(check('links', 'README links resolve', 12, 'skip', 'No external links to check'));+ } else {+ const dead = links.filter((entry) => !isHealthyState(entry.state) && entry.state !== 'auth_required' && entry.state !== 'rate_limited');+ const detail = dead.length ? `${dead.length}/${links.length} dead: ${dead.slice(0, 4).map((entry) => entry.url).join(', ')}` : `${links.length} checked, all resolve`;+ checks.push(+ dead.length === 0+ ? check('links', 'README links resolve', 12, 'pass', detail)+ : dead.length / links.length <= 0.25+ ? check('links', 'README links resolve', 12, 'warn', detail, 'Fix or drop the dead links.')+ : check('links', 'README links resolve', 12, 'fail', detail, 'Most external links are dead. The README needs a pass.')+ );+ }++ // Advertised packages actually exist.+ const packages = repo.packages || { checked: [], missing: [] };+ if (!packages.checked.length) {+ checks.push(check('packages', 'Advertised packages exist on npm', 15, 'skip', 'This repository advertises no npm package'));+ } else if (packages.missing.length) {+ checks.push(+ check(+ 'packages',+ 'Advertised packages exist on npm',+ 15,+ 'fail',+ `${packages.missing.length} of ${packages.checked.length} were never published: ${packages.missing.join(', ')}`,+ 'Publish them or correct the install instructions. Readers currently hit a 404.'+ )+ );+ } else {+ const deprecated = packages.checked.filter((entry) => entry.deprecated);+ checks.push(+ deprecated.length+ ? check('packages', 'Advertised packages exist on npm', 15, 'warn', `Published, but deprecated: ${deprecated.map((entry) => entry.name).join(', ')}`)+ : check('packages', 'Advertised packages exist on npm', 15, 'pass', `${packages.checked.length} verified against the registry`)+ );+ }++ // Published version matches the manifest.+ if (packages.ownPackage?.published && repo.packageVersion) {+ const same = packages.ownPackage.latest === repo.packageVersion;+ checks.push(+ same+ ? check('release-sync', 'npm matches the committed version', 6, 'pass', `both at ${repo.packageVersion}`)+ : check('release-sync', 'npm matches the committed version', 6, 'warn', `manifest ${repo.packageVersion}, registry ${packages.ownPackage.latest}`, 'Publish the current version or bump the manifest.')+ );+ } else {+ checks.push(check('release-sync', 'npm matches the committed version', 6, 'skip', 'Nothing published to compare against'));+ }++ checks.push(+ repo.topics?.length >= 3+ ? check('topics', 'Discoverable by topic', 3, 'pass', repo.topics.slice(0, 8).join(', '))+ : repo.topics?.length+ ? check('topics', 'Discoverable by topic', 3, 'warn', `only ${repo.topics.length} topic(s)`)+ : check('topics', 'Discoverable by topic', 3, 'fail', 'No topics set', 'Add topics so the repository is findable.')+ );++ const pushedAt = repo.pushedAt ? Date.parse(repo.pushedAt) : NaN;+ const ageDays = Number.isFinite(pushedAt) ? Math.floor((Date.now() - pushedAt) / DAY) : null;+ checks.push(+ ageDays === null+ ? check('activity', 'Recently touched', 8, 'skip', 'No push timestamp')+ : ageDays <= 120+ ? check('activity', 'Recently touched', 8, 'pass', `last push ${ageDays} day(s) ago`)+ : ageDays <= 400+ ? check('activity', 'Recently touched', 8, 'warn', `last push ${ageDays} day(s) ago`)+ : check('activity', 'Recently touched', 8, 'fail', `last push ${ageDays} day(s) ago`, 'Archive it, or ship the fix it has been waiting for.')+ );++ const graded = checks.filter((entry) => VALUE[entry.status] !== null);+ const total = graded.reduce((sum, entry) => sum + entry.weight, 0);+ const earned = graded.reduce((sum, entry) => sum + entry.weight * VALUE[entry.status], 0);+ const score = total === 0 ? 0 : Math.round((earned / total) * 100);++ return { score, grade: gradeFor(score), checks };+}++/** Fleet-level rollup used by the dashboard header and /api/fleet. */+export function summarise(repos) {+ const scored = repos.filter((repo) => typeof repo.score === 'number');+ const scores = scored.map((repo) => repo.score).sort((a, b) => a - b);+ const median = scores.length ? (scores.length % 2 ? scores[(scores.length - 1) / 2] : Math.round((scores[scores.length / 2 - 1] + scores[scores.length / 2]) / 2)) : 0;++ const deployments = repos.flatMap((repo) => repo.deployments || []);+ const links = repos.flatMap((repo) => repo.links || []);+ const missingPackages = repos.flatMap((repo) => (repo.packages?.missing || []).map((name) => ({ repo: repo.name, name })));++ const byGrade = {};+ for (const entry of GRADES) byGrade[entry.grade] = 0;+ for (const repo of scored) byGrade[repo.grade.grade] = (byGrade[repo.grade.grade] || 0) + 1;++ return {+ repos: repos.length,+ stars: repos.reduce((sum, repo) => sum + (repo.stars || 0), 0),+ medianScore: median,+ averageScore: scored.length ? Math.round(scored.reduce((sum, repo) => sum + repo.score, 0) / scored.length) : 0,+ byGrade,+ deployments: {+ total: deployments.length,+ healthy: deployments.filter((entry) => isHealthyState(entry.state)).length,+ byState: deployments.reduce((acc, entry) => ({ ...acc, [entry.state]: (acc[entry.state] || 0) + 1 }), {})+ },+ links: {+ total: links.length,+ dead: links.filter((entry) => !isHealthyState(entry.state) && entry.state !== 'auth_required' && entry.state !== 'rate_limited').length+ },+ missingPackages+ };+}diff --git a/services/fleet-console/src/server.js b/services/fleet-console/src/server.jsnew file mode 100644index 000000000..41721e289--- /dev/null+++ b/services/fleet-console/src/server.js@@ -0,0 +1,209 @@+#!/usr/bin/env node+/**+ * Fleet Console HTTP server.+ *+ * Routes:+ * GET / the dashboard, or the scanning state before the first snapshot+ * GET /r/:repo one repository with every measurement behind its score+ * GET /docs how the score is computed and how to embed a badge+ * GET /api/fleet the whole snapshot+ * GET /api/repo/:repo one repository+ * GET /api/status scan progress, safe to poll+ * GET /api/attention only what is broken, ranked, for automation+ * POST /api/scan trigger a scan (requires FLEET_SCAN_TOKEN)+ * GET /badge/fleet.svg fleet median badge+ * GET /badge/:repo.svg per-repository health badge+ * GET /badge/:repo/deployment.svg+ * GET /healthz liveness+ */++import { createServer } from 'node:http';+import { config } from './config.js';+import { runScan, progress } from './scan.js';+import * as store from './store.js';+import { dashboardPage, scanningPage } from './views/dashboard.js';+import { repoPage, notFoundPage } from './views/repo.js';+import { docsPage } from './views/docs.js';+import { repoBadge, deploymentBadge, fleetBadge } from './badge.js';++const send = (res, status, body, headers = {}) => {+ res.writeHead(status, {+ 'content-length': Buffer.byteLength(body),+ 'x-content-type-options': 'nosniff',+ 'referrer-policy': 'no-referrer',+ ...headers+ });+ res.end(body);+};++const html = (res, status, body) => send(res, status, body, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'public, max-age=60' });++const json = (res, status, value, { maxAge = 60 } = {}) =>+ send(res, status, JSON.stringify(value, null, 2), {+ 'content-type': 'application/json; charset=utf-8',+ 'cache-control': `public, max-age=${maxAge}`,+ 'access-control-allow-origin': '*'+ });++const svg = (res, body) =>+ send(res, 200, body, {+ 'content-type': 'image/svg+xml; charset=utf-8',+ // Badges are embedded in READMEs that GitHub proxies; a short TTL keeps them fresh without hammering.+ 'cache-control': 'public, max-age=900, s-maxage=900',+ 'access-control-allow-origin': '*'+ });++/** Only what is broken, ranked worst first. Built for automation, not for reading. */+function attention(snapshot) {+ const items = [];+ for (const repo of snapshot.repos) {+ for (const deployment of repo.deployments || []) {+ if (deployment.state === 'live' || deployment.state === 'redirected') continue;+ items.push({ repo: repo.name, severity: 'high', kind: 'deployment_down', target: deployment.url, state: deployment.state, detail: deployment.detail || deployment.why });+ }+ for (const name of repo.packages?.missing || []) {+ items.push({ repo: repo.name, severity: 'high', kind: 'package_unpublished', target: name, state: 'not_found', detail: 'advertised for install but absent from the npm registry' });+ }+ for (const link of repo.links || []) {+ if (link.state === 'live' || link.state === 'redirected' || link.state === 'auth_required' || link.state === 'rate_limited') continue;+ items.push({ repo: repo.name, severity: 'low', kind: 'dead_link', target: link.url, state: link.state, detail: link.detail || '' });+ }+ for (const check of repo.checks || []) {+ if (check.status !== 'fail' || check.id === 'deployment' || check.id === 'packages' || check.id === 'links') continue;+ items.push({ repo: repo.name, severity: 'medium', kind: `check_failed:${check.id}`, target: repo.name, state: 'fail', detail: check.fix || check.evidence });+ }+ }+ const rank = { high: 0, medium: 1, low: 2 };+ items.sort((a, b) => rank[a.severity] - rank[b.severity] || a.repo.localeCompare(b.repo));+ return { generatedAt: snapshot.generatedAt, owner: snapshot.owner, count: items.length, items };+}++/** A repository without the noisy full probe payload, for list endpoints. */+const slim = (repo) => ({+ name: repo.name,+ description: repo.description,+ stars: repo.stars,+ language: repo.language,+ score: repo.score,+ grade: repo.grade?.grade || null,+ url: repo.htmlUrl,+ live: (repo.deployments || []).filter((entry) => entry.state === 'live' || entry.state === 'redirected').map((entry) => entry.url),+ broken: (repo.deployments || []).filter((entry) => entry.state !== 'live' && entry.state !== 'redirected').map((entry) => ({ url: entry.url, state: entry.state })),+ unpublishedPackages: repo.packages?.missing || []+});++async function triggerScan(reason) {+ if (progress.running) return;+ try {+ const snapshot = await runScan();+ await store.save(snapshot);+ console.log(`[scan] ${reason}: ${snapshot.repos.length} repos in ${(snapshot.durationMs / 1000).toFixed(1)}s, median ${snapshot.summary.medianScore}`);+ } catch (error) {+ console.error(`[scan] ${reason} failed:`, error?.message || error);+ }+}++const handler = async (req, res) => {+ const url = new URL(req.url, `http://${req.headers.host || 'localhost'}`);+ const path = url.pathname.replace(/\/+$/, '') || '/';+ const snapshot = store.getSnapshot();++ if (path === '/healthz') {+ return json(res, 200, { ok: true, hasSnapshot: Boolean(snapshot), scanning: progress.running, owner: config.owner }, { maxAge: 0 });+ }++ if (path === '/api/status') {+ return json(res, 200, { hasSnapshot: Boolean(snapshot), generatedAt: snapshot?.generatedAt || null, progress, owner: config.owner, authenticated: Boolean(config.githubToken) }, { maxAge: 0 });+ }++ if (path === '/api/scan') {+ if (req.method !== 'POST') return json(res, 405, { error: 'use POST' }, { maxAge: 0 });+ if (!config.scanToken) return json(res, 403, { error: 'FLEET_SCAN_TOKEN is not configured, so on-demand scans are disabled' }, { maxAge: 0 });+ const supplied = req.headers.authorization?.replace(/^Bearer\s+/i, '') || url.searchParams.get('token') || '';+ if (supplied !== config.scanToken) return json(res, 401, { error: 'bad token' }, { maxAge: 0 });+ if (progress.running) return json(res, 409, { error: 'a scan is already running', progress }, { maxAge: 0 });+ triggerScan('on demand');+ return json(res, 202, { started: true, progress }, { maxAge: 0 });+ }++ if (path === '/badge/fleet.svg') return svg(res, fleetBadge(snapshot));++ const deploymentBadgeMatch = path.match(/^\/badge\/([^/]+)\/deployment\.svg$/);+ if (deploymentBadgeMatch) return svg(res, deploymentBadge(store.findRepo(decodeURIComponent(deploymentBadgeMatch[1]))));++ const badgeMatch = path.match(/^\/badge\/(.+)\.svg$/);+ if (badgeMatch) return svg(res, repoBadge(store.findRepo(decodeURIComponent(badgeMatch[1]))));++ if (path === '/api/fleet') {+ if (!snapshot) return json(res, 503, { error: 'no snapshot yet', progress }, { maxAge: 0 });+ const full = url.searchParams.get('full') === '1';+ return json(res, 200, full ? snapshot : { ...snapshot, repos: snapshot.repos.map(slim) });+ }++ if (path === '/api/attention') {+ if (!snapshot) return json(res, 503, { error: 'no snapshot yet', progress }, { maxAge: 0 });+ return json(res, 200, attention(snapshot));+ }++ const apiRepo = path.match(/^\/api\/repo\/(.+)$/);+ if (apiRepo) {+ const repo = store.findRepo(decodeURIComponent(apiRepo[1]));+ if (!repo) return json(res, 404, { error: 'no such repository in the current snapshot' }, { maxAge: 0 });+ return json(res, 200, { ...repo, history: store.historyFor(repo.name) });+ }++ if (path === '/docs') return html(res, 200, docsPage({ owner: config.owner, snapshot }));++ const repoPath = path.match(/^\/r\/(.+)$/);+ if (repoPath) {+ const name = decodeURIComponent(repoPath[1]);+ const repo = store.findRepo(name);+ if (!repo) return html(res, 404, notFoundPage({ owner: config.owner, name }));+ return html(res, 200, repoPage({ repo, owner: config.owner, history: store.historyFor(repo.name) }));+ }++ if (path === '/') {+ if (!snapshot) return html(res, 200, scanningPage({ owner: config.owner, progress, authenticated: Boolean(config.githubToken) }));+ return html(res, 200, dashboardPage({ snapshot, history: store.getHistory() }));+ }++ return html(res, 404, notFoundPage({ owner: config.owner, name: path.slice(1) }));+};++async function main() {+ await store.load();++ const server = createServer((req, res) => {+ handler(req, res).catch((error) => {+ console.error('[request]', req.method, req.url, error?.message || error);+ if (!res.headersSent) json(res, 500, { error: 'internal error' }, { maxAge: 0 });+ else res.end();+ });+ });++ server.listen(config.port, () => {+ console.log(`[fleet-console] listening on :${config.port} for owner ${config.owner}${config.githubToken ? '' : ' (unauthenticated GitHub access)'}`);+ });++ if (config.scanOnBoot && !store.getSnapshot()) triggerScan('boot');+ if (config.scanIntervalMs > 0) {+ setInterval(() => triggerScan('scheduled'), config.scanIntervalMs).unref?.();+ }++ for (const signal of ['SIGTERM', 'SIGINT']) {+ process.on(signal, () => {+ console.log(`[fleet-console] ${signal}, closing`);+ server.close(() => process.exit(0));+ setTimeout(() => process.exit(0), 8000).unref();+ });+ }+}++if (import.meta.url === `file://${process.argv[1]}`) {+ main().catch((error) => {+ console.error('[fleet-console] failed to start:', error);+ process.exit(1);+ });+}++export { handler, attention, slim };diff --git a/services/fleet-console/src/store.js b/services/fleet-console/src/store.jsnew file mode 100644index 000000000..7dee59f60--- /dev/null+++ b/services/fleet-console/src/store.js@@ -0,0 +1,80 @@+/**+ * Snapshot store.+ *+ * The current snapshot lives in memory and is mirrored to disk so a restart+ * comes back with data instead of an empty dashboard. A compact history of+ * previous scans is kept alongside it, because a score is far more useful as a+ * trend than as a number.+ */++import { mkdir, readFile, writeFile, rename } from 'node:fs/promises';+import { join } from 'node:path';+import { config } from './config.js';++const SNAPSHOT = 'snapshot.json';+const HISTORY = 'history.json';++let current = null;+let history = [];++const path = (name) => join(config.dataDir, name);++const writeAtomic = async (name, value) => {+ await mkdir(config.dataDir, { recursive: true });+ const target = path(name);+ const temp = `${target}.${process.pid}.tmp`;+ await writeFile(temp, JSON.stringify(value), 'utf8');+ await rename(temp, target);+};++const readJson = async (name) => {+ try {+ return JSON.parse(await readFile(path(name), 'utf8'));+ } catch {+ return null;+ }+};++/** Load whatever the previous process left behind. Safe to call once at boot. */+export async function load() {+ current = await readJson(SNAPSHOT);+ const stored = await readJson(HISTORY);+ history = Array.isArray(stored) ? stored : [];+ return current;+}++export const getSnapshot = () => current;+export const getHistory = () => history;++/** History reduced to one repository, oldest first. */+export const historyFor = (name) =>+ history+ .map((entry) => ({ at: entry.at, score: entry.scores?.[name] }))+ .filter((entry) => typeof entry.score === 'number');++/** Persist a completed scan and append its compact form to the history. */+export async function save(snapshot) {+ current = snapshot;++ const scores = {};+ for (const repo of snapshot.repos) {+ if (typeof repo.score === 'number') scores[repo.name] = repo.score;+ }+ history.push({+ at: snapshot.generatedAt,+ medianScore: snapshot.summary.medianScore,+ averageScore: snapshot.summary.averageScore,+ healthyDeployments: snapshot.summary.deployments.healthy,+ totalDeployments: snapshot.summary.deployments.total,+ deadLinks: snapshot.summary.links.dead,+ missingPackages: snapshot.summary.missingPackages.length,+ scores+ });+ if (history.length > config.historyLimit) history = history.slice(-config.historyLimit);++ await writeAtomic(SNAPSHOT, snapshot);+ await writeAtomic(HISTORY, history);+ return snapshot;+}++export const findRepo = (name) => current?.repos?.find((repo) => repo.name.toLowerCase() === String(name || '').toLowerCase()) || null;diff --git a/services/fleet-console/src/views/dashboard.js b/services/fleet-console/src/views/dashboard.jsnew file mode 100644index 000000000..b387871d0--- /dev/null+++ b/services/fleet-console/src/views/dashboard.js@@ -0,0 +1,255 @@+/**+ * The fleet dashboard: header rollup, filter toolbar, and one card per+ * repository. Filtering and sorting run client side over data already in the+ * document, so there is no round trip and the page keeps working with the+ * network gone.+ */++import { esc, attr, ago, page, ring, sparkline } from './html.js';+import { PROBE_STATES } from '../probe.js';++const tone = (value, good, warn) => (value >= good ? 'good' : value >= warn ? 'warn' : 'bad');++function statTiles(summary, history) {+ const healthPct = summary.deployments.total ? Math.round((summary.deployments.healthy / summary.deployments.total) * 100) : null;+ const tiles = [+ { k: 'Repositories', v: summary.repos.toLocaleString(), s: `${summary.stars.toLocaleString()} stars total` },+ { k: 'Median health', v: summary.medianScore, s: `mean ${summary.averageScore}`, cls: tone(summary.medianScore, 75, 55) },+ {+ k: 'Live deployments',+ v: healthPct === null ? 'n/a' : `${healthPct}%`,+ s: `${summary.deployments.healthy} of ${summary.deployments.total} advertised URLs respond`,+ cls: healthPct === null ? '' : tone(healthPct, 90, 65)+ },+ {+ k: 'Dead README links',+ v: summary.links.dead.toLocaleString(),+ s: `${summary.links.total.toLocaleString()} checked`,+ cls: summary.links.dead === 0 ? 'good' : summary.links.dead <= 5 ? 'warn' : 'bad'+ },+ {+ k: 'Unpublished packages',+ v: summary.missingPackages.length.toLocaleString(),+ s: 'advertised in a README but absent from npm',+ cls: summary.missingPackages.length === 0 ? 'good' : 'bad'+ }+ ];++ 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>`+ : '';++ 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')}+${trend}+</section>`;+}++function repoCard(repo) {+ const chips = [];+ const deployments = repo.deployments || [];+ if (deployments.length) {+ const bad = deployments.filter((entry) => entry.state !== 'live' && entry.state !== 'redirected');+ chips.push(+ bad.length === 0+ ? `<span class="chip good">${deployments.length} deployment${deployments.length === 1 ? '' : 's'} live</span>`+ : `<span class="chip bad">${bad.length}/${deployments.length} deployment${deployments.length === 1 ? '' : 's'} down</span>`+ );+ }+ const missing = repo.packages?.missing || [];+ if (missing.length) chips.push(`<span class="chip bad">${missing.length} package${missing.length === 1 ? '' : 's'} unpublished</span>`);+ const dead = (repo.links || []).filter((entry) => entry.state !== 'live' && entry.state !== 'redirected' && entry.state !== 'auth_required' && entry.state !== 'rate_limited');+ if (dead.length) chips.push(`<span class="chip warn">${dead.length} dead link${dead.length === 1 ? '' : 's'}</span>`);+ if (!repo.license) chips.push('<span class="chip warn">No license</span>');+ if (!repo.hasDocsDir) chips.push('<span class="chip mute">No docs/</span>');+ if (repo.scanError) chips.push('<span class="chip bad">Scan error</span>');+ if (!chips.length) chips.push('<span class="chip good">All checks pass</span>');++ const searchBlob = [repo.name, repo.description, repo.language, ...(repo.topics || [])].join(' ').toLowerCase();+ const hasProblem = missing.length || dead.length || deployments.some((entry) => entry.state !== 'live' && entry.state !== 'redirected');++ return `<article class="card" data-name="${attr(repo.name.toLowerCase())}" data-search="${attr(searchBlob)}"+ data-score="${attr(repo.score ?? -1)}" data-stars="${attr(repo.stars)}" data-grade="${attr(repo.grade?.grade || '?')}"+ data-pushed="${attr(repo.pushedAt || '')}" data-problem="${hasProblem ? '1' : '0'}">+ ${ring(repo.score, repo.grade)}+ <div class="body">+ <h3><a href="/r/${encodeURIComponent(repo.name)}">${esc(repo.name)}</a></h3>+ <p>${esc(repo.description || 'No description set.')}</p>+ <div class="meta">+ <span>${repo.stars.toLocaleString()} stars</span>+ ${repo.language ? `<span>${esc(repo.language)}</span>` : ''}+ <span>updated ${esc(ago(repo.pushedAt))}</span>+ </div>+ <div class="chips">${chips.join('')}</div>+ </div>+</article>`;+}++function attentionPanel(snapshot) {+ const rows = [];+ for (const repo of snapshot.repos) {+ for (const deployment of repo.deployments || []) {+ if (deployment.state === 'live' || deployment.state === 'redirected') continue;+ rows.push({ repo: repo.name, kind: 'Deployment', state: deployment.state, detail: deployment.url, extra: deployment.detail || deployment.why });+ }+ for (const name of repo.packages?.missing || []) {+ rows.push({ repo: repo.name, kind: 'Package', state: 'not_found', detail: name, extra: 'advertised for install but never published' });+ }+ }+ if (!rows.length) {+ return `<section class="panel"><h2>Needs attention</h2><div class="pad" style="color:var(--muted)">+Nothing is broken. Every advertised deployment responds and every advertised package exists.</div></section>`;+ }+ rows.sort((a, b) => a.repo.localeCompare(b.repo));+ return `<section class="panel"><h2>Needs attention (${rows.length})</h2>+<div class="scroll"><table>+<thead><tr><th>Repository</th><th>What</th><th>State</th><th>Target</th><th>Detail</th></tr></thead>+<tbody>+${rows+ .map(+ (row) => `<tr>+ <td><a href="/r/${encodeURIComponent(row.repo)}">${esc(row.repo)}</a></td>+ <td>${esc(row.kind)}</td>+ <td><span class="chip ${PROBE_STATES[row.state]?.tone || 'bad'}">${esc(PROBE_STATES[row.state]?.label || row.state)}</span></td>+ <td class="mono">${esc(row.detail)}</td>+ <td style="color:var(--muted)">${esc(row.extra || '')}</td>+</tr>`+ )+ .join('\n')}+</tbody></table></div></section>`;+}++/** 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 body = `<section class="hero">+ <h1>${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 and+ packages each one advertises, and checks them against the live internet. The first pass takes a few minutes.</p>+</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>+ <p class="mono" id="status" style="margin:12px 0 0; color:var(--muted)">+ ${progress.running ? `${progress.done} / ${progress.total || '?'} repositories${progress.current ? ` — currently ${esc(progress.current)}` : ''}` : progress.error ? `Last scan failed: ${esc(progress.error)}` : 'Idle. The scheduled scan will start shortly.'}+ </p>+</div></section>`;++ return page({+ title: `Fleet Console — ${owner}`,+ description: `Live health console for the open-source fleet owned by ${owner}.`,+ owner,+ body,+ script: `+(function(){+ var status=document.getElementById('status'), bar=document.querySelector('.bar span'), meter=document.querySelector('.bar');+ function tick(){+ fetch('/api/status',{headers:{accept:'application/json'}}).then(function(r){return r.json()}).then(function(d){+ if(d.hasSnapshot){ location.reload(); return; }+ var pct = d.progress.total ? Math.round(d.progress.done/d.progress.total*100) : 0;+ if(bar) bar.style.width = pct+'%';+ if(meter) meter.setAttribute('aria-valuenow', String(pct));+ if(status) status.textContent = d.progress.running+ ? d.progress.done+' / '+(d.progress.total||'?')+' repositories'+(d.progress.current?' — currently '+d.progress.current:'')+ : (d.progress.error ? 'Last scan failed: '+d.progress.error : 'Idle. The scheduled scan will start shortly.');+ setTimeout(tick, 3000);+ }).catch(function(){ setTimeout(tick, 8000); });+ }+ setTimeout(tick, 2000);+})();`+ });+}++/** The populated dashboard. */+export function dashboardPage({ snapshot, history }) {+ const { owner, summary } = snapshot;+ const body = `<section class="hero">+ <h1>${esc(owner)}: ${summary.repos} repositories, measured</h1>+ <p class="lede">Every URL below was requested from this server within the last scan. Every package name was resolved against the+ npm registry. A repository scores on the promises it makes, so a library with nothing deployed is never marked down for it.</p>+</section>+${statTiles(summary, history)}+${snapshot.partial ? `<div class="note"><strong>Partial scan.</strong> ${esc(snapshot.summary.repos)} of ${esc(snapshot.totalOwned)} repositories were reachable within the GitHub rate-limit budget${snapshot.rateLimit.resetAt ? `, which resets at ${esc(snapshot.rateLimit.resetAt)}` : ''}.</div>` : ''}+${attentionPanel(snapshot)}++<div class="toolbar" role="search">+ <div class="search">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m20 20-3.5-3.5"/></svg>+ <input id="q" type="search" placeholder="Filter by name, description, language or topic (press /)" aria-label="Filter repositories">+ </div>+ <select class="btn" id="sort" aria-label="Sort repositories">+ <option value="score">Sort: lowest score first</option>+ <option value="score-desc">Sort: highest score first</option>+ <option value="stars">Sort: most stars</option>+ <option value="pushed">Sort: recently updated</option>+ <option value="name">Sort: name</option>+ </select>+ <button class="btn" id="problems" type="button" aria-pressed="false">Only problems</button>+ <span class="mono" id="count" style="color:var(--muted)"></span>+</div>++<section class="grid" id="grid" aria-label="Repositories">+${snapshot.repos.map(repoCard).join('\n')}+</section>+<div class="empty hidden" id="none"><h2>No repository matches that filter</h2><p>Try a shorter query, or clear the "only problems" filter.</p></div>++<p style="margin-top:26px;color:var(--muted);font-size:12.5px">+Scanned ${esc(ago(snapshot.generatedAt))} in ${(snapshot.durationMs / 1000).toFixed(1)}s.+${snapshot.authenticated ? '' : 'Running unauthenticated against the GitHub API. '}+<a href="/api/fleet">Download the full JSON</a>.</p>`;++ return page({+ title: `Fleet Console — ${owner}`,+ description: `Live health of ${summary.repos} open-source repositories owned by ${owner}: deployment probes, link rot, and npm publish verification.`,+ owner,+ body,+ script: `+(function(){+ var grid=document.getElementById('grid'), q=document.getElementById('q'),+ sort=document.getElementById('sort'), only=document.getElementById('problems'),+ none=document.getElementById('none'), count=document.getElementById('count');+ var cards=[].slice.call(grid.children);+ var onlyProblems=false;++ function apply(){+ var term=(q.value||'').trim().toLowerCase(), shown=0;+ cards.forEach(function(card){+ var ok = (!term || card.dataset.search.indexOf(term)>-1) && (!onlyProblems || card.dataset.problem==='1');+ card.classList.toggle('hidden', !ok);+ if(ok) shown++;+ });+ none.classList.toggle('hidden', shown>0);+ count.textContent = shown+' of '+cards.length+' shown';+ }++ function order(){+ var mode=sort.value;+ var sorted=cards.slice().sort(function(a,b){+ if(mode==='stars') return (+b.dataset.stars)-(+a.dataset.stars);+ if(mode==='name') return a.dataset.name.localeCompare(b.dataset.name);+ if(mode==='pushed') return (b.dataset.pushed||'').localeCompare(a.dataset.pushed||'');+ var av=+a.dataset.score, bv=+b.dataset.score;+ if(mode==='score-desc') return bv-av || (+b.dataset.stars)-(+a.dataset.stars);+ return av-bv || (+b.dataset.stars)-(+a.dataset.stars);+ });+ sorted.forEach(function(card){ grid.appendChild(card); });+ }++ q.addEventListener('input', apply);+ sort.addEventListener('change', function(){ order(); apply(); });+ only.addEventListener('click', function(){+ onlyProblems=!onlyProblems;+ only.setAttribute('aria-pressed', String(onlyProblems));+ apply();+ });+ document.addEventListener('keydown', function(event){+ if(event.key==='/' && document.activeElement!==q){ event.preventDefault(); q.focus(); q.select(); }+ if(event.key==='Escape' && document.activeElement===q){ q.value=''; apply(); q.blur(); }+ });+ order(); apply();+})();`+ });+}diff --git a/services/fleet-console/src/views/docs.js b/services/fleet-console/src/views/docs.jsnew file mode 100644index 000000000..f1e630bd1--- /dev/null+++ b/services/fleet-console/src/views/docs.js@@ -0,0 +1,105 @@+/**+ * The public documentation page.+ *+ * A score nobody can audit is a number nobody should trust, so the weights,+ * the probe taxonomy and the API are all published here rather than living+ * only in the source.+ */++import { esc, page } from './html.js';+import { GRADES } from '../score.js';+import { PROBE_STATES } from '../probe.js';++const CHECKS = [+ ['Claimed deployments respond', 20, 'Every URL the repository advertises as its running site is requested. Skipped when it advertises none.'],+ ['Advertised packages exist on npm', 15, 'Every package name in an install line is resolved against the registry. Skipped when there are none.'],+ ['README links resolve', 12, 'External links are probed. Auth walls and rate limits do not count as dead.'],+ ['Has a real README', 8, 'A README under 600 bytes counts as a stub.'],+ ['Ships documentation beyond the README', 8, 'A docs/, doc/, documentation/, website/ or site/ directory.'],+ ['Recently touched', 8, 'Pushed within 120 days passes, within 400 warns.'],+ ['Declares a license', 6, 'GitHub must be able to classify it.'],+ ['npm matches the committed version', 6, 'The manifest version against the registry latest tag. Skipped when nothing is published.'],+ ['Has a description', 4, 'The About field on GitHub.'],+ ['Discoverable by topic', 3, 'Three or more topics pass.']+];++export function docsPage({ owner, snapshot }) {+ const example = snapshot?.repos?.[0]?.name || 'your-repo';+ const body = `<section class="hero">+ <h1>How Fleet Console works</h1>+ <p class="lede">Fleet Console takes a GitHub owner, reads what every repository claims about itself, and then checks those+ claims against the live internet. Nothing here is self-reported: a repository cannot mark its own homework.</p>+</section>++<section class="panel"><h2>The measurement loop</h2><div class="pad">+<ol style="margin:0;padding-left:20px;color:var(--muted);line-height:1.75">+ <li><strong style="color:var(--text)">Enumerate.</strong> Every public, non-fork, non-archived repository owned by <code>${esc(owner)}</code>, sorted by stars.</li>+ <li><strong style="color:var(--text)">Read the claims.</strong> The README, the root <code>package.json</code>, the repository homepage field, and the published GitHub Pages URL.</li>+ <li><strong style="color:var(--text)">Separate promises from references.</strong> A link labelled "live demo", a link on a known hosting provider, a host that spells out the repository name, or the homepage field is a deployment claim. Everything else is an ordinary outbound link, checked for rot but never treated as a broken deployment.</li>+ <li><strong style="color:var(--text)">Probe.</strong> Each URL is requested with a real HTTP call and classified by outcome, not by a pass/fail boolean.</li>+ <li><strong style="color:var(--text)">Verify the registry.</strong> Every package name in an install line is resolved against npm. A README telling readers to install something that was never published is a defect no test suite catches, because the failure lives in prose.</li>+ <li><strong style="color:var(--text)">Score.</strong> Weighted checks, with skipped checks removed from the denominator.</li>+</ol>+</div></section>++<section class="panel"><h2>Weights</h2>+<div class="scroll"><table>+<thead><tr><th>Check</th><th>Weight</th><th>What it measures</th></tr></thead>+<tbody>${CHECKS.map(([name, weight, detail]) => `<tr><td>${esc(name)}</td><td class="mono">${weight}</td><td style="color:var(--muted)">${esc(detail)}</td></tr>`).join('')}</tbody>+</table></div>+<div class="pad" style="color:var(--muted);font-size:13px">+A check returns pass, warn, fail or skip. Pass earns its full weight, warn earns half, fail earns nothing, and skip is removed+from both sides of the fraction. That last rule is the important one: a library with nothing deployed and nothing published is+not a broken library, and scoring it as one would make the whole fleet report useless.+</div></section>++<section class="panel"><h2>Grades</h2><div class="pad"><div class="chips">+${GRADES.map((entry) => `<span class="chip ${entry.tone}">${esc(entry.grade)} · ${entry.min}+ · ${esc(entry.label)}</span>`).join('')}+</div></div></section>++<section class="panel"><h2>Probe states</h2><div class="pad"><div class="chips">+${Object.entries(PROBE_STATES).map(([key, value]) => `<span class="chip ${value.tone}">${esc(value.label)}</span>`).join('')}+</div>+<p style="color:var(--muted);font-size:13px;margin-bottom:0">"Is it up?" is not a boolean. A suspended hosting account returns 402,+an expired certificate fails the handshake, and a deleted DNS record never connects at all. Each needs a different fix, so each+gets its own state.</p>+</div></section>++<section class="panel"><h2>Badges</h2><div class="pad">+<p style="margin-top:0">A build badge tells you the tests passed on some commit. These tell you whether the URLs a README+advertises answered a request. Paste either into a README and it stops being possible for that README to claim a deployment+that is gone.</p>+<div class="scroll"><table>+<thead><tr><th>Badge</th><th>Markdown</th></tr></thead>+<tbody>+<tr><td><img src="/badge/fleet.svg" alt="Fleet median health badge"></td><td class="mono"></td></tr>+<tr><td><img src="/badge/${encodeURIComponent(example)}.svg" alt="Per repository health badge"></td><td class="mono">}.svg)</td></tr>+<tr><td><img src="/badge/${encodeURIComponent(example)}/deployment.svg" alt="Deployment badge"></td><td class="mono">}/deployment.svg)</td></tr>+</tbody></table></div>+</div></section>++<section class="panel"><h2>API</h2>+<div class="scroll"><table>+<thead><tr><th>Endpoint</th><th>Returns</th></tr></thead>+<tbody>+<tr><td class="mono"><a href="/api/fleet">GET /api/fleet</a></td><td>The whole snapshot, one slim record per repository. Add <code>?full=1</code> for every probe.</td></tr>+<tr><td class="mono"><a href="/api/attention">GET /api/attention</a></td><td>Only what is broken, ranked worst first. Built for automation.</td></tr>+<tr><td class="mono"><a href="/api/repo/${encodeURIComponent(example)}">GET /api/repo/:name</a></td><td>One repository with every check, probe and score point in its history.</td></tr>+<tr><td class="mono"><a href="/api/status">GET /api/status</a></td><td>Scan progress. Safe to poll.</td></tr>+<tr><td class="mono">POST /api/scan</td><td>Trigger a scan. Requires the <code>FLEET_SCAN_TOKEN</code> bearer token.</td></tr>+<tr><td class="mono"><a href="/healthz">GET /healthz</a></td><td>Liveness.</td></tr>+</tbody></table></div>+</section>++<section class="panel"><h2>Run it against your own fleet</h2><div class="pad">+<p style="margin-top:0">Nothing about any particular owner is compiled into this service. Point <code>FLEET_OWNER</code> at any+GitHub user or organisation and it discovers that fleet at runtime.</p>+<pre class="mono" style="background:var(--surface-2);padding:14px;border-radius:10px;overflow-x:auto;margin:0">FLEET_OWNER=your-org GITHUB_TOKEN=ghp_... npm start</pre>+<p style="color:var(--muted);font-size:13px;margin-bottom:0">Without a token GitHub allows 60 requests an hour, which covers a+handful of repositories. The dashboard says so rather than reporting the rest as broken.</p>+</div></section>++<p style="margin-top:26px"><a href="/">← Back to the fleet</a></p>`;++ return page({ title: 'How it works — Fleet Console', description: 'How Fleet Console measures the health of an open-source fleet: the checks, the weights, the probe taxonomy and the API.', owner, body });+}diff --git a/services/fleet-console/src/views/html.js b/services/fleet-console/src/views/html.jsnew file mode 100644index 000000000..455923600--- /dev/null+++ b/services/fleet-console/src/views/html.js@@ -0,0 +1,277 @@+/**+ * Shared HTML shell: escaping, the design tokens, and the page chrome.+ *+ * Everything is inlined. The console ships no external stylesheet, font or+ * script, so it renders identically behind a strict CSP and stays readable if+ * the network drops halfway through a page load.+ */++const ENTITIES = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };++export const esc = (value) => String(value ?? '').replace(/[&<>"']/g, (char) => ENTITIES[char]);++export const attr = (value) => esc(value);++/** Human-readable relative time, past tense. */+export function ago(iso) {+ const then = Date.parse(iso || '');+ if (!Number.isFinite(then)) return 'never';+ const seconds = Math.max(1, Math.round((Date.now() - then) / 1000));+ const units = [+ [60, 'second'],+ [60, 'minute'],+ [24, 'hour'],+ [30, 'day'],+ [12, 'month'],+ [Number.POSITIVE_INFINITY, 'year']+ ];+ let value = seconds;+ for (const [size, name] of units) {+ if (value < size) return `${Math.round(value)} ${name}${Math.round(value) === 1 ? '' : 's'} ago`;+ value /= size;+ }+ return 'a long time ago';+}++export const STYLES = `+*,*::before,*::after{box-sizing:border-box}+:root{+ --bg:#f6f7f9; --surface:#fff; --surface-2:#eef1f6; --border:#dfe4ee;+ --text:#141824; --muted:#5b6478; --accent:#2358d8; --accent-soft:#e4ebfb;+ --good:#0f8a5f; --good-soft:#dff3e9; --warn:#96620a; --warn-soft:#fbeed3; --bad:#c0392f; --bad-soft:#fae1de;+ --ring:#2358d8; --shadow:0 1px 2px rgba(20,24,36,.06),0 8px 24px rgba(20,24,36,.06);+ --radius:14px; --mono:ui-monospace,SFMono-Regular,"SF Mono",Menlo,Consolas,monospace;+}+@media (prefers-color-scheme:dark){+ :root{+ --bg:#0a0c11; --surface:#12151d; --surface-2:#171c26; --border:#242a39;+ --text:#e7eaf2; --muted:#8d96ab; --accent:#7aa7ff; --accent-soft:#16233d;+ --good:#48d09a; --good-soft:#0f2b22; --warn:#f2bb4b; --warn-soft:#2d2410; --bad:#ff7d72; --bad-soft:#33191a;+ --ring:#7aa7ff; --shadow:0 1px 2px rgba(0,0,0,.4),0 10px 30px rgba(0,0,0,.35);+ }+}+:root[data-theme="light"]{+ --bg:#f6f7f9; --surface:#fff; --surface-2:#eef1f6; --border:#dfe4ee;+ --text:#141824; --muted:#5b6478; --accent:#2358d8; --accent-soft:#e4ebfb;+ --good:#0f8a5f; --good-soft:#dff3e9; --warn:#96620a; --warn-soft:#fbeed3; --bad:#c0392f; --bad-soft:#fae1de;+ --ring:#2358d8; --shadow:0 1px 2px rgba(20,24,36,.06),0 8px 24px rgba(20,24,36,.06);+}+:root[data-theme="dark"]{+ --bg:#0a0c11; --surface:#12151d; --surface-2:#171c26; --border:#242a39;+ --text:#e7eaf2; --muted:#8d96ab; --accent:#7aa7ff; --accent-soft:#16233d;+ --good:#48d09a; --good-soft:#0f2b22; --warn:#f2bb4b; --warn-soft:#2d2410; --bad:#ff7d72; --bad-soft:#33191a;+ --ring:#7aa7ff; --shadow:0 1px 2px rgba(0,0,0,.4),0 10px 30px rgba(0,0,0,.35);+}+html{-webkit-text-size-adjust:100%}+body{+ margin:0; background:var(--bg); color:var(--text);+ font:15px/1.55 ui-sans-serif,system-ui,-apple-system,"Segoe UI",Roboto,Inter,Helvetica,Arial,sans-serif;+ -webkit-font-smoothing:antialiased;+}+a{color:var(--accent); text-decoration:none}+a:hover{text-decoration:underline}+:focus-visible{outline:2px solid var(--ring); outline-offset:2px; border-radius:6px}+.wrap{max-width:1180px; margin:0 auto; padding:0 20px 72px}+.skip{position:absolute;left:-9999px}+.skip:focus{left:12px;top:12px;z-index:20;background:var(--surface);padding:10px 14px;border:1px solid var(--border);border-radius:8px}++header.top{position:sticky; top:0; z-index:10; background:color-mix(in srgb,var(--bg) 88%,transparent); backdrop-filter:blur(10px); border-bottom:1px solid var(--border)}+.top .wrap{padding:14px 20px; display:flex; align-items:center; gap:16px}+.brand{display:flex; align-items:center; gap:10px; font-weight:650; letter-spacing:-.01em; color:var(--text)}+.brand:hover{text-decoration:none}+.brand .dot{width:10px;height:10px;border-radius:50%;background:var(--good);box-shadow:0 0 0 4px var(--good-soft)}+.brand small{display:block;font-weight:450;color:var(--muted);font-size:12px;letter-spacing:0}+.top nav{margin-left:auto; display:flex; align-items:center; gap:6px; flex-wrap:wrap}+.btn{+ appearance:none; border:1px solid var(--border); background:var(--surface); color:var(--text);+ border-radius:9px; padding:7px 12px; font-size:13px; font-weight:520; cursor:pointer;+ transition:background .15s ease,border-color .15s ease,transform .1s ease;+}+.btn:hover{background:var(--surface-2); border-color:var(--muted)}+.btn:active{transform:translateY(1px)}+.btn[aria-pressed="true"]{background:var(--accent-soft); border-color:var(--accent); color:var(--accent)}++.hero{padding:34px 0 20px}+h1{margin:0 0 8px; font-size:30px; line-height:1.15; letter-spacing:-.02em}+.lede{margin:0; color:var(--muted); max-width:72ch}++.stats{display:grid; grid-template-columns:repeat(auto-fit,minmax(158px,1fr)); gap:12px; margin:24px 0 8px}+.stat{background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:14px 16px; box-shadow:var(--shadow)}+.stat .k{font-size:11px; text-transform:uppercase; letter-spacing:.07em; color:var(--muted); font-weight:600}+.stat .v{font-size:26px; font-weight:640; letter-spacing:-.02em; margin-top:4px; font-variant-numeric:tabular-nums}+.stat .s{font-size:12px; color:var(--muted); margin-top:2px}+.stat.good .v{color:var(--good)} .stat.warn .v{color:var(--warn)} .stat.bad .v{color:var(--bad)}++.toolbar{display:flex; gap:10px; flex-wrap:wrap; align-items:center; margin:26px 0 16px; position:sticky; top:63px; z-index:9; padding:10px 0; background:linear-gradient(var(--bg) 70%,transparent)}+.search{flex:1 1 260px; min-width:200px; position:relative}+.search input{+ width:100%; padding:9px 12px 9px 34px; border-radius:10px; border:1px solid var(--border);+ background:var(--surface); color:var(--text); font-size:14px;+}+.search svg{position:absolute; left:11px; top:50%; transform:translateY(-50%); color:var(--muted)}+select.btn{padding-right:8px}++.grid{display:grid; grid-template-columns:repeat(auto-fill,minmax(320px,1fr)); gap:14px}+.card{+ background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); padding:16px;+ display:flex; gap:14px; box-shadow:var(--shadow);+ transition:transform .14s ease,border-color .14s ease,box-shadow .14s ease;+}+.card:hover{transform:translateY(-2px); border-color:var(--accent)}+.card:focus-within{border-color:var(--accent)}+.card .body{min-width:0; flex:1}+.card h3{margin:0 0 4px; font-size:15px; letter-spacing:-.01em}+.card h3 a{color:var(--text)}+.card h3 a:hover{color:var(--accent)}+.card p{margin:0 0 10px; color:var(--muted); font-size:13px; display:-webkit-box; -webkit-line-clamp:2; -webkit-box-orient:vertical; overflow:hidden}+.meta{display:flex; gap:10px; flex-wrap:wrap; font-size:12px; color:var(--muted); font-variant-numeric:tabular-nums}+.chips{display:flex; gap:6px; flex-wrap:wrap; margin-top:10px}+.chip{font-size:11px; font-weight:600; padding:3px 8px; border-radius:999px; border:1px solid transparent; white-space:nowrap}+.chip.good{background:var(--good-soft); color:var(--good); border-color:color-mix(in srgb,var(--good) 30%,transparent)}+.chip.warn{background:var(--warn-soft); color:var(--warn); border-color:color-mix(in srgb,var(--warn) 30%,transparent)}+.chip.bad{background:var(--bad-soft); color:var(--bad); border-color:color-mix(in srgb,var(--bad) 30%,transparent)}+.chip.mute{background:var(--surface-2); color:var(--muted); border-color:var(--border)}++.ring{flex:0 0 auto; width:58px; height:58px; position:relative}+.ring svg{transform:rotate(-90deg)}+.ring .num{position:absolute; inset:0; display:grid; place-items:center; font-weight:660; font-size:15px; font-variant-numeric:tabular-nums}+.ring .grade{position:absolute; left:50%; bottom:-9px; transform:translateX(-50%); font-size:10px; font-weight:700; letter-spacing:.06em; padding:1px 6px; border-radius:999px; background:var(--surface-2); border:1px solid var(--border)}++.empty{text-align:center; padding:64px 20px; border:1px dashed var(--border); border-radius:var(--radius); color:var(--muted)}+.empty h2{color:var(--text); margin:0 0 8px; font-size:19px}+.empty .btn{margin-top:14px}++.bar{height:8px; border-radius:999px; background:var(--surface-2); overflow:hidden; border:1px solid var(--border)}+.bar span{display:block; height:100%; background:var(--accent); transition:width .4s ease}++table{width:100%; border-collapse:collapse; font-size:13px}+th,td{text-align:left; padding:9px 10px; border-bottom:1px solid var(--border); vertical-align:top}+th{font-size:11px; text-transform:uppercase; letter-spacing:.06em; color:var(--muted)}+td.mono,.mono{font-family:var(--mono); font-size:12px; word-break:break-all}+.scroll{overflow-x:auto; -webkit-overflow-scrolling:touch}++.panel{background:var(--surface); border:1px solid var(--border); border-radius:var(--radius); box-shadow:var(--shadow); margin:18px 0; overflow:hidden}+.panel > h2{margin:0; padding:14px 16px; font-size:14px; border-bottom:1px solid var(--border); letter-spacing:-.01em}+.panel .pad{padding:16px}+.check{display:flex; gap:12px; padding:13px 16px; border-bottom:1px solid var(--border)}+.check:last-child{border-bottom:0}+.check .mark{flex:0 0 auto; width:20px; height:20px; border-radius:6px; display:grid; place-items:center; font-size:12px; font-weight:700; margin-top:1px}+.check .mark.pass{background:var(--good-soft); color:var(--good)}+.check .mark.warn{background:var(--warn-soft); color:var(--warn)}+.check .mark.fail{background:var(--bad-soft); color:var(--bad)}+.check .mark.skip{background:var(--surface-2); color:var(--muted)}+.check strong{display:block; font-size:13.5px; font-weight:600}+.check .ev{color:var(--muted); font-size:12.5px; margin-top:3px; word-break:break-word}+.check .fix{margin-top:6px; font-size:12.5px; padding:7px 10px; border-radius:8px; background:var(--accent-soft); color:var(--text); border-left:3px solid var(--accent)}++footer.foot{border-top:1px solid var(--border); margin-top:44px; padding:22px 0; color:var(--muted); font-size:12.5px}+.note{background:var(--warn-soft); border:1px solid color-mix(in srgb,var(--warn) 35%,transparent); color:var(--text); padding:11px 14px; border-radius:10px; font-size:13px; margin:16px 0}+.hidden{display:none !important}+@media (max-width:640px){+ h1{font-size:24px}+ .top .wrap{gap:10px}+ .brand small{display:none}+ .toolbar{position:static; background:none}+ .grid{grid-template-columns:1fr}+}+@media (prefers-reduced-motion:reduce){*{transition:none !important; animation:none !important}}+`;++/** Score ring, drawn as inline SVG so it needs no chart library. */+export function ring(score, grade) {+ const value = typeof score === 'number' ? Math.max(0, Math.min(100, score)) : 0;+ const radius = 24;+ const circumference = 2 * Math.PI * radius;+ const filled = (value / 100) * circumference;+ const tone = grade?.tone === 'good' ? 'var(--good)' : grade?.tone === 'warn' ? 'var(--warn)' : 'var(--bad)';+ const label = typeof score === 'number' ? `Health score ${value} out of 100, grade ${grade?.grade || '?'}` : 'Not scored';+ return `<div class="ring" role="img" aria-label="${attr(label)}">+ <svg width="58" height="58" viewBox="0 0 58 58" aria-hidden="true">+ <circle cx="29" cy="29" r="${radius}" fill="none" stroke="var(--surface-2)" stroke-width="5"/>+ <circle cx="29" cy="29" r="${radius}" fill="none" stroke="${tone}" stroke-width="5" stroke-linecap="round"+ stroke-dasharray="${filled.toFixed(2)} ${(circumference - filled).toFixed(2)}"/>+ </svg>+ <span class="num" aria-hidden="true">${typeof score === 'number' ? value : '?'}</span>+ <span class="grade" aria-hidden="true">${esc(grade?.grade || '?')}</span>+</div>`;+}++/** Sparkline of past scores, inline SVG. */+export function sparkline(points, { width = 220, height = 44 } = {}) {+ if (!points.length) return '<p class="mono" style="color:var(--muted)">No history yet. The next scan starts the trend line.</p>';+ if (points.length === 1) return `<p class="mono" style="color:var(--muted)">One data point so far: ${points[0].score}.</p>`;+ const values = points.map((point) => point.score);+ const min = Math.min(...values, 0);+ const max = Math.max(...values, 100);+ const span = max - min || 1;+ const step = width / (points.length - 1);+ const coords = points.map((point, index) => [index * step, height - ((point.score - min) / span) * (height - 6) - 3]);+ const line = coords.map(([x, y], index) => `${index === 0 ? 'M' : 'L'}${x.toFixed(1)},${y.toFixed(1)}`).join(' ');+ const area = `${line} L${width},${height} L0,${height} Z`;+ const last = values[values.length - 1];+ const first = values[0];+ const tone = last >= first ? 'var(--good)' : 'var(--bad)';+ return `<svg width="${width}" height="${height}" viewBox="0 0 ${width} ${height}" role="img"+ aria-label="Score history: ${values.join(', ')}. Now ${last}, first recorded ${first}.">+ <path d="${area}" fill="${tone}" opacity=".12"/>+ <path d="${line}" fill="none" stroke="${tone}" stroke-width="2" stroke-linejoin="round" stroke-linecap="round"/>+ <circle cx="${coords[coords.length - 1][0].toFixed(1)}" cy="${coords[coords.length - 1][1].toFixed(1)}" r="3" fill="${tone}"/>+</svg>`;+}++/**+ * Full page shell.+ * @param {{title:string, description:string, body:string, script?:string, owner:string}} input+ */+export function page({ title, description, body, script = '', owner }) {+ return `<!doctype html>+<html lang="en" data-theme="">+<head>+<meta charset="utf-8">+<meta name="viewport" content="width=device-width,initial-scale=1">+<title>${esc(title)}</title>+<meta name="description" content="${attr(description)}">+<meta name="color-scheme" content="dark light">+<link rel="icon" href="data:image/svg+xml,${encodeURIComponent('<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32"><circle cx="16" cy="16" r="13" fill="none" stroke="%234ade80" stroke-width="5"/></svg>')}">+<style>${STYLES}</style>+<script>+(function(){try{var t=localStorage.getItem('fleet-theme');if(t)document.documentElement.dataset.theme=t;}catch(e){}})();+</script>+</head>+<body>+<a class="skip" href="#main">Skip to content</a>+<header class="top">+ <div class="wrap">+ <a class="brand" href="/"><span class="dot" aria-hidden="true"></span><span>Fleet Console<small>${esc(owner)}</small></span></a>+ <nav>+ <a class="btn" href="/api/fleet">JSON API</a>+ <a class="btn" href="/docs">Docs</a>+ <button class="btn" id="theme" type="button" aria-label="Switch colour theme">Theme</button>+ </nav>+ </div>+</header>+<main id="main" class="wrap">+${body}+</main>+<footer class="foot">+ <div class="wrap" style="padding-bottom:0">+ Fleet Console probes the live internet on every scan. Every number on this page is measured, never assumed.+ <a href="/api/fleet">Machine-readable output</a> and <a href="/docs">documentation</a> are public.+ </div>+</footer>+<script>+(function(){+ var root=document.documentElement, btn=document.getElementById('theme');+ function current(){ return root.dataset.theme || (matchMedia('(prefers-color-scheme: dark)').matches?'dark':'light'); }+ btn && btn.addEventListener('click',function(){+ var next = current()==='dark' ? 'light' : 'dark';+ root.dataset.theme=next;+ try{ localStorage.setItem('fleet-theme',next); }catch(e){}+ btn.setAttribute('aria-label','Switch to '+(next==='dark'?'light':'dark')+' theme');+ });+})();+${script}+</script>+</body>+</html>`;+}diff --git a/services/fleet-console/src/views/repo.js b/services/fleet-console/src/views/repo.jsnew file mode 100644index 000000000..b95bb9510--- /dev/null+++ b/services/fleet-console/src/views/repo.js@@ -0,0 +1,141 @@+/**+ * Per-repository detail: the score with every check that produced it, the raw+ * probe table, the npm verification table, and the score trend.+ *+ * A score with no evidence is an opinion. Every row here carries the+ * measurement it came from, including latency and the final URL after+ * redirects, so a disputed result can be re-run by hand.+ */++import { esc, attr, ago, page, ring, sparkline } from './html.js';+import { PROBE_STATES } from '../probe.js';++const MARK = { pass: '✓', warn: '!', fail: '✕', skip: '–' };++const stateChip = (state) => `<span class="chip ${PROBE_STATES[state]?.tone || 'bad'}">${esc(PROBE_STATES[state]?.label || state)}</span>`;++function probeTable(rows, { emptyText, showWhy = false }) {+ if (!rows.length) return `<div class="pad" style="color:var(--muted)">${esc(emptyText)}</div>`;+ return `<div class="scroll"><table>+<thead><tr><th>URL</th><th>State</th><th>Status</th><th>Latency</th>${showWhy ? '<th>Why it is treated as a deployment</th>' : '<th>Detail</th>'}</tr></thead>+<tbody>+${rows+ .map(+ (row) => `<tr>+ <td class="mono"><a href="${attr(row.url)}" rel="noopener nofollow" target="_blank">${esc(row.url)}</a></td>+ <td>${stateChip(row.state)}</td>+ <td class="mono">${row.status === null ? 'n/a' : esc(row.status)}</td>+ <td class="mono">${esc(row.ms)} ms</td>+ <td style="color:var(--muted)">${esc(showWhy ? row.why || '' : row.detail || '')}</td>+</tr>`+ )+ .join('\n')}+</tbody></table></div>`;+}++function packageTable(packages) {+ const rows = packages?.checked || [];+ if (!rows.length) return '<div class="pad" style="color:var(--muted)">This repository advertises no npm package.</div>';+ return `<div class="scroll"><table>+<thead><tr><th>Package</th><th>Registry</th><th>Latest</th><th>Advertised in</th></tr></thead>+<tbody>+${rows+ .map(+ (row) => `<tr>+ <td class="mono">${esc(row.name)}</td>+ <td>${row.error ? `<span class="chip warn">Lookup failed</span>` : row.published ? (row.deprecated ? '<span class="chip warn">Deprecated</span>' : '<span class="chip good">Published</span>') : '<span class="chip bad">Never published</span>'}</td>+ <td class="mono">${esc(row.latest || '-')}</td>+ <td style="color:var(--muted)">${row.role === 'manifest' ? 'package.json' : 'README install line'}</td>+</tr>`+ )+ .join('\n')}+</tbody></table></div>`;+}++export function repoPage({ repo, owner, history }) {+ const checks = repo.checks || [];+ const passed = checks.filter((entry) => entry.status === 'pass').length;+ const graded = checks.filter((entry) => entry.status !== 'skip').length;++ const body = `<p style="margin:22px 0 0;font-size:13px"><a href="/">← Back to the fleet</a></p>+<section class="hero" style="padding-top:14px">+ <div style="display:flex;gap:18px;align-items:flex-start;flex-wrap:wrap">+ ${ring(repo.score, repo.grade)}+ <div style="min-width:260px;flex:1">+ <h1 style="margin-bottom:6px">${esc(repo.name)}</h1>+ <p class="lede">${esc(repo.description || 'No description set.')}</p>+ <div class="meta" style="margin-top:10px">+ <span>${repo.stars.toLocaleString()} stars</span>+ ${repo.language ? `<span>${esc(repo.language)}</span>` : ''}+ <span>${repo.license ? esc(repo.license) : 'no license'}</span>+ <span>updated ${esc(ago(repo.pushedAt))}</span>+ <span>${passed}/${graded} checks pass</span>+ </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('')}+ <a class="btn" href="/api/repo/${encodeURIComponent(repo.name)}">JSON</a>+ <a class="btn" href="/badge/${encodeURIComponent(repo.name)}.svg">Badge</a>+ </div>+ </div>+ </div>+</section>++${repo.scanError ? `<div class="note"><strong>This repository failed to scan.</strong> ${esc(repo.scanError)}</div>` : ''}++<section class="panel">+ <h2>Health checks</h2>+ ${checks+ .map(+ (check) => `<div class="check">+ <span class="mark ${esc(check.status)}" aria-hidden="true">${MARK[check.status] || '?'}</span>+ <div>+ <strong>${esc(check.title)} <span style="font-weight:450;color:var(--muted)">(weight ${esc(check.weight)}${check.status === 'skip' ? ', not counted' : ''})</span></strong>+ <div class="ev">${esc(check.evidence)}</div>+ ${check.fix && check.status !== 'pass' && check.status !== 'skip' ? `<div class="fix"><strong>Fix:</strong> ${esc(check.fix)}</div>` : ''}+ </div>+ </div>`+ )+ .join('\n')}+</section>++<section class="panel">+ <h2>Advertised deployments</h2>+ ${probeTable(repo.deployments || [], { emptyText: 'This repository advertises no deployment, so it is not graded on one.', showWhy: true })}+</section>++<section class="panel">+ <h2>npm registry verification</h2>+ ${packageTable(repo.packages)}+</section>++<section class="panel">+ <h2>README links</h2>+ ${probeTable(repo.links || [], { emptyText: 'The README carries no external links to check.' })}+</section>++<section class="panel">+ <h2>Score history</h2>+ <div class="pad">${sparkline(history)}</div>+</section>`;++ return page({+ title: `${repo.name} — Fleet Console`,+ description: `Measured health of ${owner}/${repo.name}: ${passed} of ${graded} checks pass, score ${repo.score}.`,+ owner,+ body+ });+}++export function notFoundPage({ owner, name }) {+ return page({+ title: 'Not found — Fleet Console',+ description: 'No such repository in the current snapshot.',+ owner,+ body: `<div class="empty" style="margin-top:60px">+ <h2>No repository called "${esc(name)}" in the current snapshot</h2>+ <p>It may be private, archived, a fork, or beyond this scan's repository limit.</p>+ <a class="btn" href="/">Back to the fleet</a>+</div>`+ });+}