Public: anyone can read this; the crew can change it.
The Resilience page shows each THREATS.md protection green, red or untested from the last gate #1938
scout/forge:scout/1814-the-resilience-page-shows-each-threats-m → main 9 commits fork
12 files
changed +465
−1
README.md +1
| @@ -551,6 +551,7 @@ mechanical rather than advisory. | ||
| 551 | 551 | |
| 552 | 552 | `docs/FLOW.md` is where every issue stands: `GET /api/v1/repos/:owner/:name/flow` returns each open issue's stage, since, stalled and unblock, plus what went live in the last 24 h. |
| 553 | 553 | Where the whole forge waits is a forge admin's: `/flow` shows each stage from ready to live with what waits, the oldest wait and its capacity, under one sentence naming the bottleneck, and beside each what it let out in the last hour with a 24-hour sparkline, under a line of landings and the median ask→live — every count links to the items it counts. A stalled step is a card on the home (Studio mode) for anyone who can write to the repository: an open pull whose check was never asked for, or is red, past its stage's allowance, with its stage, how long it has been stuck, and one button — Run check or Re-run — that asks for a check at the head and returns to the home. The terminal's **Stalled steps** command (palette) lists the same steps, live, and Enter or `r` does the same re-run; both read `flow/stalled.ts` and act through `flow/unblock.ts`, and neither shows anything to someone who cannot write. The terminal's Flow command and the MCP `flow` tool read the same: the sentence, the landings line, and each stage's count out in the last hour and in 24 h. |
| 554 | A forge admin also has `/resilience`: every protection in `docs/THREATS.md` as green, red, "No test yet" (the doc says so) or "Not run" (the last default-branch gate did not report its file). The gate writes one pass/fail per test file to `.forge-cache/gate-results.json`; after each default-branch check, red or green, the forge moves it, for the forge's own repository (`FORGE_REPO`) only, to `check-cache/<repo id>/gate-results.json` in the data directory (temp file, rename). A pull's gate never writes it. It is a web page only — the terminal and MCP leave admin-only pages out on purpose. | |
| 554 | 555 | |
| 555 | 556 | The terminal also has an Access command (`:` → Access), a site admin's: it reads the same last-day non-browser requests as Settings → Access and the `access` MCP tool, newest first, and filters them with `s` (since), `u` (user agent) and `p` (path), `c` to clear. |
| 556 | 557 |
scripts/gate.ts +1
| @@ -97,6 +97,7 @@ export const GATE: readonly string[] = [ | ||
| 97 | 97 | "test/release-rollback.test.ts", |
| 98 | 98 | "test/release-swap.test.ts", |
| 99 | 99 | "test/threats-doc.test.ts", |
| 100 | "test/resilience.test.ts", | |
| 100 | 101 | "test/returns.test.ts", |
| 101 | 102 | "test/review-route.test.ts", |
| 102 | 103 | "test/review-lines.test.ts", |
scripts/shards.ts +11
| @@ -191,6 +191,17 @@ export function weigher( | ||
| 191 | 191 | times.get(normalise(file)) ?? (bytes.get(file) ?? 0) * perByte; |
| 192 | 192 | } |
| 193 | 193 | |
| 194 | /** | |
| 195 | * The gate's verdict per test file, for the Resilience page: one file per | |
| 196 | * result, `pass` when it exited 0. A file that never started has no entry. | |
| 197 | */ | |
| 198 | export function formatGateResults(results: readonly ShardResult[]): string { | |
| 199 | const out: Record<string, "pass" | "fail"> = {}; | |
| 200 | for (const r of results) | |
| 201 | if (r.files.length === 1) out[normalise(r.files[0]!)] = r.code === 0 ? "pass" : "fail"; | |
| 202 | return JSON.stringify(out, null, 2) + "\n"; | |
| 203 | } | |
| 204 | ||
| 194 | 205 | /** |
| 195 | 206 | * The table as it is checked in: keys sorted, seconds to one decimal, one |
| 196 | 207 | * file per line, so a refresh reads as a small diff. |
scripts/test-shards.ts +6
| @@ -42,6 +42,7 @@ import { availableParallelism, tmpdir } from "node:os"; | ||
| 42 | 42 | import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, statSync, writeFileSync } from "node:fs"; |
| 43 | 43 | import { join } from "node:path"; |
| 44 | 44 | import { |
| 45 | formatGateResults, | |
| 45 | 46 | formatTimes, |
| 46 | 47 | heaviestFirst, |
| 47 | 48 | overlayTimes, |
| @@ -530,6 +531,11 @@ if (!record && !timed && results.length > 1) | ||
| 530 | 531 | console.log( |
| 531 | 532 | `Slowest shard ${Math.max(...spread).toFixed(1)}s, fastest ${Math.min(...spread).toFixed(1)}s.`, |
| 532 | 533 | ); |
| 534 | if (timed) { | |
| 535 | // Green or red: the Resilience page wants to know which files failed. | |
| 536 | mkdirSync(CHECK_CACHE, { recursive: true }); | |
| 537 | writeFileSync(`${CHECK_CACHE}/gate-results.json`, formatGateResults(results)); | |
| 538 | } | |
| 533 | 539 | if (record || timed) { |
| 534 | 540 | if (ending.code !== 0) { |
| 535 | 541 | console.log( |
src/checks/cache.ts +1 −1
| @@ -37,7 +37,7 @@ export const CACHE_BYTES = 64 * 1024 * 1024; | ||
| 37 | 37 | |
| 38 | 38 | const NAME = /^[A-Za-z0-9_][A-Za-z0-9_.-]{0,99}$/; |
| 39 | 39 | |
| 40 | const repoCache = (dataDir: string, repoId: string): string => | |
| 40 | export const repoCache = (dataDir: string, repoId: string): string => | |
| 41 | 41 | join(dataDir, "check-cache", repoId.replace(/[^A-Za-z0-9_-]/g, "_")); |
| 42 | 42 | |
| 43 | 43 | /** The regular files of `dir` worth copying, or none if it breaks a bound. */ |
src/checks/gate-results.ts added +84
| @@ -0,0 +1,84 @@ | ||
| 1 | /** | |
| 2 | * The last gate's verdict on each test file, for the Resilience page. The | |
| 3 | * gate (`scripts/test-shards.ts`) writes `.forge-cache/gate-results.json` | |
| 4 | * in its checkout, green or red; its cell cannot reach the data directory, | |
| 5 | * so the forge carries the file out afterwards, by a temp file and a rename. | |
| 6 | * Only the forge's own repository (`FORGE_REPO`), and only its default | |
| 7 | * branch, may: any other tenant's check, or a pull's, never decides what | |
| 8 | * the page says holds. The file is kept per repository, beside its cache. | |
| 9 | */ | |
| 10 | ||
| 11 | import { lstatSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs"; | |
| 12 | import { join } from "node:path"; | |
| 13 | import { getRepo, type Repo } from "../core/repos.ts"; | |
| 14 | import type { Database } from "bun:sqlite"; | |
| 15 | import { CHECK_CACHE, repoCache } from "./cache.ts"; | |
| 16 | ||
| 17 | export const GATE_RESULTS = "gate-results.json"; | |
| 18 | ||
| 19 | export type GateResults = Readonly<Record<string, "pass" | "fail">>; | |
| 20 | ||
| 21 | const MAX_BYTES = 1024 * 1024; | |
| 22 | const TEST_FILE = /^test\/[A-Za-z0-9_.\/-]+\.test\.ts$/; | |
| 23 | ||
| 24 | /** Only well-formed verdicts for test paths survive; anything else is none. */ | |
| 25 | export function parseGateResults(raw: string): GateResults { | |
| 26 | let parsed: unknown; | |
| 27 | try { | |
| 28 | parsed = JSON.parse(raw); | |
| 29 | } catch { | |
| 30 | return {}; | |
| 31 | } | |
| 32 | if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) | |
| 33 | return {}; | |
| 34 | const out: Record<string, "pass" | "fail"> = {}; | |
| 35 | for (const [file, verdict] of Object.entries(parsed)) | |
| 36 | if (TEST_FILE.test(file) && (verdict === "pass" || verdict === "fail")) | |
| 37 | out[file] = verdict; | |
| 38 | return out; | |
| 39 | } | |
| 40 | ||
| 41 | const kept = (dataDir: string, repoId: string): string => | |
| 42 | join(repoCache(dataDir, repoId), GATE_RESULTS); | |
| 43 | ||
| 44 | /** Whether `repo` is the repository the forge was told is its own code. */ | |
| 45 | export const isForgeRepo = (forgeRepo: string | undefined, repo: Repo): boolean => | |
| 46 | forgeRepo !== undefined && forgeRepo === `${repo.ownerName}/${repo.name}`; | |
| 47 | ||
| 48 | /** The forge's own repository, if it is named and there. */ | |
| 49 | export function forgeOwnRepo(db: Database, forgeRepo: string | undefined): Repo | undefined { | |
| 50 | const [owner, name, extra] = (forgeRepo ?? "").split("/"); | |
| 51 | if (!owner || !name || extra !== undefined) return undefined; | |
| 52 | return getRepo(db, owner, name); | |
| 53 | } | |
| 54 | ||
| 55 | /** What the page reads: the repository's kept verdicts, or none. */ | |
| 56 | export function readGateResults(dataDir: string, repoId: string): GateResults { | |
| 57 | try { | |
| 58 | const path = kept(dataDir, repoId); | |
| 59 | if (lstatSync(path).size > MAX_BYTES) return {}; | |
| 60 | return parseGateResults(readFileSync(path, "utf8")); | |
| 61 | } catch { | |
| 62 | return {}; | |
| 63 | } | |
| 64 | } | |
| 65 | ||
| 66 | /** Moves the checkout's verdicts under the repository's cache directory; how many were kept. */ | |
| 67 | export function carryGateResults( | |
| 68 | checkout: string, | |
| 69 | dataDir: string, | |
| 70 | repoId: string, | |
| 71 | ): number { | |
| 72 | const from = join(checkout, CHECK_CACHE, GATE_RESULTS); | |
| 73 | const stat = lstatSync(from, { throwIfNoEntry: false }); | |
| 74 | if (!stat?.isFile() || stat.size > MAX_BYTES) return 0; | |
| 75 | const verdicts = parseGateResults(readFileSync(from, "utf8")); | |
| 76 | const count = Object.keys(verdicts).length; | |
| 77 | if (count === 0) return 0; | |
| 78 | const to = kept(dataDir, repoId); | |
| 79 | mkdirSync(repoCache(dataDir, repoId), { recursive: true }); | |
| 80 | const tmp = `${to}.${process.pid}.tmp`; | |
| 81 | writeFileSync(tmp, JSON.stringify(verdicts, null, 2) + "\n"); | |
| 82 | renameSync(tmp, to); | |
| 83 | return count; | |
| 84 | } |
src/checks/service.ts +11
| @@ -47,6 +47,7 @@ import { checkKey, provenBy, recordProven } from "./proven.ts"; | ||
| 47 | 47 | import { giveHistory } from "./history.ts"; |
| 48 | 48 | import { readLearned } from "./learned.ts"; |
| 49 | 49 | import { keepCache, restoreCache } from "./cache.ts"; |
| 50 | import { carryGateResults, isForgeRepo } from "./gate-results.ts"; | |
| 50 | 51 | import { ASKED, redMain, unheld } from "./red_main.ts"; |
| 51 | 52 | import { IMPACT_FILE, keepImpact, seedImpact } from "./impact-store.ts"; |
| 52 | 53 | import { getIssueById } from "../core/issues.ts"; |
| @@ -816,6 +817,16 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle { | ||
| 816 | 817 | }); |
| 817 | 818 | } |
| 818 | 819 | if (!ran.ok && ran.error === JOB_VANISHED) return { ok: false, error: JOB_VANISHED }; |
| 820 | // Red or green, the default branch's gate leaves its per-file verdicts | |
| 821 | // for the Resilience page; a pull's never do, nor any other repository's. | |
| 822 | if (x.keep === true && isForgeRepo(app.config.forgeRepo, repo)) { | |
| 823 | try { | |
| 824 | const carried = carryGateResults(dir, app.config.dataDir, repo.id); | |
| 825 | if (carried > 0) write(`gate results: ${carried} test files`); | |
| 826 | } catch (error) { | |
| 827 | write(`gate results not kept: ${String(error)}`); | |
| 828 | } | |
| 829 | } | |
| 819 | 830 | if (!ran.ok) { |
| 820 | 831 | const { summary, detail } = summariseCheckFailure( |
| 821 | 832 | checkLines, |
src/core/reserved.ts +1
| @@ -86,6 +86,7 @@ export const SYSTEM_NAMES: readonly string[] = [ | ||
| 86 | 86 | "og", |
| 87 | 87 | "organizations", |
| 88 | 88 | "origins", |
| 89 | "resilience", | |
| 89 | 90 | "robots.txt", |
| 90 | 91 | "llms.txt", |
| 91 | 92 | "runs", |
src/http/server.ts +3
| @@ -8,6 +8,7 @@ | ||
| 8 | 8 | import { TOOLBAR_NAME, toolbarResponse } from "../apps/toolbar.ts"; |
| 9 | 9 | import { unsealReleased } from "../actions/sealed.ts"; |
| 10 | 10 | import { accessPage } from "../web/pages/access.ts"; |
| 11 | import { resiliencePage } from "../web/pages/resilience.ts"; | |
| 11 | 12 | import { capacityPage, capacitySet } from "../web/pages/capacity.ts"; |
| 12 | 13 | import { flowPage } from "../web/pages/flow.ts"; |
| 13 | 14 | import { limitsPage, limitsSet } from "../web/pages/admin-limits.ts"; |
| @@ -640,6 +641,8 @@ export function buildRouter(): Router<Handler> { | ||
| 640 | 641 | router.add("GET", "/map", globalMapPage); |
| 641 | 642 | // The pipeline's stages and its bottleneck, for a forge admin (#1554); literal, above /:owner. |
| 642 | 643 | router.add("GET", "/flow", flowPage); |
| 644 | // Each THREATS.md protection green, red or untested from the last gate; literal, above /:owner. | |
| 645 | router.add("GET", "/resilience", resiliencePage); | |
| 643 | 646 | // A selection's spend and runs over time; literal, above /:owner. |
| 644 | 647 | router.add("GET", "/fleet/graph", fleetGraphPage); |
| 645 | 648 | router.add("GET", "/fleet/graph/live", fleetGraphLive); |
src/web/layout.ts +1
| @@ -275,6 +275,7 @@ const STATIC_PALETTE: PaletteItem[] = [ | ||
| 275 | 275 | { t: "Apps", h: "/apps", c: "Go to" }, |
| 276 | 276 | { t: "Explore", h: "/explore", c: "Go to" }, |
| 277 | 277 | { t: "Map", h: "/map", c: "Go to" }, |
| 278 | { t: "Resilience", h: "/resilience", c: "Go to" }, | |
| 278 | 279 | { t: "What you asked for", h: "/asked", c: "Go to" }, |
| 279 | 280 | { t: "Front page", h: "/front", c: "Go to" }, |
| 280 | 281 | { t: "New app", h: "/apps/new", c: "Create" }, |
src/web/pages/resilience.ts added +129
| @@ -0,0 +1,129 @@ | ||
| 1 | /** | |
| 2 | * Resilience: each protection `docs/THREATS.md` promises, green, red or | |
| 3 | * "no test yet". The doc names the test file behind every protection; the | |
| 4 | * last gate left one verdict per test file in `gate-results.json` under the | |
| 5 | * data directory (`{"test/x.test.ts": "pass" | "fail"}`). A line is red when | |
| 6 | * its file failed, green when it passed, "no test yet" when the doc says so, | |
| 7 | * and "not run" when the doc cites a file the last gate did not report. | |
| 8 | */ | |
| 9 | ||
| 10 | import { existsSync, readFileSync } from "node:fs"; | |
| 11 | import { join } from "node:path"; | |
| 12 | import { forgeOwnRepo, readGateResults, type GateResults } from "../../checks/gate-results.ts"; | |
| 13 | import type { Ctx } from "../../http/context.ts"; | |
| 14 | import { html, type Html } from "../html.ts"; | |
| 15 | import { notFoundPage, signInFirst } from "../chrome.ts"; | |
| 16 | import { page } from "../layout.ts"; | |
| 17 | import { badge, listCard, row } from "../ui.ts"; | |
| 18 | ||
| 19 | export type Standing = "green" | "red" | "untested" | "unreported"; | |
| 20 | ||
| 21 | export interface Protection { | |
| 22 | /** The adversary heading it sits under. */ | |
| 23 | who: string; | |
| 24 | text: string; | |
| 25 | /** The cited test file, or undefined for "none yet". */ | |
| 26 | file: string | undefined; | |
| 27 | } | |
| 28 | ||
| 29 | export type { GateResults }; | |
| 30 | ||
| 31 | const TEST_FILE = /^`(test\/[A-Za-z0-9_.-]+\.test\.ts)`$/; | |
| 32 | ||
| 33 | /** Every bullet and table row of the doc that ends in a test or "none yet". */ | |
| 34 | export function protectionsOf(doc: string): Protection[] { | |
| 35 | const found: Protection[] = []; | |
| 36 | let who = ""; | |
| 37 | let text: string[] = []; | |
| 38 | for (const line of doc.split("\n")) { | |
| 39 | if (line.startsWith("## ")) { | |
| 40 | who = line.slice(3).trim(); | |
| 41 | text = []; | |
| 42 | } else if (line.startsWith("- ")) { | |
| 43 | text = [line.slice(2).trim()]; | |
| 44 | } else if (/^\s+Test: /.test(line)) { | |
| 45 | const what = line.replace(/^\s+Test: /, "").trim(); | |
| 46 | if (text.length > 0 && who !== "") | |
| 47 | found.push({ who, text: text.join(" "), file: TEST_FILE.exec(what)?.[1] }); | |
| 48 | text = []; | |
| 49 | } else if (/^\s+\S/.test(line) && text.length > 0) { | |
| 50 | text.push(line.trim()); | |
| 51 | } else if (line.startsWith("| ") && line.includes("→")) { | |
| 52 | const cells = line.split("|").map((c) => c.trim()); | |
| 53 | const last = cells.at(-2) ?? ""; | |
| 54 | found.push({ who, text: cells[1] ?? "", file: TEST_FILE.exec(last)?.[1] }); | |
| 55 | } | |
| 56 | } | |
| 57 | return found; | |
| 58 | } | |
| 59 | ||
| 60 | /** What the last gate said about one protection. */ | |
| 61 | export function standing(p: Protection, results: GateResults): Standing { | |
| 62 | if (p.file === undefined) return "untested"; | |
| 63 | const verdict = results[p.file]; | |
| 64 | if (verdict === "fail") return "red"; | |
| 65 | return verdict === "pass" ? "green" : "unreported"; | |
| 66 | } | |
| 67 | ||
| 68 | const LOOK: Record<Standing, { label: string; tone: "success" | "danger" | "default" | "attn" }> = { | |
| 69 | green: { label: "Green", tone: "success" }, | |
| 70 | red: { label: "Red", tone: "danger" }, | |
| 71 | untested: { label: "No test yet", tone: "attn" }, | |
| 72 | unreported: { label: "Not run", tone: "default" }, | |
| 73 | }; | |
| 74 | ||
| 75 | const DOC = join(import.meta.dir, "../../../docs/THREATS.md"); | |
| 76 | ||
| 77 | function read(path: string): string { | |
| 78 | return existsSync(path) ? readFileSync(path, "utf8") : ""; | |
| 79 | } | |
| 80 | ||
| 81 | /** The page body for a doc and a gate result — plain data in, markup out. */ | |
| 82 | export function resilienceBody(doc: string, results: GateResults): Html { | |
| 83 | const all = protectionsOf(doc); | |
| 84 | if (all.length === 0) | |
| 85 | return html`<p class="muted">No protections are written down.</p>`; | |
| 86 | const groups = new Map<string, Protection[]>(); | |
| 87 | for (const p of all) groups.set(p.who, [...(groups.get(p.who) ?? []), p]); | |
| 88 | const count = (s: Standing) => all.filter((p) => standing(p, results) === s).length; | |
| 89 | return html`<p class="muted"> | |
| 90 | ${count("green")} green, ${count("red")} red, ${count("untested")} with no | |
| 91 | test yet, ${count("unreported")} not run in the last gate. | |
| 92 | </p> | |
| 93 | ${[...groups].map(([who, items]) => | |
| 94 | listCard( | |
| 95 | items.map((p) => { | |
| 96 | const look = LOOK[standing(p, results)]; | |
| 97 | return row({ | |
| 98 | title: p.text, | |
| 99 | meta: | |
| 100 | p.file === undefined | |
| 101 | ? html`none yet` | |
| 102 | : html`<span class="mono">${p.file}</span>`, | |
| 103 | trail: html`<span | |
| 104 | data-file="${p.file ?? ""}" | |
| 105 | data-standing="${standing(p, results)}" | |
| 106 | >${badge(look.label, { tone: look.tone })}</span | |
| 107 | >`, | |
| 108 | }); | |
| 109 | }), | |
| 110 | { head: html`<h2>${who}</h2>` }, | |
| 111 | ), | |
| 112 | )}`; | |
| 113 | } | |
| 114 | ||
| 115 | // GET /resilience | |
| 116 | export function resiliencePage(ctx: Ctx): Response { | |
| 117 | // Which defences are failing right now is for the forge's admins, as /flow is. | |
| 118 | if (!ctx.auth.user) return signInFirst(ctx); | |
| 119 | if (!ctx.auth.user.isAdmin) return notFoundPage(ctx); | |
| 120 | const own = forgeOwnRepo(ctx.app.db, ctx.app.config.forgeRepo); | |
| 121 | const results = own === undefined ? {} : readGateResults(ctx.app.config.dataDir, own.id); | |
| 122 | return page({ | |
| 123 | ctx, | |
| 124 | title: "Resilience", | |
| 125 | description: "Each protection the forge promises, and whether the last gate proved it.", | |
| 126 | body: html`<div class="page-head"><h1>Resilience</h1></div> | |
| 127 | ${resilienceBody(read(DOC), results)}`, | |
| 128 | }); | |
| 129 | } |
test/resilience.test.ts added +216
| @@ -0,0 +1,216 @@ | ||
| 1 | import { afterAll, beforeAll, expect, test } from "bun:test"; | |
| 2 | import { repoCache } from "../src/checks/cache.ts"; | |
| 3 | import { existsSync, mkdirSync, writeFileSync } from "node:fs"; | |
| 4 | import { mkdtemp, rm } from "node:fs/promises"; | |
| 5 | import { tmpdir } from "node:os"; | |
| 6 | import { join } from "node:path"; | |
| 7 | import { createApp, type App } from "../src/app.ts"; | |
| 8 | import { commitToBranch, createRepo } from "../src/actions/repos.ts"; | |
| 9 | import { startChecks, type ChecksHandle } from "../src/checks/service.ts"; | |
| 10 | import { listRuns } from "../src/core/runs.ts"; | |
| 11 | import type { Repo } from "../src/core/repos.ts"; | |
| 12 | import type { User } from "../src/core/users.ts"; | |
| 13 | import { carryGateResults, parseGateResults } from "../src/checks/gate-results.ts"; | |
| 14 | import { createUser } from "../src/core/users.ts"; | |
| 15 | import { formatGateResults } from "../scripts/shards.ts"; | |
| 16 | import { serve, type Servers } from "../src/http/server.ts"; | |
| 17 | import { | |
| 18 | protectionsOf, | |
| 19 | standing, | |
| 20 | } from "../src/web/pages/resilience.ts"; | |
| 21 | ||
| 22 | const DOC = `# Threats | |
| 23 | ||
| 24 | ## A stolen token | |
| 25 | ||
| 26 | - Tokens carry a scope. | |
| 27 | Test: \`test/tokens.test.ts\` | |
| 28 | - Revoking every token at once. | |
| 29 | Test: none yet | |
| 30 | - Sessions are HttpOnly. | |
| 31 | Test: \`test/own-session.test.ts\` | |
| 32 | ||
| 33 | ## Internal calls | |
| 34 | ||
| 35 | | call | protection | test | | |
| 36 | | --- | --- | --- | | |
| 37 | | runner → forge | a passport | \`test/passport.test.ts\` | | |
| 38 | `; | |
| 39 | ||
| 40 | test("a gate result with the cited file failed marks the line red", () => { | |
| 41 | const ps = protectionsOf(DOC); | |
| 42 | expect(ps.map((p) => p.file)).toEqual([ | |
| 43 | "test/tokens.test.ts", | |
| 44 | undefined, | |
| 45 | "test/own-session.test.ts", | |
| 46 | "test/passport.test.ts", | |
| 47 | ]); | |
| 48 | const results = { | |
| 49 | "test/tokens.test.ts": "fail", | |
| 50 | "test/own-session.test.ts": "pass", | |
| 51 | } as const; | |
| 52 | expect(ps.map((p) => standing(p, results))).toEqual([ | |
| 53 | "red", | |
| 54 | "untested", | |
| 55 | "green", | |
| 56 | "unreported", | |
| 57 | ]); | |
| 58 | }); | |
| 59 | ||
| 60 | test("a malformed gate result says nothing rather than something false", () => { | |
| 61 | expect(parseGateResults("not json")).toEqual({}); | |
| 62 | expect(parseGateResults("[1]")).toEqual({}); | |
| 63 | expect(parseGateResults('{"test/a.test.ts":"pass","test/b.test.ts":"maybe"}')).toEqual({ | |
| 64 | "test/a.test.ts": "pass", | |
| 65 | }); | |
| 66 | }); | |
| 67 | ||
| 68 | let dir: string; | |
| 69 | let checkout: string; | |
| 70 | let app: App; | |
| 71 | let servers: Servers; | |
| 72 | let checks: ChecksHandle; | |
| 73 | let alice: User; | |
| 74 | let forge: Repo; | |
| 75 | let other: Repo; | |
| 76 | ||
| 77 | const login = async (username: string): Promise<string> => { | |
| 78 | const res = await fetch(`${servers.url}/signin`, { | |
| 79 | method: "POST", | |
| 80 | redirect: "manual", | |
| 81 | headers: { | |
| 82 | "content-type": "application/x-www-form-urlencoded", | |
| 83 | origin: servers.url, | |
| 84 | }, | |
| 85 | body: new URLSearchParams({ username, password: "a-good-passphrase" }), | |
| 86 | }); | |
| 87 | return (res.headers.get("set-cookie") ?? "").split(";")[0] ?? ""; | |
| 88 | }; | |
| 89 | ||
| 90 | beforeAll(async () => { | |
| 91 | dir = await mkdtemp(join(tmpdir(), "forge-resilience-")); | |
| 92 | checkout = await mkdtemp(join(tmpdir(), "forge-resilience-co-")); | |
| 93 | app = createApp({ dataDir: dir, port: 0, forgeRepo: "alice/forge" }); | |
| 94 | servers = await serve(app); | |
| 95 | checks = startChecks(app, { forgeUrl: servers.url, concurrency: 1 }); | |
| 96 | for (const [username, adminIfFirst] of [["alice", true], ["bob", false]] as const) { | |
| 97 | const made = await createUser(app.db, { | |
| 98 | trusted: true, | |
| 99 | username, | |
| 100 | email: `${username}@forge.local`, | |
| 101 | password: "a-good-passphrase", | |
| 102 | adminIfFirst, | |
| 103 | }); | |
| 104 | if (!made.ok) throw new Error(made.error); | |
| 105 | if (username === "alice") alice = made.value; | |
| 106 | } | |
| 107 | for (const name of ["forge", "other"]) { | |
| 108 | const made = await createRepo(app, alice, { name, visibility: "public" }); | |
| 109 | if (!made.ok) throw new Error(String(made.error)); | |
| 110 | if (name === "forge") forge = made.value; | |
| 111 | else other = made.value; | |
| 112 | } | |
| 113 | // What the gate writes in its checkout, and what the forge carries out. | |
| 114 | mkdirSync(join(checkout, ".forge-cache")); | |
| 115 | writeFileSync( | |
| 116 | join(checkout, ".forge-cache/gate-results.json"), | |
| 117 | formatGateResults([ | |
| 118 | { files: ["test/tokens.test.ts"], code: 1, output: "" }, | |
| 119 | { files: ["test/own-session.test.ts"], code: 0, output: "" }, | |
| 120 | ]), | |
| 121 | ); | |
| 122 | }); | |
| 123 | afterAll(async () => { | |
| 124 | await checks.stop(); | |
| 125 | servers.stop(); | |
| 126 | app.close(); | |
| 127 | await rm(dir, { recursive: true, force: true }); | |
| 128 | await rm(checkout, { recursive: true, force: true }); | |
| 129 | }); | |
| 130 | ||
| 131 | test("the gate's writer and the forge's carry put the verdicts where the page reads", async () => { | |
| 132 | expect(carryGateResults(checkout, dir, forge.id)).toBe(2); | |
| 133 | const cookie = await login("alice"); | |
| 134 | const res = await fetch(`${servers.url}/resilience`, { headers: { cookie } }); | |
| 135 | expect(res.status).toBe(200); | |
| 136 | const body = await res.text(); | |
| 137 | const standingOf = (file: string) => | |
| 138 | new RegExp(`data-file="${file}"\\s+data-standing="(\\w+)"`).exec(body)?.[1]; | |
| 139 | expect(standingOf("test/tokens.test.ts")).toBe("red"); | |
| 140 | expect(standingOf("test/own-session.test.ts")).toBe("green"); | |
| 141 | expect(body).toContain("No test yet"); | |
| 142 | }); | |
| 143 | ||
| 144 | test("a checkout without verdicts carries nothing and leaves the last ones", () => { | |
| 145 | const empty = join(checkout, "none"); | |
| 146 | mkdirSync(empty); | |
| 147 | expect(carryGateResults(empty, dir, forge.id)).toBe(0); | |
| 148 | expect(parseGateResults(JSON.stringify({ "../x": "pass" }))).toEqual({}); | |
| 149 | }); | |
| 150 | ||
| 151 | test("a guest is sent to sign in and a non-admin gets 404", async () => { | |
| 152 | const guest = await fetch(`${servers.url}/resilience`, { redirect: "manual" }); | |
| 153 | expect(guest.status).not.toBe(200); | |
| 154 | expect(await guest.text()).not.toContain("test/tokens.test.ts"); | |
| 155 | const bob = await fetch(`${servers.url}/resilience`, { | |
| 156 | headers: { cookie: await login("bob") }, | |
| 157 | }); | |
| 158 | expect(bob.status).toBe(404); | |
| 159 | }); | |
| 160 | ||
| 161 | // A check that leaves the gate's verdict file the way the gate does. | |
| 162 | const verdictCheck = (file: string, verdict: string): string => | |
| 163 | JSON.stringify({ | |
| 164 | check: { | |
| 165 | run: `mkdir -p .forge-cache && echo '{"${file}":"${verdict}"}' > .forge-cache/gate-results.json`, | |
| 166 | install: "", | |
| 167 | }, | |
| 168 | }) + "\n"; | |
| 169 | ||
| 170 | async function checked(repo: Repo, file: string, verdict: string) { | |
| 171 | const pushed = await commitToBranch(app, alice, repo, { | |
| 172 | message: "A gate", | |
| 173 | files: [{ path: "forge.json", content: verdictCheck(file, verdict) }], | |
| 174 | }); | |
| 175 | if (!pushed.ok) throw new Error(JSON.stringify(pushed.error)); | |
| 176 | for (let i = 0; i < 600; i++) { | |
| 177 | const run = listRuns(app.db, repo.id, { kind: "check", limit: 20 }).find( | |
| 178 | (r) => r.commitOid === pushed.value.commitOid, | |
| 179 | ); | |
| 180 | if (run && (run.state === "ok" || run.state === "failed")) return; | |
| 181 | await Bun.sleep(50); | |
| 182 | } | |
| 183 | throw new Error("check did not settle"); | |
| 184 | } | |
| 185 | ||
| 186 | const standingOn = async (file: string) => { | |
| 187 | const res = await fetch(`${servers.url}/resilience`, { | |
| 188 | headers: { cookie: await login("alice") }, | |
| 189 | }); | |
| 190 | const body = await res.text(); | |
| 191 | return new RegExp(`data-file="${file}"\\s+data-standing="(\\w+)"`).exec(body)?.[1]; | |
| 192 | }; | |
| 193 | ||
| 194 | test("only the forge's own default branch decides the page, not another repository's", async () => { | |
| 195 | // Start from a page the forge's own check has not touched. | |
| 196 | await rm(join(dir, "check-cache"), { recursive: true, force: true }); | |
| 197 | // Another tenant's default-branch check claims a defence holds: nothing changes. | |
| 198 | await checked(other, "test/passport.test.ts", "pass"); | |
| 199 | expect(await standingOn("test/passport.test.ts")).toBe("unreported"); | |
| 200 | expect(existsSync(join(repoCache(dir, other.id), "gate-results.json"))).toBe(false); | |
| 201 | // The forge's own default-branch check is believed. | |
| 202 | await checked(forge, "test/passport.test.ts", "fail"); | |
| 203 | expect(await standingOn("test/passport.test.ts")).toBe("red"); | |
| 204 | }); | |
| 205 | ||
| 206 | test("a pull's check never writes the verdicts", async () => { | |
| 207 | const before = await standingOn("test/passport.test.ts"); | |
| 208 | const branch = await commitToBranch(app, alice, forge, { | |
| 209 | message: "A pull's gate", | |
| 210 | branch: "pull-branch", | |
| 211 | files: [{ path: "forge.json", content: verdictCheck("test/passport.test.ts", "pass") }], | |
| 212 | }); | |
| 213 | if (!branch.ok) throw new Error(JSON.stringify(branch.error)); | |
| 214 | await Bun.sleep(1500); | |
| 215 | expect(await standingOn("test/passport.test.ts")).toBe(before); | |
| 216 | }); |
new above
offline