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

An app's first build shows its preview from its first push: a draft that deploys, and is checked once at the end #16345

Merged opened this

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

Merged

talk/early-push → main 0 commits 2 threads · 2 unresolved

  • Merged. talk/early-push was merged into main as 61d3d5c.

Review

Sign in to review this change.
28 files changed +818 −31
docs/CREW.md +9 −1
@@ -71,7 +71,15 @@ puts the agent on a branch named after the issue, and runs Claude Code
7171 headless with a brief that says who it is, what the task is, how to finish,
7272 and what will be refused. The pull opens at the agent's first push, marked
7373 "In progress" with a link to the run's log, and its preview follows each later
74 push (`src/crew/early.ts`). When the agent stops, the forge pushes what it
74 push (`src/crew/early.ts`). An app's first build (the repository's first issue, the
75 "Build <name>" that new_app opens, while nothing has merged) is told to push as soon as the app
76 first runs and after each step, and its pull opens as a draft (the pull's `draft_run`, set only
77 there, never read from the body): each push redeploys its preview and runs no check, no review
78 starts, and no door lands it. When the run ends the draft is filled in and its final head is
79 checked (`pull.ready`), as any pull's. A run that ends without filling it in, or a forge that
80 stopped under it, readies it too (on the run's end, and on the lease tick), and the repository's
81 admin can press Mark ready on the pull page, the API (`POST .../pulls/:number/ready`) or the
82 terminal (`D`). When the agent stops, the forge pushes what it
7583 committed and fills in that same pull (the agent's last message is the
7684 description). A run that ends without reporting leaves the pull saying so, with
7785 the log link; a run that is only paused (a limit, an outage) keeps saying "In
src/actions/pulls.ts +58 −1
@@ -35,7 +35,10 @@ import {
3535 toldBy,
3636 createPull,
3737 getPull,
38 clearDraft,
39 isDraft,
3840 mergePull as landPull,
41 strandedDrafts,
3942 pullDiff,
4043 pullStatus,
4144 type CreatePullError,
@@ -46,7 +49,7 @@ import {
4649 } from "../core/pulls.ts";
4750 import { isStructural, pillarsOf } from "../core/pillars.ts";
4851 import type { Repo } from "../core/repos.ts";
49 import { canRead } from "../core/repos.ts";
52 import { canRead, getRepoById } from "../core/repos.ts";
5053 import { sealedByNumber } from "../core/sealed.ts";
5154 import {
5255 addReviewComment,
@@ -94,6 +97,7 @@ import {
9497 } from "../origins/write-through.ts";
9598 import {
9699 requireParticipant,
100 requireRepoAdmin,
97101 requireWriter,
98102 type AccessError,
99103 } from "./access.ts";
@@ -149,6 +153,11 @@ export interface OpenPullInput {
149153 revertsIssueId?: string;
150154 /** The variant group the pull joins (`actions/tell.ts`); absent for an ordinary pull. */
151155 variantGroup?: string;
156 /**
157 * The run writing it, when it opens as a draft (`CreatePullInput.draftRun`): `crew/early.ts`
158 * only.
159 */
160 draftRun?: string;
152161 /** Who opened it on another forge, and where; native repos only (`CreatePullInput.origin`). */
153162 origin?: { author: string; htmlUrl: string };
154163 /**
@@ -356,6 +365,7 @@ async function createThePull(
356365 : {}),
357366 ...(input.revertsIssueId ? { revertsIssueId: input.revertsIssueId } : {}),
358367 ...(input.variantGroup ? { variantGroup: input.variantGroup } : {}),
368 ...(input.draftRun ? { draftRun: input.draftRun } : {}),
359369 ...(input.origin ? { origin: input.origin } : {}),
360370 },
361371 );
@@ -517,6 +527,10 @@ export async function mergePull(
517527 // reflects it, with the merge commit the origin actually made.
518528 if (pull.originHeadRepo !== null || repo.origin !== null)
519529 return err("mirrored");
530 // A draft is an app's first build still being written (`crew/early.ts`): no door lands it, not a
531 // person's press, not the merge queue, not the owner's break-glass, whatever its review or check
532 // says. It lands once the run fills it in. Read from the row, not the caller's copy.
533 if (isDraft(getPull(app.db, repo.id, pull.number) ?? pull)) return err("draft");
520534 // A fork someone keeps lands as a true merge whatever was asked (#8935).
521535 const strategy = landingKind(app.db, pull, requested, repo.landing);
522536 // A fork may have pushed since the pull opened; merge what is being
@@ -1153,3 +1167,46 @@ export function approveGuestPull(
11531167 });
11541168 return done;
11551169 }
1170
1171 /**
1172 * The pull is no draft now (its run ended, is gone, or its admin said so): ask for the check on its
1173 * head (`pull.ready`), the one its pushes while a draft did not run. The check's verdict is what
1174 * review and landing wait on, as for any pull. False when it was not a draft, so the check is asked
1175 * for once.
1176 */
1177 export function readyPull(app: App, actor: User | undefined, repo: Repo, pull: Pull): boolean {
1178 if (!clearDraft(app.db, pull.id)) return false;
1179 app.bus.append({
1180 kind: "pull.ready",
1181 repoId: repo.id,
1182 ...(actor === undefined ? {} : { actorId: actor.id }),
1183 payload: { number: pull.number, headOid: (getPull(app.db, repo.id, pull.number) ?? pull).headOid },
1184 });
1185 return true;
1186 }
1187
1188 /**
1189 * The repository's admin marks a draft ready by hand: the way out when its build will not end on
1190 * its own. The page's Mark ready, the API and the terminal all call this.
1191 */
1192 export function markReady(app: App, actor: User | undefined, repo: Repo, pull: Pull): Result<void, AccessError | "not_draft"> {
1193 const admin = requireRepoAdmin(app, actor, repo);
1194 if (!admin.ok) return admin;
1195 if (pull.repoId !== repo.id) return err("not_found");
1196 return readyPull(app, admin.value, repo, pull) ? ok(undefined) : err("not_draft");
1197 }
1198
1199 /**
1200 * Every draft whose run is over or gone is readied: a run that died without filling its pull in, or
1201 * a forge that stopped under it, never leaves a person's first app locked. Called when a run ends
1202 * and on the lease tick (`main.ts`), so a crash is caught on the next boot.
1203 */
1204 export function readyStranded(app: App): number {
1205 let readied = 0;
1206 for (const { repoId, number } of strandedDrafts(app.db)) {
1207 const repo = getRepoById(app.db, repoId);
1208 const pull = repo === undefined ? undefined : getPull(app.db, repoId, number);
1209 if (repo !== undefined && pull !== undefined && readyPull(app, undefined, repo, pull)) readied++;
1210 }
1211 return readied;
1212 }
src/checks/event_handler.ts +14 −5
@@ -2,8 +2,9 @@
22 import { pullDir } from "../core/pulls.ts";
33 import type { App } from "../app.ts";
44 import { announceRun } from "../actions/runs.ts";
5 import { readyStranded } from "../actions/pulls.ts";
56 import type { ForgeEvent } from "../core/events.ts";
6 import { getPull, listPulls, type Pull } from "../core/pulls.ts";
7 import { getPull, isDraft, listPulls, type Pull } from "../core/pulls.ts";
78 import { getRepoById, type Repo } from "../core/repos.ts";
89 import { getRun, cancelRunsForPull, checksForHead } from "../core/runs.ts";
910 import { resolveOid } from "../git/merge.ts";
@@ -19,6 +20,11 @@ export async function onEvent(lane: LaneState, event: ForgeEvent): Promise<void>
1920 if (!repo) return;
2021 const actor = event.actorId ?? undefined;
2122 switch (event.kind) {
23 // A crew run ended: a draft it left (a run that died before filling its pull in) is ready now.
24 case "run.finished": {
25 if (event.payload["kind"] === "agent") readyStranded(app);
26 return;
27 }
2228 case "push": {
2329 // A fork that silently followed holds its parent's commit, byte for
2430 // byte: checking the copy proves nothing the parent's own check did
@@ -58,7 +64,7 @@ export async function onEvent(lane: LaneState, event: ForgeEvent): Promise<void>
5864 state: "open",
5965 limit: 200,
6066 })) {
61 if (pull.crossRepo || pull.headBranch !== branch) continue;
67 if (pull.crossRepo || pull.headBranch !== branch || isDraft(pull)) continue;
6268 await lane.request(
6369 repo,
6470 `pull-${pull.number}`,
@@ -76,7 +82,8 @@ export async function onEvent(lane: LaneState, event: ForgeEvent): Promise<void>
7682 const number = event.payload["number"];
7783 if (typeof number !== "number") return;
7884 const pull = getPull(app.db, repo.id, number);
79 if (!pull) return;
85 // A draft (an app's first build, still being written) deploys and is not checked yet.
86 if (!pull || isDraft(pull)) return;
8087 const head = await headOf(app, repo, pull);
8188 if (head !== undefined)
8289 await lane.request(
@@ -89,12 +96,14 @@ export async function onEvent(lane: LaneState, event: ForgeEvent): Promise<void>
8996 );
9097 return;
9198 }
92 case "pull.pushed": {
99 case "pull.pushed":
100 // A draft's run ended: its final head is checked now.
101 case "pull.ready": {
93102 const number = event.payload["number"];
94103 const headOid = event.payload["headOid"];
95104 if (typeof number !== "number" || typeof headOid !== "string") return;
96105 const pull = getPull(app.db, repo.id, number);
97 if (!pull) return;
106 if (!pull || (event.kind === "pull.pushed" && isDraft(pull))) return;
98107 await lane.request(
99108 repo,
100109 `pull-${pull.number}`,
src/contract/openapi/routes/index.ts +1
@@ -418,6 +418,7 @@ export { route as postApiV1ReposOwnerNamePullsNumberChecks } from "./postApiV1Re
418418 export { route as postApiV1ReposOwnerNamePullsNumberComments } from "./postApiV1ReposOwnerNamePullsNumberComments.ts";
419419 export { route as postApiV1ReposOwnerNamePullsNumberLooks } from "./postApiV1ReposOwnerNamePullsNumberLooks.ts";
420420 export { route as postApiV1ReposOwnerNamePullsNumberMerge } from "./postApiV1ReposOwnerNamePullsNumberMerge.ts";
421 export { route as postApiV1ReposOwnerNamePullsNumberReady } from "./postApiV1ReposOwnerNamePullsNumberReady.ts";
421422 export { route as postApiV1ReposOwnerNamePullsNumberReviewStates } from "./postApiV1ReposOwnerNamePullsNumberReviewStates.ts";
422423 export { route as postApiV1ReposOwnerNamePullsNumberReviews } from "./postApiV1ReposOwnerNamePullsNumberReviews.ts";
423424 export { route as postApiV1ReposOwnerNamePullsNumberSlices } from "./postApiV1ReposOwnerNamePullsNumberSlices.ts";
src/contract/openapi/routes/postApiV1ReposOwnerNamePullsNumberReady.ts added +16
@@ -0,0 +1,16 @@
1 import { REPO, type Route } from "../shared.ts";
2
3 export const route: Route = {
4 method: "post",
5 path: `${REPO}/pulls/{number}/ready`,
6 summary: "Mark a draft pull ready, so its check runs now",
7 detail:
8 "Mark a draft (an app's first build still being written) ready: its check runs on its head now, and review and landing follow it as for any pull. The way out when its build will not end on its own; the repository's admin only (rw scope); answers `{ ready: true }`",
9 auth: true,
10 role: "member",
11 refusals: {
12 forbidden: "you do not administer the repository (403)",
13 not_draft: "the pull is not a draft (409)",
14 },
15 refuses: [401, 404],
16 };
src/core/event_audience.ts +1
@@ -75,6 +75,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([
7575 "issue.raised",
7676 "issue.blocked",
7777 "pull.pushed",
78 "pull.ready",
7879 "forge.spawn.live",
7980 "forge.spawn.failed",
8081 "fork.diverged",
src/core/migration-pins/20261124232400-pull-draft.pin added +1
@@ -0,0 +1,1 @@
1 bd0315f9602c78d5d661fd0c6092bb57ddcb161a62d7e7c04ba0ff2a1905fcec
src/core/migrations/20261124232400-pull-draft.ts added +8
@@ -0,0 +1,8 @@
1 // A pull opened as a draft by an app's first build (`crew/early.ts`): the run that is still
2 // writing it. Its pushes deploy and are not checked, no review starts and no door lands it until
3 // the run ends, the run is gone, or the repository's admin marks it ready, each of which clears it.
4 // Null for every other pull. Set only where the crew opens the pull, never from the body. Additive.
5 export default `
6 ALTER TABLE pull ADD COLUMN draft_run TEXT;
7 CREATE INDEX pull_draft ON pull(draft_run) WHERE draft_run IS NOT NULL;
8 `;
src/core/pulls.ts +66 −3
@@ -70,6 +70,11 @@ export interface Pull extends Issue {
7070 readonly revertsPullId: string | null;
7171 /** The variant group this pull belongs to; null for an ordinary pull. */
7272 readonly variantGroup: string | null;
73 /**
74 * The run still writing it, while it is an app's first build's draft (`crew/early.ts`); null
75 * once it is ready, and for every other pull.
76 */
77 readonly draftRun: string | null;
7378 }
7479
7580 interface PullRow {
@@ -83,6 +88,7 @@ interface PullRow {
8388 origin_head_repo: string | null;
8489 reverts_issue_id: string | null;
8590 variant_group: string | null;
91 draft_run: string | null;
8692 }
8793
8894 function fromRow(issue: Issue, row: PullRow): Pull {
@@ -100,6 +106,7 @@ function fromRow(issue: Issue, row: PullRow): Pull {
100106 originHeadRepo: row.origin_head_repo,
101107 revertsPullId: row.reverts_issue_id,
102108 variantGroup: row.variant_group,
109 draftRun: row.draft_run,
103110 };
104111 }
105112
@@ -188,6 +195,8 @@ export interface CreatePullInput {
188195 revertsIssueId?: string;
189196 /** The variant group the pull joins; absent for an ordinary pull. */
190197 variantGroup?: string;
198 /** The run writing it, when it opens as a draft: only `crew/early.ts` sets it. */
199 draftRun?: string;
191200 /**
192201 * Who opened it on another forge, and where (#9011): written with the
193202 * issue row, so the pull is a guest (`origins/guest.ts`) from its first
@@ -325,8 +334,8 @@ export async function createPull(
325334
326335 const headRepoId = headRepoIdOf(input);
327336 db.query(
328 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id, reverts_issue_id, variant_group)
329 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`,
337 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id, reverts_issue_id, variant_group, draft_run)
338 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`,
330339 ).run(
331340 issue.value.id,
332341 input.baseBranch,
@@ -336,6 +345,7 @@ export async function createPull(
336345 headRepoId,
337346 input.revertsIssueId ?? null,
338347 input.variantGroup ?? null,
348 input.draftRun ?? null,
339349 );
340350
341351 // A durable, fetchable ref for the PR head — the way tooling addresses it,
@@ -1165,7 +1175,9 @@ export type MergePullError =
11651175 /** The head is green, but the check ran on an older base than main now is (#12656). */
11661176 | "check_stale"
11671177 /** A team the pull's issue names has a reviewer here and has not approved this head (#10080). */
1168 | { readonly kind: "team_review_required"; readonly teams: readonly string[] };
1178 | { readonly kind: "team_review_required"; readonly teams: readonly string[] }
1179 /** The pull is a draft (`draftRun`): its build still runs, whoever presses and however. */
1180 | "draft";
11691181
11701182 /** The base a landing must find, and the tree it must write (#2036). */
11711183 export interface LandingExpect {
@@ -1669,3 +1681,54 @@ export function mergedPerDay(db: Database, repoIds: readonly string[], days: num
16691681 }
16701682 return { days: labels, merged: labels.map((d) => counts.get(d)!) };
16711683 }
1684
1685 /**
1686 * The first words of a draft's body (`crew/early.ts`), for the person reading it. Words only: what
outdated

Draft state is read from the body text, so anyone who can edit the body can set or clear it. Make it a column set only by the early-pull opener (finding 1).

1687 * makes a pull a draft is its row (`draftRun`), which only the crew's early open sets.
1688 */
1689 export const DRAFT_BODY = "Draft, in progress:";
1690
1691 /** What every door says of a draft it will not land: one sentence, the same everywhere. */
1692 export const DRAFT_REFUSAL = "This pull is a draft while its build runs; it lands when the build finishes.";
1693
1694 /** The pull page's and the terminal's status line for a draft. */
1695 export const DRAFT_LINE = "Draft: its build is still running.";
1696
1697 /** Whether the pull is still a draft. */
1698 export const isDraft = (pull: Pick<Pull, "draftRun">): boolean => pull.draftRun !== null;
1699
1700 /**
1701 * The pull is no draft from now on. True only for the one call that cleared it, so the check is
1702 * asked for once however many paths ready it at the same moment.
1703 */
1704 export function clearDraft(db: Database, pullId: string): boolean {
1705 return db.query("UPDATE pull SET draft_run = NULL WHERE issue_id = ?1 AND draft_run IS NOT NULL").run(pullId).changes === 1;
1706 }
1707
1708 /** The drafts whose run is over or gone: nothing will ready them but this (`crew/drafts.ts`). */
1709 export function strandedDrafts(db: Database): { repoId: string; number: number }[] {
1710 return db
1711 .query<{ repoId: string; number: number }, []>(
1712 `SELECT i.repo_id AS repoId, i.number AS number
1713 FROM pull p INDEXED BY pull_draft
1714 JOIN issue i ON i.id = p.issue_id
1715 LEFT JOIN run r ON r.id = p.draft_run
1716 WHERE p.draft_run IS NOT NULL AND (r.id IS NULL OR r.state NOT IN ('queued', 'running'))`,
1717 )
1718 .all();
1719 }
1720
1721 /**
1722 * Whether a run on `issueNumber` is an app's first build: the repository's first issue (the one
1723 * `new_app` opens, "Build <name>") while no pull has ever merged into it.
1724 */
1725 export function isFirstBuild(db: Database, repoId: string, issueNumber: number): boolean {
1726 if (issueNumber !== 1) return false;
1727 const merged = db
1728 .query<{ one: number }, [string]>(
1729 `SELECT 1 AS one FROM pull p JOIN issue i ON i.id = p.issue_id
1730 WHERE i.repo_id = ?1 AND p.merged_at IS NOT NULL LIMIT 1`,
1731 )
1732 .get(repoId);
1733 return merged === null;
1734 }
src/crew/brief.ts +10
@@ -45,6 +45,11 @@ export interface BriefInput {
4545 readonly branch: string;
4646 readonly forgeUrl: string;
4747 readonly isApp: boolean;
48 /**
49 * An app's first build (`isFirstBuild`): push early, each step; the pull is a draft until the
50 * end.
51 */
52 readonly firstBuild?: boolean;
4853 readonly previewUrl?: string | undefined;
4954 /** Where this repository's app answers; the shell may reach these and no other app. */
5055 readonly ownApp?: OwnApp | undefined;
@@ -225,6 +230,11 @@ export function systemPrompt(input: BriefInput): string {
225230 "",
226231 "This repository is an app the forge runs. Production follows the default branch; each open pull gets a preview from its branch on every push.",
227232 "- `forge.json` says how the app runs; keep it working.",
233 ...(input.firstBuild === true
234 ? [
235 "- This is the app's first build, and the person who asked for it is watching its preview. As soon as the app first runs, however little it does, commit and `git push`; then push again after each working step. The forge opens your pull as a draft at the first push and redeploys its preview on every push; the check runs once, on your last push, when the run ends.",
236 ]
237 : []),
228238 "- Keep state under `FORGE_APP_DATA`. Never write elsewhere at runtime.",
229239 "- The app's terminal (`tty` in forge.json) is reached with the exact command in `FORGE_APP_SSH` (for example `ssh -p 2222 notes@localhost`: the app is the login name, the forge is the host). When a page or the terminal tells people how to connect, print that variable verbatim and never invent a form like `[email protected]`; when it is unset, say the terminal is off.",
230240 "- Run the tests (`bun test`, or whatever `forge.json` names) before you push: the deploy runs them, and a failing test fails the preview. When a test fails, fix the code; change the test only when the test was wrong, and say which in the pull.",
src/crew/early.ts +19 −7
@@ -5,8 +5,9 @@
55 * for the first few seconds, then every few; each look costs git processes.
66 * The first time it is a commit beyond the base, the pull opens with the
77 * title, base and head `landWork` would use, and a body that says the work
8 * is in progress and where the run's log is. Every later push reaches the
9 * pull's preview as any push does. At the end `landWork` finds this pull by
8 * is in progress and where the run's log is; for an app's first build, a draft (`DRAFT_BODY`),
9 * whose pushes deploy the preview and run no check until `fillPull` or `settle` readies it. Every
10 * later push reaches the pull's preview as any push does. At the end `landWork` finds this pull by
1011 * its head and fills it in (`fillPull`); it never opens a second.
1112 */
1213
@@ -17,7 +18,8 @@ import type { App } from "../app.ts";
1718 import type { Agent } from "../core/agents.ts";
1819 import type { Issue } from "../core/issues.ts";
1920 import { listComments } from "../core/issues.ts";
20 import { listPulls, type Pull } from "../core/pulls.ts";
21 import { DRAFT_BODY, getPull, isDraft, listPulls, type Pull } from "../core/pulls.ts";
22 import { readyPull } from "../actions/pulls.ts";
2123 import { listReviews } from "../core/reviews.ts";
2224 import type { Repo } from "../core/repos.ts";
2325 import { getUserById } from "../core/users.ts";
@@ -74,6 +76,11 @@ export interface EarlyInput {
7476 /** A pull already stands for this work: nothing to open. */
7577 continuing: boolean;
7678 intervalMs?: number;
79 /**
80 * An app's first build (`isFirstBuild`): the pull opens as a draft, whose pushes deploy its
81 * preview and run no check until the run ends.
82 */
83 draft?: boolean;
7784 /** Called once when this watcher opens the pull; a throw is logged, not raised. */
7885 onOpened?: () => void;
7986 }
@@ -136,15 +143,16 @@ export function watchForPull(input: EarlyInput): EarlyPull {
136143 return;
137144 const opened = await openPull(input.app, input.agent.user, input.repo, {
138145 title: input.issue.title,
139 body: `${IN_PROGRESS} @${input.agent.user.username} is still working on this; the description is filled in when the run ends. Run log: ${log}\n\n${trailerFor(input.issue)}`,
146 body: `${input.draft === true ? `${DRAFT_BODY} its preview follows each push` : IN_PROGRESS} @${input.agent.user.username} is still working on this; the description is filled in when the run ends. Run log: ${log}\n\n${trailerFor(input.issue)}`,
140147 baseBranch: input.repo.defaultBranch,
141148 headBranch: input.branch,
142149 headRepo: input.fork,
143150 ...(input.variantGroup === null ? {} : { variantGroup: input.variantGroup }),
151 ...(input.draft === true ? { draftRun: input.run.id } : {}),
144152 });
145153 input.write(
146154 opened.ok
147 ? `opened pull #${opened.value.number} at the first push, in progress`
155 ? `opened pull #${opened.value.number} at the first push, ${input.draft === true ? "a draft: its pushes deploy, the check runs at the end" : "in progress"}`
148156 : `could not open the pull early: ${JSON.stringify(opened.error)}`,
149157 );
150158 if (opened.ok && input.onOpened !== undefined) {
@@ -196,10 +204,12 @@ export function watchForPull(input: EarlyInput): EarlyPull {
196204 setIssueState(input.app, input.agent.user, input.repo, pull, "closed");
197205 return;
198206 }
199 if (!pull.body.startsWith(IN_PROGRESS)) return;
207 if (!pull.body.startsWith(IN_PROGRESS) && !isDraft(pull)) return;
200208 editIssue(input.app, input.agent.user, input.repo, pull, {
201209 body: `${ENDED} Run log: ${log}\n\n${trailerFor(input.issue)}`,
202210 });
211 // A draft whose run ended without filling it in is no draft now: its check runs.
212 readyPull(input.app, input.agent.user, input.repo, pull);
203213 },
204214 stop: async () => {
205215 clearTimeout(timer);
@@ -215,7 +225,7 @@ export function watchForPull(input: EarlyInput): EarlyPull {
215225 * who edits the body but keeps those words has it filled in over.
216226 */
217227 export function isEarlyBody(body: string): boolean {
218 return body.startsWith(IN_PROGRESS) || body.startsWith(ENDED);
228 return body.startsWith(IN_PROGRESS) || body.startsWith(ENDED) || body.startsWith(DRAFT_BODY);
219229 }
220230
221231 /** The run is over: the early pull's body becomes the run's report. */
@@ -230,4 +240,6 @@ export function fillPull(
230240 if (!isEarlyBody(pull.body)) return;
231241 const body = `${report === "" ? "" : `${report}\n\n`}${trailerFor(issue)}`;
232242 editIssue(app, agent.user, repo, pull, { body });
243 // A draft filled in is ready: the check runs on its final head, and review follows its verdict.
244 readyPull(app, agent.user, repo, getPull(app.db, repo.id, pull.number) ?? pull);
233245 }
src/crew/review.ts +3 −1
@@ -22,7 +22,7 @@ import type { App } from "../app.ts";
2222 import { crewWithRole, type Agent } from "../core/agents.ts";
2323 import { getHold, holdsFor, lastReleasesFor } from "../core/holds.ts";
2424 import { getIssueById, LIST_LIMIT_MAX } from "../core/issues.ts";
25 import { listPulls, pullDiff, type Pull, pullDir} from "../core/pulls.ts";
25 import { isDraft, listPulls, pullDiff, type Pull, pullDir} from "../core/pulls.ts";
2626 import { getRepoById, PILLAR_MAX, type Repo } from "../core/repos.ts";
2727 import { teamsOfPull, teamVerdicts } from "../core/issue_teams.ts";
2828 import { listReviews, reviewSummariesFor, reviewSummary, type Review } from "../core/reviews.ts";
@@ -570,6 +570,8 @@ export async function sendToReview(
570570 const reviewers = reviewersOf(app.db, repo.id);
571571 // A paused reviewer reads like an empty seat: the pull waits for a person, and says so.
572572 if (reviewers.length === 0 || reviewerPaused(repo)) return "none";
573 // A draft is a first build still being written (`crew/early.ts`): it waits for its run to end.
574 if (isDraft(pull)) return "wait";
573575 // A stranger's pull is the crew's to filter on an autonomous repository
574576 // (#9575); anywhere else a guest waits for a person's word before the
575577 // crew touches it (`origins/guest.ts`).
src/crew/runner.ts +5 −1
@@ -71,7 +71,7 @@ import {
7171 sourceFollowing,
7272 upstreamFollowing,
7373 } from "../actions/upstream_follow.ts";
74 import { getPull, listPulls, type Pull, pullDir } from "../core/pulls.ts";
74 import { getPull, isFirstBuild, listPulls, type Pull, pullDir } from "../core/pulls.ts";
7575 import {
7676 canWrite,
7777 forkParentFor,
@@ -1380,6 +1380,9 @@ async function work(
13801380 branch,
13811381 forgeUrl: options.forgeUrl,
13821382 isApp: record !== undefined,
1383 // An app's first build (new_app's "Build <name>", nothing merged yet): the person watches its
1384 // preview from the first push, so the brief asks for early pushes and the pull is a draft.
1385 firstBuild: record !== undefined && pull === undefined && issue.kind === "issue" && isFirstBuild(app.db, repo.id, issue.number),
13831386 previewUrl,
13841387 ownApp: ownApp(app, repo),
13851388 policy,
@@ -1807,6 +1810,7 @@ async function work(
18071810 write,
18081811 variantGroup: run.variantGroup,
18091812 continuing: pullStands,
1813 draft: brief.firstBuild,
18101814 onOpened: () =>
18111815 write(
18121816 watch.line(
src/fleet/verbs.ts +2
@@ -12,6 +12,7 @@
1212
1313 import { NOT_A_MEMBER } from "../core/roles.ts";
1414 import { CHECK_STALE_REFUSAL } from "../checks/stale.ts";
15 import { DRAFT_REFUSAL } from "../core/pulls.ts";
1516 import { AGENT_NOT_ON_CREW } from "../actions/crew_limit_words.ts";
1617 import type { App } from "../app.ts";
1718 import {
@@ -126,6 +127,7 @@ const WORDS: Record<string, string> = {
126127 agent_not_on_crew: AGENT_NOT_ON_CREW,
127128 already_merged: "a merged pull stays closed",
128129 check_stale: CHECK_STALE_REFUSAL,
130 draft: DRAFT_REFUSAL,
129131 reason_required: "a bug closed without a fix says why: add a reason",
130132 invalid_note: "a reason is one sentence of at most 300 characters",
131133 finished: "already finished",
src/http/api.ts +2
@@ -243,6 +243,7 @@ import {
243243 type Run,
244244 } from "../core/runs.ts";
245245 import { CHECK_STALE_REFUSAL } from "../checks/stale.ts";
246 import { DRAFT_REFUSAL } from "../core/pulls.ts";
246247 import { resolveOid } from "../git/merge.ts";
247248 import { readForgeUsage, readUsage, usageDays, USAGE_DAYS_MAX } from "../actions/usage.ts";
248249 import { readReturns, reportSpend, RETURNS_DAYS } from "../actions/returns.ts";
@@ -667,6 +668,7 @@ export function originAware(error: string, status = 422): Response {
667668 "a bug closed without a fix says why: send `note` (one sentence, at most 300 characters)",
668669 );
669670 if (error === "check_stale") return apiError("check_stale", 409, CHECK_STALE_REFUSAL);
671 if (error === "draft") return apiError("draft", 409, DRAFT_REFUSAL);
670672 if (error === "planner_paused") return apiError("planner_paused", 409, PAUSE_REFUSAL);
671673 if (error === "planner_ceiling") return apiError("planner_ceiling", 409, CEILING_REFUSAL);
672674 if (error === "mirrored")
src/http/api/pulls.ts +19
@@ -25,6 +25,7 @@ import {
2525 import {
2626 addReview,
2727 anchorId,
28 markReady,
2829 mergePull,
2930 openPull,
3031 pullThreads,
@@ -531,6 +532,24 @@ export function pullRoutes(router: Router<Handler>): void {
531532 },
532533 );
533534
535 // The repository's admin marks a draft ready: its check runs now (`markReady`).
536 router.add(
537 "POST",
538 "/api/v1/repos/:owner/:name/pulls/:number/ready",
539 (ctx) => {
540 const denied = requireScope(ctx, "rw");
541 if (denied) return denied;
542 const found = loadPull(ctx);
543 if ("error" in found) return found.error;
544 const done = markReady(ctx.app, ctx.auth.user, found.repo, found.pull);
545 if (!done.ok)
546 return done.error === "not_draft"
547 ? json({ error: "not_draft", message: "This pull is not a draft." }, 409)
548 : respondAccess(done.error, 422);
549 return json({ ready: true });
550 },
551 );
552
534553 router.add(
535554 "POST",
536555 "/api/v1/repos/:owner/:name/pulls/:number/merge",
src/http/respond.ts +1
@@ -126,6 +126,7 @@ export const HINTS: Record<number, Hint & { codes?: Record<string, Hint> }> = {
126126 },
127127 checks_required: { core: "The pull's head needs a passing check or deploy first: push a fix or wait for the check, then repeat the call." },
128128 check_stale: { core: "The pull's check ran on an older main: re-run the check on the current head, then repeat the call." },
129 draft: { core: "This pull is a draft while its build runs: wait for the run to end, then repeat the call." },
129130 },
130131 },
131132 413: {
src/http/server.ts +2
@@ -456,6 +456,7 @@ import {
456456 pullMergeSubmit,
457457 pullSliceSubmit,
458458 pullLandPastSubmit,
459 pullReadySubmit,
459460 pullChecksSubmit,
460461 stuckSubmit,
461462 pullReviewStateSubmit,
@@ -1622,6 +1623,7 @@ export function buildRouter(): Router<Handler> {
16221623 router.add("POST", "/:owner/:name/pulls/:number/merge", pullMergeSubmit);
16231624 router.add("POST", "/:owner/:name/pulls/:number/slice", pullSliceSubmit);
16241625 router.add("POST", "/:owner/:name/pulls/:number/land-past", pullLandPastSubmit);
1626 router.add("POST", "/:owner/:name/pulls/:number/ready", pullReadySubmit);
16251627 router.add("POST", "/:owner/:name/pulls/:number/state", (ctx) =>
16261628 stateSubmit(ctx, "pull"),
16271629 );
src/main.ts +4
@@ -32,6 +32,7 @@ import { refreshCatalogQuietly } from "./packs/catalog.ts";
3232 import { loadTrustedHosts } from "./origins/trusted-hosts.ts";
3333 import { flushFlagUses, loadFlags } from "./core/flags.ts";
3434 import { reconcile } from "./core/reconcile.ts";
35 import { readyStranded } from "./actions/pulls.ts";
3536 import { offerStartingBoards } from "./actions/boards.ts";
3637 import { pruneStalePillarLabels, syncAllPillars } from "./actions/pillars.ts";
3738 import { bootHostedChildren, childAwake } from "./spawn/host.ts";
@@ -1156,6 +1157,9 @@ const leaseTimer = setInterval(() => during("lease", () => {
11561157 crew === undefined ? ["deploy", "agent"] : ["deploy"],
11571158 );
11581159 requeueAbandonedChecks(app, STALE_AFTER_MS);
1160 // A draft whose run is over or gone (a crash, a restart) is ready: a first app never stays
1161 // locked.
1162 readyStranded(app);
11591163 // A grant whose run is no longer running is a crash's leftover: close it.
11601164 releaseOrphans(app.db);
11611165 }, undefined, app), 30_000);
src/tui/screens/common.ts +3
@@ -9,6 +9,7 @@
99
1010 import { DELETING_SAYS } from "../../core/repo_deleting.ts";
1111 import { CHECK_STALE_REFUSAL } from "../../checks/stale.ts";
12 import { DRAFT_REFUSAL } from "../../core/pulls.ts";
1213 import { PASSWORD_TOO_LONG } from "../../core/hash-gate.ts";
1314 import { refusalText } from "../../http/refusal.ts";
1415 import { fullSentence, isFullError, noteFullHere } from "../../kernel/full_disk.ts";
@@ -1066,6 +1067,8 @@ const MESSAGES: Record<string, string> = {
10661067 // gate refusing, so like `review_required` it names what to do about it.
10671068 checks_required: "this needs a passing deploy of its current head first",
10681069 check_stale: CHECK_STALE_REFUSAL,
1070 draft: DRAFT_REFUSAL,
1071 not_draft: "this pull is not a draft",
10691072 invalid_slug: "a slug is lowercase letters, digits and single hyphens",
10701073 slug_taken: "that slug is taken by another app",
10711074 already_app: "this repository is already an app",
src/tui/screens/pull.ts +44 −5
@@ -41,6 +41,7 @@ import {
4141 addReview,
4242 approveGuestPull,
4343 approveToRun as letItRun,
44 markReady,
4445 mergePull,
4546 pullThreads,
4647 resolveReviewThread,
@@ -82,10 +83,10 @@ import { nextOfPull, type Next } from "../../flow/next_actor.ts";
8283 import { landingLine } from "../../flow/landing_line.ts";
8384 import { stepLine, stepOfPull, type PathStep } from "../../flow/path.ts";
8485 import { fromKeptFork } from "../../core/landing_kind.ts";
85 import { getPull, pullDir, variantSiblings, type MergePullError, type Pull } from "../../core/pulls.ts";
86 import { DRAFT_LINE, getPull, isDraft, pullDir, variantSiblings, type MergePullError, type Pull } from "../../core/pulls.ts";
8687 import { voteVariant } from "../../actions/variants.ts";
8788 import { costLineFor } from "../../core/ledger_rollup.ts";
88 import { getRepoById, type Repo } from "../../core/repos.ts";
89 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
8990 import { canVerdict } from "../../core/verdict.ts";
9091 import { reviewWords } from "../../actions/review_words.ts";
9192 import { verdictOf, type Verdict } from "../../web/pages/pull-verdict.ts";
@@ -711,6 +712,7 @@ export function pullScreen(
711712 merged: facts.mergedAt !== null,
712713 closed: detail.issue.state === "closed",
713714 onOrigin: mirrored(),
715 draft: draft(),
714716 mergeable: facts.mergeable,
715717 ahead: facts.diff !== null && facts.diff.files.length === 0 ? 0 : 1,
716718 conflicts: facts.conflicts.length,
@@ -950,6 +952,22 @@ export function pullScreen(
950952 * Whether `L` is on offer: an open pull, an owner who is a person, and
951953 * landing stopped (`checks/bypass.ts`). The same rule the page's form follows.
952954 */
955 /** `D` is the repository admin's, as on the page (`markReady` decides). */
956 const mayMarkReady = (): boolean =>
957 repo !== undefined && f.user !== undefined && f.user.kind !== "agent" && canAdmin(f.db, repo, f.user);
958 const readyNow = (): void => {
959 if (repo === undefined) return;
960 const row = getPull(f.db, repo.id, number);
961 if (row === undefined) return;
962 const done = markReady(f.app, f.user, repo, row);
963 if (!done.ok) {
964 ctx.toast(errorText(typeof done.error === "string" ? done.error : "forbidden"), "danger");
965 return;
966 }
967 void reload();
968 ctx.toast("marked ready: its check runs now", "success");
969 };
970
953971 const mayLandPast = (): boolean => {
954972 if (repo === undefined || !bypassOffered(f.app, f.user, repo)) return false;
955973 const row = getPull(f.db, repo.id, number);
@@ -1179,8 +1197,12 @@ export function pullScreen(
11791197 };
11801198
11811199 const mirrored = (): boolean => repo === undefined || repo.origin !== null;
1200 const draft = (): boolean => {
1201 const row = repo === undefined ? undefined : getPull(f.db, repo.id, number);
1202 return row !== undefined && isDraft(row);
1203 };
11821204 const state = (): MergeState =>
1183 mergeState(detail?.issue, facts, mirrored(), gated(), checksGated(), holding.length > 0);
1205 mergeState(detail?.issue, facts, mirrored(), gated(), checksGated(), holding.length > 0, draft());
11841206
11851207 const screen: Screen = {
11861208 title: `#${number}`,
@@ -1234,6 +1256,7 @@ export function pullScreen(
12341256 ? [binding(["v"], "see the conflict blocks")]
12351257 : []),
12361258 binding(["m"], "merge", { disabled: state() !== "ready" }),
1259 ...(state() === "draft" && mayMarkReady() ? [binding(["D"], "mark ready: its check runs now")] : []),
12371260 ...(wall !== undefined && mayWrite() ? [binding(["w"], "the access wall: allow or send back")] : []),
12381261 ...(mayLandPast() ? [binding(["L"], "land past the gate")] : []),
12391262 ...(mayOffer() ? [binding(["O"], "offer this merged pull upstream")] : []),
@@ -1367,6 +1390,7 @@ export function pullScreen(
13671390 standing: standing(),
13681391 required: requireReview,
13691392 teams,
1393 draft: draft(),
13701394 });
13711395 tabs(s, tabRow!, c, {
13721396 items: [
@@ -1626,6 +1650,11 @@ export function pullScreen(
16261650 }
16271651 return true;
16281652 }
1653 // The admin's way out of a draft whose build will not end on its own (`markReady`).
1654 if (e.key === "D" && state() === "draft" && mayMarkReady()) {
1655 readyNow();
1656 return true;
1657 }
16291658 // A merge the gate would refuse says so here rather than going quiet:
16301659 // `m` doing nothing is indistinguishable from `m` being unbound.
16311660 if (e.key === "m" && mayWrite() && state() === "review_required") {
@@ -1798,6 +1827,8 @@ export type MergeState =
17981827 | "team_required"
17991828 /** The head's deploy is not green yet — `mergePull` refuses it too. */
18001829 | "checks_required"
1830 /** An app's first build still being written (`draftRun`) — `mergePull` refuses it too. */
1831 | "draft"
18011832 | "ready"
18021833 | "unknown";
18031834
@@ -1987,6 +2018,7 @@ export function mergeState(
19872018 gated = false,
19882019 checksGated = false,
19892020 teamsHeld = false,
2021 draft = false,
19902022 ): MergeState {
19912023 if (issue === undefined || pull === null || pull === undefined)
19922024 return "unknown";
@@ -1995,6 +2027,8 @@ export function mergeState(
19952027 // A mirror's merge belongs to the origin, which is truth for it: merging
19962028 // here would rewrite the base branch and be overwritten by the next fetch.
19972029 if (mirrored) return "mirrored";
2030 // Its build is still running: nothing about the diff, the reviews or the checks is final yet.
2031 if (draft) return "draft";
19982032 if (pull.mergeable === null) return "unknown";
19992033 if (pull.diff !== null && pull.diff.files.length === 0) return "empty";
20002034 if (!pull.mergeable) return "conflicts";
@@ -2032,9 +2066,11 @@ function drawMergeBox(
20322066 standing: Standing;
20332067 required: boolean;
20342068 teams: readonly TeamVerdict[];
2069 /** An app's first build still being written. */
2070 draft: boolean;
20352071 },
20362072 ): void {
2037 const state = mergeState(issue, pull, mirrored, o.gated, o.checksGated, o.holding.length > 0);
2073 const state = mergeState(issue, pull, mirrored, o.gated, o.checksGated, o.holding.length > 0, o.draft);
20382074 const tone =
20392075 state === "merged"
20402076 ? "merged"
@@ -2045,7 +2081,8 @@ function drawMergeBox(
20452081 : state === "mirrored" ||
20462082 state === "review_required" ||
20472083 state === "team_required" ||
2048 state === "checks_required"
2084 state === "checks_required" ||
2085 state === "draft"
20492086 ? "attn"
20502087 : "default";
20512088 // Where it is going belongs on the frame, not on a body row: the box is
@@ -2070,6 +2107,8 @@ function drawMergeBox(
20702107 ? `Merge on the origin${issue.originUrl === null ? "" : ` — ${issue.originUrl}`}`
20712108 : state === "conflicts"
20722109 ? `Conflicts in ${plural(conflicts.length, "file")}: ${conflicts.slice(0, 3).join(", ")}`
2110 : state === "draft"
2111 ? DRAFT_LINE
20732112 : state === "empty"
20742113 ? "Nothing to merge — the base already has these commits"
20752114 : state === "review_required"
src/web/pages/pull-verdict.ts +8 −3
@@ -7,7 +7,7 @@
77 * `mergeBox` and `mergePull` ask, in the same order, so the line and the
88 * button never disagree.
99 */
10 import { changedSentences } from "../../core/pulls.ts";
10 import { changedSentences, DRAFT_LINE } from "../../core/pulls.ts";
1111 import type { Diff } from "../../git/diff.ts";
1212 import { html, when, type Html } from "../html.ts";
1313 import { btn, dot, type Tone } from "../ui.ts";
@@ -17,6 +17,8 @@ export interface VerdictInput {
1717 readonly closed: boolean;
1818 /** A mirror: the merge belongs to the origin. */
1919 readonly onOrigin: boolean;
20 /** An app's first build still being written (`draftRun`): nothing lands it yet. */
21 readonly draft: boolean;
2022 readonly mergeable: boolean;
2123 readonly ahead: number;
2224 readonly conflicts: number;
@@ -38,7 +40,7 @@ export interface Verdict {
3840 /** A fixed phrase of ours, never a person's text. */
3941 readonly words: string;
4042 /** Set when a reviewer's asked-for changes hold the pull: callers read this, never the words. */
41 readonly kind?: "changes_requested";
43 readonly kind?: "changes_requested" | "draft";
4244 readonly action: { readonly label: string; readonly href: string } | null;
4345 }
4446
@@ -51,6 +53,7 @@ export function verdictOf(v: VerdictInput, thread: string, page = ""): Verdict {
5153 if (v.merged) return { tone: "merged", words: "Merged", action: null };
5254 if (v.closed) return { tone: undefined, words: "Closed without merging", action: null };
5355 if (v.onOrigin) return { tone: "attn", words: "Merges on the origin", action: null };
56 if (v.draft) return { tone: "attn", words: DRAFT_LINE, kind: "draft", action: null };
5457 if (!v.mergeable) {
5558 if (v.ahead === 0) return { tone: "danger", words: "Nothing left to apply", action: null };
5659 if (v.conflicts > 0)
@@ -91,7 +94,9 @@ export function verdictOf(v: VerdictInput, thread: string, page = ""): Verdict {
9194 export function verdictLine(verdict: Verdict, show: { readonly action?: boolean } = {}): Html {
9295 return html`<div class="bar mt" data-verdict role="status">
9396 ${dot(verdict.tone)}
94 <strong>${verdict.words}</strong>
97 ${verdict.kind === "draft"
98 ? html`<dl class="row-facts"><div><dt>Draft</dt><dd>${verdict.words.slice("Draft: ".length)}</dd></div></dl>`
99 : html`<strong>${verdict.words}</strong>`}
95100 ${when(show.action === false ? null : verdict.action, (a) => btn(a.label, { href: a.href, size: "sm", ...(verdict.tone === "success" ? { variant: "primary" as const } : {}) }))}
96101 </div>`;
97102 }
src/web/pages/pull.ts +39
@@ -21,6 +21,7 @@ import type { AccessError } from "../../actions/access.ts";
2121 import { NO_WRITE_ACCESS, PULL_GONE } from "../../actions/pull_words.ts";
2222 import {
2323 addReview,
24 markReady,
2425 mergePull,
2526 pullThreads,
2627 resolveReviewThread,
@@ -56,6 +57,7 @@ import { redMain } from "../../checks/red_main.ts";
5657 import { mainLineFor } from "../../checks/red_main_line.ts";
5758 import { runningProgress } from "../../checks/progress.ts";
5859 import { CHECK_STALE_REFUSAL, checkStale, checksHold } from "../../checks/stale.ts";
60 import { DRAFT_REFUSAL, isDraft } from "../../core/pulls.ts";
5961 import { checkSummary, type CheckSummary } from "../../core/runs.ts";
6062 import {
6163 anchorKey,
@@ -227,6 +229,7 @@ export function verdictFacts(
227229 merged: pull.mergedAt !== null,
228230 closed: pull.state === "closed",
229231 onOrigin: repo.origin !== null || pull.originHeadRepo !== null,
232 draft: isDraft(pull),
230233 mergeable: status?.mergeable ?? false,
231234 ahead: status?.ahead ?? 0,
232235 conflicts: status?.conflicts.length ?? 0,
@@ -615,6 +618,19 @@ function mergeBox(
615618 // base branch here and be overwritten by the next fetch, and merging through
616619 // the API would have to reproduce the origin's strategy, protections and
617620 // required checks exactly. So the box says where the button is instead.
621 // An app's first build still being written: no Merge, and the admin's way out when it will not
622 // end on its own.
623 if (isDraft(pull)) {
624 const admin = ctx.auth.user !== undefined && ctx.auth.user.kind !== "agent" && canAdmin(ctx.app.db, repo, ctx.auth.user);
625 return box(
626 "attn",
627 icon("clock"),
628 "Nothing to merge until its build ends.",
629 html`Its preview follows each push. When the build ends, its check runs and review starts.`,
630 when(admin, () => markReadyForm(thread)),
631 );
632 }
633
618634 if (repo.origin !== null || pull.originHeadRepo !== null) {
619635 const at = repo.origin;
620636 return box(
@@ -1385,6 +1401,7 @@ export function mergeFailure(error: AccessError | MergePullError): string {
13851401 if (error === "review_required")
13861402 return "This pull request needs an approving review of its current head, and does not have one. Nothing was merged.";
13871403 if (error === "check_stale") return CHECK_STALE_REFUSAL;
1404 if (error === "draft") return DRAFT_REFUSAL;
13881405 if (error === "checks_required")
13891406 return "This pull request needs a passing deploy of its current head, and does not have one yet. Nothing was merged.";
13901407 if (error === "forbidden" || error === "unauthorized")
@@ -1744,6 +1761,28 @@ export function slicesCard(
17441761 );
17451762 }
17461763
1764 /** The repository admin's way out of a draft whose build will not end on its own. */
1765 export function markReadyForm(thread: string): Html {
1766 return html`<form method="post" action="${thread}/ready" data-now="Marked ready" data-now-once>
1767 ${btn("Mark ready", { size: "sm", icon: "check" })}
1768 </form>`;
1769 }
1770
1771 // POST /:owner/:name/pulls/:number/ready — the admin marks a draft ready (`markReady`).
1772 export async function pullReadySubmit(ctx: Ctx): Promise<Response> {
1773 const found = pullContext(ctx);
1774 if (found instanceof Response) return found;
1775 const form = await readForm(ctx, "rw");
1776 if (form instanceof Response) return form;
1777 const dest = `${repoBase(found.repo)}/pulls/${found.pull.number}`;
1778 const done = markReady(ctx.app, ctx.auth.user, found.repo, found.pull);
1779 if (!done.ok)
1780 return done.error === "not_draft"
1781 ? flashTo(ctx, dest, { message: "This pull is not a draft." })
1782 : forbiddenPage(ctx, "Only a person who administers this repository can do this.");
1783 return flashTo(ctx, dest, { message: "Marked ready: its check runs now, and review follows it." });
1784 }
1785
17471786 // POST /:owner/:name/pulls/:number/land-past — the owner's break-glass (#7790).
17481787 export async function pullLandPastSubmit(ctx: Ctx): Promise<Response> {
17491788 const found = pullContext(ctx);
src/web/studio/change.ts +13 −2
@@ -25,6 +25,7 @@ import { appsRuntime, envsFor } from "../../apps/runtime.ts";
2525 import { getAppByRepo, type AppRecord } from "../../core/apps.ts";
2626 import {
2727 getPull,
28 isDraft,
2829 pullStatus,
2930 revertOf,
3031 toldBy,
@@ -70,7 +71,7 @@ import {
7071 import { previewBlock } from "../pages/apps.ts";
7172 import { filmstrip, filmstripJs } from "../pages/filmstrip.ts";
7273 import { lookCard } from "../pages/looks.ts";
73 import { approveHereCard, keptChange, pullChecksLineFor, reachLine, teamsCard, verdictFacts } from "../pages/pull.ts";
74 import { approveHereCard, keptChange, pullChecksLineFor, reachLine, teamsCard, markReadyForm, verdictFacts } from "../pages/pull.ts";
7475 import { landAsIs, shipsOn } from "./land_as_is.ts";
7576 import { changeSummary, verdictLine, verdictOf } from "../pages/pull-verdict.ts";
7677 import { guestWalls, strangerCard } from "../pages/pull-guest.ts";
@@ -635,8 +636,18 @@ async function changeConversation(
635636 // sooner and in plain words. The same wording and the same button serve a
636637 // person's own change (`own`, above) exactly as they serve the crew's — one
637638 // card, one vocabulary, whoever opened the change.
639 // A draft is a first build still being written: no Ship, only what it waits on, and its admin's
640 // Mark ready when the build will not end on its own.
641 const draftNote = !isDraft(pull)
642 ? undefined
643 : html`<p>Its preview follows each push. When the build ends, its check runs and review starts.</p>${when(
644 ctx.auth.user !== undefined && ctx.auth.user.kind !== "agent" && canAdmin(db, repo, ctx.auth.user),
645 () => html`<div class="bar mt">${markReadyForm(thread)}</div>`,
646 )}`;
638647 const decisionBody =
639 decision !== undefined
648 draftNote !== undefined
649 ? draftNote
650 : decision !== undefined
640651 ? conflicted && decision.kind === "look" && decision.pull
641652 ? html`<p>${decision.who} finished "${decision.pull.title}", but ${conflictWords(
642653 pull.baseBranch,
test/api-pulls-module.test.ts +1 −1
@@ -47,7 +47,7 @@ const routesOf = (add: (r: Router<Handler>) => void) => {
4747
4848 test("apiRoutes registers every pull route, as one run in its old place", () => {
4949 const moved = routesOf(pullRoutes);
50 expect(moved.length).toBe(23);
50 expect(moved.length).toBe(24);
5151 expect(moved[0]).toBe("GET /api/v1/repos/:owner/:name/pulls");
5252 const all = routesOf((r) => apiRoutes(r, () => false));
5353 const at = all.indexOf(moved[0]!);
test/crew-draft.test.ts added +465
@@ -0,0 +1,465 @@
1 /**
2 * An app's first build shows its preview from its first push (the owner, 2026-11-24: "will i
3 * automatically see the preview when the first commit is made?"). Its early pull opens as a draft:
4 * each push deploys the preview and runs no check; the run's end fills it in and asks for the check
5 * on the final head (`pull.ready`). Until then no review starts, and no door lands it: the web, the
6 * API, MCP and the merge queue all refuse it through `mergePull`, with one sentence. A draft is the
7 * pull's row (`draftRun`), set only where the crew opens it, never its body; a run that dies or a
8 * forge that stops never leaves it locked, and the repository's admin can mark it ready by hand.
9 * Any other build is as before: its early pull is checked from its first push.
10 */
11 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
12 import type { App } from "../src/app.ts";
13 import { openIssue } from "../src/actions/issues.ts";
14 import { forkRepo } from "../src/actions/repos.ts";
15 import { addCrew, createAgentRow, getAgentByName, type Agent } from "../src/core/agents.ts";
16 import {
17 DRAFT_BODY,
18 DRAFT_REFUSAL,
19 DRAFT_LINE,
20 getPull,
21 isDraft,
22 isFirstBuild,
23 type Pull,
24 } from "../src/core/pulls.ts";
25 import { getForkOf, type Repo } from "../src/core/repos.ts";
26 import { createRun, listRuns } from "../src/core/runs.ts";
27 import { createUser, type User } from "../src/core/users.ts";
28 import { systemPrompt } from "../src/crew/brief.ts";
29 import { ENDED, fillPull, pullOfBranch, watchForPull, type EarlyPull } from "../src/crew/early.ts";
30 import { markReady, mergePull, openPull, readyStranded } from "../src/actions/pulls.ts";
31 import { announceRun } from "../src/actions/runs.ts";
32 import { assignIssue } from "../src/actions/issues.ts";
33 import { addToCrew } from "../src/actions/crew.ts";
34 import { createRepo } from "../src/actions/repos.ts";
35 import { editFiles } from "../src/actions/contents.ts";
36 import { createApp as createAppRecord } from "../src/core/apps.ts";
37 import { createIssue } from "../src/core/issues.ts";
38 import { finishRun, getRun } from "../src/core/runs.ts";
39 import { createForgeApp } from "../src/tui/forge.ts";
40 import { headlessTerminal } from "../src/tui/term/terminal.ts";
41 import { pullScreen } from "../src/tui/screens/pull.ts";
42 import { local } from "../src/tui/screens/where.ts";
43 import { settleApp } from "./helpers/tui.ts";
44 import { existsSync, rmSync, readFileSync, writeFileSync } from "node:fs";
45 import { join } from "node:path";
46 import { sendToReview } from "../src/crew/review.ts";
47 import { seatAs } from "./helpers/seat.ts";
48 import { createSession } from "../src/core/sessions.ts";
49 import { createToken } from "../src/core/tokens.ts";
50 import { mergeFailure } from "../src/web/pages/pull.ts";
51 import { errorText } from "../src/tui/screens/common.ts";
52 import { resolveOid } from "../src/git/merge.ts";
53 import { repoDir } from "../src/git/repos.ts";
54 import { ok } from "../src/kernel/result.ts";
55 import {
56 startStandInCrew,
57 stopStandInCrew,
58 type StandInCrew,
59 } from "./helpers/crew-standin.ts";
60 import { waitFor } from "./helpers/poll.ts";
61
62 describe("an app's first build pushes early, as a draft", () => {
63 let standIn: StandInCrew;
64 let app: App;
65 let alice: User;
66 let bot: User;
67 let repo: Repo;
68 let agent: Agent;
69 /** Each branch's watcher, stopped, kept for its `settle`. */
70 const watchers = new Map<string, EarlyPull>();
71
72 beforeAll(async () => {
73 // A check that passes at once: what is asserted is whether one is asked for, never its work.
74 standIn = await startStandInCrew({ checkStep: async () => ok(), files: [{ path: "forge.json", content: '{"check":{"run":"true"}}\n' }] });
75 ({ app, alice, bot, repo } = standIn);
76 agent = getAgentByName(app.db, "bot")!;
77 // The fork the bot pushes to, as its first run would make it.
78 const forked = await forkRepo(app, bot, repo);
79 if (!forked.ok) throw new Error(String(forked.error));
80 }, 30_000);
81
82 afterAll(() => stopStandInCrew(standIn));
83
84 /** A branch in the bot's fork, one commit of content the base does not hold. */
85 const branchAhead = async (branch: string, what: string): Promise<string> => {
86 const fork = getForkOf(app.db, bot.id, repo.id)!;
87 const forkBare = repoDir(app.reposRoot, fork.ownerName, fork.name);
88 const bare = repoDir(app.reposRoot, repo.ownerName, repo.name);
89 const git = async (args: string[], input?: string): Promise<string> => {
90 const p = Bun.spawn(["git", ...args], {
91 cwd: forkBare,
92 stdin: input === undefined ? "ignore" : new TextEncoder().encode(input),
93 stdout: "pipe",
94 stderr: "pipe",
95 env: {
96 PATH: process.env["PATH"] ?? "",
97 GIT_AUTHOR_NAME: "t",
98 GIT_AUTHOR_EMAIL: "[email protected]",
99 GIT_COMMITTER_NAME: "t",
100 GIT_COMMITTER_EMAIL: "[email protected]",
101 },
102 });
103 const out = await new Response(p.stdout).text();
104 expect(await p.exited).toBe(0);
105 return out.trim();
106 };
107 const baseTip = (await resolveOid(
108 bare,
109 `refs/heads/${repo.defaultBranch}`,
110 ))!;
111 // The base's tree with one more file: real content, so the head declares what main does.
112 const blob = await git(["hash-object", "-w", "--stdin"], `${what}\n`);
113 const listed = await git(["ls-tree", baseTip]);
114 const tree = await git(["mktree"], `${listed}\n100644 blob ${blob}\t${branch.replaceAll("/", "-")}.txt\n`);
115 const commit = await git(["commit-tree", tree, "-p", baseTip, "-m", what]);
116 await git(["update-ref", `refs/heads/${branch}`, commit]);
117 return commit;
118 };
119
120 /** Watch a branch as a run does, and wait for its early pull. */
121 const earlyPull = async (
122 branch: string,
123 title: string,
124 draft: boolean,
125 kind: "deploy" | "agent" = "deploy",
126 ): Promise<Pull> => {
127 const fork = getForkOf(app.db, bot.id, repo.id)!;
128 const issue = openIssue(app, alice, repo, { title, body: "x" });
129 if (!issue.ok) throw new Error("issue");
130 await branchAhead(branch, title);
131 // The run the draft names: a deploy row no runtime here picks up, or a crew run's row that no
132 // worker runs (`kind: "agent"`, never handed to the crew), for the tests of its end.
133 const run = createRun(app.db, { repoId: repo.id, kind });
134 // Running, so the crew's queue never takes it up, with a fresh lease, so no sweep calls it
135 // abandoned.
136 if (kind === "agent") app.db.run("UPDATE run SET state = 'running', heartbeat_at = ?2 WHERE id = ?1", [run.id, new Date().toISOString()]);
137 const watcher = watchForPull({
138 app,
139 repo,
140 agent,
141 issue: issue.value,
142 run,
143 fork,
144 branch,
145 forkBare: repoDir(app.reposRoot, fork.ownerName, fork.name),
146 bare: repoDir(app.reposRoot, repo.ownerName, repo.name),
147 forgeUrl: "http://forge.test",
148 write: () => {},
149 variantGroup: null,
150 continuing: false,
151 intervalMs: 20,
152 draft,
153 });
154 expect(
155 await waitFor(() => pullOfBranch(app, repo, fork, branch) !== undefined),
156 ).toBe(true);
157 await watcher.stop();
158 watchers.set(branch, watcher);
159 return pullOfBranch(app, repo, fork, branch)!;
160 };
161
162 const checksOf = (pull: Pull) =>
163 listRuns(app.db, repo.id, { kind: "check" }).filter(
164 (r) => r.issueId === pull.id,
165 );
166
167 test("the draft's open and its pushes ask for no check; the run's end fills it in and checks its final head", async () => {
168 const pull = await earlyPull("bot/first-build", "Build garden", true);
169 expect(pull.body.startsWith(DRAFT_BODY)).toBe(true);
170 // A later push while it is a draft: deployed by the runtime as any push, and not checked.
171 app.bus.append({
172 kind: "pull.pushed",
173 repoId: repo.id,
174 actorId: bot.id,
175 payload: { number: pull.number, headOid: pull.headOid },
176 });
177 // Events are heard in order: once another build's pull, opened after these, has its check, the
178 // draft's open and push have been heard, and asked for none.
179 const other = await earlyPull("bot/after-draft", "Plant asters", false);
180 expect(await waitFor(() => checksOf(other).length > 0)).toBe(true);
181 expect(checksOf(pull)).toEqual([]);
182 // The run ends: the body becomes its report and the check is asked for, once, on the head.
183 fillPull(
184 app,
185 agent,
186 repo,
187 pull,
188 { ...pull, kind: "issue", number: 1 },
189 "Planted.",
190 );
191 expect(await waitFor(() => checksOf(pull).length > 0)).toBe(true);
192 expect(checksOf(pull).map((r) => r.commitOid)).toEqual([pull.headOid]);
193 expect(isDraft(getPull(app.db, repo.id, pull.number)!)).toBe(false);
194 }, 30_000);
195
196 test("any other build is as before: its early pull is checked from its first push", async () => {
197 const pull = await earlyPull("bot/other-build", "Plant tulips", false);
198 expect(pull.body.startsWith(DRAFT_BODY)).toBe(false);
199 expect(await waitFor(() => checksOf(pull).length > 0)).toBe(true);
200 }, 30_000);
201
202 test("a first build is the repository's first issue while nothing has merged into it, and only its brief asks for early pushes", async () => {
203 const made = await createRepo(app, alice, { name: "meadow", visibility: "public" });
204 if (!made.ok) throw new Error(String(made.error));
205 const meadow = made.value;
206 const first = openIssue(app, alice, meadow, { title: "Build meadow", body: "x" });
207 const second = openIssue(app, alice, meadow, { title: "Then a pond", body: "x" });
208 if (!first.ok || !second.ok) throw new Error("issue");
209 expect([first.value.number, second.value.number]).toEqual([1, 2]);
210 expect(isFirstBuild(app.db, meadow.id, 1)).toBe(true);
211 expect(isFirstBuild(app.db, meadow.id, 2)).toBe(false);
212 // An open pull changes nothing; one merged into it does.
213 const proposed = createIssue(app.db, { repoId: meadow.id, authorId: alice.id, title: "A path", body: "", kind: "pull" });
214 if (!proposed.ok) throw new Error("pull");
215 app.db.run("INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid) VALUES (?1, 'main', 'path', 'a', 'b')", [proposed.value.id]);
216 expect(isFirstBuild(app.db, meadow.id, 1)).toBe(true);
217 app.db.run("UPDATE pull SET merged_at = '2026-11-24T00:00:00Z' WHERE issue_id = ?1", [proposed.value.id]);
218 expect(isFirstBuild(app.db, meadow.id, 1)).toBe(false);
219 const brief = (firstBuild: boolean) =>
220 systemPrompt({
221 agent,
222 repo,
223 issue: first.value,
224 branch: "b",
225 forgeUrl: "http://forge.test",
226 isApp: true,
227 firstBuild,
228 resuming: false,
229 });
230 expect(brief(true)).toContain(
231 "This is the app's first build, and the person who asked for it is watching its preview.",
232 );
233 expect(brief(false)).not.toContain("first build");
234 });
235
236 describe("the runner, on an app's repository", () => {
237 let orchard: Repo;
238 const release = () => join(standIn.dataDir, "release");
239 // The repository, its app and its crew once, for both runs: each test is one run.
240 beforeAll(async () => {
241 const made = await createRepo(app, alice, { name: "orchard", visibility: "public" });
242 if (!made.ok) throw new Error(String(made.error));
243 orchard = made.value;
244 const seeded = await editFiles(app, alice, orchard, { message: "Start", files: [{ path: "README.md", content: "# orchard\n" }] });
245 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
246 if (!createAppRecord(app.db, { repoId: orchard.id, slug: "orchard", access: "public" }).ok) throw new Error("app");
247 expect(addToCrew(app, alice, orchard, "bot").ok).toBe(true);
248 }, 30_000);
249 /** One run on a new issue: what its pull and brief were while it lingered, then its end. */
250 const runOn = async (title: string) => {
251 rmSync(release(), { force: true });
252 const issue = openIssue(app, alice, orchard, { title, body: "LINGER-ME by the wall." });
253 if (!issue.ok) throw new Error("issue");
254 expect(assignIssue(app, alice, orchard, issue.value, bot).ok).toBe(true);
255 const branch = `bot/${issue.value.number}-${title.toLowerCase().replaceAll(" ", "-")}`;
256 const opened = () => listRuns(app.db, orchard.id, { kind: "agent" }).find((r) => r.branch === branch);
257 const fork = () => getForkOf(app.db, bot.id, orchard.id);
258 const pull = () => { const f = fork(); return f === undefined ? undefined : pullOfBranch(app, orchard, f, branch); };
259 // The agent has pushed and lingers: the pull opened at its push, while the run still runs.
260 expect(await waitFor(() => pull() !== undefined, { within: 20_000 })).toBe(true);
261 const brief = readFileSync(standIn.argsFile, "utf8");
262 const seen = { number: issue.value.number, draftRun: pull()!.draftRun, run: opened()?.id, brief };
263 writeFileSync(release(), "");
264 expect(await waitFor(() => { const r = opened(); return r !== undefined && r.state !== "queued" && r.state !== "running"; }, { within: 30_000 })).toBe(true);
265 return seen;
266 };
267
268 test("a run on an app's issue 1 opens its pull as a draft naming that run, with the first-build brief", async () => {
269 const first = await runOn("Plant apples");
270 expect(first.number).toBe(1);
271 expect(first.draftRun).toBe(first.run!);
272 expect(first.brief).toContain("This is the app's first build");
273 }, 30_000);
274
275 test("a run on a later issue opens no draft and has no first-build brief", async () => {
276 const second = await runOn("Plant pears");
277 // The first build's pull took #2: this is the repository's next issue, not its first.
278 expect(second.number).toBeGreaterThan(1);
279 expect(second.draftRun).toBeNull();
280 expect(second.brief).not.toContain("This is the app's first build");
281 expect(existsSync(release())).toBe(true);
282 }, 30_000);
283 });
284
285 test("a body that starts with the draft's words is no draft: a pull opened through the API with them is checked", async () => {
286 const fork = getForkOf(app.db, bot.id, repo.id)!;
287 await branchAhead("bot/says-draft", "Says draft");
288 const opened = await openPull(app, bot, repo, { title: "Says draft", body: `${DRAFT_BODY} not really`, baseBranch: repo.defaultBranch, headBranch: "bot/says-draft", headRepo: fork });
289 if (!opened.ok) throw new Error(JSON.stringify(opened.error));
290 expect(isDraft(opened.value)).toBe(false);
291 expect(await waitFor(() => checksOf(opened.value).length > 0)).toBe(true);
292 }, 30_000);
293
294 test("a run that dies mid-draft leaves its pull saying so, and settle asks for the check on its head", async () => {
295 const pull = await earlyPull("bot/dies", "Plant lilies", true);
296 expect(checksOf(pull)).toEqual([]);
297 watchers.get("bot/dies")!.settle();
298 expect(getPull(app.db, repo.id, pull.number)!.body.startsWith(ENDED)).toBe(true);
299 expect(await waitFor(() => checksOf(pull).length > 0)).toBe(true);
300 }, 30_000);
301
302 test("no review starts on a draft, however green its head; filled in, it goes to review", async () => {
303 const made = await createUser(app.db, { username: "quill", email: "[email protected]", agent: true, origin: "agent" });
304 if (!made.ok) throw new Error(made.error);
305 createAgentRow(app.db, { userId: made.value.id, brief: "b" });
306 addCrew(app.db, repo.id, made.value.id, alice.id);
307 seatAs(app.db, repo.id, made.value.id, "reviewer");
308 // Every green pull of the earlier tests is sent to the new reviewer too: room for this one.
309 app.db.run("UPDATE repo SET reviewer_slots = 99 WHERE id = ?1", [repo.id]);
310 const pull = await earlyPull("bot/reviewed", "Plant daisies", true);
311 await standIn.checks.request(repo, `pull-${pull.number}`, pull.headOid, "manual", pull.id, alice.id);
312 expect(await waitFor(() => checksOf(pull).some((r) => r.state === "ok"))).toBe(true);
313 expect(await sendToReview(app, repo, getPull(app.db, repo.id, pull.number)!)).toBe("wait");
314 const reviews = () => listRuns(app.db, repo.id, { kind: "agent" }).filter((r) => r.issueId === pull.id && r.reason === "review");
315 expect(reviews()).toEqual([]);
316 fillPull(app, agent, repo, getPull(app.db, repo.id, pull.number)!, { ...pull, kind: "issue", number: 1 }, "Daisies.");
317 expect(await sendToReview(app, repo, getPull(app.db, repo.id, pull.number)!)).toBe("sent");
318 expect(reviews().length).toBe(1);
319 }, 30_000);
320
321 describe("no door lands a draft: the merge path refuses it, whatever its review or check says", () => {
322 const url = () => standIn.servers.url;
323 const token = () => createToken(app.db, alice.id, "t", "rw").token;
324 const stillOpen = (pull: Pull) => {
325 const now = getPull(app.db, repo.id, pull.number)!;
326 return now.state === "open" && now.mergedAt === null;
327 };
328
329 test("the API refuses it with the sentence", async () => {
330 const pull = await earlyPull("bot/api", "Plant roses", true);
331 const res = await fetch(`${url()}/api/v1/repos/${repo.ownerName}/${repo.name}/pulls/${pull.number}/merge`, { method: "POST", headers: { authorization: `Bearer ${token()}`, "content-type": "application/json" }, body: "{}" });
332 expect(res.status).toBe(409);
333 expect(await res.json()).toMatchObject({ error: "draft", message: DRAFT_REFUSAL });
334 expect(stillOpen(pull)).toBe(true);
335 }, 30_000);
336
337 test("MCP's merge tool refuses it, merging or landing as it is, with the sentence", async () => {
338 const pull = await earlyPull("bot/mcp", "Plant tulips", true);
339 // Land as it is ships only on a green check: one asked for by hand is green here.
340 await standIn.checks.request(repo, `pull-${pull.number}`, pull.headOid, "manual", pull.id, alice.id);
341 expect(await waitFor(() => checksOf(pull).some((r) => r.state === "ok"))).toBe(true);
342 for (const action of [{}, { action: "land" }]) {
343 const res = await fetch(`${url()}/mcp`, { method: "POST", headers: { authorization: `Bearer ${token()}`, "content-type": "application/json", accept: "application/json, text/event-stream" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "tools/call", params: { name: "merge", arguments: { repo: `${repo.ownerName}/${repo.name}`, number: pull.number, dryRun: false, ...action } } }) });
344 expect(JSON.stringify(await res.json())).toContain(DRAFT_REFUSAL);
345 }
346 expect(stillOpen(pull)).toBe(true);
347 }, 30_000);
348
349 test("the web form refuses it with the sentence, and the terminal says the same words", async () => {
350 const pull = await earlyPull("bot/web", "Plant irises", true);
351 const cookie = `forge_session=${createSession(app.db, alice.id).token}`;
352 const res = await fetch(`${url()}/${repo.ownerName}/${repo.name}/pulls/${pull.number}/merge`, { method: "POST", redirect: "manual", headers: { cookie, origin: url(), "content-type": "application/x-www-form-urlencoded" }, body: "strategy=merge" });
353 expect(res.status).toBe(303);
354 expect(stillOpen(pull)).toBe(true);
355 expect(mergeFailure("draft")).toBe(DRAFT_REFUSAL);
356 expect(errorText("draft")).toBe(DRAFT_REFUSAL);
357 }, 30_000);
358
359 test("the merge queue's call and the owner's break-glass refuse it; filled in, it no longer reads as a draft", async () => {
360 const pull = await earlyPull("bot/queue", "Plant asters", true);
361 for (const opts of [{}, { pastReviews: true }, { pastGate: true }]) {
362 const queued = await mergePull(app, alice, repo, pull, "squash", undefined, opts);
363 expect(queued.ok ? "landed" : queued.error).toBe("draft");
364 }
365 expect(stillOpen(pull)).toBe(true);
366 fillPull(app, agent, repo, getPull(app.db, repo.id, pull.number)!, { ...pull, kind: "issue", number: 1 }, "Asters.");
367 const after = await mergePull(app, alice, repo, getPull(app.db, repo.id, pull.number)!, "squash");
368 expect(after.ok ? "landed" : after.error).not.toBe("draft");
369 }, 30_000);
370 });
371
372 describe("a draft is never locked: a run that ends or is gone readies it, and so does its admin", () => {
373 test("a crew run that ends without filling its draft in readies it, and its check runs", async () => {
374 const pull = await earlyPull("bot/run-ends", "Plant poppies", true, "agent");
375 expect(checksOf(pull)).toEqual([]);
376 finishRun(app.db, pull.draftRun!, { state: "failed", summary: "the agent died" });
377 announceRun(app, getRun(app.db, pull.draftRun!)!);
378 expect(await waitFor(() => !isDraft(getPull(app.db, repo.id, pull.number)!))).toBe(true);
379 expect(await waitFor(() => checksOf(pull).length > 0)).toBe(true);
380 }, 30_000);
381
382 test("the lease tick readies a draft whose run is gone, as after a crash, and only that one", async () => {
383 // Rows no worker here touches (the crew would end a crew run's row it is not running), so the
384 // lease tick alone can ready the one whose run is gone.
385 const gone = await earlyPull("bot/crashed", "Plant cosmos", true);
386 // A run still going, whose draft stays one.
387 const going = await earlyPull("bot/still-going", "Plant zinnias", true);
388 app.db.run("UPDATE run SET state = 'running' WHERE id = ?1", [going.draftRun!]);
389 // A forge that died under its run: the run's row is gone (or ended) with no event said.
390 app.db.run("DELETE FROM run WHERE id = ?1", [gone.draftRun!]);
391 expect(readyStranded(app)).toBeGreaterThanOrEqual(1);
392 expect(isDraft(getPull(app.db, repo.id, gone.number)!)).toBe(false);
393 expect(isDraft(getPull(app.db, repo.id, going.number)!)).toBe(true);
394 expect(await waitFor(() => checksOf(gone).length > 0)).toBe(true);
395 expect(readyStranded(app)).toBe(0);
396 }, 30_000);
397
398 test("the page says it is a draft, offers no Merge, and its admin's Mark ready readies it; anyone else is refused", async () => {
399 const pull = await earlyPull("bot/web-ready", "Plant peonies", true);
400 const page = async (who: User) => {
401 const res = await fetch(`${standIn.servers.url}/${repo.ownerName}/${repo.name}/pulls/${pull.number}`, { headers: { cookie: `forge_session=${createSession(app.db, who.id).token}` } });
402 return (await res.text()).replace(/\s+/g, " ");
403 };
404 const seen = await page(alice);
405 expect(seen).toContain(`<dt>Draft</dt><dd>${DRAFT_LINE.slice("Draft: ".length)}</dd>`);
406 expect(seen).not.toContain("Merge pull request");
407 expect(seen).toContain(`action="/${repo.ownerName}/${repo.name}/pulls/${pull.number}/ready"`);
408 const made = await createUser(app.db, { username: "wren", email: "[email protected]", origin: "seed", trusted: true, password: "a-good-passphrase" });
409 if (!made.ok) throw new Error(made.error);
410 expect(await page(made.value)).not.toContain("/ready");
411 const press = (who: User) =>
412 fetch(`${standIn.servers.url}/${repo.ownerName}/${repo.name}/pulls/${pull.number}/ready`, { method: "POST", redirect: "manual", headers: { cookie: `forge_session=${createSession(app.db, who.id).token}`, origin: standIn.servers.url, "content-type": "application/x-www-form-urlencoded" }, body: "" });
413 expect((await press(made.value)).status).not.toBe(303);
414 expect(isDraft(getPull(app.db, repo.id, pull.number)!)).toBe(true);
415 expect((await press(alice)).status).toBe(303);
416 expect(isDraft(getPull(app.db, repo.id, pull.number)!)).toBe(false);
417 expect(await waitFor(() => checksOf(pull).length > 0)).toBe(true);
418 expect(await page(alice)).not.toContain("<dt>Draft</dt>");
419 }, 30_000);
420
421 test("the API marks it ready for its admin, once; a token of someone else is refused", async () => {
422 const pull = await earlyPull("bot/api-ready", "Plant asters again", true);
423 const call = (userId: string) =>
424 fetch(`${standIn.servers.url}/api/v1/repos/${repo.ownerName}/${repo.name}/pulls/${pull.number}/ready`, { method: "POST", headers: { authorization: `Bearer ${createToken(app.db, userId, "t", "rw").token}` } });
425 const wren = await createUser(app.db, { username: "wren2", email: "[email protected]", origin: "seed", trusted: true, password: "a-good-passphrase" });
426 if (!wren.ok) throw new Error(wren.error);
427 expect((await call(wren.value.id)).status).not.toBe(200);
428 expect(isDraft(getPull(app.db, repo.id, pull.number)!)).toBe(true);
429 const done = await call(alice.id);
430 expect([done.status, await done.json()]).toEqual([200, { ready: true }]);
431 expect(isDraft(getPull(app.db, repo.id, pull.number)!)).toBe(false);
432 const again = await call(alice.id);
433 expect([again.status, ((await again.json()) as { error: string }).error]).toEqual([409, "not_draft"]);
434 expect(markReady(app, bot, repo, getPull(app.db, repo.id, pull.number)!).ok).toBe(false);
435 }, 30_000);
436
437 test("the terminal's pull screen says it is a draft, merges nothing, and D readies it for its admin", async () => {
438 const pull = await earlyPull("bot/tty-ready", "Plant lupins", true);
439 const drive = async (keys: string[]) => {
440 const terminal = headlessTerminal(160, 44);
441 const { app: tui, session } = createForgeApp(app, { sshUsername: alice.username, remoteAddress: "127.0.0.1", fingerprint: "SHA256:t", user: alice }, { terminal, exitHooks: false });
442 tui.start();
443 await settleApp(tui);
444 tui.push(pullScreen(session, tui.ctx, local(session, repo), pull.number));
445 await settleApp(tui);
446 const frames = [tui.screen.toText()];
447 for (const k of keys) {
448 terminal.feed(k);
449 await settleApp(tui);
450 frames.push(tui.screen.toText());
451 }
452 tui.stop();
453 return frames;
454 };
455 const [shown] = await drive([]);
456 expect(shown).toContain(DRAFT_LINE);
457 expect(shown).toContain("mark ready");
458 await drive(["m"]);
459 expect(isDraft(getPull(app.db, repo.id, pull.number)!)).toBe(true);
460 await drive(["D"]);
461 expect(isDraft(getPull(app.db, repo.id, pull.number)!)).toBe(false);
462 expect(await waitFor(() => checksOf(pull).length > 0)).toBe(true);
463 }, 30_000);
464 });
465 });
test/number-retired.test.ts +1
@@ -76,6 +76,7 @@ test("the pull heading marks its number with .num", () => {
7676 originHeadRepo: null,
7777 revertsPullId: null,
7878 variantGroup: null,
79 draftRun: null,
7980 };
8081 const head = String(changeHead({ app, auth: { user: undefined, scope: undefined, via: "none" } } as Ctx, repo, pull, null, undefined));
8182 expect(head).toContain('<h1>a pull <span class="num">#2</span></h1>');
test/pull-verdict.test.ts +3 −1
@@ -124,7 +124,7 @@ test("ready offers Go to merge beside the verdict on Files; conflicted offers Re
124124 });
125125
126126 const base: VerdictInput = {
127 merged: false, closed: false, onOrigin: false, mergeable: true, ahead: 1, conflicts: 0,
127 merged: false, closed: false, onOrigin: false, draft: false, mergeable: true, ahead: 1, conflicts: 0,
128128 baseBranch: "main", reviewGated: false, changesRequested: false, teamsHolding: 0,
129129 checksHeld: false, checkState: "ok", mayMerge: true,
130130 };
@@ -132,6 +132,8 @@ const base: VerdictInput = {
132132 test("verdictOf names what holds a pull, in the merge box's order", () => {
133133 const words = (o: Partial<VerdictInput>) => verdictOf({ ...base, ...o }, "/a/b/pulls/1").words;
134134 expect(words({})).toBe("Ready to land");
135 // A draft is said before anything about its diff, reviews or checks: none of it is final yet.
136 expect(words({ draft: true, reviewGated: true, checksHeld: true })).toBe("Draft: its build is still running.");
135137 expect(words({ reviewGated: true, changesRequested: true })).toBe("A reviewer asked for changes");
136138 expect(words({ reviewGated: true })).toBe("Waiting for a review");
137139 expect(words({ teamsHolding: 1 })).toBe("Waiting for a team's review");

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs