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

When the base moves, a pull's green reads "checked against an older main" and re-checks on its own #1995

Parked opened this
Closed without merging

scout/forge:scout/1179-when-the-base-moves-a-pull-s-green-reads → main 5 commits fork 7 threads · 7 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +539 −27
README.md +4
@@ -1016,6 +1016,10 @@ Once a sibling ships or all but one close, the item leaves the feed. The
10161016 terminal has no feed; the item is in `GET /api/v1/feed` and the MCP feed tool
10171017 as kind `choose`.
10181018
1019 ### A stale green
1020
1021 When a pull's base moves, a passing check that merged the old tip reads "checked against an older main" on the page, the inbox, `GET …/pulls/:number/checks` and the MCP's `pull` (`checkStale: true`). It does not land by rule, and is not counted for a required check, until it is checked again. The check service asks for that re-check (`src/checks/stale.ts`) only into free slots, at most two pulls a tick, newest pull first.
1022
10191023 ### OG cards as PNG
10201024
10211025 `/og/{repo,app,issue,pull,run}/<ref>.png` is the same public card as the `.svg`,
docs/MCP.md +1 −1
@@ -30,7 +30,7 @@ for a tunnel and a forge that sleeps.
3030 | `apps` | the apps you can see: live or not, where served, how each runs itself, what is working | |
3131 | `tell` | a sentence becomes an issue, a builder is picked, a run starts on the crew's next tick | yes |
3232 | `say` | speak on an issue or a pull; a working builder hears it as its next step | yes |
33 | `pull` | `{ repo, number }`: a pull's title, state, head and base, and for an open pull whether it merges into the base's current head (`mergeable`) and the paths that stop it (`conflicts`), and `check: { state, baseOid }`: the latest check's state and the base tip it was merged with (empty when it merged nothing); `mergeable` and `conflicts` are the same fields as `GET …/pulls/:number`, `check` is `state` and `run.baseOid` from `GET …/pulls/:number/checks` | |
33 | `pull` | `{ repo, number }`: a pull's title, state, head and base, and for an open pull whether it merges into the base's current head (`mergeable`) and the paths that stop it (`conflicts`), and `check: { state, baseOid }`: the latest check's state and the base tip it was merged with (empty when it merged nothing); `mergeable` and `conflicts` are the same fields as `GET …/pulls/:number`, `check` is `state` and `run.baseOid` from `GET …/pulls/:number/checks`. `checkStale` is true when the last passing check merged a base tip that is no longer the base's head: the pull is re-checked and does not land by rule until then. |
3434 | `edit` | a new title or body for an issue or a pull: its author's, or a writer's; an agent edits only what it wrote | yes |
3535 | `seal` | `{ repo, number, sealed }`: seal a security report (and the pull that fixes it) so only writers and the crew see it, or unseal it for every reader; a writer's, recorded | yes |
3636 | `now` | what the crew is doing right now: who, on what, since when, at what cost; a planner that declined the direction and waits for you comes first (`run: null`, its words in `says`) | |
scripts/gate.ts +1
@@ -312,6 +312,7 @@ export const GATE: readonly string[] = [
312312 "test/check-land-main.test.ts",
313313 "test/check-tiers.test.ts",
314314 "test/pull-check-again.test.ts",
315 "test/check-stale.test.ts",
315316 "test/holds.test.ts",
316317 "test/hollow.test.ts",
317318 "test/flags.test.ts",
src/checks/service.ts +44 −1
@@ -49,6 +49,7 @@ import { giveHistory } from "./history.ts";
4949 import { readLearned } from "./learned.ts";
5050 import { keepCache, restoreCache } from "./cache.ts";
5151 import { ASKED, redMain, unheld } from "./red_main.ts";
52 import { BASE_MOVED, STALE_PER_TICK, stalePulls } from "./stale.ts";
5253 import { IMPACT_FILE, keepImpact, seedImpact } from "./impact-store.ts";
5354 import { getIssueById } from "../core/issues.ts";
5455 import { repoDir } from "../git/repos.ts";
@@ -1017,8 +1018,50 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
10171018 return (await resolveOid(dir, ref)) ?? (pull.headOid || undefined);
10181019 }
10191020
1021 let refreshing = false;
1022 /**
1023 * Ask again for the pulls whose green merged an older base (#1179), only
1024 * into slots nothing else wants and at most `STALE_PER_TICK` a tick: main's
1025 * own gate and the pulls just pushed come first.
1026 */
1027 async function refreshStale(): Promise<void> {
1028 if (stopped || refreshing) return;
1029 const waiting = listActive(app.db, "check").filter(
1030 (run) => run.state === "queued",
1031 ).length;
1032 const free = capacity() - inFlight.size - waiting;
1033 if (free <= 0) return;
1034 refreshing = true;
1035 try {
1036 const stale = await stalePulls(
1037 app.db,
1038 async (p) => {
1039 const repo = getRepoById(app.db, p.repoId);
1040 const pull = repo && getPull(app.db, repo.id, p.number);
1041 if (!repo || !pull) return "";

This runs for every green open pull on every 5 s tick. pullDir can run followBase (a git update) and resolveOid forks git. Memoize the tip per repoId + baseBranch within the call, and skip the whole scan when no base tip changed since the last tick.

1042 const dir = await pullDir(app.db, app.reposRoot, repo, pull);
1043 return (await resolveOid(dir, `refs/heads/${p.baseBranch}`)) ?? "";
1044 },
1045 Math.min(free, STALE_PER_TICK),
1046 );
1047 for (const p of stale) {
1048 const repo = getRepoById(app.db, p.repoId);
1049 if (!repo) continue;
1050 await request(repo, `pull-${p.number}`, p.headOid, BASE_MOVED, p.issueId);

Nothing tests this call: no test shows that a stale pull gets a base moved run queued, that a fresh pull does not, or that the free-slot cap holds. Add one.

1051 }
1052 } catch (error) {
1053 log.error("stale checks could not be asked for again", {
1054 error: String(error),
1055 });
1056 } finally {
1057 refreshing = false;
1058 }
1059 }
1060
10201061 const timer = setInterval(() => {
1021 if (!stopped) schedule();
1062 if (stopped) return;
1063 schedule();
1064 void refreshStale();
10221065 }, TICK_MS);
10231066 schedule();
10241067 void catchUp();
src/checks/stale.ts added +91
@@ -0,0 +1,91 @@
1 /**
2 * A green that merged an older base is not ready (#1179). When the base
3 * branch moves, every open pull's last passing check was made against a main
4 * that is gone: the pull reads "checked against an older main", never lands
5 * by rule, and is checked again here — when a slot is free, a few per tick,
6 * so main's own gate is never starved by the pulls behind it.
7 *
8 * Plain data in, plain data out: which pulls to ask for, given what the
9 * database says and where each base stands. The service asks.
10 */
11
12 import type { Database } from "bun:sqlite";
13 import { checksForHead, isCheckStale, listActive } from "../core/runs.ts";
14
15 /** The most stale pulls asked for again in one tick. */
16 export const STALE_PER_TICK = 2;
17
18 /** The check's reason on a run made because the base moved. */
19 export const BASE_MOVED = "base moved";
20
21 export interface StalePull {
22 readonly repoId: string;
23 readonly issueId: string;
24 readonly number: number;
25 readonly headOid: string;
26 readonly baseBranch: string;
27 }
28
29 /**
30 * The open pulls whose last check passed against a base tip that is not the
31 * base's head now, newest pull first, one per pull, and none that already
32 * has a check waiting or running. `tipOf` says where a pull's base stands;
33 * it is asked once per repository and base branch in a call, not per pull,
34 * so an idle forge forks git once per base, not once per green pull.
35 */
36 export async function stalePulls(
37 db: Database,
38 tipOf: (pull: StalePull) => Promise<string>,
39 limit: number,
40 ): Promise<StalePull[]> {
41 if (limit <= 0) return [];
42 const open = db
43 .query<
44 {
45 repo_id: string;
46 issue_id: string;
47 number: number;
48 head_oid: string;
49 base_branch: string;
50 },
51 []
52 >(
53 `SELECT issue.repo_id, issue.id AS issue_id, issue.number,
54 pull.head_oid, pull.base_branch
55 FROM pull JOIN issue ON issue.id = pull.issue_id
56 WHERE issue.state = 'open' AND pull.merged_at IS NULL
57 AND pull.head_oid <> ''
58 ORDER BY issue.created_at DESC LIMIT 200`,
59 )
60 .all();
61 const busy = new Set(
62 listActive(db, "check").flatMap((r) => (r.issueId ? [r.issueId] : [])),
63 );
64 const out: StalePull[] = [];
65 const tips = new Map<string, Promise<string>>();
66 const tipFor = (pull: StalePull): Promise<string> => {
67 const key = `${pull.repoId}\0${pull.baseBranch}`;
68 let tip = tips.get(key);
69 if (tip === undefined) {
70 tip = tipOf(pull);
71 tips.set(key, tip);
72 }
73 return tip;
74 };
75 for (const row of open) {
76 if (out.length >= limit) break;
outdated

tipOf is called once per green pull, though every pull on the same repo and base has the same tip. Resolve it once per (repo, base) here or in the caller, and add a test that counts the calls.

77 if (busy.has(row.issue_id)) continue;
78 const latest = checksForHead(db, row.issue_id, row.head_oid)[0];
79 if (latest === undefined || latest.state !== "ok" || latest.baseOid === "")
80 continue;
81 const pull: StalePull = {
82 repoId: row.repo_id,
83 issueId: row.issue_id,
84 number: row.number,
85 headOid: row.head_oid,
86 baseBranch: row.base_branch,
87 };
88 if (isCheckStale(latest, await tipFor(pull))) out.push(pull);
89 }
90 return out;
91 }
src/core/pulls.ts +18 −10
@@ -835,11 +835,15 @@ export async function mergePull(
835835 const there = await pullStatus(input.sealedFrom, pull, input.gate);
836836 if (there.reviews !== null && !there.reviews.mergeable)
837837 return err("review_required");
838 if (
839 input.gate?.requireChecks === true &&
840 checkSummary(input.gate.db, pull.id, there.headOid).state !== "ok"
841 )
842 return err("checks_required");
838 if (input.gate?.requireChecks === true) {
839 const seen = checkSummary(
840 input.gate.db,
841 pull.id,
842 there.headOid,
843 there.baseOid,
844 );
845 if (seen.state !== "ok" || seen.stale) return err("checks_required");
846 }
843847 if (!there.mergeable)
844848 return err(
845849 there.conflicts.length > 0
@@ -864,11 +868,15 @@ export async function mergePull(
864868 return err("review_required");
865869 // The check is the latest deploy run of *this* head. Read here, not
866870 // handed in, for the same reason as the review verdict above.
867 if (
868 input.gate?.requireChecks === true &&
869 checkSummary(input.gate.db, pull.id, status.headOid).state !== "ok"
870 )
871 return err("checks_required");
871 if (input.gate?.requireChecks === true) {
872 const seen = checkSummary(
873 input.gate.db,
874 pull.id,
875 status.headOid,
876 status.baseOid,
877 );
878 if (seen.state !== "ok" || seen.stale) return err("checks_required");
879 }
872880 const landed = await merge(dir, {
873881 baseBranch: pull.baseBranch,
874882 baseOid: status.baseOid,
src/core/runs.ts +21 −2
@@ -778,17 +778,36 @@ export interface CheckSummary {
778778 /** `ok` when the latest deploy of this head succeeded; `none` when there is none. */
779779 readonly state: RunState | "none";
780780 readonly run: Run | null;
781 /** A green that merged an older base tip than the base's head now: not ready (#1179). */
782 readonly stale: boolean;
783 }
784
785 /**
786 * A passing check is stale when it merged a base tip that is no longer the
787 * base's head. A check that merged nothing (`baseOid` empty) or a base tip
788 * not asked about has nothing to be stale against.
789 */
790 export function isCheckStale(run: Run | null, baseTip: string): boolean {
791 return (
792 run !== null &&
793 run.state === "ok" &&
794 run.baseOid !== "" &&
795 baseTip !== "" &&
796 run.baseOid !== baseTip
797 );
781798 }
782799
783800 export function checkSummary(
784801 db: Database,
785802 issueId: string,
786803 headOid: string,
804 /** The base branch's head now; when given, a green on an older one is `stale`. */
805 baseTip = "",
787806 ): CheckSummary {
788807 const latest = checksForHead(db, issueId, headOid)[0];
789808 return latest
790 ? { state: latest.state, run: latest }
791 : { state: "none", run: null };
809 ? { state: latest.state, run: latest, stale: isCheckStale(latest, baseTip) }
810 : { state: "none", run: null, stale: false };
792811 }
793812
794813 /**
src/crew/autonomy.ts +4
@@ -69,6 +69,7 @@ import {
6969 } from "../core/repos.ts";
7070 import {
7171 activeRunFor,
72 isCheckStale,
7273 automaticRunsSince,
7374 listActive,
7475 type Run,
@@ -1310,6 +1311,9 @@ export async function landIfGreen(
13101311 return false;
13111312 }
13121313 }
1314 // A green that merged an older base is not ready: it lands once the
1315 // re-check (`checks/stale.ts`) has run against this tip (#1179).
1316 if (checks.some((c) => isCheckStale(c, baseTip))) return false;
13131317 // A pull that loosens the contract is a change of policy, which is a
13141318 // wall: decided by a person, never crossed by the crew. The pull stays
13151319 // green and open, on the studio's cards, until someone lands it.
src/http/api.ts +9
@@ -304,6 +304,7 @@ import type { Closing } from "../actions/issues.ts";
304304 import {
305305 checksForHead,
306306 getRun,
307 isCheckStale,
307308 isTerminal,
308309 listActiveRuns,
309310 type Run,
@@ -5006,9 +5007,17 @@ export function apiRoutes(router: Router<Handler>): void {
50065007 const head = await pullHeadOid(ctx, found.repo, found.pull);
50075008 const runs = checksForHead(ctx.app.db, found.pull.id, head);
50085009 const latest = runs[0];
5010 const open = found.pull.state === "open" && found.pull.mergedAt === null;
5011 const baseTip = open
5012 ? ((await resolveOid(
5013 await pullDirOf(ctx, found.repo, found.pull),
5014 `refs/heads/${found.pull.baseBranch}`,
5015 )) ?? "")
5016 : "";
50095017 return json({
50105018 head,
50115019 state: latest?.state ?? "none",
5020 checkStale: isCheckStale(latest ?? null, baseTip),
50125021 required: found.repo.requireChecks,
50135022 run: latest ?? null,
50145023 runs,
src/http/mcp.ts +11 −4
@@ -99,6 +99,7 @@ import {
9999 } from "../core/repos.ts";
100100 import { plannerDeclines } from "../crew/autonomy.ts";
101101 import { checkSummary, listActiveRuns } from "../core/runs.ts";
102 import { resolveOid } from "../git/merge.ts";
102103 import { scopeAllows } from "../core/tokens.ts";
103104 import { getUsersByIds, type User } from "../core/users.ts";
104105 import { openapi } from "../contract/openapi.ts";
@@ -482,11 +483,16 @@ const TOOLS: readonly Tool[] = [
482483 : undefined;
483484 if (pull === undefined || !mayView(ctx.app.db, repo, pull, user))
484485 return bad("no_such_pull", `no pull #${String(n)}`);
485 const state = await pullMergeState(
486 await pullDir(ctx.app.db, ctx.app.reposRoot, repo, pull),
487 pull,
486 const dir = await pullDir(ctx.app.db, ctx.app.reposRoot, repo, pull);
487 const state = await pullMergeState(dir, pull);
488 const check = checkSummary(
489 ctx.app.db,
490 pull.id,
491 pull.headOid,
492 pull.state === "open" && pull.mergedAt === null
493 ? ((await resolveOid(dir, `refs/heads/${pull.baseBranch}`)) ?? "")
494 : "",
488495 );
489 const check = checkSummary(ctx.app.db, pull.id, pull.headOid);
490496 return good({
491497 number: pull.number,
492498 title: pull.title,
@@ -494,6 +500,7 @@ const TOOLS: readonly Tool[] = [
494500 base: pull.baseBranch,
495501 head: pull.headBranch,
496502 check: { state: check.state, baseOid: check.run?.baseOid ?? "" },
503 checkStale: check.stale,
497504 ...(state ?? {}),
498505 });
499506 },
src/tui/screens/pull.ts +25 −6
@@ -48,9 +48,10 @@ import {
4848 import { getAppByRepo } from "../../core/apps.ts";
4949 import { getIssue, type Issue } from "../../core/issues.ts";
5050 import { pullMayRun } from "../../core/pull_trust.ts";
51 import { getPull, variantSiblings, type Pull } from "../../core/pulls.ts";
51 import { getPull, pullDir, variantSiblings, type Pull } from "../../core/pulls.ts";
5252 import { voteVariant } from "../../actions/variants.ts";
5353 import { getRepoById, type Repo } from "../../core/repos.ts";
54 import { resolveOid } from "../../git/merge.ts";
5455 import { checkSummary, type CheckSummary } from "../../core/runs.ts";
5556 import { err, ok } from "../../kernel/result.ts";
5657 import { getUsersByIds } from "../../core/users.ts";
@@ -175,7 +176,7 @@ export function standingText(standing: Standing, required: boolean): string {
175176 type Tab = 0 | 1 | 2;
outdated

This only adds stale: false to the empty case. The real summary at line 271 is never asked about the base tip, so the terminal shows checks: passed on a stale green. Pass the base tip and add a stale wording to checksText and checksRefusal, as on the page.

176177
177178 /** The checks on a pull, before any deploy has run. */
178 const NO_CHECK: CheckSummary = { state: "none", run: null };
179 const NO_CHECK: CheckSummary = { state: "none", run: null, stale: false };
179180
180181 /** What each verdict is called on screen — one wording, every surface. */
181182 const VERDICT_WORDS: Record<ReviewFact["state"], string> = {
@@ -267,11 +268,25 @@ export function pullScreen(
267268 : envsFor(f.app, f.user, record).find(
268269 (e) => e.env === previewEnv(number),
269270 );
270 check =
271 row === undefined
272 ? NO_CHECK
273 : checkSummary(f.db, row.id, row.headOid || (facts?.headOid ?? ""));
274271 checkBase = row?.baseBranch ?? facts?.baseBranch ?? "";
272 const headForCheck = row?.headOid || (facts?.headOid ?? "");
273 check =
274 row === undefined ? NO_CHECK : checkSummary(f.db, row.id, headForCheck);
275 // Only a passing check that names its base can be stale; resolve the
276 // base tip for that one case, so no other reload forks git.
277 if (
278 row !== undefined &&
279 repo !== undefined &&
280 check.state === "ok" &&
281 check.run?.baseOid
282 ) {
283 const baseTip =
284 (await resolveOid(
285 await pullDir(f.db, f.app.reposRoot, repo, row),
286 `refs/heads/${checkBase}`,
287 )) ?? "";
288 check = checkSummary(f.db, row.id, headForCheck, baseTip);
289 }
275290 const runs =
276291 repo === undefined || row === undefined
277292 ? undefined
@@ -1171,6 +1186,8 @@ export function checksText(
11711186 ? ` · checked against ${baseBranch} at ${run.baseOid.slice(0, 7)}`
11721187 : ""
11731188 }`;
1189 if (check.stale)
1190 return `checks: checked against an older ${baseBranch || "base"} — checking again`;
11741191 switch (check.state) {
11751192 case "ok":
11761193 return `checks: passed${summary}`;
@@ -1189,6 +1206,8 @@ export function checksText(
11891206
11901207 /** Why `m` is refused by the checks gate, in words a person can act on. */
11911208 export function checksRefusal(check: CheckSummary): string {
1209 if (check.stale)
1210 return "the check ran against an older base — it is checking again";
11921211 switch (check.state) {
11931212 case "failed":
11941213 return `the deploy of this head failed${check.run?.summary ? `: ${check.run.summary}` : ""}`;
src/web/pages/pull.ts +10 −1
@@ -238,6 +238,10 @@ export function checksLine(
238238 ? html`<span class="bad"
239239 >${icon("x")}Conflicts in ${conflicts} ${conflicts === 1 ? "file" : "files"}</span
240240 >${link}`
241 : check.stale
242 ? html`<span class="now"
243 >${icon("clock")}Checked against an older ${baseBranch || "main"}; checking again</span
244 >${link}`
241245 : check.state === "ok"
242246 ? html`<span class="ok">${icon("check")}Checks passed</span>${link}`
243247 : check.state === "failed"
@@ -741,7 +745,12 @@ export async function pullFilesPage(ctx: Ctx): Promise<Response> {
741745 const by = standings(ctx.app.db, pull, status.headOid);
742746 // The checks are the deploy runs of the live head, read here for the same
743747 // reason the review gate is: the box and the merge answer one question.
744 const check = checkSummary(ctx.app.db, pull.id, status.headOid);
748 const check = checkSummary(
749 ctx.app.db,
outdated

check now carries stale, but mergeBox (L485) still gates on check.state !== "ok" alone. With requireChecks, a stale green shows an enabled Merge button that refuses with checks_required. Use check.state !== "ok" || check.stale, with a why line that says it is checking against the new base (#2014).

750 pull.id,
751 status.headOid,
752 status.baseOid,
753 );
745754 const isApp = getAppByRepo(ctx.app.db, repo.id) !== undefined;
746755 const tier = await tierOf(dir, status.headOid, check);
747756 const threads = pullThreads(ctx.app, pull);
src/web/studio/words.ts +14 −1
@@ -32,6 +32,7 @@ import {
3232 type CheckSummary,
3333 type Run,
3434 } from "../../core/runs.ts";
35 import { resolveOid } from "../../git/merge.ts";
3536 import { html, type Html } from "../html.ts";
3637 import { icon } from "../ui.ts";
3738
@@ -239,11 +240,23 @@ export async function pullWord(
239240 ? "parked by the crew"
240241 : "closed without shipping",
241242 };
242 const check = checkSummary(ctx.db, pull.id, pull.headOid);
243 let check = checkSummary(ctx.db, pull.id, pull.headOid);
244 // Only a passing check that names its base can be stale: fork git for that
245 // alone, not for every row of the inbox.
246 if (check.state === "ok" && check.run?.baseOid) {
247 const baseTip =
248 (await resolveOid(ctx.dir, `refs/heads/${pull.baseBranch}`)) ?? "";
249 check = checkSummary(ctx.db, pull.id, pull.headOid, baseTip);
250 }
243251 // A repository that is not an app never deploys a head, so it never gets
244252 // a look: an open change there waits on a person, and says so.
245253 if (ctx.record === undefined && check.state === "none")
246254 return { word: "waiting", note: "open — waiting on a person" };
outdated

This hardcodes "main". The page says older ${baseBranch}, so a pull into release would read differently here and there. Use pull.baseBranch. Also, pullWord now spawns a git rev-parse for every pull on the inbox, even closed ones. Resolve the tip only after the open/merged early returns (it already is), and only when the check is ok with a baseOid. Then the common inbox render does not fork git for each row.

255 if (check.stale)

The pull word is right. The inbox's look/review asks in asks.ts don't check stale, though, so the same pull still gets "green — ready for a look. Ship it" there. Resolve the tip the same way (only when the check is ok and has a baseOid) and skip the ask while stale (#2014).

256 return {
257 word: "working",
258 note: `checked against an older ${pull.baseBranch} — checking again`,
259 };
247260 if (check.state === "ok") {
248261 const reviewer = waitsForReviewer(ctx.db, pull.repoId, pull);
249262 if (reviewer !== undefined)
test/check-stale.test.ts added +285
@@ -0,0 +1,285 @@
1 /**
2 * A green that merged an older base is not ready (#1179): the base moves and
3 * the pull reads "checked against an older main" on the page, the API and the
4 * MCP; it is asked for again, a few a tick; it never lands by rule while
5 * stale; a re-check against the new tip turns it green.
6 */
7
8 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
9 import { mkdtemp, rm } from "node:fs/promises";
10 import { tmpdir } from "node:os";
11 import { join } from "node:path";
12 import { openPull } from "../src/actions/pulls.ts";
13 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
14 import { createApp } from "../src/app.ts";
15 import { getPull, type Pull } from "../src/core/pulls.ts";
16 import { getRepoById, type Repo } from "../src/core/repos.ts";
17 import {
18 checkSummary,
19 claimRun,
20 createRun,
21 finishRun,
22 listRuns,
23 setRunBase,
24 } from "../src/core/runs.ts";
25 import { createToken } from "../src/core/tokens.ts";
26 import { createUser, type User } from "../src/core/users.ts";
27 import { landIfGreen } from "../src/crew/autonomy.ts";
28 import { startChecks } from "../src/checks/service.ts";
29 import { BASE_MOVED, stalePulls, STALE_PER_TICK } from "../src/checks/stale.ts";
30 import { resolveOid } from "../src/git/merge.ts";
31 import { repoDir } from "../src/git/repos.ts";
32 import { serve, type Servers } from "../src/http/server.ts";
33 import { checksRefusal, checksText } from "../src/tui/screens/pull.ts";
34 import { checksLine } from "../src/web/pages/pull.ts";
35
36 describe("a stale green", () => {
37 let dataDir: string;
38 let app: ReturnType<typeof createApp>;
39 let alice: User;
40 let repo: Repo;
41 let servers: Servers;
42 let token: string;
43 const fresh = () => getRepoById(app.db, repo.id)!;
44 const tip = async () =>
45 (await resolveOid(repoDir(app.reposRoot, repo.ownerName, repo.name), "refs/heads/main"))!;
46
47 const pullOn = async (branch: string): Promise<Pull> => {
48 const c = await commitToBranch(app, alice, repo, {
49 branch,
50 base: "main",
51 message: branch,
52 files: [{ path: `${branch}.md`, content: "x\n" }],
53 });
54 if (!c.ok) throw new Error(JSON.stringify(c.error));
55 const o = await openPull(app, alice, repo, {
56 title: branch,
57 body: "",
58 baseBranch: "main",
59 headBranch: branch,
60 });
61 if (!o.ok) throw new Error(String(o.error));
62 return o.value;
63 };
64 /** A passing check of the pull's head that merged `against`. */
65 const pass = (pull: Pull, against: string) => {
66 const run = createRun(app.db, {
67 repoId: repo.id,
68 kind: "check",
69 issueId: pull.id,
70 env: `pull-${pull.number}`,
71 commitOid: pull.headOid,
72 reason: "pull",
73 });
74 claimRun(app.db, run.id);
75 setRunBase(app.db, run.id, against);
76 finishRun(app.db, run.id, { state: "ok", summary: "check passed" });
77 };
78 const moveBase = async (
79 name: string,
80 files = [{ path: `${name}.md`, content: "m\n" }],
81 ) => {
82 const c = await commitToBranch(app, alice, repo, {
83 message: name,
84 files,
85 });
86 if (!c.ok) throw new Error(JSON.stringify(c.error));
87 };
88
89 beforeAll(async () => {
90 dataDir = await mkdtemp(join(tmpdir(), "forge-stale-"));
91 app = createApp({ dataDir, port: 0 });
92 const made = await createUser(app.db, {
93 trusted: true,
94 username: "alice",
95 email: "[email protected]",
96 password: "a-good-passphrase",
97 adminIfFirst: true,
98 });
99 if (!made.ok) throw new Error(made.error);
100 alice = made.value;
101 const r = await createRepo(app, alice, { name: "garden", visibility: "public" });
102 if (!r.ok) throw new Error(String(r.error));
103 repo = r.value;
104 await commitToBranch(app, alice, repo, {
105 message: "seed",
106 files: [{ path: "README.md", content: "# garden\n" }],
107 });
108 app.db
109 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1")
110 .run(repo.id, alice.id);
111 servers = await serve(app);
112 token = createToken(app.db, alice.id, "t", "ro").token;
113 }, 30_000);
114
115 afterAll(async () => {
116 servers.stop();
117 app.close();
118 await rm(dataDir, { recursive: true, force: true });
119 });
120
121 test("base moves → stale on the summary, the page, the API and the MCP; a re-check turns it green", async () => {
122 const pull = await pullOn("shown");
123 pass(pull, await tip());
124 expect(checkSummary(app.db, pull.id, pull.headOid, await tip()).stale).toBe(false);
125
126 const read = async () => {
127 const api = (await (
128 await fetch(`${servers.url}/api/v1/repos/alice/garden/pulls/${pull.number}/checks`, {
129 headers: { authorization: `Bearer ${token}` },
130 })
131 ).json()) as { checkStale: boolean };
132 const rpc = (await (
133 await fetch(`${servers.url}/mcp`, {
134 method: "POST",
135 headers: {
136 "content-type": "application/json",
137 accept: "application/json, text/event-stream",
138 authorization: `Bearer ${token}`,
139 },
140 body: JSON.stringify({
141 jsonrpc: "2.0",
142 id: 1,
143 method: "tools/call",
144 params: { name: "pull", arguments: { repo: "alice/garden", number: pull.number } },
145 }),
146 })
147 ).json()) as any;
148 const mcp = JSON.parse(rpc.result.content[0].text) as { checkStale: boolean };
149 const page = await (
150 await fetch(`${servers.url}/alice/garden/pulls/${pull.number}`)
151 ).text();
152 return { api: api.checkStale, mcp: mcp.checkStale, page };
153 };
154 const before = await read();
155 expect([before.api, before.mcp]).toEqual([false, false]);
156 expect(before.page).not.toContain("older main");
157
158 await moveBase("moved");
159 const stale = checkSummary(app.db, pull.id, pull.headOid, await tip());
160 expect(stale.state).toBe("ok");
161 expect(stale.stale).toBe(true);
162 const after = await read();
163 expect([after.api, after.mcp]).toEqual([true, true]);
164 expect(after.page.toLowerCase()).toContain("checked against an older main");
165 expect(after.page).not.toContain("ready for a look");
166 expect(checksLine("/alice/garden", stale, false, true, false, "", "", 0, "main").text).toContain(
167 "Checked against an older main",
168 );
169
170 pass(pull, await tip());
171 const green = await read();
172 expect([green.api, green.mcp]).toEqual([false, false]);
173 expect(green.page).toContain("ready for a look");
174 });
175
176 test("landing refuses a stale green, and lands the re-checked one", async () => {
177 const pull = await pullOn("lands");
178 pass(pull, await tip());
179 await moveBase("moved-again");
180 expect(await landIfGreen(app, fresh(), pull)).toBe(false);
181 expect(getPull(app.db, repo.id, pull.number)!.mergedAt).toBeNull();
182 pass(pull, await tip());
183 expect(await landIfGreen(app, fresh(), pull)).toBe(true);
184 expect(getPull(app.db, repo.id, pull.number)!.mergedAt).not.toBeNull();
185 });
186
187 test("stale pulls are picked newest first, one per pull, capped, and not while a check is under way", async () => {
188 const shown = getPull(app.db, repo.id, 1)!;
189 const a = await pullOn("pick-a");
190 const b = await pullOn("pick-b");
191 const c = await pullOn("pick-c");
192 const old = await tip();
193 for (const p of [a, b, c]) pass(p, old);
194 await moveBase("moved-third");
195 const now = await tip();
196 const tipOf = async () => now;
197 const picked = await stalePulls(app.db, tipOf, 10);
198 const numbers = picked.map((p) => p.number);
199 expect(numbers.slice(0, 3)).toEqual([c.number, b.number, a.number]);
200 expect(new Set(numbers).size).toBe(numbers.length);
201 // Several pulls on one base ask for its tip once.
202 let asked = 0;
203 await stalePulls(
204 app.db,
205 async () => {
206 asked++;
207 return now;
208 },
209 10,
210 );
211 expect(asked).toBe(1);
212 expect(await stalePulls(app.db, tipOf, STALE_PER_TICK)).toHaveLength(STALE_PER_TICK);
213 expect(await stalePulls(app.db, tipOf, 0)).toHaveLength(0);
214 // A check already waiting for the pull is the re-check.
215 createRun(app.db, {
216 repoId: repo.id,
217 kind: "check",
218 issueId: c.id,
219 env: `pull-${c.number}`,
220 commitOid: c.headOid,
221 reason: "base moved",
222 });
223 expect((await stalePulls(app.db, tipOf, 10)).map((p) => p.number)).not.toContain(c.number);
224 // Once checked against the new tip, none is stale.
225 for (const p of [a, b]) pass(p, now);
226 pass(shown, now);
227 expect(await stalePulls(app.db, tipOf, 10)).toHaveLength(0);
228 });
229
230 test("the terminal reads a stale green as stale, in words and in the refusal", () => {
231 const run = {
232 id: "r",
233 summary: "check passed",
234 baseOid: "abcdef1234",
235 createdAt: Date.now(),
236 } as never;
237 const stale = { state: "ok", run, stale: true } as const;
238 expect(checksText(stale, true, true, "release")).toBe(
239 "checks: checked against an older release — checking again",
240 );
241 expect(checksText({ ...stale, stale: false }, true, true, "release")).toContain(
242 "checks: passed",
243 );
244 expect(checksRefusal(stale)).toContain("older base");
245 expect(checksRefusal({ ...stale, stale: false })).not.toContain("older base");
246 });
247
248 test("the service asks again for stale pulls only, within the free slots", async () => {
249 // A check is only asked for where the repository declares one.
250 await moveBase("declare-check", [
251 {
252 path: "forge.json",
253 content: '{"check": {"run": "true", "install": ""}}\n',
254 },
255 ]);
256 const a = await pullOn("loop-a");
257 const b = await pullOn("loop-b");
258 const c = await pullOn("loop-c");
259 const d = await pullOn("loop-d");
260 const old = await tip();
261 for (const p of [a, b, c]) pass(p, old);
262 await moveBase("moved-loop");
263 const now = await tip();
264 pass(d, now);
265 const mine = new Set([a.id, b.id, c.id, d.id]);
266 const asked = () =>
267 listRuns(app.db, repo.id, { kind: "check", limit: 200 }).filter(
268 (r) => r.reason === BASE_MOVED && r.issueId !== null && mine.has(r.issueId),
269 );
270 const checks = startChecks(app, { forgeUrl: servers.url, concurrency: 2 });
271 try {
272 const deadline = Date.now() + 15_000;
273 while (asked().length === 0 && Date.now() < deadline) await Bun.sleep(100);
274 const first = asked();
275 expect(first.length).toBeGreaterThan(0);
276 // One tick asks for at most STALE_PER_TICK, newest pull first.
277 expect(first.length).toBeLessThanOrEqual(STALE_PER_TICK);
278 expect(first.some((r) => r.issueId === d.id)).toBe(false);
279 expect(first.every((r) => [a.id, b.id, c.id].includes(r.issueId!))).toBe(true);
280 } finally {
281 await checks.stop();
282 }
283 expect(asked().some((r) => r.issueId === d.id)).toBe(false);
284 }, 30_000);
285 });
test/pull-checks-line.test.ts +1 −1
@@ -1,7 +1,7 @@
11 import { expect, test } from "bun:test";
22 import { checksLine } from "../src/web/pages/pull.ts";
33
4 const ok = { state: "ok", run: null } as const;
4 const ok = { state: "ok", run: null, stale: false } as const;
55
66 test("a conflicted pull with a passing check has no green mark and says so", () => {
77 const line = checksLine("/a/b", ok, false, true, false, "", "", 2).text;

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs