// 🤖 Contract test for the public status dashboards: the fields each page in
// web/status/ declares it reads (its FIELDS manifest) must exist in the JSON
// deploy/status-publish.sh generates. The fixtures in test/status-fixtures/
// are the script's own --dry-run output (fleet.json, books.json,
// books-no-expenses.json, books-hetzner-constant.json; regenerate with
// `./deploy/status-publish.sh --dry-run
` after changing the generator —
// the no-expenses variant via STATUS_DRY_EXPENSES=omit, the hetzner-constant
// one via STATUS_DRY_EXPENSES=hetzner-constant) plus the hand-pinned degraded
// shape (books-unavailable.json, matching books_unavailable()). If this
// fails, page and generator have drifted — fix whichever side changed, then
// the fixtures.
//
// The security ledger rides the same pattern with its own generator:
// test/status-fixtures/security.json is deploy/security-scan.sh's --dry-run
// output (the ATTENTION shape, folded from a fixture govulncheck stream full
// of fake CVE/GHSA/GO ids — regenerate with
// `./deploy/security-scan.sh --dry-run test/status-fixtures`), and
// web/status/security.json is the committed real scan. Both must satisfy the
// redaction contract below: status + counts + sha + timestamp, NEVER an
// advisory id or package path (an unpatched-vuln inventory is an attacker
// roadmap — see the scan script's disclosure header).
// node test/status-contract.test.mjs
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
let failures = 0;
async function test(name, fn) {
try {
await fn();
console.log("PASS " + name);
} catch (e) {
console.log("FAIL " + name + " — " + (e && e.message));
failures++;
}
}
const read = (p) => readFileSync(new URL("../" + p, import.meta.url), "utf8");
const fleet = JSON.parse(read("test/status-fixtures/fleet.json"));
// One dry-run fixture per capacity band (STATUS_DRY_CAPACITY=… regenerates
// them) — the abstract derivation is pinned at every level.
const fleetGF = JSON.parse(read("test/status-fixtures/fleet-getting-full.json"));
const fleetAC = JSON.parse(read("test/status-fixtures/fleet-at-capacity.json"));
// STATUS_DRY_MESH_PEER=1 regenerates this one — a second, live mesh peer's
// self-published stats merged into hosts.boxes alongside the local box.
const fleetMH = JSON.parse(read("test/status-fixtures/fleet-multi-host.json"));
const books = JSON.parse(read("test/status-fixtures/books.json"));
const booksDown = JSON.parse(read("test/status-fixtures/books-unavailable.json"));
const booksNoExp = JSON.parse(read("test/status-fixtures/books-no-expenses.json"));
const booksHzConst = JSON.parse(read("test/status-fixtures/books-hetzner-constant.json"));
// Pull the FIELDS manifest out of a page's inline script.
function fields(html) {
const m = html.match(/const FIELDS = \[([\s\S]*?)\];/);
assert.ok(m, "page declares a FIELDS manifest");
return [...m[1].matchAll(/"([^"]+)"/g)].map((x) => x[1]);
}
// Resolve a dotted path against an object; "seg[]" descends into a non-empty
// array — ANY element carrying the rest of the path satisfies it (the
// expenses providers are heterogeneous by design: month-to-date providers
// carry month_to_date_cents, flat-rate ones monthly_cents).
function resolve(obj, path) {
const segs = path.split(".");
function walk(cur, i) {
if (i === segs.length) return cur;
if (cur === null || typeof cur !== "object") return undefined;
const seg = segs[i];
if (seg.endsWith("[]")) {
const arr = cur[seg.slice(0, -2)];
if (!Array.isArray(arr) || arr.length === 0) return undefined;
for (const el of arr) {
const v = walk(el, i + 1);
if (v !== undefined) return v;
}
return undefined;
}
return walk(cur[seg], i + 1);
}
return walk(obj, 0);
}
const indexHtml = read("web/status/index.html");
const booksHtml = read("web/status/books.html");
// The carbon page reads TWO shapes. `built` is COMMITTED data (accrued by
// tools/carbon-tally.mjs) — the real web/status/carbon.json is its own fixture,
// and carries only { updated_at, methodology, built:{…} } (run absent → page
// shows "pending"). The live `run` block is injected by deploy/status-publish.sh
// at upload; its shape is pinned by the dry-run fixture test/status-fixtures/
// carbon.json (built + run — regenerate with `./deploy/status-publish.sh
// --dry-run ` then copy /carbon.json here).
const carbon = JSON.parse(read("web/status/carbon.json"));
const carbonRun = JSON.parse(read("test/status-fixtures/carbon.json"));
const carbonHtml = read("web/status/carbon.html");
// The contributors index is COMMITTED data too (tools/contributors.mjs).
const contributors = JSON.parse(read("web/status/contributors.json"));
const contributorsHtml = read("web/status/contributors.html");
// The tier-economics snapshot is COMMITTED data (re-derived by hand from
// docs/tier-economics.md when prices or input rates change) — the real
// web/status/economics.json is its own fixture, like the carbon ledger.
const economics = JSON.parse(read("web/status/economics.json"));
const economicsHtml = read("web/status/economics.html");
// The music ledger is COMMITTED data too (tools/music-ledger.mjs):
// an index plus one shard per month, so the page never fetches more than a
// month at a time.
const music = JSON.parse(read("web/status/music.json"));
const musicHtml = read("web/status/music.html");
const musicShards = music.months.map((m) => [m, JSON.parse(read("web/status/music-" + m + ".json"))]);
// The security ledger: the dry-run fixture (attention shape — proves the
// dirty path redacts) plus, when present, the committed real scan. The real
// file may legitimately be absent (the page then shows "scan pending", never
// a fake clean), so it's checked only when it exists.
const securityFix = JSON.parse(read("test/status-fixtures/security.json"));
const securityHtml = read("web/status/security.html");
let securityLive = null;
try { securityLive = JSON.parse(read("web/status/security.json")); } catch { /* absent = pending, honest */ }
const securityShapes = [["security fixture", securityFix]]
.concat(securityLive ? [["committed security.json", securityLive]] : []);
await test("fleet page fields all exist in the generator's fleet.json", () => {
for (const f of fields(indexHtml)) {
assert.notEqual(resolve(fleet, f), undefined, "fleet.json is missing " + f);
}
});
await test("books page fields all exist in one of the two books shapes", () => {
for (const f of fields(booksHtml)) {
const hit = resolve(books, f) !== undefined || resolve(booksDown, f) !== undefined;
assert.ok(hit, "neither books.json shape has " + f);
}
});
await test("carbon page fields resolve — built in committed carbon.json, run in the live fixture", () => {
for (const f of fields(carbonHtml)) {
if (f.startsWith("run.")) {
// run.* is absent from the committed file by design — pinned by the fixture.
assert.notEqual(resolve(carbonRun, f), undefined, "run fixture is missing " + f);
} else {
assert.notEqual(resolve(carbon, f), undefined, "committed carbon.json is missing " + f);
}
}
});
await test("contributors page fields all exist in the committed contributors.json", () => {
for (const f of fields(contributorsHtml)) {
assert.notEqual(resolve(contributors, f), undefined, "contributors.json is missing " + f);
}
});
await test("economics page fields all exist in the committed economics.json", () => {
for (const f of fields(economicsHtml)) {
assert.notEqual(resolve(economics, f), undefined, "economics.json is missing " + f);
}
});
await test("music page fields all exist in the committed music.json index", () => {
for (const f of fields(musicHtml)) {
assert.notEqual(resolve(music, f), undefined, "music.json is missing " + f);
}
});
// The music ledger publishes deliberately-chosen content, so its own
// hygiene is structural: month shards that match the index and their own
// filenames, no external art (data URIs only, deduped in the shard's albums
// map — the contributor-avatars rule), skip-filtered rows only (≥60s apart
// per listener, checked across shard boundaries), and signal words from the
// fixed vocabulary — a bare catalog stream carries none, because Music
// can't tell a direct pick from autoplay.
await test("music shards are well-formed, sorted, art self-contained", () => {
assert.match(music.updated_at, /^\d{4}-\d{2}-\d{2}T/, "index updated_at is ISO");
assert.deepEqual(music.months, [...music.months].sort().reverse(), "index months newest-first");
const artKey = (t) => t.album_id != null ? String(t.album_id) : t.track + " — " + t.artist;
let total = 0;
const lastBy = new Map(); // per listener, across shards oldest→newest
for (const [m, s] of [...musicShards].reverse()) {
assert.equal(s.month, m, "shard month matches its filename");
for (const uri of Object.values(s.albums)) {
assert.match(uri, /^data:image\//, m + ": album art must be a data URI");
}
let prev = "";
for (const t of s.tracks) {
assert.ok(t.ts >= prev, m + ": not sorted oldest-first at " + t.ts);
prev = t.ts;
assert.equal(t.ts.slice(0, 7), m, "row " + t.ts + " outside its shard month");
assert.ok(t.track && t.artist && t.album && t.listener, "row is complete");
assert.ok(["Apple Music", "local file", "library"].includes(t.source), "source word: " + t.source);
assert.ok(Array.isArray(t.signals) && t.signals.every((x) => ["queued", "radio", "shuffle"].includes(x)),
"signals ⊆ {queued,radio,shuffle}: " + JSON.stringify(t.signals));
assert.ok(!(artKey(t) in s.albums) || typeof s.albums[artKey(t)] === "string", "art key resolves");
const last = lastBy.get(t.listener);
if (last && last.track !== t.track) {
assert.ok(Date.parse(t.ts) - Date.parse(last.ts) >= 60_000,
"skip leaked: " + last.track + " held under 60s before " + t.track);
}
lastBy.set(t.listener, t);
}
total += s.tracks.length;
}
assert.equal(music.totals.tracks, total, "index totals.tracks is the shard sum");
});
await test("security page fields all exist in the scanner's security.json", () => {
for (const [name, s] of securityShapes) {
for (const f of fields(securityHtml)) {
assert.notEqual(resolve(s, f), undefined, name + " is missing " + f);
}
}
});
// Contributor entries stay well-formed as the tool regenerates them: known
// kinds, positive commit counts, sorted by the metric, humans carry a profile
// link + self-contained data-URI avatar (the pages allow no external hosts),
// and no email address ever reaches the published JSON.
await test("contributors entries are well-formed, sorted, and email-free", () => {
let prev = Infinity;
for (const c of contributors.contributors) {
assert.ok(["human", "ai"].includes(c.kind), "kind: " + c.kind);
assert.ok(Number.isInteger(c.commits) && c.commits > 0, c.id + ": commits");
assert.ok(c.commits <= prev, "not sorted by commits at " + c.id);
prev = c.commits;
assert.ok(c.name && c.id, "name + id present");
if (c.kind === "human") {
assert.match(c.url, /^https:\/\/github\.com\//, c.id + ": profile url");
assert.match(c.avatar, /^data:image\//, c.id + ": avatar must be a data URI");
}
}
assert.ok(!/[\w.+-]+@[\w-]+\.[\w.]+/.test(JSON.stringify(contributors).replace(/data:image\/[^"]+/g, "")),
"an email address leaked into contributors.json");
});
// The tier-economics snapshot must stay internally consistent as it's
// re-derived (docs/tier-economics.md: the formulas are the contract, the
// numbers a snapshot): net follows the Stripe fee line exactly (the two fee
// constants below mirror the input-rates table — update both together),
// profit ≈ net − cost within the doc's ~rounding, margin is profit over
// GROSS, and every tier's included allowance sits below its break-even —
// the "no tier can structurally lose money" claim the page makes in prose.
await test("economics snapshot arithmetic + structurally-profitable claim hold", () => {
assert.match(economics.as_of, /^\d{4}-\d{2}-\d{2}$/, "as_of is a date");
assert.equal(economics.currency, "eur");
const q = economics.free_spaces_per_account;
assert.ok(Number.isInteger(q) && q >= 1, "free-space quota is a positive integer");
assert.ok(economics.price_book.length > 0 && economics.storage_allowances.length > 0
&& economics.input_rates.length > 0 && economics.estimates.length > 0, "all four tables non-empty");
for (const p of economics.price_book) {
assert.ok(Number.isInteger(p.yearly_cents) && p.yearly_cents > 0, p.tier + ": yearly_cents is integer cents");
if ("monthly_cents" in p) {
assert.ok(Number.isInteger(p.monthly_cents) && p.monthly_cents > 0, p.tier + ": monthly_cents is integer cents");
// A monthly toggle must cost more per year than the annual price, or
// the annual default the page defends would be the worse deal.
assert.ok(12 * p.monthly_cents >= p.yearly_cents, p.tier + ": 12×monthly ≥ yearly");
}
}
const allowance = new Map(economics.storage_allowances.map((s) => [s.tier, s.gb]));
for (const s of economics.storage_allowances) {
assert.ok(Number.isInteger(s.gb) && s.gb > 0, s.tier + ": allowance is a positive GB integer");
}
for (const e of economics.estimates) {
const label = e.plan + " · " + e.billing;
const charges = e.billing === "monthly" ? 12 : 1;
// Stripe fee constants (1.5% + €0.25 per charge) from the input-rates table.
const net = e.gross_year_cents - 25 * charges - 0.015 * e.gross_year_cents;
assert.ok(Math.abs(e.net_year_cents - net) <= 1,
label + ": net must follow the fee model (" + e.net_year_cents + " vs " + net.toFixed(1) + ")");
assert.ok(e.cost_year_cents > 0 && e.cost_year_cents < e.net_year_cents, label + ": cost sits inside net");
const tol = Math.max(5, Math.round(e.gross_year_cents * 0.005)); // costs are ~ estimates
assert.ok(Math.abs(e.profit_year_cents - (e.net_year_cents - e.cost_year_cents)) <= tol,
label + ": profit ≈ net − cost (" + e.profit_year_cents + ")");
assert.ok(Math.abs(e.margin_pct - (100 * e.profit_year_cents) / e.gross_year_cents) <= 1,
label + ": margin is profit over gross");
const gb = allowance.get(e.plan);
assert.ok(Number.isInteger(gb), label + ": plan has a storage-allowance row");
assert.ok(e.break_even_gb > gb, label + ": allowance must sit below break-even (structurally profitable)");
}
});
// A manifest entry nobody reads is drift too: each leaf property must appear
// in the page's render code, not just the manifest.
await test("every declared field is actually read by its page", () => {
for (const [html, fs] of [[indexHtml, fields(indexHtml)], [booksHtml, fields(booksHtml)], [carbonHtml, fields(carbonHtml)], [contributorsHtml, fields(contributorsHtml)], [securityHtml, fields(securityHtml)], [economicsHtml, fields(economicsHtml)], [musicHtml, fields(musicHtml)]]) {
const body = html.slice(html.indexOf("];") + 2);
for (const f of fs) {
const leaf = f.split(".").pop().replace("[]", "");
assert.ok(body.includes(leaf), "manifest field " + f + " is never used");
}
}
});
// The degraded shape must be renderable: available flips the page, reason is
// the message.
await test("degraded books shape carries available:false + reason", () => {
assert.equal(booksDown.available, false);
assert.equal(typeof booksDown.reason, "string");
});
// Privacy re-check on the committed fixtures (the dry-run asserts this too —
// belt and suspenders on what's in git): no fixture hostname, subscription,
// customer, transaction, or provider-account/workspace id may appear in
// published output.
await test("fixtures contain no per-payer ids or hostnames", () => {
for (const j of [fleet, fleetGF, fleetAC, books, booksDown, booksNoExp, booksHzConst, carbon, carbonRun, contributors, economics, ...securityShapes.map(([, s]) => s)]) {
const s = JSON.stringify(j);
assert.ok(!/sub_|cus_|txn_|wrkspc_|req_fixture|ce_fixture|dnsfix|hzfix|\.example|\.sock/.test(s), "leak in " + s.slice(0, 80));
}
});
// ---- the security ledger: redacted by contract --------------------------------
// The disclosure line (deploy/security-scan.sh header): the published block is
// a STATUS + COUNT only. The schema is an ALLOWLIST — any extra key fails, so
// an advisory id, package path, or version list can't ship by accident.
await test("security ledger carries only the redacted hygiene schema", () => {
for (const [name, s] of securityShapes) {
assert.deepEqual(Object.keys(s).sort(), ["dependencies", "generated_at", "go_modules", "scanned_sha"], name + ": keys");
assert.match(s.generated_at, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/, name + ": generated_at is ISO UTC");
// The build sha is already public via the signed release feed — the one
// version identifier the page may carry.
assert.match(s.scanned_sha, /^[0-9a-f]{7,40}$/, name + ": scanned_sha is a git sha");
assert.ok(Number.isInteger(s.go_modules) && s.go_modules > 0, name + ": go_modules is a positive count");
assert.deepEqual(Object.keys(s.dependencies).sort(), ["advisories_under_remediation", "status"], name + ": dependency keys");
assert.ok(["clean", "attention", "pending"].includes(s.dependencies.status),
name + ": status is a vocabulary word, got " + s.dependencies.status);
const n = s.dependencies.advisories_under_remediation;
assert.ok(Number.isInteger(n) && n >= 0, name + ": count is an integer ≥ 0");
// Status and count must agree — "clean" beside a nonzero count (or the
// reverse) would be a lie in one direction or the other.
assert.equal(n > 0, s.dependencies.status === "attention", name + ": status agrees with the count");
}
});
// The redaction guard: no advisory id in ANY grammar (Go vulndb GO-…, CVE,
// GHSA) — an unpatched finding publishes as a count, never a name. The
// fixture was folded from a stream FULL of such ids, so this proves the
// generator strips them, not merely that the input was clean.
await test("security ledger never names an advisory", () => {
for (const [name, s] of securityShapes) {
const t = JSON.stringify(s);
assert.ok(!/CVE-\d{4}-\d+|GHSA-|GO-\d{4}-\d+/i.test(t), name + " carries an advisory id: " + t.slice(0, 120));
}
});
// Pin the dirty path end-to-end: the dry-run's fixture stream carries two
// advisories with symbol-level findings (one of them twice — findings dedupe
// by advisory) plus a module-level-only informational one that must NOT
// count. Redacted result: attention + 2, and nothing else.
await test("security dry-run fixture folds to attention + count 2", () => {
assert.equal(securityFix.dependencies.status, "attention");
assert.equal(securityFix.dependencies.advisories_under_remediation, 2);
assert.equal(securityFix.scanned_sha, "abc1234");
assert.equal(securityFix.go_modules, 42);
});
// Expenses publish ITEMIZED by design — decision #19's other half (income
// aggregates, expenses itemize; the amounts are public on purpose). The
// schema is still an ALLOWLIST: provider word + EXACTLY ONE amount key
// (month_to_date_cents for metered providers, monthly_cents / yearly_cents
// for flat subscriptions, to_date_cents for a cumulative operator-attested
// lifetime figure — each as billed: a yearly fee is never divided into a
// fake monthly, a lifetime figure never smeared across months) + its own
// billing currency, nothing else — so an account id, invoice id, or
// resource-level line can't ship by accident. Currencies stay per-provider,
// never FX-converted, and only usd/eur exist today.
await test("expenses carry only the allowed itemized schema", () => {
const exp = books.expenses;
assert.ok(exp, "books fixture carries expenses");
assert.deepEqual(Object.keys(exp).sort(), ["month", "providers"], "expenses keys");
assert.match(exp.month, /^\d{4}-\d{2}$/, "expenses.month is YYYY-MM");
// Each provider's key set carries exactly one of the four amount keys —
// the deepEqual below enforces the exactly-one rule per provider.
const allowed = {
"aws": ["currency", "month_to_date_cents", "provider"],
"hetzner": ["currency", "monthly_cents", "provider"],
"anthropic": ["currency", "month_to_date_cents", "provider"],
"claude.ai": ["currency", "provider", "to_date_cents"],
"dnsimple": ["currency", "month_to_date_cents", "provider"],
"apple": ["currency", "provider", "yearly_cents"],
};
// The dry-run's fixed fixture exercises every provider, in publish order.
assert.deepEqual(exp.providers.map((p) => p.provider),
["aws", "hetzner", "anthropic", "claude.ai", "dnsimple", "apple"], "fixture exercises all providers");
for (const p of exp.providers) {
assert.ok(p.provider in allowed, "unknown provider " + p.provider);
assert.deepEqual(Object.keys(p).sort(), allowed[p.provider], p.provider + " keys");
assert.ok(["usd", "eur"].includes(p.currency), p.provider + " currency ∈ {usd,eur}, got " + p.currency);
const cents = p.month_to_date_cents ?? p.monthly_cents ?? p.yearly_cents ?? p.to_date_cents;
assert.ok(Number.isInteger(cents) && cents >= 0, p.provider + " amount is integer cents ≥ 0");
}
});
// No providers resolve → the whole expenses object is omitted (degrade, never
// zero, never guess). The degraded income shape needn't carry it either.
await test("expenses omit entirely when no provider resolves", () => {
assert.ok(!("expenses" in booksNoExp), "no-expenses fixture must omit the key");
assert.equal(booksNoExp.available, true, "omission is independent of income availability");
});
// Hetzner's figure is API-computed when the operator constant is unset: the
// default fixture pins the servers-API math (two dry-run fixture pages, each
// server priced by the ONE server_type.prices[] entry matching its own
// location — gross monthly EUR 16.4288 + 4.5100 = 20.9388, rounded once at
// the total to 2094 cents). And when STATUS_HETZNER_MONTHLY_CENTS is set the
// constant wins over a resolvable API path — operator truth beats computed.
// Either way the key shape is identical (monthly_cents, eur).
await test("hetzner: API-computed cents with rounding; constant overrides", () => {
const hz = books.expenses.providers.find((p) => p.provider === "hetzner");
assert.deepEqual(hz, { provider: "hetzner", monthly_cents: 2094, currency: "eur" },
"API path: location-matched gross sum, rounded");
const hzc = booksHzConst.expenses.providers.find((p) => p.provider === "hetzner");
assert.deepEqual(hzc, { provider: "hetzner", monthly_cents: 1400, currency: "eur" },
"constant override: the operator figure publishes, same shape");
});
// The carbon tally must stay internally consistent as entries accrue — the
// totals are the sum of the ledger, each entry's kg derives from its output
// tokens × the published factors, and each SOURCE's periods are chronological
// and non-overlapping (tools/carbon-tally.mjs appends strictly after that
// source's last period_end; an overlap means two branches double-counted the
// same window — drop the younger entry and re-run --write). Sources are
// anonymous name-pair labels, same rule as the fleet's box labels: the tally
// is public, so never a hostname or username.
await test("carbon tally arithmetic + per-source chronology hold", () => {
const b = carbon.built;
const f = b.factors_mg_co2e_per_output_token;
assert.ok(f.low < f.central && f.central < f.high, "factors ordered");
let out = 0, kg = { low: 0, central: 0, high: 0 };
const prevEnd = new Map();
for (const e of b.entries) {
assert.match(e.source, /^[a-z]+-[a-z]+$/, "source must be a name-pair label, got " + e.source);
assert.ok(["measured", "extrapolated"].includes(e.basis), "basis word: " + e.basis);
assert.ok(Date.parse(e.period_start) < Date.parse(e.period_end), "period runs forward");
assert.ok(Date.parse(e.period_start) >= (prevEnd.get(e.source) ?? -Infinity),
e.source + " periods overlap at " + e.period_start);
prevEnd.set(e.source, Date.parse(e.period_end));
for (const band of ["low", "central", "high"]) {
const want = (e.output_tokens * f[band]) / 1e6; // mg → kg
assert.ok(Math.abs(e["kg_" + band] - want) <= 0.06,
"entry kg_" + band + " ≠tokens × factor (" + e["kg_" + band] + " vs " + want.toFixed(2) + ")");
kg[band] += e["kg_" + band];
}
out += e.output_tokens;
}
assert.equal(b.totals.output_tokens, out, "built.totals.output_tokens is the ledger sum");
for (const band of ["low", "central", "high"]) {
assert.ok(Math.abs(b.totals["kg_" + band] - kg[band]) <= 0.05,
"built.totals.kg_" + band + " is the ledger sum");
}
assert.equal(Date.parse(carbon.updated_at), Math.max(...b.entries.map((e) => Date.parse(e.period_end))),
"updated_at is the newest built period_end");
});
// The injected run block: an ALLOWLIST schema (any extra key fails, so a needle
// can't ship by accident), banded low≤central≤high, aggregates only — no
// hostname/IP/socket, and the per-space denominator is the public instance
// count, NEVER per-member.
await test("run block carries only the allowed operational schema, banded, no needles", () => {
const r = carbonRun.run;
assert.deepEqual(Object.keys(r).sort(),
["cumulative_kg", "daily_kg", "generated_at", "grid_g_per_kwh", "per_space_daily_kg",
"pue", "services", "since", "spaces", "vcpus", "watts"], "run keys");
assert.match(r.generated_at, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}Z$/, "generated_at is ISO UTC");
assert.match(r.since, /^\d{4}-\d{2}-\d{2}$/, "since is a date");
assert.ok(Number.isInteger(r.spaces) && r.spaces > 0, "spaces is a positive instance count");
assert.ok(Number.isInteger(r.vcpus) && r.vcpus > 0, "vcpus is a positive count");
assert.ok(typeof r.pue === "number" && r.pue >= 1, "pue is a real ≥ 1");
for (const band of ["watts", "grid_g_per_kwh", "daily_kg", "cumulative_kg", "per_space_daily_kg"]) {
assert.deepEqual(Object.keys(r[band]).sort(), ["central", "high", "low"], band + " is banded");
assert.ok(r[band].low <= r[band].central && r[band].central <= r[band].high, band + " ordered low≤central≤high");
}
for (const s of r.services) {
assert.deepEqual(Object.keys(s).sort(), ["daily_kg_central", "name"], "service " + s.name + " keys");
assert.ok(typeof s.name === "string" && s.name.length > 0, "service name");
assert.ok(typeof s.daily_kg_central === "number" && s.daily_kg_central >= 0, s.name + " daily kg ≥ 0");
}
const t = JSON.stringify(r);
assert.ok(!/\d+\.\d+\.\d+\.\d+|[a-z0-9-]+\.(sock|example|com|net|chat|at)\b/i.test(t),
"run block reads like a hostname/IP: " + t.slice(0, 80));
});
// The run math folds server_type + region grid → watts → kg exactly, so the
// generator's arithmetic can't drift (mirrors deploy/status-publish.sh's
// carbon_run_object + its dry-run assertions). 6 vCPUs (cpx31=4 + cx22=2), the
// Germany fixture grid 350 g/kWh, W/vCPU central 3.5, PUE 1.15, 10-day span, 6
// spaces.
await test("run fixture folds server_type + grid to the asserted watts→kg math", () => {
const r = carbonRun.run;
assert.equal(r.vcpus, 6, "vCPUs summed across the servers fixture");
assert.equal(r.watts.central, 21, "6 vCPU × 3.5 W");
assert.equal(r.grid_g_per_kwh.central, 350, "Germany fixture grid");
assert.equal(r.pue, 1.15);
// 6 × 3.5 × 24 × 350 × 1.15 / 1e6 + 0.001 (AWS) + 0.005 (inference) = 0.20886.
assert.equal(r.daily_kg.central, 0.20886, "daily central kg");
assert.equal(r.cumulative_kg.central, 2.0886, "cumulative = daily × 10 days");
assert.equal(r.per_space_daily_kg.central, 0.03481, "per space = daily ÷ 6 spaces");
// The service breakdown's central terms sum to the daily central (router term
// is the watts→kg piece; AWS + inference are the small explicit terms).
const sum = r.services.reduce((a, s) => a + s.daily_kg_central, 0);
assert.ok(Math.abs(sum - r.daily_kg.central) <= 1e-6, "services sum to the daily central");
});
// Capacity + hosts publish ABSTRACT levels only (Paul's call: bucketed words,
// never needles). The schema is an ALLOWLIST — any extra key under hosts /
// capacity fails, so a precise number (remaining slots, GB, percentages, cap
// values) can't ship by accident, and the level/load words themselves must be
// digit-free vocabulary entries.
const fleetShapes = [
["fleet", fleet], ["fleet-getting-full", fleetGF], ["fleet-at-capacity", fleetAC],
["fleet-multi-host", fleetMH],
];
await test("hosts + capacity carry only the allowed abstract schema", () => {
for (const [name, f] of fleetShapes) {
assert.deepEqual(Object.keys(f.capacity).sort(), ["level"], name + ": capacity keys");
assert.ok(["plenty", "getting-full", "at-capacity"].includes(f.capacity.level),
name + ": capacity.level is a band word, got " + f.capacity.level);
assert.deepEqual(Object.keys(f.hosts).sort(), ["boxes", "count"], name + ": hosts keys");
assert.equal(f.hosts.count, f.hosts.boxes.length, name + ": count matches boxes");
for (const b of f.hosts.boxes) {
// region is optional (omitted when the operator sets none). When present
// it must be a coarse public area — continent + country — and must never
// read like an IP or hostname (no dots-and-digits / label.tld shapes).
// always_on is likewise optional: a REMOTE mesh peer's self-published
// snapshot (mesh_peer_boxes) never carries it — that's a local-box-only
// concept — so a peer's key set is the "required" set on its own,
// while the LOCAL box always adds always_on.
const required = ["asleep", "awake", "label", "load"];
const keys = Object.keys(b).sort();
const allowed = required.concat(["always_on", "region"]).sort();
assert.ok(required.every((k) => keys.includes(k)), name + ": box missing a required key: " + keys);
assert.ok(keys.every((k) => allowed.includes(k)), name + ": box carries a disallowed key: " + keys);
if ("region" in b) {
assert.equal(typeof b.region, "string", name + ": region is a string");
assert.ok(!/\d+\.\d+|[a-z0-9-]+\.[a-z]{2,}/i.test(b.region),
name + ": region reads like an IP/hostname: " + b.region);
}
// Labels are anonymous ordinals — never a hostname, IP, or URL.
assert.match(b.label, /^[a-z]+-[a-z]+$/, name + ": box label must be a name-action pair");
assert.ok([null, "comfortable", "busy", "critical"].includes(b.load),
name + ": box load is a band word or null, got " + b.load);
}
// No digit may ride in the capacity subtree — the band word is the entire
// public surface.
assert.ok(!/\d/.test(JSON.stringify(f.capacity)), name + ": capacity carries a number");
}
});
// The multi-host fixture specifically: a second, live mesh peer merges into
// hosts.boxes without displacing the local box, and count reflects both.
await test("multi-host fixture merges the local box with a live mesh peer", () => {
assert.equal(fleetMH.hosts.count, 2, "hosts.count reflects both boxes");
assert.equal(fleetMH.hosts.boxes.length, 2);
const [local, peer] = fleetMH.hosts.boxes;
assert.ok("always_on" in local, "the local box still reports always_on");
assert.ok(!("always_on" in peer), "a remote peer never reports always_on (a genuinely local-box-only concept)");
assert.equal(peer.region, "UK · London", "a peer's own LCHAT_BOX_REGION rides through the merge verbatim");
assert.notEqual(local.label, peer.label, "the two boxes must have distinct labels");
});
// The local box's own row must prefer its self-published, ownership-filtered
// snapshot (mesh-self-stats.json in the dry-run fixture: awake=1) over its
// raw local `ss` sweep (which would show awake=2, see the single-box `fleet`
// fixture) — otherwise this box's own row still overlaps a peer's, even once
// the peer's row is correctly filtered.
await test("the local box's own row prefers its self-published stats over its raw ss sweep", () => {
const [local] = fleetMH.hosts.boxes;
assert.equal(local.awake, 1, "local.awake must come from the self-published snapshot, not the unfiltered ss sweep (2)");
assert.notEqual(local.awake, fleet.hosts.boxes[0].awake,
"a regression would make the mesh-off and mesh-on local rows identical again");
});
// A host genuinely running on a mesh peer has no local socket on this box, so
// the top-level instances.awake/asleep must sum every box's own verified
// split, not just this box's — otherwise a peer-hosted instance reads as
// "asleep" fleet-wide even while it's actually awake there.
await test("top-level awake/asleep are fleet-wide, not just the local box", () => {
const [local, peer] = fleetMH.hosts.boxes;
assert.equal(fleetMH.instances.awake, local.awake + peer.awake,
"instances.awake must sum every box's own awake count");
assert.equal(fleetMH.instances.asleep, fleetMH.instances.hibernating - fleetMH.instances.awake,
"instances.asleep must be hibernating minus the fleet-wide awake total");
assert.notEqual(fleetMH.instances.awake, local.awake,
"a regression would silently drop back to only the local box's awake count");
});
// Each committed fixture set derives its band — pins the 70/90 thresholds and
// the disk-floor rule in the generator (see dry_run's capacity fixtures).
await test("capacity fixtures derive plenty / getting-full / at-capacity", () => {
assert.equal(fleet.capacity.level, "plenty");
assert.equal(fleetGF.capacity.level, "getting-full");
assert.equal(fleetAC.capacity.level, "at-capacity");
assert.equal(fleet.hosts.boxes[0].load, "comfortable");
// getting-full is driven by the registered ratio, not memory — capacity and
// box load are independent signals.
assert.equal(fleetGF.hosts.boxes[0].load, "comfortable");
assert.equal(fleetAC.hosts.boxes[0].load, "critical");
// The STATUS_BOX_REGION seam: the dry-run's fixed coarse region rides
// through to the box row verbatim.
assert.equal(fleet.hosts.boxes[0].region, "EU · Germany");
});
// ---- the shared masthead + nav (status-nav.js): one copy, no drift ------------
// The pages drifted while each carried its own copy of the masthead + nav
// (stale link lists, bare h1 overrides quietly moving the masthead between
// pages). Now every dashboard ships two empty mounts filled by the one
// builder — so no page may carry an inline copy, no page CSS may reach the
// shared masthead with a bare h1 selector, and the builder's GROUPS must
// cover exactly the dashboard pages that exist.
await test("status pages all mount the shared masthead + nav, no inline copies", () => {
const navJs = read("web/status/status-nav.js");
const navPages = [...navJs.matchAll(/\["([a-z-]+\.html)"/g)].map((m) => m[1]);
const pages = ["index.html", "hardening.html", "security.html", "books.html", "economics.html",
"funding.html", "carbon.html", "contributors.html", "prompts.html", "ssh.html", "music.html",
"roadmap.html", "milestones.html"];
assert.deepEqual([...navPages].sort(), [...pages].sort(), "GROUPS covers exactly the dashboard pages");
for (const p of pages) {
const html = read("web/status/" + p);
assert.match(html, /<\/header>/, p + ": masthead mount missing");
assert.ok(html.includes(''), p + ": empty nav mount missing");
assert.ok(html.includes('src="./status-nav.js"'), p + ": shared include missing");
assert.ok(!html.includes("group-label"), p + ": carries an inline nav copy");
assert.ok(!html.includes('class="brand"'), p + ": carries an inline masthead copy");
const style = (html.match(/