@devries-cameron20 / t3code-1 / commits / c1a24f884e
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

fix(forgejo): a pull request watch passes once the required checks pass (#18775)

Co-authored-by: Julius Marminge <julius0216@outlook.com>

Igor Makowski committed Oct 20, 2026 at 04:05 UTC c1a24f884edd7f64f2039c89df9d5918e970d20b
3 files changed +294 -51
packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts
+44 -19
@@ -33,8 +33,11 @@ import {
33 forgejoChecks,
34 forgejoReactions,
35 } from "./forgejoPullRequestJson.ts";
36 +import { ForgejoBranchStatusChecks, markRequiredForgejoChecks } from "./forgejoRequiredChecks.ts";
37 import { definition } from "../client/definition.ts";
38
39 +const isForgejoCliError = Schema.is(ForgejoCli.ForgejoCliError);
40 +
41 const CAPABILITIES: PullRequestCapabilities = {
42 diff: true,
43 viewedFiles: "environment",
@@ -202,6 +205,44 @@ export const make = Effect.gen(function* () {
205 );
206 return permissions(repo, pr, viewer);
207 });
208 + const readChecks = Effect.fn("ForgejoPullRequestProvider.readChecks")(function* (
209 + input: ProviderRepositoryRef,
210 + pr: typeof ForgejoPullRequest.Type,
211 + ) {
212 + const branch = read(
213 + {
214 + ...input,
215 + path: `${repoPath(input)}/branches/${pr.base.ref.split("/").map(encodeURIComponent).join("/")}`,
216 + },
217 + ForgejoBranchStatusChecks,
218 + ).pipe(
219 + Effect.catchTags({
220 + PullRequestProviderError: (error) => {
221 + if (
222 + isForgejoCliError(error.cause) &&
223 + (error.cause.reason === "forbidden" || error.cause.reason === "not-found")
224 + ) {
225 + return Effect.succeed({});
226 + }
227 + return Effect.fail(error);
228 + },
229 + }),
230 + );
231 + const [statuses, policy] = yield* Effect.all(
232 + [
233 + page(
234 + {
235 + ...input,
236 + path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
237 + },
238 + ForgejoStatus,
239 + ),
240 + branch,
241 + ],
242 + { concurrency: 2 },
243 + );
244 + return markRequiredForgejoChecks(forgejoChecks(statuses.items, pr.html_url), policy);
245 + });
246 const unsupported = (operation: string) =>
247 Effect.fail(failure(operation, `Forgejo does not expose ${operation} through its API.`));
248 const provider: PullRequestProviderApi = {
@@ -244,17 +285,7 @@ export const make = Effect.gen(function* () {
285 getChangeRequestChecks: Effect.fn("ForgejoPullRequestProvider.getChangeRequestChecks")(
286 function* (input) {
287 const pr = yield* getPull(input);
247 - const statuses = yield* page(
248 - {
249 - ...input,
250 - path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
251 - },
252 - ForgejoStatus,
253 - );
254 - return {
255 - state: forgejoChangeRequest(pr).state,
256 - checks: forgejoChecks(statuses.items, pr.html_url),
257 - };
288 + return { state: forgejoChangeRequest(pr).state, checks: yield* readChecks(input, pr) };
289 },
290 ),
291 getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) {
@@ -262,13 +293,7 @@ export const make = Effect.gen(function* () {
293 [getPull(input), getRepo(input), getViewer(input)],
294 { concurrency: 3 },
295 );
265 - const statuses = yield* page(
266 - {
267 - ...input,
268 - path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
269 - },
270 - ForgejoStatus,
271 - );
296 + const checks = yield* readChecks(input, pr);
297 return {
298 ...forgejoChangeRequest(pr),
299 headSha: pr.head.sha,
@@ -278,7 +303,7 @@ export const make = Effect.gen(function* () {
303 const actor = forgejoActor(user);
304 return actor ? [actor] : [];
305 }),
281 - checks: forgejoChecks(statuses.items, pr.html_url),
306 + checks,
307 baseComparison: !pr.merge_base
308 ? "unknown"
309 : pr.merge_base === pr.base.sha
packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts
+198 -32
@@ -136,7 +136,8 @@ it.effect("reads the newest Forgejo checks without repository or viewer requests
136 });
137 assert.strictEqual(result.state, "open");
138 assert.strictEqual(result.checks[0]?.status, "failure");
139 - assert.deepStrictEqual(paths, [
139 + assert.deepStrictEqual(paths.toSorted(), [
140 + "repos/acme/web/branches/main",
141 "repos/acme/web/pulls/1",
142 "repos/acme/web/statuses/head?sort=recentupdate&limit=50&page=1",
143 "repos/acme/web/statuses/head?sort=recentupdate&limit=50&page=2",
@@ -146,16 +147,18 @@ it.effect("reads the newest Forgejo checks without repository or viewer requests
147 Layer.mock(ForgejoCli.ForgejoCli)({
148 api: (input) => {
149 paths.push(input.path);
149 - assert.match(input.path, /^repos\/acme\/web\/(pulls\/1|statuses\/head)/);
150 + assert.match(input.path, /^repos\/acme\/web\/(pulls\/1|statuses\/head|branches\/main)/);
151 return Effect.succeed(
152 processOutput(
152 - input.path.endsWith("pulls/1")
153 - ? `{"number":1,"title":"Checks","body":"","html_url":"https://forgejo.test/acme/web/pulls/1", "user":null,"state":"open","merged":false,
153 + input.path.endsWith("branches/main")
154 + ? `{"name":"main","protected":false,"enable_status_check":false,"status_check_contexts":[]}`
155 + : input.path.endsWith("pulls/1")
156 + ? `{"number":1,"title":"Checks","body":"","html_url":"https://forgejo.test/acme/web/pulls/1", "user":null,"state":"open","merged":false,
157 "head":{"ref":"feature","sha":"head","repo":null},"base":{"ref":"main","sha":"base","repo":null},
158 "created_at":"2026-09-16T00:00:00Z","updated_at":"2026-09-16T00:00:00Z","closed_at":null,"merged_at":null,"labels":[]}`
156 - : input.path.endsWith("page=1")
157 - ? `[{"context":"build","status":"failure","description":null,"target_url":null,"updated_at":"2026-09-16T00:00:00.500Z"},{"context":"build","status":"success","description":null,"target_url":null,"updated_at":"2026-09-16T00:00:00Z"}]`
158 - : "[]",
159 + : input.path.endsWith("page=1")
160 + ? `[{"context":"build","status":"failure","description":null,"target_url":null,"updated_at":"2026-09-16T00:00:00.500Z"},{"context":"build","status":"success","description":null,"target_url":null,"updated_at":"2026-09-16T00:00:00Z"}]`
161 + : "[]",
162 ),
163 );
164 },
@@ -164,6 +167,164 @@ it.effect("reads the newest Forgejo checks without repository or viewer requests
167 );
168 });
169
170 +const requiredChecksPullRequest = {
171 + number: 7,
172 + title: "Required checks",
173 + body: "",
174 + html_url: "https://forgejo.test/acme/web/pulls/7",
175 + user: { login: "maria" },
176 + state: "open",
177 + merged: false,
178 + head: { ref: "feature", sha: "head", repo: null },
179 + base: { ref: "release/1.x", sha: "base", repo: null },
180 + created_at: "2026-10-12T00:00:00Z",
181 + updated_at: "2026-10-12T00:00:00Z",
182 + closed_at: null,
183 + merged_at: null,
184 + labels: [],
185 +};
186 +const requiredChecksStatuses = [
187 + ["ci/required-build", "success"],
188 + ["ci/optional-lint", "failure"],
189 +].map(([context, status]) => ({
190 + context,
191 + status,
192 + description: null,
193 + target_url: null,
194 + updated_at: "2026-10-12T00:00:00Z",
195 +}));
196 +
197 +const requiredChecksInput = {
198 + cwd: "/repo",
199 + repository: "acme/web",
200 + host: "forgejo.test",
201 + number: 7,
202 +};
203 +const requiredChecksLayer = (
204 + branch: Effect.Effect<unknown, ForgejoCli.ForgejoCliError>,
205 + statuses = requiredChecksStatuses,
206 +) =>
207 + Layer.mock(ForgejoCli.ForgejoCli)({
208 + api: (input) => {
209 + const [path, query] = input.path.split("?");
210 + const respond = (response: unknown) =>
211 + encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
212 + switch (path) {
213 + case "repos/acme/web/pulls/7":
214 + return respond(requiredChecksPullRequest);
215 + case "repos/acme/web/statuses/head":
216 + return respond(new URLSearchParams(query).get("page") === "1" ? statuses : []);
217 + case "repos/acme/web/branches/release/1.x":
218 + return Effect.flatMap(branch, respond);
219 + case "repos/acme/web":
220 + return respond({ full_name: "acme/web", permissions: { push: true, admin: false } });
221 + case "user":
222 + return respond({ login: "maria" });
223 + default:
224 + return Effect.die(`Unexpected Forgejo request: ${input.path}`);
225 + }
226 + },
227 + });
228 +
229 +it.effect.each([
230 + ["ci/required-deploy", true],
231 + ["test-*", true],
232 + ["ci/[ab]", false],
233 +] as const)("keeps missing required pattern %s pending (supported: %s)", ([missing, supported]) =>
234 + Effect.gen(function* () {
235 + const provider = yield* ForgejoPullRequestProvider.make;
236 + const readChecks = provider.getChangeRequestChecks;
237 + if (readChecks === undefined) return yield* Effect.die("checks read missing");
238 + const summary = yield* readChecks(requiredChecksInput);
239 + const detail = yield* provider.getChangeRequest(requiredChecksInput);
240 + for (const checks of [summary.checks, detail.checks]) {
241 + assert.deepStrictEqual(
242 + checks.map((check) => [check.name, check.status, check.required]),
243 + [
244 + ["ci/required-build", "success", supported ? true : undefined],
245 + ["ci/optional-lint", supported ? "failure" : "success", undefined],
246 + [missing, "pending", supported ? true : undefined],
247 + ],
248 + );
249 + if (!supported) {
250 + assert.strictEqual(
251 + checks.at(-1)?.description,
252 + "Required check pattern cannot be evaluated.",
253 + );
254 + }
255 + }
256 + }).pipe(
257 + Effect.provide(
258 + requiredChecksLayer(
259 + Effect.succeed({
260 + name: "release/1.x",
261 + protected: true,
262 + enable_status_check: true,
263 + status_check_contexts: ["ci/required-*", missing, missing],
264 + }),
265 + supported
266 + ? requiredChecksStatuses
267 + : requiredChecksStatuses.map((status) => ({ ...status, status: "success" })),
268 + ),
269 + ),
270 + ),
271 +);
272 +
273 +it.effect.each([
274 + ["older branch metadata", Effect.succeed({ name: "release/1.x", protected: true })],
275 + ...(["not-found", "forbidden"] as const).map(
276 + (reason) =>
277 + [
278 + reason,
279 + Effect.fail(
280 + new ForgejoCli.ForgejoCliError({
281 + command: "fj",
282 + cwd: "/repo",
283 + reason,
284 + httpStatus: reason === "not-found" ? 404 : 403,
285 + detail: "Branch metadata unavailable.",
286 + }),
287 + ),
288 + ] as const,
289 + ),
290 +] as const)("keeps all statuses gating with %s", ([, branch]) =>
291 + Effect.gen(function* () {
292 + const provider = yield* ForgejoPullRequestProvider.make;
293 + const readChecks = provider.getChangeRequestChecks;
294 + if (readChecks === undefined) return yield* Effect.die("checks read missing");
295 + const summary = yield* readChecks(requiredChecksInput);
296 + const detail = yield* provider.getChangeRequest(requiredChecksInput);
297 + for (const checks of [summary.checks, detail.checks]) {
298 + assert.deepStrictEqual(
299 + checks.map((check) => [check.name, check.status, check.required]),
300 + [
301 + ["ci/required-build", "success", undefined],
302 + ["ci/optional-lint", "failure", undefined],
303 + ],
304 + );
305 + }
306 + }).pipe(Effect.provide(requiredChecksLayer(branch))),
307 +);
308 +
309 +it.effect.each([
310 + ["rate limit", { reason: "rate-limit", httpStatus: 429 }, "rate-limited"],
311 + ["authentication failure", { reason: "authentication", httpStatus: 401 }, "unauthenticated"],
312 + ["server failure", { httpStatus: 503 }, "failed"],
313 + ["network failure", {}, "failed"],
314 +] as const)("propagates branch metadata %s", ([detail, fields, reason]) => {
315 + const cause = new ForgejoCli.ForgejoCliError({ command: "fj", cwd: "/repo", detail, ...fields });
316 + return Effect.gen(function* () {
317 + const provider = yield* ForgejoPullRequestProvider.make;
318 + const readChecks = provider.getChangeRequestChecks;
319 + if (readChecks === undefined) return yield* Effect.die("checks read missing");
320 + for (const read of [readChecks, provider.getChangeRequest]) {
321 + const error = yield* read(requiredChecksInput).pipe(Effect.flip);
322 + assert.strictEqual(error.reason, reason);
323 + assert.strictEqual(error.cause, cause);
324 + }
325 + }).pipe(Effect.provide(requiredChecksLayer(Effect.fail(cause))));
326 +});
327 +
328 it.effect("opens Forgejo Actions check links on the pull request's server", () =>
329 Effect.gen(function* () {
330 const provider = yield* ForgejoPullRequestProvider.make;
@@ -194,31 +355,33 @@ it.effect("opens Forgejo Actions check links on the pull request's server", () =
355 target_url,
356 updated_at: "2026-10-11T00:00:00Z",
357 });
197 - const body = input.path.endsWith("pulls/1")
198 - ? {
199 - number: 1,
200 - title: "Checks",
201 - body: "",
202 - html_url: "https://forgejo.test/git/acme/web/pulls/1",
203 - user: null,
204 - state: "open",
205 - merged: false,
206 - head: { ref: "feature", sha: "head", repo: null },
207 - base: { ref: "main", sha: "base", repo: null },
208 - created_at: "2026-10-11T00:00:00Z",
209 - updated_at: "2026-10-11T00:00:00Z",
210 - closed_at: null,
211 - merged_at: null,
212 - labels: [],
213 - }
214 - : input.path.endsWith("page=1")
215 - ? [
216 - // Forgejo includes any sub-path mount in the relative links it reports.
217 - status("actions", "/git/acme/web/actions/runs/7/jobs/2"),
218 - status("external", "https://ci.example/build/9"),
219 - status("none", null),
220 - ]
221 - : [];
358 + const body = input.path.endsWith("branches/main")
359 + ? {}
360 + : input.path.endsWith("pulls/1")
361 + ? {
362 + number: 1,
363 + title: "Checks",
364 + body: "",
365 + html_url: "https://forgejo.test/git/acme/web/pulls/1",
366 + user: null,
367 + state: "open",
368 + merged: false,
369 + head: { ref: "feature", sha: "head", repo: null },
370 + base: { ref: "main", sha: "base", repo: null },
371 + created_at: "2026-10-11T00:00:00Z",
372 + updated_at: "2026-10-11T00:00:00Z",
373 + closed_at: null,
374 + merged_at: null,
375 + labels: [],
376 + }
377 + : input.path.endsWith("page=1")
378 + ? [
379 + // Forgejo includes any sub-path mount in the relative links it reports.
380 + status("actions", "/git/acme/web/actions/runs/7/jobs/2"),
381 + status("external", "https://ci.example/build/9"),
382 + status("none", null),
383 + ]
384 + : [];
385 return encodeJsonEffect(body).pipe(Effect.orDie, Effect.map(processOutput));
386 },
387 }),
@@ -297,6 +460,9 @@ it.effect.each([
460 case "repos/maria/project/statuses/head":
461 response = [];
462 break;
463 + case "repos/maria/project/branches/main":
464 + response = { name: "main", protected: false };
465 + break;
466 default:
467 return Effect.die(`Unexpected Forgejo request: ${input.path}`);
468 }
packages/source-control-forgejo/src/server/forgejoRequiredChecks.ts new
+52
@@ -0,0 +1,52 @@
1 +import * as Schema from "effect/Schema";
2 +import type { PullRequestCheck } from "@t3tools/contracts";
3 +
4 +// The branch endpoint reports the governing protection rule with repository read access.
5 +export const ForgejoBranchStatusChecks = Schema.Struct({
6 + enable_status_check: Schema.optional(Schema.Boolean),
7 + status_check_contexts: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
8 +});
9 +
10 +// Forgejo compiles each context with gobwas/glob and no separator, so `*` and `**` both match any
11 +// run of characters, `/` included, and `?` matches one character. Classes, alternation and escapes
12 +// are not handled.
13 +const UNSUPPORTED_GLOB = /[[\]{}\\]/;
14 +const contextPattern = (glob: string) =>
15 + new RegExp(
16 + `^${Array.from(glob, (char) =>
17 + char === "*" ? ".*" : char === "?" ? "." : char.replace(/[.+^$()|]/g, "\\$&"),
18 + ).join("")}$`,
19 + "su",
20 + );
21 +
22 +export function markRequiredForgejoChecks(
23 + checks: ReadonlyArray<PullRequestCheck>,
24 + branch: typeof ForgejoBranchStatusChecks.Type,
25 +): ReadonlyArray<PullRequestCheck> {
26 + const contexts = branch.enable_status_check ? (branch.status_check_contexts ?? []) : [];
27 + if (contexts.length === 0) return checks;
28 + const unsupported = [...new Set(contexts.filter((context) => UNSUPPORTED_GLOB.test(context)))];
29 + if (unsupported.length > 0) {
30 + // Keep all observed checks gating, but never pass a policy we cannot evaluate.
31 + return [
32 + ...checks,
33 + ...unsupported.map((name) => ({
34 + name,
35 + status: "pending" as const,
36 + description: "Required check pattern cannot be evaluated.",
37 + url: null,
38 + })),
39 + ];
40 + }
41 + const patterns = [...new Set(contexts)].map((name) => ({ name, pattern: contextPattern(name) }));
42 + const marked = checks.map((check) =>
43 + patterns.some(({ pattern }) => pattern.test(check.name)) ? { ...check, required: true } : check,
44 + );
45 + // Forgejo keeps an unmatched required pattern pending, including wildcards.
46 + const missing = patterns.flatMap(({ name, pattern }) =>
47 + !name.trim() || checks.some((check) => pattern.test(check.name))
48 + ? []
49 + : [{ name, status: "pending", description: null, url: null, required: true } as const],
50 + );
51 + return [...marked, ...missing];
52 +}