Public: anyone can read this; the crew can change it.

The gate every push is judged by runs 23 of the repository's 113 test files #304

Closed opened this
Closed without merging

mason/forge:mason/261-the-gate-every-push-is-judged-by-runs-23 → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +560 −5
CLAUDE.md +9
@@ -74,6 +74,15 @@ bun run src/main.ts # boots on :3000, data in ./data
7474 the reason is printed so a skip is never read as a pass.
7575 - **`bun run check` is the gate**, and it reads its command from
7676 `forge.json`, so what you see is exactly what the push will be judged by.
77 It covers the whole suite: `scripts/suite.ts` runs every `test/*.test.ts`,
78 so a file you add is in the gate the moment it exists. The few it does not
79 run are listed in `EXCLUDED` in that file, each with a one-line reason and
80 the issue that puts it back — `test/check-list.test.ts` makes an exclusion
81 without a reason, an issue, or a file on disk red. Never hand the check a
82 list of test files; that hole cost the crew #238, #253 and #261. The suite
83 runs in two `bun test` shards (~5 min, against ~9 sequentially);
84 `SUITE_WORKERS=1 bun run scripts/suite.ts` is the sequential run, and
85 `SUITE_WORKERS=n` is how you try a wider one.
7786 - **Every non-trivial change ships with a test.** Prefer protocol-level tests
7887 that boot a real app (`createApp` + `serve`) over unit mocks. Adversarial
7988 tests (can this be bypassed?) are worth more than happy-path ones.
README.md +8 −1
@@ -302,7 +302,14 @@ bun run check # exactly what the forge runs against every push
302302 ```
303303
304304 `bun run check` is the gate: the same command `forge.json` declares, so what
305 it says here is what the deploy will say. Two things it will not do:
305 it says here is what the deploy will say. It types the tree and then runs the
306 whole suite — `scripts/suite.ts` starts from every `test/*.test.ts`, so a new
307 test file is judged from the moment it exists, and the handful it leaves out
308 are listed there with a reason and an issue each. It splits those files over
309 two `bun test` children — about five minutes here against nine in a row —
310 and prints every failing test across both at the end; `SUITE_WORKERS=1`
311 runs them sequentially, `SUITE_WORKERS=n` over more. Two things it will not
312 do:
306313
307314 - **It never borrows your git configuration.** A test drives a real `git`
308315 against a forge it booted a second ago, and builds that child's
forge.json +1 −1
@@ -6,7 +6,7 @@
66 "ready": 90
77 },
88 "check": {
9 "run": "bun x tsc --noEmit && bun test --timeout 60000 test/crew.test.ts test/crew-wrapup.test.ts test/crew-limits.test.ts test/crew-sandbox.test.ts test/steer.test.ts test/landing.test.ts test/decide.test.ts test/ledger.test.ts test/checks.test.ts test/dependencies.test.ts test/autonomy.test.ts test/studio.test.ts test/studio-words.test.ts test/forks.test.ts test/fork-flow.test.ts test/cross-repo-pull.test.ts test/pulls.test.ts test/repos.test.ts test/apps.test.ts test/apps-adversarial.test.ts test/web.test.ts test/git-trust.test.ts test/helpers.test.ts",
9 "run": "bun x tsc --noEmit && bun run scripts/suite.ts",
1010 "timeout": 1800
1111 }
1212 }
scripts/suite.ts added +238
@@ -0,0 +1,238 @@
1 /**
2 * The suite the gate runs: every `test/*.test.ts`, minus a short list that
3 * says out loud why each one is out.
4 *
5 * The gate used to name its files by hand, so a new test file joined the
6 * suite and the gate ignored it — silently, forever (#261). The default is
7 * inverted here: a file in `test/` is in the gate the moment it exists, and
8 * leaving one out costs an entry in `EXCLUDED` with a reason and the issue
9 * that will put it back. `test/check-list.test.ts` makes that mechanical —
10 * an exclusion with no reason, no issue, or no file on disk is red.
11 *
12 * Run as a script (this is what `forge.json`'s `check.run` calls), it splits
13 * that set across `bun test` children and exits red if any of them is.
14 * Sequentially the suite is nine minutes, and a check that long is hostage to
15 * the forge's own restarts — a run whose forge goes away is failed outright,
16 * so the gate loses to a deploy of `main` rather than to a test (#303). In
17 * two shards it is five, which is also the difference between a crew member
18 * running the gate before a push and guessing (#277).
19 */
20
21 import { readdirSync, statSync } from "node:fs";
22
23 /** One test file the gate does not run, and the reason a reader can check. */
24 export type Exclusion = {
25 /** Path from the repository root, e.g. `test/looks.test.ts`. */
26 readonly file: string;
27 /** One line: why it is out, ending in the issue that puts it back. */
28 readonly reason: string;
29 };
30
31 /**
32 * Measured on 2026-09-22 against `main` at `7845c46`: the whole suite is
33 * 1754 tests across 115 files in 8m36s sequentially — inside the check's
34 * 1800s timeout — with 20 red, all of them in the eight files below. Each
35 * carries the issue that owns it. Nothing else is excluded: slow is not a
36 * reason while the suite fits.
37 */
38 export const EXCLUDED: readonly Exclusion[] = [
39 {
40 file: "test/web-apps.test.ts",
41 reason:
42 "9 red: asserts dashboard and repo headings the studio redesign moved (#290)",
43 },
44 {
45 file: "test/web-code.test.ts",
46 reason: "4 red: asserts the pre-studio search page and repo rows (#291)",
47 },
48 {
49 file: "test/web-origins.test.ts",
50 reason: "1 red: asserts the dashboard's old 'On your machine' card (#291)",
51 },
52 {
53 file: "test/ssh-site.test.ts",
54 reason: "1 red: asserts the dashboard's old Terminal card (#291)",
55 },
56 {
57 file: "test/looks.test.ts",
58 reason: "1 red: asserts the studio look ask's pre-redesign markup (#291)",
59 },
60 {
61 file: "test/surfaces-adversarial.test.ts",
62 reason: "2 red: /apps and the dashboard cards query per row again (#292)",
63 },
64 {
65 file: "test/agents.test.ts",
66 reason: "1 red: fifty concurrent pushes lose auth on the hook socket (#293)",
67 },
68 {
69 file: "test/highlight.test.ts",
70 reason:
71 "1 red: a 10,000-character line scans in 25ms against a 10ms bound (#294)",
72 },
73 ];
74
75 /** The repository root, wherever this file is run from. */
76 const root = new URL("..", import.meta.url).pathname;
77
78 /** Every `test/*.test.ts`, sorted, whether or not the gate runs it. */
79 export function allTestFiles(): string[] {
80 return readdirSync(new URL("../test", import.meta.url))
81 .filter((name) => name.endsWith(".test.ts"))
82 .map((name) => `test/${name}`)
83 .sort();
84 }
85
86 /** The files the gate runs: everything, minus `EXCLUDED`. */
87 export function suiteFiles(): string[] {
88 const out = new Set(EXCLUDED.map((one) => one.file));
89 return allTestFiles().filter((file) => !out.has(file));
90 }
91
92 /**
93 * How many `bun test` children run at once. `SUITE_WORKERS` overrides it;
94 * `SUITE_WORKERS=1` is the old sequential run, for anyone chasing a test
95 * that only fails beside its neighbours.
96 *
97 * Two, not more: measured here, four shards turned `test/steer.test.ts` and
98 * `test/tui-workflows.test.ts` red — both wait on wall-clock deadlines, and
99 * a loaded machine is enough to miss them. Two halves the nine minutes and
100 * was green twice running; a faster gate than that is #277's, and it wants
101 * those deadlines made load-proof first.
102 */
103 export function workerCount(
104 env: Record<string, string | undefined> = process.env,
105 ): number {
106 const asked = Number(env["SUITE_WORKERS"] ?? "");
107 if (Number.isInteger(asked) && asked > 0) return asked;
108 return Math.max(1, Math.min(2, navigator.hardwareConcurrency));
109 }
110
111 /**
112 * Split files across `workers` shards, biggest first into the lightest shard
113 * — bytes are a rough stand-in for how long a file takes, and the run is only
114 * as fast as its slowest shard. Deterministic: same tree, same shards, so a
115 * failure is reproducible with the shard's own command line.
116 */
117 export function shardFiles(
118 files: readonly string[],
119 workers: number,
120 weight: (file: string) => number = (file) =>
121 statSync(new URL(`../${file}`, import.meta.url)).size,
122 ): string[][] {
123 const shards: string[][] = Array.from({ length: Math.max(1, workers) }, () =>
124 [],
125 );
126 const load = new Array<number>(shards.length).fill(0);
127 const heaviestFirst = [...files].sort(
128 (a, b) => weight(b) - weight(a) || a.localeCompare(b),
129 );
130 for (const file of heaviestFirst) {
131 let lightest = 0;
132 for (let i = 1; i < load.length; i++)
133 if ((load[i] ?? 0) < (load[lightest] ?? 0)) lightest = i;
134 shards[lightest]?.push(file);
135 load[lightest] = (load[lightest] ?? 0) + weight(file);
136 }
137 return shards.filter((shard) => shard.length > 0).map((shard) => shard.sort());
138 }
139
140 /** What one `bun test` child said and how it ended. */
141 export type ShardRun = {
142 readonly shard: readonly string[];
143 readonly out: string;
144 readonly err: string;
145 readonly code: number;
146 };
147
148 /** The whole run in one shape: the tally, every red test, and the verdict. */
149 export type Summary = {
150 readonly pass: number;
151 readonly fail: number;
152 readonly skip: number;
153 readonly tests: number;
154 readonly files: number;
155 /** Every failing test by name, then the command that repeats its shard. */
156 readonly red: string[];
157 readonly ok: boolean;
158 };
159
160 /**
161 * Add the shards up. The last shard's own summary is not the run's, and a
162 * reader should not have to scroll several of them to learn what broke — so
163 * the counts are summed and the failing tests gathered in one place, in
164 * shard order, each red shard followed by the command that repeats it alone.
165 */
166 export function summarize(runs: readonly ShardRun[]): Summary {
167 const total = { pass: 0, fail: 0, skip: 0, tests: 0, files: 0 };
168 const red: string[] = [];
169 for (const [index, run] of runs.entries()) {
170 const whole = `${run.out}\n${run.err}`;
171 total.pass += tally(whole, "pass");
172 total.fail += tally(whole, "fail");
173 total.skip += tally(whole, "skip");
174 const ran = /^Ran (\d+) tests? across (\d+) files?/m.exec(whole);
175 total.tests += Number(ran?.[1] ?? 0);
176 total.files += Number(ran?.[2] ?? 0);
177 for (const line of whole.split("\n"))
178 if (line.startsWith("(fail)")) red.push(line.trim());
179 if (run.code !== 0)
180 red.push(`shard ${index + 1} red: bun test ${run.shard.join(" ")}`);
181 }
182 return { ...total, red, ok: runs.every((run) => run.code === 0) };
183 }
184
185 /** `bun test`'s own tally line for one outcome, e.g. ` 345 pass`. */
186 function tally(output: string, what: "pass" | "fail" | "skip"): number {
187 const found = new RegExp(`^\\s*(\\d+) ${what}\\s*$`, "m").exec(output);
188 return Number(found?.[1] ?? 0);
189 }
190
191 if (import.meta.main) {
192 const files = suiteFiles();
193 const shards = shardFiles(files, workerCount());
194 console.log(
195 `suite: ${files.length} test files in ${shards.length} shard(s)` +
196 (EXCLUDED.length === 0
197 ? ""
198 : `, ${EXCLUDED.length} excluded (scripts/suite.ts says why)`),
199 );
200 const started = Date.now();
201 // Each shard's output is held and printed whole, in shard order: two
202 // reporters writing to one terminal at once is unreadable, and a check log
203 // is read after the fact anyway.
204 const runs = await Promise.all(
205 shards.map(async (shard): Promise<ShardRun> => {
206 const proc = Bun.spawn(["bun", "test", "--timeout", "60000", ...shard], {
207 cwd: root,
208 stdio: ["ignore", "pipe", "pipe"],
209 });
210 const [out, err, code] = await Promise.all([
211 new Response(proc.stdout).text(),
212 new Response(proc.stderr).text(),
213 proc.exited,
214 ]);
215 return { shard, out, err, code };
216 }),
217 );
218 for (const [index, run] of runs.entries()) {
219 console.log(
220 `\n--- shard ${index + 1}/${shards.length}: ${run.shard.length} files, ` +
221 `exit ${run.code} ---`,
222 );
223 process.stdout.write(run.out);
224 process.stderr.write(run.err);
225 }
226 const summary = summarize(runs);
227 if (summary.red.length > 0) {
228 console.log(`\n--- red across ${shards.length} shard(s) ---`);
229 for (const line of summary.red) console.log(line);
230 }
231 const seconds = ((Date.now() - started) / 1000).toFixed(1);
232 console.log(
233 `\nsuite: ${summary.pass} pass, ${summary.fail} fail, ${summary.skip} ` +
234 `skip — ${summary.tests} tests across ${summary.files} files in ` +
235 `${seconds}s`,
236 );
237 process.exit(summary.ok ? 0 : 1);
238 }
src/kernel/log.ts +10
@@ -42,6 +42,16 @@ export function setLogLevel(level: LogLevel): void {
4242 threshold = level;
4343 }
4444
45 /**
46 * The floor in force. One process holds one of these, and the suite runs
47 * every test file in one process: a caller that lowers the floor for a
48 * moment needs to be able to put back what it found rather than guess the
49 * default (#261).
50 */
51 export function logLevel(): LogLevel {
52 return threshold;
53 }
54
4555 export function createLog(scope: string): Log {
4656 const emit = (level: LogLevel, message: string, fields?: LogFields) => {
4757 if (order[level] < order[threshold]) return;
src/origins/mirror.ts +10 −1
@@ -62,9 +62,18 @@ export interface MirrorResult {
6262 /**
6363 * How long to wait between tries of a new mirror's first fetch. Mutable so a
6464 * test that wants a failure now can have it now; the forge keeps the default.
65 *
66 * It is one object for the whole process, so a test that shortens it owns
67 * putting `DEFAULT_FIRST_FETCH_RETRY_MS` back — the suite runs every file in
68 * one process, and a file that inherits somebody else's 50ms is red for a
69 * reason that is not in it (#261).
6570 */
71 export const DEFAULT_FIRST_FETCH_RETRY_MS: readonly number[] = [
72 2_000, 5_000, 10_000,
73 ];
74
6675 export const firstFetchRetry = {
67 ms: [2_000, 5_000, 10_000] as readonly number[],
76 ms: DEFAULT_FIRST_FETCH_RETRY_MS,
6877 };
6978
7079 export async function mirrorRepo(
test/check-list.test.ts added +227
@@ -0,0 +1,227 @@
1 /**
2 * The gate covers the suite, and can only stop covering it out loud.
3 *
4 * For a long while `forge.json`'s check named its test files by hand: 23 of
5 * 114, so a file that joined the suite was never run before a push and rotted
6 * unseen — twice found red on `main` after the fact (#238, #253, then #261).
7 * The list is gone; `scripts/suite.ts` starts from every `test/*.test.ts` and
8 * subtracts an explicit `EXCLUDED`. These tests are what keeps that true: a
9 * file left out needs a reason and an issue, an exclusion for a file that no
10 * longer exists is a stale claim, and a check command that names test files
11 * is the old hand-list coming back.
12 */
13
14 import { describe, expect, test } from "bun:test";
15 import { existsSync } from "node:fs";
16 import {
17 allTestFiles,
18 EXCLUDED,
19 shardFiles,
20 suiteFiles,
21 summarize,
22 workerCount,
23 } from "../scripts/suite.ts";
24
25 const manifest = (await Bun.file(
26 new URL("../forge.json", import.meta.url),
27 ).json()) as { check?: { run?: string; timeout?: number } };
28
29 const command = manifest.check?.run ?? "";
30
31 describe("the gate in forge.json", () => {
32 test("runs the suite through scripts/suite.ts, and names no test file itself", () => {
33 expect(command).toContain("scripts/suite.ts");
34 // A hand-written list is the hole this closes: any `.test.ts` in the
35 // command means files are being chosen one at a time again.
36 expect(command).not.toContain(".test.ts");
37 // Types first, then the suite — the gate a crew member runs locally with
38 // `bun run check` is this exact string (`scripts/check.ts`).
39 expect(command).toContain("tsc --noEmit");
40 });
41
42 test("declares the timeout the measured suite fits in", () => {
43 // 1754 tests across 115 files took 8m36s in one process on a crew
44 // machine, five minutes in two shards (#261).
45 expect(manifest.check?.timeout ?? 0).toBeGreaterThanOrEqual(1800);
46 });
47 });
48
49 describe("every test file is in the gate, or excluded for a stated reason", () => {
50 test("no file is in neither", () => {
51 const covered = new Set([
52 ...suiteFiles(),
53 ...EXCLUDED.map((one) => one.file),
54 ]);
55 const orphans = allTestFiles().filter((file) => !covered.has(file));
56 expect(orphans).toEqual([]);
57 });
58
59 test("the gate is every test file minus exactly the exclusions", () => {
60 expect(suiteFiles().length).toBe(allTestFiles().length - EXCLUDED.length);
61 for (const one of EXCLUDED) expect(suiteFiles()).not.toContain(one.file);
62 });
63
64 test("each exclusion names a test file that exists", () => {
65 const known = new Set(allTestFiles());
66 for (const one of EXCLUDED) {
67 expect(one.file.startsWith("test/") && one.file.endsWith(".test.ts")).toBe(
68 true,
69 );
70 // A file that was deleted or renamed leaves an exclusion that quietly
71 // covers nothing; the entry has to go when the file does.
72 expect(`${one.file} exists`).toBe(
73 `${one.file} ${known.has(one.file) ? "exists" : "is gone"}`,
74 );
75 expect(existsSync(new URL(`../${one.file}`, import.meta.url))).toBe(true);
76 }
77 });
78
79 test("each exclusion carries a one-line reason and the issue that ends it", () => {
80 for (const one of EXCLUDED) {
81 const reason = one.reason.trim();
82 expect(`${one.file}: ${reason.length > 20}`).toBe(`${one.file}: true`);
83 expect(reason).not.toContain("\n");
84 // Not a note — a ticket. Something outside the gate is work someone
85 // owns, and the number is how a reader finds out whether it is done.
86 expect(`${one.file}: ${/#\d+/.test(reason)}`).toBe(`${one.file}: true`);
87 }
88 });
89
90 test("no file is excluded twice", () => {
91 const files = EXCLUDED.map((one) => one.file);
92 expect([...new Set(files)].length).toBe(files.length);
93 });
94 });
95
96 describe("the shards the gate runs the suite in", () => {
97 // A fixed list with known weights: the split is arithmetic, and a test of
98 // it should not depend on how big today's test files happen to be.
99 const weights: Record<string, number> = {
100 a: 9,
101 b: 8,
102 c: 5,
103 d: 4,
104 e: 3,
105 f: 2,
106 g: 1,
107 };
108 const files = Object.keys(weights);
109 const weight = (file: string) => weights[file] ?? 0;
110
111 test("the shards are disjoint and cover every file", () => {
112 for (const workers of [1, 2, 3, 4, 7]) {
113 const shards = shardFiles(files, workers, weight);
114 const flat = shards.flat();
115 expect(flat.sort()).toEqual([...files].sort());
116 expect(new Set(flat).size).toBe(files.length);
117 expect(shards.length).toBeLessThanOrEqual(workers);
118 }
119 });
120
121 test("no shard is empty, and never more shards than files", () => {
122 const shards = shardFiles(["only"], 4, weight);
123 expect(shards).toEqual([["only"]]);
124 });
125
126 test("the heaviest files are spread, not stacked", () => {
127 const [first, second] = shardFiles(files, 2, weight);
128 const load = (shard: string[] | undefined) =>
129 (shard ?? []).reduce((sum, file) => sum + weight(file), 0);
130 // 32 in total: a greedy split puts 16 either side, and anything within a
131 // file's weight of that is a balanced shard.
132 expect(Math.abs(load(first) - load(second))).toBeLessThanOrEqual(9);
133 });
134
135 test("the same tree gives the same shards", () => {
136 expect(shardFiles(files, 3, weight)).toEqual(shardFiles(files, 3, weight));
137 // Order in is not order out: the split is by weight, not by argument.
138 expect(shardFiles([...files].reverse(), 3, weight)).toEqual(
139 shardFiles(files, 3, weight),
140 );
141 });
142
143 // What `bun test` writes at the end of a shard, near enough to parse.
144 const shardOutput = (
145 counts: { pass: number; fail: number; skip: number },
146 failing: readonly string[] = [],
147 ): string =>
148 [
149 ...failing.map((name) => `(fail) ${name} [1.00ms]`),
150 "",
151 ` ${counts.pass} pass`,
152 ` ${counts.skip} skip`,
153 ` ${counts.fail} fail`,
154 `Ran ${counts.pass + counts.fail + counts.skip} tests across 3 files. [9.00s]`,
155 "",
156 ].join("\n");
157
158 test("the tally is the sum of the shards, not the last one's", () => {
159 const summary = summarize([
160 {
161 shard: ["a", "b", "c"],
162 out: shardOutput({ pass: 10, fail: 0, skip: 1 }),
163 err: "",
164 code: 0,
165 },
166 {
167 shard: ["d", "e", "f"],
168 out: shardOutput({ pass: 7, fail: 0, skip: 2 }),
169 err: "",
170 code: 0,
171 },
172 ]);
173 expect(summary).toMatchObject({
174 pass: 17,
175 fail: 0,
176 skip: 3,
177 tests: 20,
178 files: 6,
179 ok: true,
180 });
181 expect(summary.red).toEqual([]);
182 });
183
184 test("one red shard makes the run red, and names what failed where", () => {
185 const summary = summarize([
186 {
187 shard: ["a"],
188 out: shardOutput({ pass: 3, fail: 0, skip: 0 }),
189 err: "",
190 code: 0,
191 },
192 {
193 shard: ["b", "c"],
194 out: shardOutput({ pass: 1, fail: 2, skip: 0 }, [
195 "suite > first claim",
196 "suite > second claim",
197 ]),
198 err: "",
199 code: 1,
200 },
201 ]);
202 expect(summary.ok).toBe(false);
203 expect(summary.fail).toBe(2);
204 expect(summary.red).toEqual([
205 "(fail) suite > first claim [1.00ms]",
206 "(fail) suite > second claim [1.00ms]",
207 "shard 2 red: bun test b c",
208 ]);
209 });
210
211 test("a shard that died without a tally still fails the run", () => {
212 // A crashed child prints no summary at all; exiting non-zero is the only
213 // thing the runner can trust, so the verdict comes from that alone.
214 const summary = summarize([
215 { shard: ["a"], out: "", err: "Segmentation fault", code: 139 },
216 ]);
217 expect(summary).toMatchObject({ pass: 0, tests: 0, ok: false });
218 expect(summary.red).toEqual(["shard 1 red: bun test a"]);
219 });
220
221 test("SUITE_WORKERS decides, and a bad one is ignored", () => {
222 expect(workerCount({ SUITE_WORKERS: "1" })).toBe(1);
223 expect(workerCount({ SUITE_WORKERS: "6" })).toBe(6);
224 for (const bad of ["0", "-2", "two", "", "1.5"])
225 expect(workerCount({ SUITE_WORKERS: bad })).toBeGreaterThanOrEqual(1);
226 });
227 });
test/fork-flow.test.ts +8
@@ -7,6 +7,10 @@ import { serve, type Servers } from "../src/http/server.ts";
77 import { resetConnectLimit } from "../src/actions/origins.ts";
88 import { listEvents } from "../src/core/events.ts";
99 import { settled } from "../src/origins/jobs.ts";
10 import {
11 DEFAULT_FIRST_FETCH_RETRY_MS,
12 firstFetchRetry,
13 } from "../src/origins/mirror.ts";
1014 import {
1115 mirrorAndWait,
1216 newFakeState,
@@ -156,6 +160,10 @@ describe("the fork flow", () => {
156160 };
157161
158162 beforeAll(async () => {
163 // "a mirror whose git is not ready yet" below seeds the upstream inside
164 // the first retry's wait, so it needs the forge's own patience, not the
165 // 50ms another file in this process may have left behind (#261).
166 firstFetchRetry.ms = DEFAULT_FIRST_FETCH_RETRY_MS;
159167 dataDir = await mkdtemp(join(tmpdir(), "forge-ff-"));
160168 originDataDir = await mkdtemp(join(tmpdir(), "forge-ff-up-"));
161169
test/kernel.test.ts +21
@@ -2,6 +2,7 @@ import { describe, expect, test } from "bun:test";
22 import { openDb } from "../src/kernel/db.ts";
33 import { ForgeError, defect } from "../src/kernel/error.ts";
44 import { id, secret } from "../src/kernel/id.ts";
5 import { logLevel, setLogLevel } from "../src/kernel/log.ts";
56 import {
67 andThen,
78 err,
@@ -147,3 +148,23 @@ describe("db", () => {
147148 expect(() => db.exec("INSERT INTO child (pid) VALUES (99)")).toThrow();
148149 });
149150 });
151
152 describe("log", () => {
153 test("the floor reads back what was set, so a borrower can restore it", () => {
154 // One process holds one floor and the suite runs every file in it: a
155 // file that lowers the floor and walks away makes another file's log
156 // capture read empty (#302). Reading it is what makes putting it back
157 // possible — this is the test that catches the next borrower.
158 const found = logLevel();
159 try {
160 setLogLevel("debug");
161 expect(logLevel()).toBe("debug");
162 setLogLevel("error");
163 expect(logLevel()).toBe("error");
164 setLogLevel(found);
165 expect(logLevel()).toBe(found);
166 } finally {
167 setLogLevel(found);
168 }
169 });
170 });
test/origins-oauth.test.ts +5
@@ -52,6 +52,11 @@ interface Fixture {
5252 }
5353
5454 async function boot(kind: "github" | "forgejo"): Promise<Fixture> {
55 // The redirect URI these flows expect is the one this fixture's own server
56 // is listening on. A crew machine exports `FORGE_URL` for its own forge,
57 // and inheriting it turns every exchange below into `redirect_uri
58 // mismatch` — same rot as `origins-security-auth.test.ts` (#261).
59 delete process.env.FORGE_URL;
5560 const dataDir = await mkdtemp(join(tmpdir(), "forge-oauth-"));
5661 const state = newFakeState(kind, LOGIN, "unused-pat");
5762 const oauth = newFakeOAuth(CLIENT_ID);
test/origins-security-auth.test.ts +11 −1
@@ -1,5 +1,8 @@
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
2 import { firstFetchRetry } from "../src/origins/mirror.ts";
2 import {
3 DEFAULT_FIRST_FETCH_RETRY_MS,
4 firstFetchRetry,
5 } from "../src/origins/mirror.ts";
36 import { mkdtemp, readFile, rm } from "node:fs/promises";
47 import { tmpdir } from "node:os";
58 import { join } from "node:path";
@@ -136,6 +139,12 @@ describe("OAuth code flow: state, PKCE, redirects, and the callback URI", () =>
136139 beforeAll(async () => {
137140 // A fetch that fails should say so now, not after the forge's patience.
138141 firstFetchRetry.ms = [50];
142 // Whatever the machine thinks this forge's address is: these tests decide
143 // when `FORGE_URL` is set, and the redirect URI they expect is the one
144 // their own server is listening on. A crew machine exports `FORGE_URL`
145 // for its own forge, and inheriting it turns every exchange below into
146 // `redirect_uri mismatch` (#261).
147 delete process.env.FORGE_URL;
139148 dataDir = await mkdtemp(join(tmpdir(), "forge-sec-code-"));
140149 const state = newFakeState("forgejo", LOGIN, ORIGIN_TOKEN);
141150 oauth = newFakeOAuth(CLIENT_ID);
@@ -154,6 +163,7 @@ describe("OAuth code flow: state, PKCE, redirects, and the callback URI", () =>
154163 });
155164 });
156165 afterAll(async () => {
166 firstFetchRetry.ms = DEFAULT_FIRST_FETCH_RETRY_MS;
157167 delete process.env.FORGE_URL;
158168 fake.stop();
159169 servers.stop();
test/view-source.test.ts +5 −1
@@ -6,7 +6,10 @@ import { createApp, type App } from "../src/app.ts";
66 import { serve, type Servers } from "../src/http/server.ts";
77 import { resetConnectLimit } from "../src/actions/origins.ts";
88 import { getUserByName, type User } from "../src/core/users.ts";
9 import { firstFetchRetry } from "../src/origins/mirror.ts";
9 import {
10 DEFAULT_FIRST_FETCH_RETRY_MS,
11 firstFetchRetry,
12 } from "../src/origins/mirror.ts";
1013 import { settled, subscribe, type MirrorStage } from "../src/origins/jobs.ts";
1114 import { forgetProviders } from "../src/origins/providers/index.ts";
1215 import {
@@ -295,6 +298,7 @@ describe("RepoSource: one repository, two places to read it from", () => {
295298 });
296299
297300 afterAll(async () => {
301 firstFetchRetry.ms = DEFAULT_FIRST_FETCH_RETRY_MS;
298302 fake.stop();
299303 servers.stop();
300304 originServers.stop();
test/web.test.ts +7
@@ -16,6 +16,7 @@ import { renderMarkdown } from "../src/web/markdown.ts";
1616 import { highlightAsset } from "../src/web/asset.ts";
1717 import { securityFloor } from "../src/http/respond.ts";
1818 import { THEME_NAMES } from "../src/design/themes.ts";
19 import { logLevel, setLogLevel } from "../src/kernel/log.ts";
1920 import { gitClientEnv } from "./helpers/git-client.ts";
2021
2122 describe("html template", () => {
@@ -836,6 +837,11 @@ describe("a refused cross-origin mutation says why in the log", () => {
836837 console.log = wrote;
837838 console.warn = wrote;
838839 console.error = wrote;
840 // The line under test is a WARN, and the floor is one global for the
841 // whole process: a file that ran earlier and left it at "error" would
842 // drop the line and make this read as "the forge logged nothing" (#261).
843 const floor = logLevel();
844 setLogLevel("info");
839845 let response: Response;
840846 try {
841847 response = await fetch(`${base}/signup`, {
@@ -849,6 +855,7 @@ describe("a refused cross-origin mutation says why in the log", () => {
849855 redirect: "manual",
850856 });
851857 } finally {
858 setLogLevel(floor);
852859 console.log = real.log;
853860 console.warn = real.warn;
854861 console.error = real.error;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs