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 #2022

Parked opened this
Closed without merging

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

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
14 files changed +794 −26
README.md +4
@@ -1263,6 +1263,10 @@ Once a sibling ships or all but one close, the item leaves the feed. The
12631263 terminal has no feed; the item is in `GET /api/v1/feed` and the MCP feed tool
12641264 as kind `choose`.
12651265
1266 ### A stale green
1267
1268 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, among the 200 newest open pulls; a re-check the service is refused (a suspended owner, an unapproved head, no check declared) is not asked for again until the head or the base moves.
1269
12661270 ### OG cards as PNG
12671271
12681272 `/og/{repo,app,issue,pull,run,map}/<ref>.png` and `/og/audit.png` are the same public cards 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`) | |
src/checks/service.ts +59 −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, staleKey } 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";
@@ -1058,8 +1059,65 @@ export function startChecks(app: App, options: ChecksOptions): ChecksHandle {
10581059 return (await resolveOid(dir, ref)) ?? (pull.headOid || undefined);
10591060 }
10601061
1062 let refreshing = false;
1063 /** Re-checks `request` refused, by `staleKey`: skipped until a tip moves. */
1064 const declinedStale = new Set<string>();
1065 /**
1066 * Ask again for the pulls whose green merged an older base (#1179), only
1067 * into slots nothing else wants and at most `STALE_PER_TICK` a tick: main's
1068 * own gate and the pulls just pushed come first.
1069 */
1070 async function refreshStale(): Promise<void> {
1071 if (stopped || refreshing) return;
1072 const waiting = listActive(app.db, "check").filter(
1073 (run) => run.state === "queued",
1074 ).length;
1075 const free = capacity() - inFlight.size - waiting;
1076 if (free <= 0) return;
1077 refreshing = true;
1078 try {
1079 const stale = await stalePulls(
1080 app.db,
1081 async (p) => {
1082 const repo = getRepoById(app.db, p.repoId);
1083 const pull = repo && getPull(app.db, repo.id, p.number);
1084 if (!repo || !pull) return "";
1085 const dir = await pullDir(app.db, app.reposRoot, repo, pull);
1086 return (await resolveOid(dir, `refs/heads/${p.baseBranch}`)) ?? "";
1087 },
1088 Math.min(free, STALE_PER_TICK),
1089 declinedStale,
1090 );
1091 for (const p of stale) {
1092 const repo = getRepoById(app.db, p.repoId);
1093 if (!repo) continue;
1094 const run = await request(
1095 repo,
1096 `pull-${p.number}`,
1097 p.headOid,
1098 BASE_MOVED,
1099 p.issueId,
1100 );
1101 if (run === undefined) {
1102 // Bounded: a refusal only outlives its tips, so drop the oldest.
1103 if (declinedStale.size >= 1000)
1104 declinedStale.delete(declinedStale.values().next().value!);
1105 declinedStale.add(staleKey(p));
1106 }
1107 }
1108 } catch (error) {
1109 log.error("stale checks could not be asked for again", {
1110 error: String(error),
1111 });
1112 } finally {
1113 refreshing = false;
1114 }
1115 }
1116
10611117 const timer = setInterval(() => {
1062 if (!stopped) schedule();
1118 if (stopped) return;
1119 schedule();
1120 void refreshStale();
10631121 }, TICK_MS);
10641122 schedule();
10651123 void catchUp();
src/checks/stale.ts added +112
@@ -0,0 +1,112 @@
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 /** Where the base stood when this was found. */
28 readonly baseTip: string;
29 }
30
31 /** What a refused re-check is remembered by: it changes when either tip moves. */
32 export const staleKey = (p: StalePull): string =>
33 `${p.issueId}:${p.headOid}:${p.baseTip}`;
34
35 /**
36 * The open pulls whose last check passed against a base tip that is not the
37 * base's head now, newest pull first, one per pull, and none that already
38 * has a check waiting or running. `tipOf` says where a pull's base stands;
39 * it is asked once per repository and base branch in a call, not per pull,
40 * so an idle forge forks git once per base, not once per green pull.
41 * `declined` holds `staleKey`s the service asked for and was refused (a
42 * suspended owner, an unapproved head, no check declared): those wait until
43 * a tip moves, so they never hold the slots against older stale pulls. Only
44 * the 200 newest open pulls are looked at.
45 */
46 export async function stalePulls(
47 db: Database,
48 tipOf: (pull: StalePull) => Promise<string>,
49 limit: number,
50 declined: ReadonlySet<string> = new Set(),
51 ): Promise<StalePull[]> {
52 if (limit <= 0) return [];
53 const open = db
54 .query<
55 {
56 repo_id: string;
57 issue_id: string;
58 number: number;
59 head_oid: string;
60 base_branch: string;
61 },
62 []
63 >(
64 `SELECT issue.repo_id, issue.id AS issue_id, issue.number,
65 pull.head_oid, pull.base_branch
66 FROM pull JOIN issue ON issue.id = pull.issue_id
67 WHERE issue.state = 'open' AND pull.merged_at IS NULL
68 AND pull.head_oid <> ''
69 ORDER BY issue.created_at DESC LIMIT 200`,
70 )
71 .all();
72 const busy = new Set(
73 listActive(db, "check").flatMap((r) => (r.issueId ? [r.issueId] : [])),
74 );
75 const out: StalePull[] = [];
76 const tips = new Map<string, Promise<string>>();
77 const tipFor = (pull: StalePull): Promise<string> => {
78 const key = `${pull.repoId}\0${pull.baseBranch}`;
79 let tip = tips.get(key);
80 if (tip === undefined) {
81 tip = tipOf(pull);
82 tips.set(key, tip);
83 }
84 return tip;
85 };
86 for (const row of open) {
87 if (out.length >= limit) break;
88 if (busy.has(row.issue_id)) continue;
89 const latest = checksForHead(db, row.issue_id, row.head_oid)[0];
90 if (latest === undefined || latest.state !== "ok" || latest.baseOid === "")
91 continue;
92 const baseTip = await tipFor({
93 repoId: row.repo_id,
94 issueId: row.issue_id,
95 number: row.number,
96 headOid: row.head_oid,
97 baseBranch: row.base_branch,
98 baseTip: "",
99 });
100 const pull: StalePull = {
101 repoId: row.repo_id,
102 issueId: row.issue_id,
103 number: row.number,
104 headOid: row.head_oid,
105 baseBranch: row.base_branch,
106 baseTip,
107 };
108 if (isCheckStale(latest, baseTip) && !declined.has(staleKey(pull)))
109 out.push(pull);
110 }
111 return out;
112 }
src/core/pulls.ts +18 −10
@@ -852,11 +852,15 @@ export async function mergePull(
852852 const there = await pullStatus(input.sealedFrom, pull, input.gate);
853853 if (there.reviews !== null && !there.reviews.mergeable)
854854 return err("review_required");
855 if (
856 input.gate?.requireChecks === true &&
857 checkSummary(input.gate.db, pull.id, there.headOid).state !== "ok"
858 )
859 return err("checks_required");
855 if (input.gate?.requireChecks === true) {
856 const seen = checkSummary(
857 input.gate.db,
858 pull.id,
859 there.headOid,
860 there.baseOid,
861 );
862 if (seen.state !== "ok" || seen.stale) return err("checks_required");
863 }
860864 if (!there.mergeable)
861865 return err(
862866 there.conflicts.length > 0
@@ -896,11 +900,15 @@ export async function mergePull(
896900 return err("review_required");
897901 // The check is the latest deploy run of *this* head. Read here, not
898902 // handed in, for the same reason as the review verdict above.
899 if (
900 input.gate?.requireChecks === true &&
901 checkSummary(input.gate.db, pull.id, status.headOid).state !== "ok"
902 )
903 return err("checks_required");
903 if (input.gate?.requireChecks === true) {
904 const seen = checkSummary(
905 input.gate.db,
906 pull.id,
907 status.headOid,
908 status.baseOid,
909 );
910 if (seen.state !== "ok" || seen.stale) return err("checks_required");
911 }
904912 const landed = await merge(dir, {
905913 baseBranch: pull.baseBranch,
906914 baseOid: status.baseOid,
src/core/runs.ts +21 −2
@@ -782,17 +782,36 @@ export interface CheckSummary {
782782 /** `ok` when the latest deploy of this head succeeded; `none` when there is none. */
783783 readonly state: RunState | "none";
784784 readonly run: Run | null;
785 /** A green that merged an older base tip than the base's head now: not ready (#1179). */
786 readonly stale: boolean;
787 }
788
789 /**
790 * A passing check is stale when it merged a base tip that is no longer the
791 * base's head. A check that merged nothing (`baseOid` empty) or a base tip
792 * not asked about has nothing to be stale against.
793 */
794 export function isCheckStale(run: Run | null, baseTip: string): boolean {
795 return (
796 run !== null &&
797 run.state === "ok" &&
798 run.baseOid !== "" &&
799 baseTip !== "" &&
800 run.baseOid !== baseTip
801 );
785802 }
786803
787804 export function checkSummary(
788805 db: Database,
789806 issueId: string,
790807 headOid: string,
808 /** The base branch's head now; when given, a green on an older one is `stale`. */
809 baseTip = "",
791810 ): CheckSummary {
792811 const latest = checksForHead(db, issueId, headOid)[0];
793812 return latest
794 ? { state: latest.state, run: latest }
795 : { state: "none", run: null };
813 ? { state: latest.state, run: latest, stale: isCheckStale(latest, baseTip) }
814 : { state: "none", run: null, stale: false };
796815 }
797816
798817 /**
src/crew/autonomy.ts +4
@@ -74,6 +74,7 @@ import {
7474 } from "../core/repos.ts";
7575 import {
7676 activeRunFor,
77 isCheckStale,
7778 automaticRunsSince,
7879 listActive,
7980 type Run,
@@ -1679,6 +1680,9 @@ async function admit(
16791680 return undefined;
16801681 }
16811682 }
1683 // A green that merged an older base is not ready: it lands once the
1684 // re-check (`checks/stale.ts`) has run against this tip (#1179).
1685 if (checks.some((c) => isCheckStale(c, baseTip))) return undefined;
16821686 // A pull that loosens the contract is a change of policy, which is a
16831687 // wall: decided by a person, never crossed by the crew. The pull stays
16841688 // green and open, on the studio's cards, until someone lands it.
src/http/api.ts +9
@@ -322,6 +322,7 @@ import type { Closing } from "../actions/issues.ts";
322322 import {
323323 checksForHead,
324324 getRun,
325 isCheckStale,
325326 isTerminal,
326327 listActiveRuns,
327328 type Run,
@@ -5233,9 +5234,17 @@ export function apiRoutes(router: Router<Handler>): void {
52335234 const head = await pullHeadOid(ctx, found.repo, found.pull);
52345235 const runs = checksForHead(ctx.app.db, found.pull.id, head);
52355236 const latest = runs[0];
5237 const open = found.pull.state === "open" && found.pull.mergedAt === null;
5238 const baseTip = open
5239 ? ((await resolveOid(
5240 await pullDirOf(ctx, found.repo, found.pull),
5241 `refs/heads/${found.pull.baseBranch}`,
5242 )) ?? "")
5243 : "";
52365244 return json({
52375245 head,
52385246 state: latest?.state ?? "none",
5247 checkStale: isCheckStale(latest ?? null, baseTip),
52395248 required: found.repo.requireChecks,
52405249 run: latest ?? null,
52415250 runs,
src/http/mcp.ts +11 −4
@@ -108,6 +108,7 @@ import {
108108 } from "../core/repos.ts";
109109 import { plannerDeclines } from "../crew/autonomy.ts";
110110 import { checkSummary, listActiveRuns } from "../core/runs.ts";
111 import { resolveOid } from "../git/merge.ts";
111112 import { scopeAllows } from "../core/tokens.ts";
112113 import { getUserByName, getUsersByIds, type User } from "../core/users.ts";
113114 import { chipsOf, isKindChip, setChip } from "../core/feed_chips.ts";
@@ -522,11 +523,16 @@ const TOOLS: readonly Tool[] = [
522523 : undefined;
523524 if (pull === undefined || !mayView(ctx.app.db, repo, pull, user))
524525 return bad("no_such_pull", `no pull #${String(n)}`);
525 const state = await pullMergeState(
526 await pullDir(ctx.app.db, ctx.app.reposRoot, repo, pull),
527 pull,
526 const dir = await pullDir(ctx.app.db, ctx.app.reposRoot, repo, pull);
527 const state = await pullMergeState(dir, pull);
528 const check = checkSummary(
529 ctx.app.db,
530 pull.id,
531 pull.headOid,
532 pull.state === "open" && pull.mergedAt === null
533 ? ((await resolveOid(dir, `refs/heads/${pull.baseBranch}`)) ?? "")
534 : "",
528535 );
529 const check = checkSummary(ctx.app.db, pull.id, pull.headOid);
530536 return good({
531537 number: pull.number,
532538 title: pull.title,
@@ -535,6 +541,7 @@ const TOOLS: readonly Tool[] = [
535541 head: pull.headBranch,
536542 proposal: pullProposalOf(ctx.app.db, pull.id) ?? null,
537543 check: { state: check.state, baseOid: check.run?.baseOid ?? "" },
544 checkStale: check.stale,
538545 ...(state ?? {}),
539546 });
540547 },
src/tui/screens/pull.ts +24 −5
@@ -52,6 +52,7 @@ import { isProposed, pullMayRun } from "../../core/pull_trust.ts";
5252 import { getPull, pullDir, variantSiblings, type Pull } from "../../core/pulls.ts";
5353 import { voteVariant } from "../../actions/variants.ts";
5454 import { getRepoById, type Repo } from "../../core/repos.ts";
55 import { resolveOid } from "../../git/merge.ts";
5556 import { checkSummary, type CheckSummary } from "../../core/runs.ts";
5657 import { err, ok } from "../../kernel/result.ts";
5758 import { getUsersByIds } from "../../core/users.ts";
@@ -178,7 +179,7 @@ export function standingText(standing: Standing, required: boolean): string {
178179 type Tab = 0 | 1 | 2;
179180
180181 /** The checks on a pull, before any deploy has run. */
181 const NO_CHECK: CheckSummary = { state: "none", run: null };
182 const NO_CHECK: CheckSummary = { state: "none", run: null, stale: false };
182183
183184 /** What each verdict is called on screen — one wording, every surface. */
184185 const VERDICT_WORDS: Record<ReviewFact["state"], string> = {
@@ -270,11 +271,25 @@ export function pullScreen(
270271 : envsFor(f.app, f.user, record).find(
271272 (e) => e.env === previewEnv(number),
272273 );
273 check =
274 row === undefined
275 ? NO_CHECK
276 : checkSummary(f.db, row.id, row.headOid || (facts?.headOid ?? ""));
277274 checkBase = row?.baseBranch ?? facts?.baseBranch ?? "";
275 const headForCheck = row?.headOid || (facts?.headOid ?? "");
276 check =
277 row === undefined ? NO_CHECK : checkSummary(f.db, row.id, headForCheck);
278 // Only a passing check that names its base can be stale; resolve the
279 // base tip for that one case, so no other reload forks git.
280 if (
281 row !== undefined &&
282 repo !== undefined &&
283 check.state === "ok" &&
284 check.run?.baseOid
285 ) {
286 const baseTip =
287 (await resolveOid(
288 await pullDir(f.db, f.app.reposRoot, repo, row),
289 `refs/heads/${checkBase}`,
290 )) ?? "";
291 check = checkSummary(f.db, row.id, headForCheck, baseTip);
292 }
278293 const runs =
279294 repo === undefined || row === undefined
280295 ? undefined
@@ -1213,6 +1228,8 @@ export function checksText(
12131228 ? ` · checked against ${baseBranch} at ${run.baseOid.slice(0, 7)}`
12141229 : ""
12151230 }`;
1231 if (check.stale)
1232 return `checks: checked against an older ${baseBranch || "base"} — checking again`;
12161233 switch (check.state) {
12171234 case "ok":
12181235 return `checks: passed${summary}`;
@@ -1231,6 +1248,8 @@ export function checksText(
12311248
12321249 /** Why `m` is refused by the checks gate, in words a person can act on. */
12331250 export function checksRefusal(check: CheckSummary): string {
1251 if (check.stale)
1252 return "the check ran against an older base — it is checking again";
12341253 switch (check.state) {
12351254 case "failed":
12361255 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,
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 +44 −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
@@ -77,6 +78,33 @@ export function servingHistory(): ServingHistory {
7778 return new Map();
7879 }
7980
81 /** The base tips one render has asked git for, by `dir\0baseBranch`. */
82 const baseTips = new WeakMap<WordCtx, Map<string, Promise<string>>>();
83
84 /**
85 * Where a base branch stands, asked of git once per (directory, branch) for
86 * the render that owns `ctx` — a page of N green pulls on one base is one
87 * `git rev-parse`, not N. Held per `ctx` so it is dropped with the render.
88 */
89 export function baseTipOf(
90 ctx: WordCtx,
91 baseBranch: string,
92 lookup: (dir: string, ref: string) => Promise<string | undefined> = resolveOid,
93 ): Promise<string> {
94 let tips = baseTips.get(ctx);
95 if (tips === undefined) {
96 tips = new Map();
97 baseTips.set(ctx, tips);
98 }
99 const key = `${ctx.dir}\0${baseBranch}`;
100 let tip = tips.get(key);
101 if (tip === undefined) {
102 tip = lookup(ctx.dir, `refs/heads/${baseBranch}`).then((oid) => oid ?? "");
103 tips.set(key, tip);
104 }
105 return tip;
106 }
107
80108 /**
81109 * Everything the word functions below need to see production: the repo's
82110 * git directory (an ancestry check reads it), the runtime plus the app
@@ -239,11 +267,26 @@ export async function pullWord(
239267 ? "parked by the crew"
240268 : "closed without shipping",
241269 };
242 const check = checkSummary(ctx.db, pull.id, pull.headOid);
270 let check = checkSummary(ctx.db, pull.id, pull.headOid);
271 // Only a passing check that names its base can be stale: fork git for that
272 // alone, not for every row of the inbox.
273 if (check.state === "ok" && check.run?.baseOid) {
274 check = checkSummary(
275 ctx.db,
276 pull.id,
277 pull.headOid,
278 await baseTipOf(ctx, pull.baseBranch),

Minor: for a sealed pull this resolves the base in ctx.dir, not in pullDir, so the inbox can disagree with the page (which uses status.baseOid). Not blocking.

279 );
280 }
243281 // A repository that is not an app never deploys a head, so it never gets
244282 // a look: an open change there waits on a person, and says so.
245283 if (ctx.record === undefined && check.state === "none")
246284 return { word: "waiting", note: "open — waiting on a person" };
285 if (check.stale)
286 return {
287 word: "working",
288 note: `checked against an older ${pull.baseBranch} — checking again`,
289 };
247290 if (check.state === "ok") {
248291 const reviewer = waitsForReviewer(ctx.db, pull.repoId, pull);
249292 if (reviewer !== undefined)
test/check-stale.test.ts added +476
@@ -0,0 +1,476 @@
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 { mergePull, openPull } from "../src/actions/pulls.ts";
13 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
14 import { createApp } from "../src/app.ts";
15 import { getPull, mergePull as landPull, type Pull } from "../src/core/pulls.ts";
16 import { setSuspended } from "../src/core/accounts.ts";
17 import { getRepoById, type Repo } from "../src/core/repos.ts";
18 import {
19 checkSummary,
20 claimRun,
21 createRun,
22 listActive,
23 finishRun,
24 listRuns,
25 setRunBase,
26 } from "../src/core/runs.ts";
27 import { createToken } from "../src/core/tokens.ts";
28 import { createUser, type User } from "../src/core/users.ts";
29 import { landIfGreen } from "../src/crew/autonomy.ts";
30 import { startChecks } from "../src/checks/service.ts";
31 import { BASE_MOVED, staleKey, stalePulls, STALE_PER_TICK } from "../src/checks/stale.ts";
32 import { resolveOid } from "../src/git/merge.ts";
33 import { repoDir } from "../src/git/repos.ts";
34 import { serve, type Servers } from "../src/http/server.ts";
35 import { baseTipOf, servingHistory, type WordCtx } from "../src/web/studio/words.ts";
36 import { checksRefusal, checksText } from "../src/tui/screens/pull.ts";
37 import { checksLine } from "../src/web/pages/pull.ts";
38
39 describe("a stale green", () => {
40 let dataDir: string;
41 let app: ReturnType<typeof createApp>;
42 let alice: User;
43 let repo: Repo;
44 let servers: Servers;
45 let token: string;
46 const fresh = () => getRepoById(app.db, repo.id)!;
47 const tip = async () =>
48 (await resolveOid(repoDir(app.reposRoot, repo.ownerName, repo.name), "refs/heads/main"))!;
49
50 const pullOn = async (branch: string): Promise<Pull> => {
51 const c = await commitToBranch(app, alice, repo, {
52 branch,
53 base: "main",
54 message: branch,
55 files: [{ path: `${branch}.md`, content: "x\n" }],
56 });
57 if (!c.ok) throw new Error(JSON.stringify(c.error));
58 const o = await openPull(app, alice, repo, {
59 title: branch,
60 body: "",
61 baseBranch: "main",
62 headBranch: branch,
63 });
64 if (!o.ok) throw new Error(String(o.error));
65 return o.value;
66 };
67 /** A passing check of the pull's head that merged `against`. */
68 const pass = (pull: Pull, against: string) => {
69 const run = createRun(app.db, {
70 repoId: repo.id,
71 kind: "check",
72 issueId: pull.id,
73 env: `pull-${pull.number}`,
74 commitOid: pull.headOid,
75 reason: "pull",
76 });
77 claimRun(app.db, run.id);
78 setRunBase(app.db, run.id, against);
79 finishRun(app.db, run.id, { state: "ok", summary: "check passed" });
80 };
81 const moveBase = async (
82 name: string,
83 files = [{ path: `${name}.md`, content: "m\n" }],
84 ) => {
85 const c = await commitToBranch(app, alice, repo, {
86 message: name,
87 files,
88 });
89 if (!c.ok) throw new Error(JSON.stringify(c.error));
90 };
91
92 beforeAll(async () => {
93 dataDir = await mkdtemp(join(tmpdir(), "forge-stale-"));
94 app = createApp({ dataDir, port: 0 });
95 const made = await createUser(app.db, {
96 trusted: true,
97 username: "alice",
98 email: "[email protected]",
99 password: "a-good-passphrase",
100 adminIfFirst: true,
101 });
102 if (!made.ok) throw new Error(made.error);
103 alice = made.value;
104 const r = await createRepo(app, alice, { name: "garden", visibility: "public" });
105 if (!r.ok) throw new Error(String(r.error));
106 repo = r.value;
107 await commitToBranch(app, alice, repo, {
108 message: "seed",
109 files: [{ path: "README.md", content: "# garden\n" }],
110 });
111 app.db
112 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1")
113 .run(repo.id, alice.id);
114 servers = await serve(app);
115 token = createToken(app.db, alice.id, "t", "ro").token;
116 }, 30_000);
117
118 afterAll(async () => {
119 servers.stop();
120 app.close();
121 await rm(dataDir, { recursive: true, force: true });
122 });
123
124 test("base moves → stale on the summary, the page, the API and the MCP; a re-check turns it green", async () => {
125 const pull = await pullOn("shown");
126 pass(pull, await tip());
127 expect(checkSummary(app.db, pull.id, pull.headOid, await tip()).stale).toBe(false);
128
129 const read = async () => {
130 const api = (await (
131 await fetch(`${servers.url}/api/v1/repos/alice/garden/pulls/${pull.number}/checks`, {
132 headers: { authorization: `Bearer ${token}` },
133 })
134 ).json()) as { checkStale: boolean };
135 const rpc = (await (
136 await fetch(`${servers.url}/mcp`, {
137 method: "POST",
138 headers: {
139 "content-type": "application/json",
140 accept: "application/json, text/event-stream",
141 authorization: `Bearer ${token}`,
142 },
143 body: JSON.stringify({
144 jsonrpc: "2.0",
145 id: 1,
146 method: "tools/call",
147 params: { name: "pull", arguments: { repo: "alice/garden", number: pull.number } },
148 }),
149 })
150 ).json()) as any;
151 const mcp = JSON.parse(rpc.result.content[0].text) as { checkStale: boolean };
152 const page = await (
153 await fetch(`${servers.url}/alice/garden/pulls/${pull.number}`)
154 ).text();
155 return { api: api.checkStale, mcp: mcp.checkStale, page };
156 };
157 const before = await read();
158 expect([before.api, before.mcp]).toEqual([false, false]);
159 expect(before.page).not.toContain("older main");
160
161 await moveBase("moved");
162 const stale = checkSummary(app.db, pull.id, pull.headOid, await tip());
163 expect(stale.state).toBe("ok");
164 expect(stale.stale).toBe(true);
165 const after = await read();
166 expect([after.api, after.mcp]).toEqual([true, true]);
167 expect(after.page.toLowerCase()).toContain("checked against an older main");
168 expect(after.page).not.toContain("ready for a look");
169 expect(checksLine("/alice/garden", stale, false, true, false, "", "", 0, "main").text).toContain(
170 "Checked against an older main",
171 );
172
173 pass(pull, await tip());
174 const green = await read();
175 expect([green.api, green.mcp]).toEqual([false, false]);
176 expect(green.page).toContain("ready for a look");
177 });
178
179 test("landing refuses a stale green, and lands the re-checked one", async () => {
180 const pull = await pullOn("lands");
181 pass(pull, await tip());
182 await moveBase("moved-again");
183 expect(await landIfGreen(app, fresh(), pull)).toBe(false);
184 expect(getPull(app.db, repo.id, pull.number)!.mergedAt).toBeNull();
185 pass(pull, await tip());
186 expect(await landIfGreen(app, fresh(), pull)).toBe(true);
187 expect(getPull(app.db, repo.id, pull.number)!.mergedAt).not.toBeNull();
188 });
189
190 test("stale pulls are picked newest first, one per pull, capped, and not while a check is under way", async () => {
191 const shown = getPull(app.db, repo.id, 1)!;
192 const a = await pullOn("pick-a");
193 const b = await pullOn("pick-b");
194 const c = await pullOn("pick-c");
195 const old = await tip();
196 for (const p of [a, b, c]) pass(p, old);
197 await moveBase("moved-third");
198 const now = await tip();
199 const tipOf = async () => now;
200 const picked = await stalePulls(app.db, tipOf, 10);
201 const numbers = picked.map((p) => p.number);
202 expect(numbers.slice(0, 3)).toEqual([c.number, b.number, a.number]);
203 expect(new Set(numbers).size).toBe(numbers.length);
204 // Several pulls on one base ask for its tip once.
205 let asked = 0;
206 await stalePulls(
207 app.db,
208 async () => {
209 asked++;
210 return now;
211 },
212 10,
213 );
214 expect(asked).toBe(1);
215 expect(await stalePulls(app.db, tipOf, STALE_PER_TICK)).toHaveLength(STALE_PER_TICK);
216 expect(await stalePulls(app.db, tipOf, 0)).toHaveLength(0);
217 // A check already waiting for the pull is the re-check.
218 createRun(app.db, {
219 repoId: repo.id,
220 kind: "check",
221 issueId: c.id,
222 env: `pull-${c.number}`,
223 commitOid: c.headOid,
224 reason: "base moved",
225 });
226 expect((await stalePulls(app.db, tipOf, 10)).map((p) => p.number)).not.toContain(c.number);
227 // Once checked against the new tip, none is stale.
228 for (const p of [a, b]) pass(p, now);
229 pass(shown, now);
230 expect(await stalePulls(app.db, tipOf, 10)).toHaveLength(0);
231 });
232
233 test("the terminal reads a stale green as stale, in words and in the refusal", () => {
234 const run = {
235 id: "r",
236 summary: "check passed",
237 baseOid: "abcdef1234",
238 createdAt: Date.now(),
239 } as never;
240 const stale = { state: "ok", run, stale: true } as const;
241 expect(checksText(stale, true, true, "release")).toBe(
242 "checks: checked against an older release — checking again",
243 );
244 expect(checksText({ ...stale, stale: false }, true, true, "release")).toContain(
245 "checks: passed",
246 );
247 expect(checksRefusal(stale)).toContain("older base");
248 expect(checksRefusal({ ...stale, stale: false })).not.toContain("older base");
249 });
250
251 test("the service asks again for stale pulls only, within the free slots", async () => {
252 // A check is only asked for where the repository declares one.
253 await moveBase("declare-check", [
254 {
255 path: "forge.json",
256 content: '{"check": {"run": "true", "install": ""}}\n',
257 },
258 ]);
259 const a = await pullOn("loop-a");
260 const b = await pullOn("loop-b");
261 const c = await pullOn("loop-c");
262 const d = await pullOn("loop-d");
263 const old = await tip();
264 for (const p of [a, b, c]) pass(p, old);
265 await moveBase("moved-loop");
266 const now = await tip();
267 pass(d, now);
268 const mine = new Set([a.id, b.id, c.id, d.id]);
269 const asked = () =>
270 listRuns(app.db, repo.id, { kind: "check", limit: 200 }).filter(
271 (r) => r.reason === BASE_MOVED && r.issueId !== null && mine.has(r.issueId),
272 );
273 const checks = startChecks(app, { forgeUrl: servers.url, concurrency: 2 });
274 try {
275 const deadline = Date.now() + 15_000;
276 while (asked().length === 0 && Date.now() < deadline) await Bun.sleep(100);
277 const first = asked();
278 expect(first.length).toBeGreaterThan(0);
279 // One tick asks for at most STALE_PER_TICK, newest pull first.
280 expect(first.length).toBeLessThanOrEqual(STALE_PER_TICK);
281 expect(first.some((r) => r.issueId === d.id)).toBe(false);
282 expect(first.every((r) => [a.id, b.id, c.id].includes(r.issueId!))).toBe(true);
283 } finally {
284 await checks.stop();
285 }
286 expect(asked().some((r) => r.issueId === d.id)).toBe(false);
287 }, 30_000);
288
289 test("a required check refuses a person's merge of a stale green, and merges after a re-check", async () => {
290 const pull = await pullOn("gated");
291 pass(pull, await tip());
292 await moveBase("moved-gate");
293 const set = await updateRepoSettings(app, alice, fresh(), { requireChecks: true });
294 expect(set.ok).toBe(true);
295 try {
296 const refused = await mergePull(app, alice, fresh(), pull, "merge");
297 expect(refused).toEqual({ ok: false, error: "checks_required" });
298 expect(getPull(app.db, repo.id, pull.number)!.mergedAt).toBeNull();
299 pass(pull, await tip());
300 const merged = await mergePull(app, alice, fresh(), pull, "merge");
301 expect(merged.ok).toBe(true);
302 expect(getPull(app.db, repo.id, pull.number)!.mergedAt).not.toBeNull();
303 } finally {
304 await updateRepoSettings(app, alice, fresh(), { requireChecks: false });
305 }
306 });
307
308 test("a re-check the service is refused does not hold the slots against older stale pulls", async () => {
309 // Nothing else is waiting for a slot.
310 for (const run of listActive(app.db, "check")) {
311 claimRun(app.db, run.id);
312 finishRun(app.db, run.id, { state: "failed", summary: "cleared" });
313 }
314 await moveBase("declare-check-2", [
315 { path: "forge.json", content: '{"check": {"run": "true", "install": ""}}\n' },
316 ]);
317 const older = await pullOn("starved");
318 const made = await createUser(app.db, {
319 trusted: true,
320 username: "bob",
321 email: "[email protected]",
322 password: "a-good-passphrase",
323 });
324 if (!made.ok) throw new Error(made.error);
325 const bob = made.value;
326 const r = await createRepo(app, bob, { name: "orchard", visibility: "public" });
327 if (!r.ok) throw new Error(String(r.error));
328 const orchard = r.value;
329 const seeded = await commitToBranch(app, bob, orchard, {
330 message: "seed",
331 files: [
332 { path: "README.md", content: "# orchard\n" },
333 { path: "forge.json", content: '{"check": {"run": "true", "install": ""}}\n' },
334 ],
335 });
336 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
337 const theirs: Pull[] = [];
338 for (const branch of ["held-a", "held-b"]) {
339 const c = await commitToBranch(app, bob, orchard, {
340 branch,
341 base: "main",
342 message: branch,
343 files: [{ path: `${branch}.md`, content: "x\n" }],
344 });
345 if (!c.ok) throw new Error(JSON.stringify(c.error));
346 const o = await openPull(app, bob, orchard, {
347 title: branch,
348 body: "",
349 baseBranch: "main",
350 headBranch: branch,
351 });
352 if (!o.ok) throw new Error(String(o.error));
353 theirs.push(o.value);
354 }
355 await moveBase("moved-starve");
356 const old = await tip();
357 // Both of bob's pulls passed against a base that has since moved on.
358 for (const p of theirs) {
359 const run = createRun(app.db, {
360 repoId: orchard.id,
361 kind: "check",
362 issueId: p.id,
363 env: `pull-${p.number}`,
364 commitOid: p.headOid,
365 reason: "pull",
366 });
367 claimRun(app.db, run.id);
368 setRunBase(app.db, run.id, "0".repeat(40));
369 finishRun(app.db, run.id, { state: "ok", summary: "check passed" });
370 }
371 pass(older, "1".repeat(40));
372 setSuspended(app.db, bob.id, new Date().toISOString());
373 const askedFor = (id: string) =>
374 listRuns(app.db, repo.id, { kind: "check", limit: 200 }).some(
375 (x) => x.reason === BASE_MOVED && x.issueId === id,
376 );
377 expect(old).toBe(await tip());
378 const checks = startChecks(app, { forgeUrl: servers.url, concurrency: 2 });
379 try {
380 const deadline = Date.now() + 20_000;
381 while (!askedFor(older.id) && Date.now() < deadline) await Bun.sleep(100);
382 expect(askedFor(older.id)).toBe(true);
383 } finally {
384 await checks.stop();
385 }
386 // The suspended owner's code was never run.
387 expect(
388 listRuns(app.db, orchard.id, { kind: "check", limit: 50 }).filter(
389 (x) => x.reason === BASE_MOVED,
390 ),
391 ).toHaveLength(0);
392 }, 40_000);
393
394 test("stalePulls skips what it is told was declined, until a tip moves", async () => {
395 const a = await pullOn("declined-a");
396 pass(a, "2".repeat(40));
397 const tipOf = async () => "3".repeat(40);
398 const [one] = await stalePulls(app.db, tipOf, 50);
399 const all = await stalePulls(app.db, tipOf, 50);
400 const mine = all.find((p) => p.number === a.number)!;
401 expect(mine).toBeDefined();
402 expect(one).toBeDefined();
403 const declined = new Set([staleKey(mine)]);
404 expect(
405 (await stalePulls(app.db, tipOf, 50, declined)).map((p) => p.number),
406 ).not.toContain(a.number);
407 expect(
408 (await stalePulls(app.db, async () => "4".repeat(40), 50, declined)).map(
409 (p) => p.number,
410 ),
411 ).toContain(a.number);
412 });
413
414 test("a page of green pulls on one base asks git for its tip once", async () => {
415 const ctx = {
416 db: app.db,
417 dir: "/x",
418 runtime: undefined,
419 record: undefined,
420 history: servingHistory(),
421 viewer: undefined,
422 } as WordCtx;
423 let asked = 0;
424 const lookup = async () => {
425 asked++;
426 return "a".repeat(40);
427 };
428 const tips = await Promise.all(
429 [1, 2, 3, 4].map(() => baseTipOf(ctx, "main", lookup)),
430 );
431 expect(new Set(tips)).toEqual(new Set(["a".repeat(40)]));
432 expect(asked).toBe(1);
433 await baseTipOf(ctx, "release", lookup);
434 expect(asked).toBe(2);
435 // A new render asks again.
436 await baseTipOf({ ...ctx }, "main", lookup);
437 expect(asked).toBe(3);
438 });
439
440 test("a sealed pull's required check refuses a stale green, and lands after a re-check", async () => {
441 const pull = await pullOn("sealed-gated");
442 // The sealed copy: a private repository holding the work (`pullDir`).
443 // It is cloned before the base moves, so its base is behind the forge's.
444 const sealed = join(dataDir, "sealed-copy.git");
445 const git = async (...args: string[]) => {
446 const proc = Bun.spawn(["git", ...args], { stdout: "pipe", stderr: "pipe" });
447 if ((await proc.exited) !== 0) throw new Error(await new Response(proc.stderr).text());
448 };
449 await git("clone", "--bare", "-q", repoDir(app.reposRoot, repo.ownerName, repo.name), sealed);
450 await git("-C", sealed, "update-ref", `refs/pull/${pull.number}/head`, pull.headOid);
451 await moveBase("moved-sealed");
452 // Fresh against the forge's base, stale against the sealed copy's: only
453 // the sealed branch's own gate can refuse it.
454 pass(pull, await tip());
455 const land = () =>
456 landPull(app.db, repoDir(app.reposRoot, repo.ownerName, repo.name), pull, {
457 strategy: "merge",
458 message: "land",
459 actorId: alice.id,
460 author: { name: "alice", email: "[email protected]" },
461 gate: { db: app.db, requireReview: false, requireChecks: true },
462 sealedFrom: sealed,
463 });
464 expect(await land()).toEqual({ ok: false, error: "checks_required" });
465 // The copy follows the base, and the same green now reads fresh there.
466 await git(
467 "-C",
468 sealed,
469 "fetch",
470 "-q",
471 repoDir(app.reposRoot, repo.ownerName, repo.name),
472 "+refs/heads/main:refs/heads/main",
473 );
474 expect((await land()).ok).toBe(true);
475 });
476 });
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