Skip to content

Commit 1db6abc

Browse files
committed
fix(forgejo): a pull request watch passes once the required checks pass
Forgejo PR watches stayed stuck after the required checks passed when one optional status kept failing. The Forgejo provider never marked any check as required, so the watch fell back to needing every check to pass. Read the base branch's protection through the branches endpoint, which only needs read access and already carries the governing rule, and mark statuses matching its status_check_contexts globs as required. If the read fails, no check is marked and the watch keeps today's all-checks behaviour.
1 parent 511d20c commit 1db6abc

5 files changed

Lines changed: 248 additions & 23 deletions

File tree

‎apps/server/src/orchestration-v2/pullRequestWatch.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,6 +263,17 @@ describe("evaluatePullRequestWatch", () => {
263263
assert.isFalse(pushed.exhausted);
264264
assert.equal(pushed.next.wakes, 1);
265265
});
266+
267+
it("reports passed when the required checks pass and an optional one failed", () => {
268+
const optional = check("ci/optional-lint", "failure");
269+
const checks = [{ ...check("ci/required-test", "success"), required: true }, optional];
270+
const result = evaluatePullRequestWatch(watch(), detail({ checks }), noRemarks);
271+
assert.deepEqual(result.changes, [
272+
{ kind: "checks-failed", failed: [optional] },
273+
{ kind: "checks-passed", count: 1, required: true },
274+
]);
275+
assert.isTrue(result.next.passed);
276+
});
266277
});
267278

268279
describe("pullRequestWatchMessage", () => {

‎packages/source-control-forgejo/src/server/ForgejoPullRequestProvider.ts‎

Lines changed: 32 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
import { SourceControlProviderKind } from "@t3tools/contracts";
22
import * as Effect from "effect/Effect";
33
import * as Schema from "effect/Schema";
4+
import * as Option from "effect/Option";
45
import * as Result from "effect/Result";
56
import type { PullRequestCapabilities, PullRequestViewerPermissions } from "@t3tools/contracts";
67
import { decodeJsonResult } from "@t3tools/shared/schemaJson";
@@ -33,6 +34,7 @@ import {
3334
forgejoChecks,
3435
forgejoReactions,
3536
} from "./forgejoPullRequestJson.ts";
37+
import { ForgejoBranchStatusChecks, markRequiredForgejoChecks } from "./forgejoRequiredChecks.ts";
3638
import { definition } from "../client/definition.ts";
3739

3840
const CAPABILITIES: PullRequestCapabilities = {
@@ -202,6 +204,33 @@ export const make = Effect.gen(function* () {
202204
);
203205
return permissions(repo, pr, viewer);
204206
});
207+
// Statuses on the head commit, with the ones the base branch requires marked. When the branch
208+
// cannot be read (older server, missing access), no check is marked and every check gates.
209+
const readChecks = (input: ProviderRepositoryRef, pr: typeof ForgejoPullRequest.Type) =>
210+
Effect.all(
211+
[
212+
page(
213+
{
214+
...input,
215+
path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
216+
},
217+
ForgejoStatus,
218+
),
219+
read(
220+
{
221+
...input,
222+
path: `${repoPath(input)}/branches/${pr.base.ref.split("/").map(encodeURIComponent).join("/")}`,
223+
},
224+
ForgejoBranchStatusChecks,
225+
).pipe(Effect.option),
226+
],
227+
{ concurrency: 2 },
228+
).pipe(
229+
Effect.map(([statuses, branch]) => {
230+
const checks = forgejoChecks(statuses.items);
231+
return Option.isSome(branch) ? markRequiredForgejoChecks(checks, branch.value) : checks;
232+
}),
233+
);
205234
const unsupported = (operation: string) =>
206235
Effect.fail(failure(operation, `Forgejo does not expose ${operation} through its API.`));
207236
const provider: PullRequestProviderApi = {
@@ -244,28 +273,15 @@ export const make = Effect.gen(function* () {
244273
getChangeRequestChecks: Effect.fn("ForgejoPullRequestProvider.getChangeRequestChecks")(
245274
function* (input) {
246275
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 { state: forgejoChangeRequest(pr).state, checks: forgejoChecks(statuses.items) };
276+
return { state: forgejoChangeRequest(pr).state, checks: yield* readChecks(input, pr) };
255277
},
256278
),
257279
getChangeRequest: Effect.fn("ForgejoPullRequestProvider.getChangeRequest")(function* (input) {
258280
const [pr, repo, viewer] = yield* Effect.all(
259281
[getPull(input), getRepo(input), getViewer(input)],
260282
{ concurrency: 3 },
261283
);
262-
const statuses = yield* page(
263-
{
264-
...input,
265-
path: `${repoPath(input)}/statuses/${encodeURIComponent(pr.head.sha)}?sort=recentupdate`,
266-
},
267-
ForgejoStatus,
268-
);
284+
const checks = yield* readChecks(input, pr);
269285
return {
270286
...forgejoChangeRequest(pr),
271287
headSha: pr.head.sha,
@@ -275,7 +291,7 @@ export const make = Effect.gen(function* () {
275291
const actor = forgejoActor(user);
276292
return actor ? [actor] : [];
277293
}),
278-
checks: forgejoChecks(statuses.items),
294+
checks,
279295
baseComparison: !pr.merge_base
280296
? "unknown"
281297
: pr.merge_base === pr.base.sha

‎packages/source-control-forgejo/src/server/ForgejoSourceControlProvider.test.ts‎

Lines changed: 112 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -137,7 +137,8 @@ it.effect("reads Forgejo checks without repository or viewer requests", () => {
137137
});
138138
assert.strictEqual(result.state, "open");
139139
assert.strictEqual(result.checks[0]?.status, "failure");
140-
assert.deepStrictEqual(paths, [
140+
assert.deepStrictEqual(paths.toSorted(), [
141+
"repos/acme/web/branches/main",
141142
"repos/acme/web/pulls/1",
142143
"repos/acme/web/statuses/head?sort=recentupdate&limit=50&page=1",
143144
"repos/acme/web/statuses/head?sort=recentupdate&limit=50&page=2",
@@ -147,16 +148,18 @@ it.effect("reads Forgejo checks without repository or viewer requests", () => {
147148
Layer.mock(ForgejoCli.ForgejoCli)({
148149
api: (input) => {
149150
paths.push(input.path);
150-
assert.match(input.path, /^repos\/acme\/web\/(pulls\/1|statuses\/head)/);
151+
assert.match(input.path, /^repos\/acme\/web\/(pulls\/1|statuses\/head|branches\/main)/);
151152
return Effect.succeed(
152153
processOutput(
153-
input.path.endsWith("pulls/1")
154-
? `{"number":1,"title":"Checks","body":"","html_url":"https://forgejo.test/acme/web/pulls/1", "user":null,"state":"open","merged":false,
154+
input.path.endsWith("branches/main")
155+
? `{"name":"main","protected":false,"enable_status_check":false,"status_check_contexts":[]}`
156+
: input.path.endsWith("pulls/1")
157+
? `{"number":1,"title":"Checks","body":"","html_url":"https://forgejo.test/acme/web/pulls/1", "user":null,"state":"open","merged":false,
155158
"head":{"ref":"feature","sha":"head","repo":null},"base":{"ref":"main","sha":"base","repo":null},
156159
"created_at":"2026-09-16T00:00:00Z","updated_at":"2026-09-16T00:00:00Z","closed_at":null,"merged_at":null,"labels":[]}`
157-
: input.path.endsWith("page=1")
158-
? `[{"context":"build","status":"failure","description":null,"target_url":null,"updated_at":"2026-09-16T00:00:00Z"}]`
159-
: "[]",
160+
: input.path.endsWith("page=1")
161+
? `[{"context":"build","status":"failure","description":null,"target_url":null,"updated_at":"2026-09-16T00:00:00Z"}]`
162+
: "[]",
160163
),
161164
);
162165
},
@@ -165,6 +168,105 @@ it.effect("reads Forgejo checks without repository or viewer requests", () => {
165168
);
166169
});
167170

171+
const requiredChecksPullRequest = {
172+
number: 7,
173+
title: "Required checks",
174+
body: "",
175+
html_url: "https://forgejo.test/acme/web/pulls/7",
176+
user: { login: "maria" },
177+
state: "open",
178+
merged: false,
179+
head: { ref: "feature", sha: "head", repo: null },
180+
base: { ref: "release/1.x", sha: "base", repo: null },
181+
created_at: "2026-10-12T00:00:00Z",
182+
updated_at: "2026-10-12T00:00:00Z",
183+
closed_at: null,
184+
merged_at: null,
185+
labels: [],
186+
};
187+
const requiredChecksStatuses = [
188+
["ci/required-build", "success"],
189+
["ci/required-test", "success"],
190+
["ci/optional-lint", "failure"],
191+
].map(([context, status]) => ({
192+
context,
193+
status,
194+
description: null,
195+
target_url: null,
196+
updated_at: "2026-10-12T00:00:00Z",
197+
}));
198+
199+
it.effect.each([
200+
[
201+
"marks the statuses a readable base branch requires",
202+
Effect.succeed({
203+
name: "release/1.x",
204+
protected: true,
205+
enable_status_check: true,
206+
status_check_contexts: ["ci/required-*"],
207+
}),
208+
[true, true, undefined],
209+
],
210+
[
211+
"keeps every Forgejo status gating when the base branch cannot be read",
212+
Effect.fail(
213+
new ForgejoCli.ForgejoCliError({
214+
command: "fj",
215+
cwd: "/repo",
216+
reason: "forbidden",
217+
detail: "Forgejo API request failed with HTTP 403.",
218+
}),
219+
),
220+
[undefined, undefined, undefined],
221+
],
222+
] as const)("%s", ([, branch, required]) =>
223+
Effect.gen(function* () {
224+
const provider = yield* ForgejoPullRequestProvider.make;
225+
const readChecks = provider.getChangeRequestChecks;
226+
if (readChecks === undefined) return yield* Effect.die("checks read missing");
227+
const input = { cwd: "/repo", repository: "acme/web", host: "forgejo.test", number: 7 };
228+
const summary = yield* readChecks(input);
229+
const detail = yield* provider.getChangeRequest(input);
230+
for (const checks of [summary.checks, detail.checks]) {
231+
assert.deepStrictEqual(
232+
checks.map((check) => [check.name, check.status, check.required]),
233+
[
234+
["ci/required-build", "success", required[0]],
235+
["ci/required-test", "success", required[1]],
236+
["ci/optional-lint", "failure", required[2]],
237+
],
238+
);
239+
}
240+
}).pipe(
241+
Effect.provide(
242+
Layer.mock(ForgejoCli.ForgejoCli)({
243+
api: (input) => {
244+
const [path, query] = input.path.split("?");
245+
const respond = (response: unknown) =>
246+
encodeJsonEffect(response).pipe(Effect.orDie, Effect.map(processOutput));
247+
switch (path) {
248+
case "repos/acme/web/pulls/7":
249+
return respond(requiredChecksPullRequest);
250+
case "repos/acme/web/statuses/head":
251+
return respond(
252+
new URLSearchParams(query).get("page") === "1" ? requiredChecksStatuses : [],
253+
);
254+
// Branch names keep their slashes; each segment is encoded on its own.
255+
case "repos/acme/web/branches/release/1.x":
256+
return Effect.flatMap(branch, respond);
257+
case "repos/acme/web":
258+
return respond({ full_name: "acme/web", permissions: { push: true, admin: false } });
259+
case "user":
260+
return respond({ login: "maria" });
261+
default:
262+
return Effect.die(`Unexpected Forgejo request: ${input.path}`);
263+
}
264+
},
265+
}),
266+
),
267+
),
268+
);
269+
168270
it.effect.each([
169271
["Ready", false, true, false, "mergeable"],
170272
["Draft", true, false, true, "unknown"],
@@ -236,6 +338,9 @@ it.effect.each([
236338
case "repos/maria/project/statuses/head":
237339
response = [];
238340
break;
341+
case "repos/maria/project/branches/main":
342+
response = { name: "main", protected: false };
343+
break;
239344
default:
240345
return Effect.die(`Unexpected Forgejo request: ${input.path}`);
241346
}
Lines changed: 54 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,54 @@
1+
import type { PullRequestCheck } from "@t3tools/contracts";
2+
import { assert, describe, it } from "@effect/vitest";
3+
4+
import { markRequiredForgejoChecks } from "./forgejoRequiredChecks.ts";
5+
6+
const check = (name: string): PullRequestCheck => ({
7+
name,
8+
status: "success",
9+
description: null,
10+
url: null,
11+
});
12+
const requiredNames = (
13+
names: ReadonlyArray<string>,
14+
contexts: ReadonlyArray<string> | null,
15+
enabled = true,
16+
) =>
17+
markRequiredForgejoChecks(names.map(check), {
18+
enable_status_check: enabled,
19+
status_check_contexts: contexts,
20+
}).flatMap((marked) => (marked.required ? [marked.name] : []));
21+
22+
describe("markRequiredForgejoChecks", () => {
23+
it("marks exact contexts", () => {
24+
assert.deepStrictEqual(requiredNames(["build", "build-docs", "lint"], ["build"]), ["build"]);
25+
});
26+
27+
it("lets * and ** match across slashes, as Forgejo compiles contexts without separators", () => {
28+
const names = ["ci/test (push)", "ci/nightly/test (push)", "lint (push)"];
29+
assert.deepStrictEqual(requiredNames(names, ["ci/*"]), names.slice(0, 2));
30+
assert.deepStrictEqual(requiredNames(names, ["ci/**"]), names.slice(0, 2));
31+
assert.deepStrictEqual(requiredNames(names, ["*(push)"]), names);
32+
});
33+
34+
it("matches one character with ? and treats regex characters literally", () => {
35+
const names = ["node 20", "node 22", "node 2", "a.b", "axb"];
36+
assert.deepStrictEqual(requiredNames(names, ["node 2?"]), ["node 20", "node 22"]);
37+
assert.deepStrictEqual(requiredNames(names, ["a.b"]), ["a.b"]);
38+
});
39+
40+
it("leaves checks unmarked when status checks are off or list no contexts", () => {
41+
assert.deepStrictEqual(requiredNames(["build"], ["build"], false), []);
42+
assert.deepStrictEqual(requiredNames(["build"], []), []);
43+
assert.deepStrictEqual(requiredNames(["build"], null), []);
44+
assert.deepStrictEqual(
45+
markRequiredForgejoChecks([check("build")], {}).map((marked) => marked.required),
46+
[undefined],
47+
);
48+
});
49+
50+
it("keeps every check gating when a context uses glob syntax it cannot match", () => {
51+
assert.deepStrictEqual(requiredNames(["build", "test-a"], ["build", "test-[ab]"]), []);
52+
assert.deepStrictEqual(requiredNames(["build", "test-a"], ["{build,lint}"]), []);
53+
});
54+
});
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
import * as Schema from "effect/Schema";
2+
import type { PullRequestCheck } from "@t3tools/contracts";
3+
4+
/**
5+
* The status-check part of `GET /repos/{owner}/{repo}/branches/{branch}`. Forgejo fills it from
6+
* the protection rule that governs the branch (exact names before globs, then the oldest rule),
7+
* and unlike `/branch_protections` it only needs read access to the repository.
8+
*/
9+
export const ForgejoBranchStatusChecks = Schema.Struct({
10+
enable_status_check: Schema.optional(Schema.Boolean),
11+
status_check_contexts: Schema.optional(Schema.NullOr(Schema.Array(Schema.String))),
12+
});
13+
14+
// Forgejo compiles each context with gobwas/glob and no separator, so `*` and `**` both match any
15+
// run of characters, `/` included, and `?` matches one character. Classes, alternation and escapes
16+
// are not handled: a rule using them keeps every check gating rather than guessing.
17+
const UNSUPPORTED_GLOB = /[[\]{}\\]/;
18+
const contextPattern = (glob: string) =>
19+
new RegExp(
20+
`^${Array.from(glob, (char) =>
21+
char === "*" ? ".*" : char === "?" ? "." : char.replace(/[.+^$()|]/g, "\\$&"),
22+
).join("")}$`,
23+
"su",
24+
);
25+
26+
/** Marks the checks the base branch requires. Without enabled status checks nothing changes. */
27+
export function markRequiredForgejoChecks(
28+
checks: ReadonlyArray<PullRequestCheck>,
29+
branch: typeof ForgejoBranchStatusChecks.Type,
30+
): ReadonlyArray<PullRequestCheck> {
31+
const contexts = branch.enable_status_check ? (branch.status_check_contexts ?? []) : [];
32+
if (contexts.length === 0 || contexts.some((context) => UNSUPPORTED_GLOB.test(context))) {
33+
return checks;
34+
}
35+
const patterns = contexts.map(contextPattern);
36+
return checks.map((check) =>
37+
patterns.some((pattern) => pattern.test(check.name)) ? { ...check, required: true } : check,
38+
);
39+
}

0 commit comments

Comments
 (0)