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

A green pull that has sat unlanded for a day says on its page, in one line, what it waits for #15812

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/15803-a-green-pull-that-has-sat-unlanded-for-a → main 0 commits fork 4 threads · 4 unresolved

  • Merged. scout/15803-a-green-pull-that-has-sat-unlanded-for-a was merged into main as 80dc1f0.

Review

Sign in to review this change.
16 files changed +517 −15
docs/features/flow-waiting.md +18
@@ -19,3 +19,21 @@ Code: `src/web/pages/flow-waiting.ts` (reads and draws), mounted by one line in
1919 ## The one action (#14086)
2020
2121 Each stalled row carries one form button, never a silent wait: an approved pull waiting gets **Re-run check** (`POST /:owner/:name/pulls/:n/checks`, the oldest one), a stale crew pull gets **Close** (`POST …/pulls/:n/state`), and a crew branch that heads no pull gets **Open a pull**, a plain link to the compose page with the branch filled in. Each button's accessible name carries the repository and pull number, and a row for someone who cannot write to its repository shows a muted line instead. Both posts are same-origin only, need write access to the repository, and come back to `/flow` with the route's own receipt sentence. In the terminal, `n`/`p` pick a row and `enter` does its action (ask a check, close, or open the new-pull screen on that branch), through the same functions and write gate; a row the person cannot write to names no action.
22
23 ## Green, not landed (#15803)
24
25 A pull whose check on its head has been green for more than six hours and that has not landed says, in one line, what it waits for and the one thing that unblocks it: "Green for 30 hours, not landed: it waits for review. To unblock: a reviewer reviews it on its current head."
26
27 The cause is the first that holds: a hold, a conflict with the base, a chapter, then whoever acts next (a person, the builder after changes were asked, a reviewer, the landing queue). `waitsFor` in `src/core/landing.ts` words it; `pullWaitsFor` in `src/flow/waits_for.ts` reads the facts.
28
29 Where it shows:
30
31 - **The pull page**, under the path and the landing estimate.
32 - **`/flow`**, the "Green, not landed" list: oldest first, at most 50, each row links the pull and lists what it waits for and the action. Only the repositories the viewer may read are listed.
33 - **The terminal**, the palette's "Pulls to land" screen, as one text line per pull, filtered the same way.
34 - **`GET /api/v1/repos/:owner/:name/pulls/:number`**, as `waitsFor: { cause, says, action, line }` or null, and the MCP `pull` tool, the same object.
35 - **The MCP `pulls` tool**, as `waitsFor`, the line or null.
36
37 One difference: the pull page, the pull's JSON, the `pull` tool and `pulls` with `repo` read the merge, so they can say "it conflicts with its base". `/flow`, the terminal and `pulls` without `repo` read no git, so for the same conflicted pull they name the next cause instead (usually review or the queue). Open the pull to see a conflict.
38
39 Cost: a list passes the check it already read, so a pull that is not green for six hours costs no extra query; only a stalled pull reads who acts next, its hold and its chapter. Test: `test/pull-waits-for.test.ts`.
src/contract/openapi/routes/getApiV1ReposOwnerNamePullsNumber.ts +1 −1
@@ -1,3 +1,3 @@
11 import { REPO, type Route } from "../shared.ts";
22
3 export const route: Route = { method: "get", path: `${REPO}/pulls/{number}`, summary: "Read one pull with its diff and review gate", detail: "Read one pull with its diff and review gate (diff=0 leaves the diff out); `check` is the word for the head's check: green, red, running or none; `checkedAgainst` is the base tip that check merged with (null before one recorded it), `checkStale` says the base has moved since, and `approvedAt` is the standing approval {at, head, base, current} or null, current false once the head or the base moved; the 200 carries a weak etag of the exact body, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body and the same etag until the head, a check verdict, a review or the state changes", auth: false, role: "anonymous", alsoStatus: [304], query: { diff: "string" }, reply: { check: "string", checkedAgainst: "string", approvedAt: "object" }, refuses: [404] };
3 export const route: Route = { method: "get", path: `${REPO}/pulls/{number}`, summary: "Read one pull with its diff and review gate", detail: "Read one pull with its diff and review gate (diff=0 leaves the diff out); `check` is the word for the head's check: green, red, running or none; `checkedAgainst` is the base tip that check merged with (null before one recorded it), `checkStale` says the base has moved since, and `approvedAt` is the standing approval {at, head, base, current} or null, current false once the head or the base moved; `waitsFor` is {cause, says, action, line} for an open pull green and unlanded over six hours, else null; the 200 carries a weak etag of the exact body, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body and the same etag until the head, a check verdict, a review or the state changes", auth: false, role: "anonymous", alsoStatus: [304], query: { diff: "string" }, reply: { check: "string", checkedAgainst: "string", approvedAt: "object", waitsFor: "object" }, refuses: [404] };
src/core/landing.ts +61
@@ -128,3 +128,64 @@ async function settle(app: App, all: boolean): Promise<number[]> {
128128 }
129129 return closed;
130130 }
131
132 /** How long a green pull may sit unlanded before it says what it waits for (#15803). */
133 export const STALL_MS = 6 * 3_600_000;
134
135 export type WaitCause = "held" | "conflicted" | "chapter" | "person" | "changes" | "review" | "queue";
136
137 /**
138 * What a stalled green pull waits for: the cause, its words, the one action, and the line that says
139 * both.
140 */
141 export interface WaitsFor {
142 readonly cause: WaitCause;
143 readonly says: string;
144 readonly action: string;
145 readonly line: string;
146 }
147
148 /** The facts a green pull's wait is read from; plain data, so every surface asks the same. */
149 export interface StallFacts {
150 /** When the head's check went green; null when it is not green. */
151 readonly greenAt: string | null;
152 /** Who acts next (`flow/next_actor.ts`); null once merged or closed. */
153 readonly next: { readonly who: "builder" | "reviewer" | "queue" | "person"; readonly why: string } | null;
154 readonly held: boolean;
155 readonly conflicted: boolean;
156 /** The words of the chapter hold on it (`chapterHold`), or null. */
157 readonly chapter: string | null;
158 }
159
160 const hoursWord = (ms: number): string => {
161 const h = Math.floor(ms / 3_600_000);
162 return h < 48 ? `${h} hours` : `${Math.floor(h / 24)} days`;
163 };
164
165 /**
166 * The one line a green pull unlanded for more than `STALL_MS` shows, or null
167 * when it is not green, not that old, or nothing is left to do. The first
168 * cause that holds is the answer: a hold, then a conflict, then a chapter,
169 * then whoever acts next.
170 */
171 export function waitsFor(f: StallFacts, now: Date = new Date()): WaitsFor | null {
172 if (f.greenAt === null || f.next === null) return null;
173 const age = now.getTime() - Date.parse(f.greenAt);
174 if (!(age > STALL_MS)) return null;
175 const pick = ((): Omit<WaitsFor, "line"> => {
176 if (f.held) return { cause: "held", says: `it is held: ${f.next.why}`, action: "the holder releases the hold, or a writer merges it" };
177 if (f.conflicted) return { cause: "conflicted", says: "it conflicts with its base", action: "the builder brings the branch up to date with its base and pushes" };
178 if (f.chapter !== null) return { cause: "chapter", says: `held by a chapter, ${f.chapter}`, action: "the owner opens the chapter its issue is in, or moves the issue into the open one" };
179 switch (f.next.who) {
180 case "person":
181 return { cause: "person", says: `it waits for a person: ${f.next.why}`, action: "a person who writes the repository merges it or requests changes" };
182 case "builder":
183 return { cause: "changes", says: "changes were asked on this head", action: "the builder pushes what the review asked" };
184 case "reviewer":
185 return { cause: "review", says: "it waits for review", action: "a reviewer reviews it on its current head" };
186 case "queue":
187 return { cause: "queue", says: "it waits for the landing queue", action: "a writer merges it, or asks for its check again so the queue takes it" };
188 }
189 })();
190 return { ...pick, line: `Green for ${hoursWord(age)}, not landed: ${pick.says}. To unblock: ${pick.action}.` };
191 }
src/flow/pages_read.ts +2 −1
@@ -181,6 +181,7 @@ export interface FlowPicture {
181181 readonly cpuClosed: readonly CpuClosedPull[];
182182 readonly approved: Waiting["approved"];
183183 readonly stale: Waiting["stale"];
184 readonly stalled?: Waiting["stalled"];
184185 /** Null until the crew forks have been read once. */
185186 readonly unproposed: UnproposedAlarm | null;
186187 readonly handover: HandoverLists;
@@ -320,7 +321,7 @@ export async function readFlowPicture(env: PagesEnv, job: FlowJob): Promise<Flow
320321 const handover = readHandoverLists(db, drift ?? [], job.now);
321322 const ms = performance.now() - t0;
322323 const unproposed = await later(env, "unproposed", UNPROPOSED_KEEP_MS, job.now, "never", () => alarmUnproposed(db, env.reposRoot, at));
323 return { at: job.now, ms, pipes, clog, cpuClosed, approved: rows.approved, stale: rows.stale, unproposed: unproposed ?? null, handover };
324 return { at: job.now, ms, pipes, clog, cpuClosed, approved: rows.approved, stale: rows.stale, stalled: rows.stalled, unproposed: unproposed ?? null, handover };
324325 }
325326
326327 /**
src/flow/waiting_rows.ts +10 −3
@@ -10,11 +10,14 @@ import { closesFromBody } from "../core/pulls.ts";
1010 import type { UnproposedAlarm } from "./alarm_unproposed.ts";
1111 import { approvedWait, type ApprovedRow, type ApprovedWait } from "./approved_wait.ts";
1212 import { staleFold, type StaleFold } from "./stale_fold.ts";
13 import { stalledPulls, type StalledPull } from "./waits_for.ts";
1314
1415 export interface Waiting {
1516 readonly approved: readonly ApprovedWait[];
1617 readonly stale: readonly (StaleFold & { readonly repo: string })[];
1718 readonly unproposed: UnproposedAlarm;
19 /** Green pulls unlanded past six hours, each with what it waits for (#15803). */
20 readonly stalled?: readonly StalledPull[];
1821 }
1922
2023 /** Open, unlanded pulls whose latest verdict is an approval, with when it came. */
@@ -58,8 +61,12 @@ function crewPulls(db: Database): { repo: string; pull: Parameters<typeof staleF
5861 }));
5962 }
6063
61 /** The two lists the database holds. */
62 export function readWaitingRows(db: Database, now: Date): Pick<Waiting, "approved" | "stale"> {
64 /** The three lists the database holds. */
65 export function readWaitingRows(db: Database, now: Date): Pick<Waiting, "approved" | "stale" | "stalled"> {
6366 const pulls = crewPulls(db);
64 return { approved: approvedWait(approvedRows(db), now), stale: staleFold(pulls.map((p) => ({ ...p.pull, repo: p.repo })), now) };
67 return {
68 approved: approvedWait(approvedRows(db), now),
69 stale: staleFold(pulls.map((p) => ({ ...p.pull, repo: p.repo })), now),
70 stalled: stalledPulls(db, now),
71 };
6572 }
src/flow/waits_for.ts added +101
@@ -0,0 +1,101 @@
1 /**
2 * What a green pull that has not landed waits for (#15803), read from the
3 * rows: the head's check, who acts next, the hold, the chapter. The words
4 * are `waitsFor`'s in `core/landing.ts`; the pull page, /flow, the `pull`
5 * and `pulls` tools all call this, so they say the same line.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { chapterHold } from "../core/chapters.ts";
10 import { getHold } from "../core/holds.ts";
11 import { STALL_MS, waitsFor, type WaitsFor } from "../core/landing.ts";
12 import { pullsByIssueIds, type Pull } from "../core/pulls.ts";
13 import { canRead, getRepo, getReposByIds, type Repo } from "../core/repos.ts";
14 import type { User } from "../core/users.ts";
15 import { checkSummary, type CheckSummary } from "../core/runs.ts";
16 import { nextOfPull } from "./next_actor.ts";
17
18 /**
19 * The pull's line, or null when it is not a green open pull unlanded past `STALL_MS`. A list that
20 * already read the head's check passes it as `known`, so a pull that is not stalled costs no query
21 * here at all (#15803: the `pulls` tool asks this of up to 200 pulls).
22 */
23 export function pullWaitsFor(
24 db: Database,
25 repo: Pick<Repo, "id" | "requireReview">,
26 pull: Pull,
27 live: { readonly headOid: string; readonly conflicts: number },
28 now: Date = new Date(),
29 known?: CheckSummary,
30 ): WaitsFor | null {
31 if (pull.state !== "open" || pull.mergedAt !== null) return null;
32 const check = known ?? checkSummary(db, pull.id, live.headOid);
33 if (check.state !== "ok" || check.run === null) return null;
34 const greenAt = check.run.finishedAt ?? check.run.createdAt;
35 // Young green pulls stop here, before the reviews, the hold and the chapter are read.
36 if (!(now.getTime() - Date.parse(greenAt) > STALL_MS)) return null;
37 return waitsFor(
38 {
39 greenAt,
40 next: nextOfPull(db, pull, live, repo),
41 held: getHold(db, pull.id) !== undefined,
42 conflicted: live.conflicts > 0,
43 chapter: chapterHold(db, repo.id, pull),
44 },
45 now,
46 );
47 }
48
49 /**
50 * The stalled pulls `user` may read: /flow's picture is drawn once for every admin, so each
51 * viewer's copy drops a private repository they cannot read (its name, hold note and chapter).
52 */
53 export function readableStalled(db: Database, rows: readonly StalledPull[], user: User | undefined): StalledPull[] {
54 const may = new Map<string, boolean>();
55 return rows.filter((s) => {
56 let ok = may.get(s.repo);
57 if (ok === undefined) {
outdated

HIGH: no visibility filter. Private repos' names, hold notes and chapter text reach /flow. Restrict to what the viewer may read.

58 const [owner, name] = s.repo.split("/");
59 const repo = owner === undefined || name === undefined ? undefined : getRepo(db, owner, name);
60 may.set(s.repo, (ok = repo !== undefined && canRead(db, repo, user)));
61 }
62 return ok;
63 });
64 }
65
66 export interface StalledPull extends WaitsFor {
67 readonly repo: string;
68 readonly number: number;
69 }
70
71 /** At most this many stalled pulls on /flow, oldest first. */
72 const MAX_STALLED = 50;
73
74 /**
75 * Every green open pull past `STALL_MS`, oldest first, with its line. No git
76 * is read: the stored head stands for the live one and a conflict is the
77 * pull page's to find.
78 */
79 export function stalledPulls(db: Database, now: Date = new Date()): StalledPull[] {
80 const ids = db
81 .query<{ id: string }, [string]>(
82 `SELECT i.id AS id FROM pull p JOIN issue i ON i.id = p.issue_id
83 WHERE i.state = 'open' AND p.merged_at IS NULL AND i.created_at < ?1
84 AND (SELECT r.state FROM run r WHERE r.kind IN ('deploy','check') AND r.issue_id = i.id AND r.commit_oid = p.head_oid
85 ORDER BY r.id DESC LIMIT 1) = 'ok'
86 ORDER BY i.created_at ASC`,
87 )
88 .all(new Date(now.getTime() - STALL_MS).toISOString())
89 .map((r) => r.id);
90 const pulls = pullsByIssueIds(db, ids);
91 const repos = getReposByIds(db, [...new Set(pulls.map((p) => p.repoId))]);
92 const out: StalledPull[] = [];
93 for (const pull of pulls) {
94 const repo = repos.get(pull.repoId);
95 if (repo === undefined) continue;
96 const w = pullWaitsFor(db, repo, pull, { headOid: pull.headOid, conflicts: 0 }, now);
97 if (w !== null) out.push({ ...w, repo: `${repo.ownerName}/${repo.name}`, number: pull.number });
98 if (out.length >= MAX_STALLED) break;
99 }
100 return out;
101 }
src/http/api.ts +5
@@ -8,6 +8,7 @@
88 * back to continue); errors are `{ error, message }`.
99 */
1010
11 import { pullWaitsFor } from "../flow/waits_for.ts";
1112 import { cursorRefusal, limitRefusal } from "../contract/page_query.ts";
1213 import { parseCursor, parseLimit } from "../contract/page_query.ts";
1314 import { noneMatch } from "./conditional.ts";
@@ -2948,6 +2949,10 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
29482949 status,
29492950 ...(diff === undefined ? {} : { diff }),
29502951 hold: hold === undefined ? null : holdJson(hold),
2952 // Green and unlanded past six hours: what it waits for and the one action (#15803).
2953 waitsFor: live
2954 ? pullWaitsFor(ctx.app.db, found.repo, found.pull, { headOid: status.headOid, conflicts: status.conflicts?.length ?? 0 })
2955 : null,
29512956 });
29522957 // Tagged by the exact bytes sent, after access was checked: a new head, verdict, review or
29532958 // merge is never hidden behind a 304.
src/http/mcp/tools/pull.ts +3 −1
@@ -10,6 +10,7 @@ import { nextOfPull } from "../../../flow/next_actor.ts";
1010 import { stepOfPull } from "../../../flow/path.ts";
1111 import { appView } from "../../../actions/apps.ts";
1212 import { countThread, listComments } from "../../../core/issues.ts";
13 import { pullWaitsFor } from "../../../flow/waits_for.ts";
1314 import { landingLine } from "../../../flow/landing_line.ts";
1415 import { pullLooks } from "../../../looks/readable.ts";
1516 import { reviewSteps } from "../../../actions/review_steps.ts";
@@ -24,7 +25,7 @@ const PULL_COMMENTS = 10;
2425
2526 export const tool: Tool = {
2627 name: "pull",
27 doc: "`{ repo, number }`: a pull's title, state, head and base, `summary` (two or three sentences: what changed, what was verified), and for an open pull whether it merges into the base's current head (`mergeable`) and the paths that stop it (`conflicts`), and `next: { who, why }` (open only; who acts next: builder, reviewer, queue or person), `step: { step, why, done }` (check, review, land or live; null once closed unlanded), and `comments` (the newest 10: author, body, at, `untrusted` on an outsider's), `commentsTotal` and `commentsNext` (older: `GET …/issues/:number/comments?cursor=`), and `looks` (newest first: `{ id, width, says, by, commit, url, at }`, the same as `GET …/pulls/:number/looks`), and `eta: { minutes, says }` (approved open pull only, else null), and `check: { state, baseOid }`: the latest check's state and the base tip it was merged with (empty when it merged nothing), `checkStale` (the base has moved since that check) and `checkedAgainst` (that base tip, or null; the same as `GET …/pulls/:number`); `mergeable` and `conflicts` are the same fields as `GET …/pulls/:number`, `check` is `state` and `run.baseOid` from `GET …/pulls/:number/checks`; `reviewSteps` (the review steps), draws the `ui://forge/pull` card: `#N title`, state with check and conflicts while open, `head → base` linked to the pull, and the preview link when the pull has an environment",
28 doc: "`{ repo, number }`: a pull's title, state, head and base, `summary` (two or three sentences: what changed, what was verified), and for an open pull whether it merges into the base's current head (`mergeable`) and the paths that stop it (`conflicts`), and `next: { who, why }` (open only; who acts next: builder, reviewer, queue or person), `step: { step, why, done }` (check, review, land or live; null once closed unlanded), and `comments` (the newest 10: author, body, at, `untrusted` on an outsider's), `commentsTotal` and `commentsNext` (older: `GET …/issues/:number/comments?cursor=`), and `looks` (newest first: `{ id, width, says, by, commit, url, at }`, the same as `GET …/pulls/:number/looks`), and `eta: { minutes, says }` (approved open pull only, else null), `waitsFor: { cause, says, action, line }` (green, unlanded 6 h+; else null), and `check: { state, baseOid }`: the latest check's state and the base tip it was merged with (empty when it merged nothing), `checkStale` (the base has moved since that check) and `checkedAgainst` (that base tip, or null; the same as `GET …/pulls/:number`); `mergeable` and `conflicts` are the same fields as `GET …/pulls/:number`, `check` is `state` and `run.baseOid` from `GET …/pulls/:number/checks`; `reviewSteps` (the review steps), draws the `ui://forge/pull` card: `#N title`, state with check and conflicts while open, `head → base` linked to the pull, and the preview link when the pull has an environment",
2829 description:
2930 "A pull: title, state, head, base; open: `mergeable`, `conflicts`, `checkStale`, `checkedAgainst`, `check`.",
3031 inputSchema: {
@@ -77,6 +78,7 @@ export const tool: Tool = {
7778 base: pull.baseBranch,
7879 head: pull.headBranch,
7980 eta: landingLine(ctx.app.db, pull, repo.id),
81 waitsFor: pullWaitsFor(db, repo, pull, { headOid: pull.headOid, conflicts: state?.conflicts?.length ?? 0 }),
8082 proposal: pullProposalOf(ctx.app.db, pull.id) ?? null,
8183 check: { state: check.state, baseOid: check.run?.baseOid ?? "" },
8284 checkStale: stale,
src/http/mcp/tools/pulls.ts +10 −3
@@ -7,13 +7,14 @@ import { listPulls, openPullPileRows, pullDir, pullMergeStates, pullsByIssueIds
77 import { checkSummary } from "../../../core/runs.ts";
88 import type { Ctx } from "../../context.ts";
99 import type { User } from "../../../core/users.ts";
10 import { pullWaitsFor } from "../../../flow/waits_for.ts";
1011 import { whyPulls } from "../../../flow/why.ts";
1112 import { pageRows } from "../page.ts";
1213 import { good, bad, limitArg, type Args, type Answer, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
1314
1415 export const tool: Tool = {
1516 name: "pulls",
16 doc: "`{ repo?, state?, limit?, cursor? }`: without `repo`, every open pull you may read, oldest first, as `{ pulls, next_cursor }` (limit 1-200, default 50): `repo`, `number`, `title`, `check`, `verdict` (approved, changes_requested or none) and `gate` (what holds it, or null; the `why` module's cause); with `repo`, a repository's pulls, newest first, one brief line each: `number`, `title`, `author`, `head`, `check` (state), `approvals`, `movedSinceApproval` (the approval was given for a head or base that has since moved), `changesRequested`, `mergeable` (null once closed); `state` open (default) or closed, `limit` 1-50 (default 20); no bodies, no diffs",
17 doc: "`{ repo?, state?, limit?, cursor? }`: without `repo`, every open pull you may read, oldest first, as `{ pulls, next_cursor }` (limit 1-200, default 50): `repo`, `number`, `title`, `check`, `verdict` (approved, changes_requested or none) and `gate` (what holds it, or null; the `why` module's cause); with `repo`, a repository's pulls, newest first, one brief line each: `number`, `title`, `author`, `head`, `check` (state), `approvals`, `movedSinceApproval` (the approval was given for a head or base that has since moved), `changesRequested`, `mergeable` (null once closed), `waitsFor` (`pull`'s `line`, or null); `state` open (default) or closed, `limit` 1-50 (default 20); no bodies, no diffs",
1718 description:
1819 "A repository's pulls, newest first; no `repo`: all open pulls you may read, oldest first.",
1920 inputSchema: {
@@ -46,17 +47,19 @@ export const tool: Tool = {
4647 const bases = await Promise.all(
4748 pulls.map((p, i) => (p.state === "open" ? refTip(dirs[i]!, `refs/heads/${p.baseBranch}`) : undefined)),
4849 );
50 const checks = pulls.map((p) => checkSummary(db, p.id, p.headOid));
4951 const answer = good({
5052 pulls: pulls.map((p, i) => ({
5153 number: p.number,
5254 title: p.title,
5355 author: p.authorName,
5456 head: p.headBranch,
55 check: checkSummary(db, p.id, p.headOid).state,
57 check: checks[i]!.state,
5658 approvals: reviews.get(p.id)?.approvals ?? 0,
5759 movedSinceApproval: movedSinceApproval(approvals.get(p.id) ?? [], p.headOid, bases[i]),
5860 changesRequested: reviews.get(p.id)?.changesRequested ?? 0,
5961 mergeable: merge[i]?.mergeable ?? null,
62 waitsFor: pullWaitsFor(db, repo, p, { headOid: p.headOid, conflicts: merge[i]?.conflicts?.length ?? 0 }, undefined, checks[i])?.line ?? null,
6063 })),
6164 });
6265 // What the card needs and the text does not say: where the pulls live, and
@@ -90,14 +93,18 @@ function pile(ctx: Ctx, user: User, args: Args): Answer {
9093 pulls: pulls.map((p, i) => {
9194 const repo = repos.get(p.repoId)!;
9295 const r = reviews.get(p.id);
96 const check = checkSummary(db, p.id, p.headOid);
9397 return {
9498 repo: `${repo.ownerName}/${repo.name}`,
9599 number: p.number,
96100 title: p.title,
97 check: checkSummary(db, p.id, p.headOid).state,
101 check: check.state,
98102 verdict: (r?.changesRequested ?? 0) > 0 ? "changes_requested" : (r?.approvals ?? 0) > 0 ? "approved" : "none",
99103 gate: whys[i]?.cause?.name ?? null,
outdated

conflicts hardcoded 0, so this line can disagree with the pull page; also several queries per pull for up to 200 pulls.

100104 why: whys[i]?.cause?.says ?? whys[i]?.next?.why ?? null,
105 // No git here, so a conflict is not known: this line can say "review" where the pull
106 // page, which reads the merge, says "conflicted" (docs/features/flow-waiting.md).
107 waitsFor: pullWaitsFor(db, repo, p, { headOid: p.headOid, conflicts: 0 }, undefined, check)?.line ?? null,
101108 };
102109 }),
103110 next_cursor,
src/tui/screens/waiting.ts +10 −5
@@ -1,13 +1,14 @@
11 /**
2 * /flow's waiting section in the terminal (#11455): the web page's three
3 * lists, read by the same `readWaiting`, gated the same way: a forge admin who
4 * is a person; anyone else is offered nothing and, were the screen reached,
5 * sees no rows. A section with nothing to say draws nothing. `n`/`p` pick a row and
6 * `enter` does its one action (re-run its check, close, open its pull), through the
2 * /flow's waiting section in the terminal (#11455): the web page's
3 * lists (green pulls unlanded past six hours with their one line, #15803), read by the same
4 * `readWaiting`, gated the same way: a forge admin who is a person; anyone else is offered nothing
5 * and, were the screen reached, sees no rows. A section with nothing to say draws nothing. `n`/`p`
6 * pick a row and `enter` does its one action (re-run its check, close, open its pull), through the
77 * functions the page's routes call, for someone who can write to that repository.
88 */
99
1010 import { readWaiting, type Waiting } from "../../web/pages/flow-waiting.ts";
11 import { readableStalled } from "../../flow/waits_for.ts";
1112 import type { Ctx, Screen } from "../app/app.ts";
1213 import { binding } from "../app/keys.ts";
1314 import { askCheck } from "../../checks/again.ts";
@@ -50,6 +51,10 @@ function entries(session: Session, w: Waiting): Entry[] {
5051 "Approved, waiting on the merge queue",
5152 w.approved.map((a) => say(a.repo, ` ${a.repo}: ${plural(a.waiting, "approved pull")} waiting; the oldest, #${String(a.oldest)}, for ${hours(a.oldestHours)}`, `re-run check on #${String(a.oldest)}`, { kind: "check", repo: a.repo, number: a.oldest })),
5253 );
54 section(
55 "Green, not landed",
56 readableStalled(session.db, w.stalled ?? [], session.user).map((s) => ({ text: ` ${s.repo} #${String(s.number)}: ${s.line}` })),
57 );
5358 section(
5459 "Stale crew pulls",
5560 w.stale.flatMap((s) => [
src/web/pages/flow-waiting.ts +10
@@ -70,6 +70,16 @@ export function waitingSection(w: Waiting, mayWrite: (repo: string) => boolean =
7070 meta: mayWrite(a.repo) ? act(`/${a.repo}/pulls/${String(a.oldest)}/checks`, `Re-run check #${String(a.oldest)}`, `Re-run check ${a.repo} #${String(a.oldest)}`, { next: "/flow" }) : noWrite,
7171 }))));
7272 }
73 const stalled = w.stalled ?? [];
74 if (stalled.length > 0) {
75 parts.push(waitingList("flow-stalled", "Green, not landed", "Green for more than six hours.", stalled.map((s) => row({
outdated

Principle 1/7/8: hand-rolled span markup and a self-explaining intro sentence; use the named row component and plain words.

76 href: `/${s.repo}/pulls/${String(s.number)}`,
77 title: `${s.repo} #${String(s.number)}`,
78 nav: true,
79 data: { "waits-for": s.cause },
80 facts: [{ label: "Waits for", value: s.says }, { label: "To unblock", value: s.action }],
81 }))));
82 }
7383 if (w.stale.length > 0) {
7484 parts.push(waitingList("flow-stale", "Stale crew pulls", "Open with no push for days; a person closes one, and its work can fold back into its issue.", w.stale.map((s) => row({
7585 title: html`<span class="valve-name"><a href="/${s.repo}/pulls/${String(s.number)}">${s.repo} #${String(s.number)}</a>
src/web/pages/flow.ts +2 −1
@@ -25,6 +25,7 @@ import { flashTo, page } from "../layout.ts";
2525 import { btn, icon, row, time } from "../ui.ts";
2626 import { handoverSection } from "./flow-handover.ts";
2727 import { waitingSection } from "./flow-waiting.ts";
28 import { readableStalled } from "../../flow/waits_for.ts";
2829 import { canWrite, getRepo } from "../../core/repos.ts";
2930 import { estimatesSection } from "./flow-estimates.ts";
3031 import { clogSection } from "./flow-clog.ts";
@@ -171,7 +172,7 @@ export async function flowPage(ctx: Ctx): Promise<Response> {
171172 ${cpuStopsSection(cpuStops(ctx.app.db).stopped, picture.cpuClosed)}
172173 </section>
173174 ${p.valves.length === 0 ? null : strip}
174 ${waitingSection({ approved: picture.approved, stale: picture.stale, unproposed: picture.unproposed ?? { fires: false, says: "", branches: [] } }, (name) => mayWriteRepo(ctx, name))}
175 ${waitingSection({ approved: picture.approved, stale: picture.stale, stalled: readableStalled(ctx.app.db, picture.stalled ?? [], user), unproposed: picture.unproposed ?? { fires: false, says: "", branches: [] } }, (name) => mayWriteRepo(ctx, name))}
175176 ${p.valves.length === 0
176177 ? null
177178 : html`<section class="pipes-block" aria-label="Where the week's money went">${pipesSvg(p)}</section>
src/web/studio/change.ts +4
@@ -93,6 +93,7 @@ import { previewVision } from "../../crew/vision.ts";
9393 import { visionPreviewCard } from "./direction.ts";
9494 import { holdCard } from "./hold.ts";
9595 import { pullMayRun } from "../../core/pull_trust.ts";
96 import { pullWaitsFor } from "../../flow/waits_for.ts";
9697 import { landingLine } from "../../flow/landing_line.ts";
9798 import { nextOfPull } from "../../flow/next_actor.ts";
9899 import { STEP_MEANS, STEPS, stepOfPull, stepWord, type PathStep } from "../../flow/path.ts";
@@ -312,6 +313,9 @@ export function changeHead(
312313 )}${when(
313314 live === null ? null : landingLine(ctx.app.db, pull, repo.id),
314315 (eta) => html`<p class="muted small" data-landing-eta>${eta.says}</p>`,
316 )}${when(
317 live === null ? null : pullWaitsFor(ctx.app.db, repo, pull, live),
318 (w) => html`<p class="small" data-waits-for="${w.cause}" role="status">${w.line}</p>`,
315319 )}${
316320 // The desk is the crew's: a guest sees no note, not even a hold on a public pull.
317321 ctx.auth.user === undefined
test/mcp-pulls.test.ts +1
@@ -120,6 +120,7 @@ test("lists open pulls in the brief shape, newest first, limited", async () => {
120120 movedSinceApproval: false,
121121 changesRequested: 0,
122122 mergeable: true,
123 waitsFor: null,
123124 });
124125 expect((await pulls(tok["rita"]!, { repo: "ada/svc", limit: 1 })).value.pulls).toHaveLength(1);
125126 expect((await pulls(tok["rita"]!, { repo: "ada/svc", state: "closed" })).value.pulls).toEqual([]);
test/pull-waits-for-api.test.ts added +76
@@ -0,0 +1,76 @@
1 /** The pull's JSON carries what a green pull unlanded past six hours waits for (#15803). */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createApp, type App } from "../src/app.ts";
7 import { openPull } from "../src/actions/pulls.ts";
8 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
9 import { getPull } from "../src/core/pulls.ts";
10 import { createSession } from "../src/core/sessions.ts";
11 import { createUser } from "../src/core/users.ts";
12 import { serve, type Servers } from "../src/http/server.ts";
13 import { id } from "../src/kernel/id.ts";
14 import { quietLogs } from "./helpers/globals.ts";
15
16 quietLogs();
17
18 let dataDir: string;
19 let app: App;
20 let servers: Servers;
21 let cookie = "";
22 let number = 0;
23 let issueId = "";
24 let repoId = "";
25 let headOid = "";
26 const cells = process.env["FORGE_CELLS"];
27
28 beforeAll(async () => {
29 process.env["FORGE_CELLS"] = "off";
30 dataDir = await mkdtemp(join(tmpdir(), "forge-waits-for-api-"));
31 app = createApp({ dataDir, port: 0 });
32 servers = await serve(app);
33 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
34 if (!made.ok) throw new Error(String(made.error));
35 const alice = made.value;
36 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
37 const repo = await createRepo(app, alice, { name: "r", visibility: "public" });
38 if (!repo.ok) throw new Error(String(repo.error));
39 repoId = repo.value.id;
40 for (const [branch, file] of [[undefined, "forge.json"], ["topic", "t.txt"]] as const) {
41 const done = await commitToBranch(app, alice, repo.value, { ...(branch === undefined ? {} : { branch }), message: "change", files: [{ path: file, content: file === "forge.json" ? "{}" : "x" }] });
42 if (!done.ok) throw new Error(JSON.stringify(done.error));
43 }
44 const pull = await openPull(app, alice, repo.value, { title: "t", body: "", baseBranch: "main", headBranch: "topic" });
45 if (!pull.ok) throw new Error(JSON.stringify(pull.error));
46 number = pull.value.number;
47 const row = getPull(app.db, repoId, number)!;
48 issueId = row.id;
49 headOid = row.headOid;
50 });
51
52 afterAll(async () => {
53 await servers.stop();
54 app.close();
55 if (cells === undefined) delete process.env["FORGE_CELLS"];
56 else process.env["FORGE_CELLS"] = cells;
57 await rm(dataDir, { recursive: true, force: true });
58 });
59
60 const read = async (): Promise<{ waitsFor: { cause: string; line: string } | null }> => {
61 const res = await fetch(`${servers.url}/api/v1/repos/alice/r/pulls/${String(number)}?diff=0`, { headers: { cookie } });
62 expect(res.status).toBe(200);
63 return (await res.json()) as { waitsFor: { cause: string; line: string } | null };
64 };
65
66 test("GET …/pulls/:number says waitsFor: null until green for six hours, then the line", async () => {
67 expect((await read()).waitsFor).toBeNull();
68 const at = new Date(Date.now() - 8 * 3_600_000).toISOString();
69 app.db.query("UPDATE issue SET created_at = ?1 WHERE id = ?2").run(at, issueId);
70 app.db
71 .query("INSERT INTO run (id, repo_id, kind, issue_id, commit_oid, state, created_at, finished_at) VALUES (?1, ?2, 'check', ?3, ?4, 'ok', ?5, ?5)")
72 .run(id(), repoId, issueId, headOid, new Date(Date.now() - 7 * 3_600_000).toISOString());
73 const w = (await read()).waitsFor;
74 expect(w).not.toBeNull();
75 expect(w!.line).toStartWith("Green for 7 hours, not landed:");
76 });
test/pull-waits-for.test.ts added +203
@@ -0,0 +1,203 @@
1 /** A green pull unlanded past six hours says, in one line, what it waits for (#15803). */
2 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { createApp, type App } from "../src/app.ts";
8 import { setHold } from "../src/core/holds.ts";
9 import { STALL_MS, waitsFor, type StallFacts, type WaitCause } from "../src/core/landing.ts";
10 import { getPull } from "../src/core/pulls.ts";
11 import { createRepo as createCoreRepo, getRepoById, type Repo } from "../src/core/repos.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { tool as pullsTool } from "../src/http/mcp/tools/pulls.ts";
14 import type { Ctx } from "../src/http/context.ts";
15 import { id } from "../src/kernel/id.ts";
16 import { pullWaitsFor, readableStalled, stalledPulls } from "../src/flow/waits_for.ts";
17 import { waitingScreen } from "../src/tui/screens/waiting.ts";
18 import { createForgeApp } from "../src/tui/forge.ts";
19 import { headlessTerminal } from "../src/tui/term/terminal.ts";
20 import { settleApp } from "./helpers/tui.ts";
21 import { readWaitingRows } from "../src/flow/waiting_rows.ts";
22 import { waitingSection } from "../src/web/pages/flow-waiting.ts";
23
24 const NOW = new Date();
25 const hoursAgo = (h: number) => new Date(NOW.getTime() - h * 3_600_000).toISOString();
26 const facts = (over: Partial<StallFacts> = {}): StallFacts => ({
27 greenAt: hoursAgo(7),
28 next: { who: "reviewer", why: "no review yet" },
29 held: false,
30 conflicted: false,
31 chapter: null,
32 ...over,
33 });
34
35 describe("waitsFor, from the facts", () => {
36 test("each cause has its line: the cause and the one action", () => {
37 const cases: [Partial<StallFacts>, WaitCause, string][] = [
38 [{}, "review", "Green for 7 hours, not landed: it waits for review. To unblock: a reviewer reviews it on its current head."],
39 [{ next: { who: "queue", why: "approved and green" } }, "queue", "Green for 7 hours, not landed: it waits for the landing queue. To unblock: a writer merges it, or asks for its check again so the queue takes it."],
40 [{ conflicted: true }, "conflicted", "Green for 7 hours, not landed: it conflicts with its base. To unblock: the builder brings the branch up to date with its base and pushes."],
41 [{ chapter: "outside Two: the crew builds only what the open chapter holds" }, "chapter", "Green for 7 hours, not landed: held by a chapter, outside Two: the crew builds only what the open chapter holds. To unblock: the owner opens the chapter its issue is in, or moves the issue into the open one."],
42 [{ held: true, next: { who: "person", why: "alice holds it: wait for the demo" } }, "held", "Green for 7 hours, not landed: it is held: alice holds it: wait for the demo. To unblock: the holder releases the hold, or a writer merges it."],
43 [{ next: { who: "person", why: "allow a new host" } }, "person", "Green for 7 hours, not landed: it waits for a person: allow a new host. To unblock: a person who writes the repository merges it or requests changes."],
44 [{ next: { who: "builder", why: "changes were asked on this head" } }, "changes", "Green for 7 hours, not landed: changes were asked on this head. To unblock: the builder pushes what the review asked."],
45 ];
46 for (const [over, cause, line] of cases) {
47 const w = waitsFor(facts(over), NOW);
48 expect(w?.cause).toBe(cause);
49 expect(w?.line).toBe(line);
50 }
51 });
52
53 test("a hold comes before a conflict, a conflict before a chapter", () => {
54 expect(waitsFor(facts({ held: true, conflicted: true, chapter: "x" }), NOW)?.cause).toBe("held");
55 expect(waitsFor(facts({ conflicted: true, chapter: "x" }), NOW)?.cause).toBe("conflicted");
56 });
57
58 test("not green, green for six hours or less, or nothing left to do: no line", () => {
59 expect(waitsFor(facts({ greenAt: null }), NOW)).toBeNull();
60 expect(waitsFor(facts({ greenAt: new Date(NOW.getTime() - STALL_MS).toISOString() }), NOW)).toBeNull();
61 expect(waitsFor(facts({ next: null }), NOW)).toBeNull();
62 expect(waitsFor(facts({ greenAt: hoursAgo(50) }), NOW)?.line).toStartWith("Green for 2 days,");
63 });
64 });
65
66 describe("read from the rows", () => {
67 let dataDir: string;
68 let app: App;
69 let alice: User;
70 let repo: Repo;
71 let n = 0;
72
73 /** An open pull whose head's check went green `h` hours ago. */
74 const greenPull = (h: number, inRepo: Repo = repo): { issueId: string; number: number } => {
75 const issueId = id();
76 n += 1;
77 app.db
78 .query(`INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, state, created_at) VALUES (?1, ?2, ?3, 'pull', 'P', '', ?4, 'open', ?5)`)
79 .run(issueId, inRepo.id, 200 + n, alice.id, hoursAgo(h + 1));
80 app.db
81 .query(`INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id) VALUES (?1, 'main', ?2, '', ?3, ?4)`)
82 .run(issueId, `br-${n}`, `oid-${n}`, inRepo.id);
83 app.db
84 .query(`INSERT INTO run (id, repo_id, kind, issue_id, commit_oid, state, created_at, finished_at) VALUES (?1, ?2, 'check', ?3, ?4, 'ok', ?5, ?5)`)
85 .run(id(), inRepo.id, issueId, `oid-${n}`, hoursAgo(h));
86 return { issueId, number: 200 + n };
87 };
88 const approve = (issueId: string, oid: string) =>
89 app.db
90 .query("INSERT INTO review (id, issue_id, author_id, state, commit_oid, created_at) VALUES (?1, ?2, ?3, 'approved', ?4, ?5)")
91 .run(id(), issueId, alice.id, oid, hoursAgo(1));
92 const lineOf = (number: number, conflicts = 0) => {
93 const pull = getPull(app.db, repo.id, number)!;
94 return pullWaitsFor(app.db, repo, pull, { headOid: pull.headOid, conflicts }, NOW);
95 };
96
97 let review: number;
98 let queue: number;
99 let held: number;
100 let young: number;
101 let bob: User;
102 let hidden: number;
103
104 beforeAll(async () => {
105 dataDir = await mkdtemp(join(tmpdir(), "forge-waits-for-"));
106 app = createApp({ dataDir, port: 0 });
107 const made = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
108 if (!made.ok) throw new Error("no user");
109 alice = made.value;
110 const r = await createRepo(app, alice, { name: "app", visibility: "public" });
111 if (!r.ok) throw new Error("no repo");
112 app.db.query("UPDATE repo SET require_review = 1 WHERE id = ?1").run(r.value.id);
113 repo = getRepoById(app.db, r.value.id)!;
114 review = greenPull(8).number;
115 const q = greenPull(9);
116 approve(q.issueId, `oid-${n}`);
117 queue = q.number;
118 const h = greenPull(10);
119 setHold(app.db, h.issueId, alice.id, "wait for the demo");
120 held = h.number;
121 young = greenPull(2).number;
122 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
123 if (!b.ok) throw new Error("no bob");
124 bob = b.value;
125 const secret = await createCoreRepo(app.db, app.reposRoot, { ownerId: bob.id, name: "secret", visibility: "private" });
126 if (!secret.ok) throw new Error(`no private repo: ${JSON.stringify(secret.error)}`);
127 const s = greenPull(20, secret.value);
128 setHold(app.db, s.issueId, bob.id, "the launch date nobody knows");
129 hidden = s.number;
130 });
131
132 afterAll(async () => {
133 app.close?.();
134 await rm(dataDir, { recursive: true, force: true });
135 });
136
137 test("a green pull per cause says its line; a young one says nothing", () => {
138 expect(lineOf(review)?.cause).toBe("review");
139 expect(lineOf(queue)?.cause).toBe("queue");
140 expect(lineOf(held)?.cause).toBe("held");
141 expect(lineOf(held)?.says).toContain("wait for the demo");
142 expect(lineOf(review, 2)?.cause).toBe("conflicted");
143 expect(lineOf(young)).toBeNull();
144 });
145
146 test("a chapter that holds the pull is its cause", () => {
147 // No chapter open and one closed: the repository rests between chapters.
148 app.db.query("INSERT INTO chapter (id, repo_id, name, state) VALUES (?1, ?2, 'One', 'closed')").run(id(), repo.id);
149 try {
150 expect(lineOf(review)?.cause).toBe("chapter");
151 } finally {
152 app.db.query("DELETE FROM chapter WHERE repo_id = ?1").run(repo.id);
153 }
154 });
155
156 test("/flow lists them oldest first with the same words, as rows with facts", () => {
157 const rows = readableStalled(app.db, stalledPulls(app.db, NOW), alice);
158 expect(rows.map((r) => r.number)).toEqual([hidden, held, queue, review]);
159 expect(rows.find((r) => r.number === review)?.line).toBe(lineOf(review)!.line);
160 const waiting = readWaitingRows(app.db, NOW);
161 const html = String(waitingSection({ ...waiting, stalled: readableStalled(app.db, waiting.stalled ?? [], alice), unproposed: { fires: false, says: "", branches: [] } }));
162 expect(html).toContain('id="flow-stalled"');
163 expect(html).toContain(`alice/app #${review}`);
164 expect(html).toContain('data-waits-for="queue"');
165 expect(html).toContain('<dl class="row-facts">');
166 expect(html).toContain(lineOf(queue)!.action);
167 });
168
169 test("a private repository's stalled pull reaches only those who may read it", () => {
170 const all = stalledPulls(app.db, NOW);
171 expect(all.some((r) => r.repo === "bob/secret" && r.number === hidden)).toBe(true);
172 const carol = { ...bob, id: "not-bob", username: "carol", isAdmin: false };
173 for (const viewer of [carol, undefined]) {
174 const seen = readableStalled(app.db, all, viewer);
175 expect(seen.some((r) => r.repo === "bob/secret")).toBe(false);
176 expect(JSON.stringify(seen)).not.toContain("the launch date nobody knows");
177 }
178 // Its owner reads it, and so does a forge admin (`canRead`: an admin reads every repository).
179 expect(readableStalled(app.db, all, bob).some((r) => r.repo === "bob/secret")).toBe(true);
180 expect(readableStalled(app.db, all, alice).some((r) => r.repo === "bob/secret")).toBe(true);
181 });
182
183 test("the terminal's Pulls to land lists the same line", async () => {
184 const term = headlessTerminal(200, 60);
185 const { app: tui, session } = createForgeApp(app, { sshUsername: alice.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:test", user: alice }, { terminal: term, exitHooks: false });
186 tui.start();
187 tui.ctx.push(waitingScreen(session, tui.ctx, { ...readWaitingRows(app.db, NOW), unproposed: { fires: false, says: "", branches: [] } }));
188 await settleApp(tui);
189 const text = tui.screen.toText();
190 tui.stop?.();
191 expect(text).toContain("Green, not landed");
192 expect(text).toContain(`alice/app #${review}: Green for`);
193 });
194
195 test("the pulls tool answers the same line", async () => {
196 const answer = (await pullsTool.run({ app } as unknown as Ctx, alice, {})) as { ok: true; value: { pulls: { number: number; waitsFor: string | null }[] } };
197 expect(answer.ok).toBe(true);
198 const body = answer.value;
199 const by = new Map(body.pulls.map((p) => [p.number, p.waitsFor]));
200 expect(by.get(review)).toBe(lineOf(review)!.line);
201 expect(by.get(young)).toBeNull();
202 });
203 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs