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

src/http/api.ts hands its largest route family to its own module, with the same answers #15375

Merged opened this

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

Merged

torque/forge:torque/15352-src-http-api-ts-hands-its-largest-route → main 0 commits fork

  • Merged. torque/15352-src-http-api-ts-hands-its-largest-route was merged into main as 7d4dfcf.

Review

Sign in to review this change.
4 files changed +1065 −917
src/http/api.ts +10 −915
@@ -8,23 +8,17 @@
88 * back to continue); errors are `{ error, message }`.
99 */
1010
11 import { pullWaitsFor } from "../flow/waits_for.ts";
1211 import { cursorRefusal, limitRefusal } from "../contract/page_query.ts";
1312 import { parseCursor, parseLimit } from "../contract/page_query.ts";
1413 import { noneMatch } from "./conditional.ts";
1514 import { queryTooLong, QUERY_TOO_LONG } from "../core/query_limit.ts";
1615 import { offeredRepoIds } from "../core/offered.ts";
17 import { parseAttestation } from "../core/attestation.ts";
1816 import { listAppReleases } from "../core/app_releases.ts";
1917 import { openapiHandler } from "../contract/served.ts";
2018 import { CHECK_ASKED } from "../actions/pull_ask_words.ts";
2119 import { liveOf } from "../perf/live.ts";
22 import { reviewWords } from "../actions/review_words.ts";
2320 import { growth, MAX_DAYS as MAX_GROWTH_DAYS } from "../core/growth.ts";
2421 import { CEILING_REFUSAL, PAUSE_REFUSAL, pausedUntil } from "../core/planner_pause.ts";
25 import { teamHoldRefusal } from "../core/teams_words.ts";
26 import { guardedRefusal } from "../crew/stranger.ts";
27 import { MAX_PASS, passOf } from "../actions/box_pass.ts";
2822 import { homeTruth } from "../system/home_truth.ts";
2923 import { upstreamFacts } from "../actions/upstream_follow.ts";
3024 import { FAMILY_WORDS } from "../actions/family_words.ts";
@@ -37,10 +31,9 @@ import { getProvenance, provenanceFacts } from "../core/provenance.ts";
3731 import { goldenPath } from "../apps/golden_path.ts";
3832 import { NOT_A_MEMBER } from "../core/roles.ts";
3933 import { storageLimitMessage } from "../core/storage.ts";
40 import { voteVariant } from "../actions/variants.ts";
4134 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../core/route_timing.ts";
4235 import { readFlow } from "../flow/read.ts";
43 import { MILESTONE_WATCH_PERSON_ONLY, VOTE_NOT_RECORDED } from "../actions/board_words.ts";
36 import { MILESTONE_WATCH_PERSON_ONLY } from "../actions/board_words.ts";
4437 import { recordDrill } from "../core/domain_drills.ts";
4538 import { drillVerdict } from "../kernel/domain_drill.ts";
4639 import { DOMAINS } from "../kernel/domains.ts";
@@ -86,11 +79,6 @@ import { countRead } from "../system/telemetry_reads.ts";
8679 import { historyFor, sourcesOut, systemWithReaders, welcome } from "../system/telemetry.ts";
8780 import { weekCard, WEEK_DAYS } from "../crew/week_card.ts";
8881 import { markReaders } from "../crew/direct.ts";
89 import {
90 addCommentThrough,
91 PLANNER_REFUSALS,
92 setIssueStateThrough,
93 } from "../actions/issues.ts";
9482 import {
9583 reattachMirror,
9684 syncRepoNow,
@@ -105,27 +93,6 @@ import {
10593 contribute,
10694 type ContributeResult,
10795 } from "../actions/contribute.ts";
108 import {
109 addReview,
110 anchorId,
111 mergePull,
112 openPull,
113 pullThreads,
114 refreshPullHead,
115 resolveReviewThread,
116 submitReview,
117 approveToRun,
118 MAX_REVIEW_LINES,
119 type ReviewInput,
120 } from "../actions/pulls.ts";
121 import { landSlice } from "../actions/pull_slices.ts";
122 import { attachLook } from "../actions/attach_look.ts";
123 import { reviewSteps, setReviewSteps } from "../actions/review_steps.ts";
124 import { stepsWords } from "../core/review_steps.ts";
125 import { lookUrl } from "../core/looks.ts";
126 import { pullFit, pullLooks } from "../looks/readable.ts";
127 import { holdPull, releasePull } from "../actions/holds.ts";
128 import { getHold, type Hold } from "../core/holds.ts";
12996 import { watchMilestone } from "../actions/watches.ts";
13097 import { THOUGHT_MAX, keepThought } from "../actions/thought.ts";
13198 import { SEARCH_LIMIT_MAX, search, searchRefusal, searchWithin, type SearchPhase } from "../actions/search.ts";
@@ -171,12 +138,7 @@ import {
171138 } from "../core/issues.ts";
172139 import {
173140 getPull,
174 listPulls,
175 variantSiblings,
176 pullDiff,
177 pullStatus,
178141 pullDir,
179 pullMergeStates,
180142 type Pull,
181143 } from "../core/pulls.ts";
182144 import {
@@ -195,22 +157,7 @@ import {
195157 } from "../core/repos.ts";
196158 import { CODE_BUDGET_MS, greppable, searchKind, searchNote } from "../core/search.ts";
197159 import { strangerCodeSearch } from "./strangers.ts";
198 import {
199 isReviewState,
200 listReviewComments,
201 listReviews,
202 withOutdated,
203 } from "../core/reviews.ts";
204 import { mintProposal } from "../actions/proposal_tokens.ts";
205 import {
206 headInNamespace,
207 PROPOSAL_BODY_MAX,
208 pullProposalOf,
209 recordPullProposal,
210 } from "../core/proposal_token.ts";
211 import { capWords, headInContribNamespace, inTurn, pullCapReached } from "../core/contribute_token.ts";
212160
213 import { takesOutside } from "../actions/contribute_token.ts";
214161 import { contributeMint } from "./api/contribute_token.ts";
215162 import {
216163 getUserByName,
@@ -252,7 +199,7 @@ import {
252199 crewAsSeen,
253200 removeFromCrew,
254201 } from "../actions/crew.ts";
255 import { assignIssue, editIssue, TAKEN_UP } from "../actions/issues.ts";
202 import { assignIssue, TAKEN_UP } from "../actions/issues.ts";
256203 import { requireReader } from "../actions/access.ts";
257204 import { gatesForReader, looksOfCheck, mayReadRunLog, mayReadRuns, runsViewKey, steerRepoRun } from "../actions/runs.ts";
258205 import { openPlan, parsePlan, proposePlan } from "../actions/plan.ts";
@@ -283,22 +230,19 @@ import {
283230 takeBackLimb,
284231 } from "../actions/limb_replan.ts";
285232 import { appsRuntime, envsFor, type AppsRuntime } from "../apps/runtime.ts";
286 import { isEnvName, previewEnv } from "../apps/data.ts";
287 import { checkWord } from "../apps/check_word.ts";
233 import { isEnvName } from "../apps/data.ts";
288234 import { getAppByRepo } from "../core/apps.ts";
289 import { crewRole, isCrew, type Agent } from "../core/agents.ts";
235 import { isCrew, type Agent } from "../core/agents.ts";
290236 import { listApps, type AppRecord } from "../core/apps.ts";
291237 import {
292 checkSummary,
293238 checksForHead,
294239 getRun,
295240 isTerminal,
296 latestRunsForIssues,
297241 RUN_STATES,
298242 type ListRunsOptions,
299243 type Run,
300244 } from "../core/runs.ts";
301 import { CHECK_STALE_REFUSAL, checkStale } from "../checks/stale.ts";
245 import { CHECK_STALE_REFUSAL } from "../checks/stale.ts";
302246 import { resolveOid } from "../git/merge.ts";
303247 import { readForgeUsage, readUsage, usageDays, USAGE_DAYS_MAX } from "../actions/usage.ts";
304248 import { readReturns, reportSpend, RETURNS_DAYS } from "../actions/returns.ts";
@@ -309,7 +253,7 @@ import { carriedFor } from "../core/carried.ts";
309253 import { readGateLog } from "../checks/gate_log.ts";
310254 import { recentGates } from "../checks/gate_result.ts";
311255 import { readRunLog, subscribeRunLog } from "../runs/log.ts";
312 import { blobForRender, commitLog, listRefs, listTree, refTip } from "../git/read.ts";
256 import { blobForRender, commitLog, listRefs, listTree } from "../git/read.ts";
313257 import { repoDir } from "../git/repos.ts";
314258 import { holds, weakEtag } from "./etag.ts";
315259 import { carriedPulls, inLandingOrder, pullPath } from "../story/wave_pulls.ts";
@@ -428,6 +372,7 @@ import { secretRoutes } from "./api/secrets.ts";
428372 import { drillRoutes } from "./api/drills.ts";
429373 import { featureRoutes } from "./api/features.ts";
430374 import { upstreamRoutes } from "./api/upstream.ts";
375 import { pullRoutes } from "./api/pulls.ts";
431376 import type { Router } from "./router.ts";
432377 import { clientAddress } from "./peer.ts";
433378 import { INVALID_TOKEN_HINT, INVALID_TOKEN_WORDS, manifestFor, registeredPageManifest } from "../actions/here.ts";
@@ -437,7 +382,7 @@ import { egressMetrics } from "../apps/egress_metrics.ts";
437382 import { forgeMetrics } from "../metrics/forge.ts";
438383 import { appSources } from "../metrics/app_sources.ts";
439384 import { ADMIN_WORDS } from "../actions/admin_words.ts";
440 import { ANSWER_WORDS, ORDER_WORDS, VISIBILITY_WORDS } from "../core/arg_words.ts";
385 import { ORDER_WORDS, VISIBILITY_WORDS } from "../core/arg_words.ts";
441386 import { censusReport } from "../perf/heap_census.ts";
442387
443388 /** Take the parent's updates for `repo` and answer as the API does, for every route that asks. */
@@ -827,34 +772,6 @@ function editFailure(error: { kind: string } & Record<string, unknown>) {
827772 * The files of an edit, out of a JSON body. `content: null` deletes; a
828773 * `base64` encoding is how a client sends bytes that are not text.
829774 */
830 /**
831 * How a line comment is anchored, said the same way by every refusal of
832 * one — the sentence a reviewer reads to send it right the second time.
833 */
834 const ANCHOR_FORMAT =
835 'An anchor is {"path": a file in the pull\'s diff, "line": its line number, "side": "new" (the head\'s numbering, for added or kept lines) or "old" (the base\'s, for removed lines)}; the line must be inside one of the diff\'s hunks: in `@@ -a,b +c,d @@` the hunk\'s first line is c on the new side and a on the old. GET …/pulls/N returns the diff.';
836
837 /**
838 * A review's line comments as the API was sent them; undefined when they are not a list of objects.
839 */
840 function reviewLines(raw: unknown): ReviewInput[] | undefined {
841 if (raw === undefined || raw === null) return [];
842 // The cap is `submitReview`'s to refuse, by name (`too_many_lines`).
843 if (!Array.isArray(raw)) return undefined;
844 const out: ReviewInput[] = [];
845 for (const row of raw) {
846 if (typeof row !== "object" || row === null) return undefined;
847 const r = row as Record<string, unknown>;
848 out.push({
849 path: str(r.path),
850 line: Number(r.line),
851 side: r.side === "old" ? "old" : "new",
852 body: str(r.body),
853 });
854 }
855 return out;
856 }
857
858775 export function editFilesFrom(raw: unknown): EditFile[] {
859776 if (!Array.isArray(raw)) return [];
860777 const files: EditFile[] = [];
@@ -1165,12 +1082,8 @@ async function pullHeadOid(ctx: Ctx, repo: Repo, pull: Pull): Promise<string> {
11651082 return (await resolveOid(await pullDirOf(ctx, repo, pull), ref)) ?? pull.headOid;
11661083 }
11671084
1168 /** A branch's tip from its ref file (no process); git is asked only when that cannot be read. */
1169 const baseTip = async (dir: string, ref: string): Promise<string | undefined> =>
1170 (await refTip(dir, ref)) ?? (await resolveOid(dir, ref));
1171
11721085 /** Where a pull's objects are (`pullDir`): its base, or a sealed one's own place. */
1173 const pullDirOf = (ctx: Ctx, repo: Repo, pull: Pull): Promise<string> =>
1086 export const pullDirOf = (ctx: Ctx, repo: Repo, pull: Pull): Promise<string> =>
11741087 pullDir(ctx.app.db, ctx.app.reposRoot, repo, pull);
11751088
11761089 export function positiveInt(raw: string | undefined): number | undefined {
@@ -1220,14 +1133,6 @@ export function loadConversation(ctx: Ctx): Found<{ issue: Issue }> {
12201133 return { repo, issue };
12211134 }
12221135
1223 /** A hold as the API says it: who, why and since when. */
1224 const holdJson = (hold: Hold) => ({
1225 by: hold.heldByName,
1226 why: hold.why,
1227 at: hold.heldAt,
1228 ...(hold.until ? { until: hold.until } : {}),
1229 });
1230
12311136 export function loadPull(ctx: Ctx): Found<{ pull: Pull }> {
12321137 const repo = loadRepo(ctx);
12331138 if (!repo) return { error: notFound() };
@@ -2701,817 +2606,7 @@ export function apiRoutes(router: Router<Handler>, isPage: (path: string) => boo
27012606 return timePhase(ctx.request, "render", () => json(read));
27022607 });
27032608
2704 // ── pull requests — so automation drives the review/merge loop ───────
2705
2706 router.add("GET", "/api/v1/repos/:owner/:name/pulls", async (ctx) => {
2707 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
2708 const repo = loadRepo(ctx);
2709 if (!repo) return notFound();
2710 const query = listQuery(ctx);
2711 if (query instanceof Response) return query;
2712 const pulls = timePhase(ctx.request, "list", () =>
2713 listPulls(ctx.app.db, repo.id, {
2714 ...query,
2715 ...sealedScope(ctx.app.db, repo, ctx.auth.user),
2716 }),
2717 );
2718 const states = await timePhaseAsync(ctx.request, "merge", async () =>
2719 pullMergeStates(
2720 await Promise.all(
2721 pulls.map(async (p) => ({ dir: await pullDirOf(ctx, repo, p), pull: p })),
2722 ),
2723 ),
2724 );
2725 const items = timePhase(ctx.request, "labels", () => {
2726 const siblings = variantSiblings(ctx.app.db, pulls);
2727 // The check word and preview address the pull page shows, so a client
2728 // lists "where to try it" without a request per pull.
2729 const checks = latestRunsForIssues(ctx.app.db, pulls.map((p) => p.id));
2730 // An address only where the pull page's preview card shows one: the
2731 // environments `envsFor` hands this viewer (a private app shows none).
2732 const record = getAppByRepo(ctx.app.db, repo.id);
2733 const runtime = record === undefined ? undefined : appsRuntime(ctx.app);
2734 const live = new Set(
2735 record === undefined ? [] : envsFor(ctx.app, ctx.auth.user, record).map((e) => e.env),
2736 );
2737 return withLabelsMany(ctx, pulls).map((item, i) => ({
2738 ...item,
2739 author: item.originAuthor ?? item.authorName,
2740 check: checkWord(checks.get(item.id), item.headOid),
2741 preview:
2742 record !== undefined && runtime !== undefined && item.state === "open" && item.mergedAt === null && live.has(previewEnv(item.number))
2743 ? runtime.urlFor(record, previewEnv(item.number))
2744 : null,
2745 variantSiblings: siblings[i] ?? [],
2746 ...(states[i] ?? {}),
2747 }));
2748 });
2749 // The tag is of the exact bytes sent, so a new verdict, head or state is never hidden behind a
2750 // 304; the page, state, limit, cursor and fields are in the body or the query that chose it.
2751 return timePhase(ctx.request, "render", () => {
2752 const text = JSON.stringify(paged(items, query.limit, (p) => p.number));
2753 const etag = weakEtag(text);
2754 const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" };
2755 if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers });
2756 return new Response(text, { headers: { "content-type": "application/json", ...headers } });
2757 });
2758 });
2759
2760 // A writer hands a child its own narrow credential for this repository
2761 // (`core/proposal_token.ts`); the secret is shown once, as for any token.
2762 router.add(
2763 "POST",
2764 "/api/v1/repos/:owner/:name/proposal-tokens",
2765 async (ctx) => {
2766 const denied = requireScope(ctx, "rw");
2767 if (denied) return denied;
2768 const repo = loadRepo(ctx);
2769 if (!repo || !canWrite(ctx.app.db, repo, ctx.auth.user)) return notFound();
2770 const input = await boundedBody(ctx.request, PROPOSAL_BODY_MAX);
2771 if (input === "too_large")
2772 return apiError("too_large", 413, `at most ${PROPOSAL_BODY_MAX} bytes`);
2773 const minted = mintProposal(ctx.app, ctx.auth.user, repo, {
2774 child: str(input.child),
2775 origin: str(input.origin),
2776 childRepo: str(input.childRepo),
2777 });
2778 if (!minted.ok)
2779 return minted.error.code === "not_found" ? notFound() : apiError(minted.error.code, 422, minted.error.message);
2780 return json(minted.value, 201);
2781 },
2782 );
2783
2784 router.add("POST", "/api/v1/repos/:owner/:name/pulls", async (ctx) => {
2785 const denied = requireScope(ctx, "rw");
2786 if (denied) return denied;
2787 const repo = loadRepo(ctx);
2788 if (!repo) return notFound();
2789 // An outside agent's token opens a pull from its own contrib/<agent>/… branch of this
2790 // repository, never from another repository, and never past what it was minted for.
2791 const outside = ctx.auth.contribute;
2792 if (outside !== undefined && (outside.repoId !== repo.id || !takesOutside(ctx.app, repo))) return forbidden();
2793 // A proposal token's body is small, and its pull comes from a branch of
2794 // its own child's namespace in this repository, never from another one.
2795 const proposal = ctx.auth.proposal;
2796 // The gate already pins a proposal token to its repository; this
2797 // repeats it so the handler is safe on its own (defense in depth).
2798 if (proposal !== undefined && proposal.repoId !== repo.id) return forbidden();
2799 const input =
2800 proposal === undefined
2801 ? await body(ctx.request)
2802 : await boundedBody(ctx.request, PROPOSAL_BODY_MAX);
2803 if (input === "too_large")
2804 return apiError("too_large", 413, `at most ${PROPOSAL_BODY_MAX} bytes`);
2805 if (
2806 outside !== undefined &&
2807 (str(input.headRepo) !== "" || !headInContribNamespace(str(input.head), outside.namespace))
2808 )
2809 return apiError(
2810 "invalid_head",
2811 422,
2812 `a contribute pull comes from a contrib/${outside.namespace}/… branch of this repository`,
2813 );
2814 if (
2815 proposal !== undefined &&
2816 (str(input.headRepo) !== "" ||
2817 !headInNamespace(str(input.head), proposal.child))
2818 )
2819 return apiError(
2820 "invalid_head",
2821 422,
2822 `a proposal pull comes from a child/${proposal.child}/… branch of this repository`,
2823 );
2824 // What the child says it proved: a verdict and a tree id, or nothing. Shown beside the
2825 // pull, never admitted on (#13645); only a proposal may send one.
2826 const attested = proposal === undefined ? undefined : parseAttestation(input.attestation);
2827 if (attested === "invalid")
2828 return apiError(
2829 "invalid_attestation",
2830 422,
2831 "an attestation is { verdict: green|red|pending|none, tree: <40 or 64 hex> }",
2832 );
2833 // `headRepo: "owner/name"` proposes a fork's branch into this base.
2834 let headRepo: Repo | undefined;
2835 const headSpec = str(input.headRepo);
2836 if (headSpec !== "") {
2837 const [owner, name, ...rest] = headSpec.split("/");
2838 headRepo =
2839 owner && name && rest.length === 0
2840 ? getRepo(ctx.app.db, owner, name)
2841 : undefined;
2842 if (!headRepo) return notFound();
2843 // A crew run's head comes from its own two repositories, never another
2844 // fork the crew member can read (defense in depth past the run gate).
2845 const run = ctx.auth.run;
2846 if (run !== undefined && headRepo.id !== run.forkId && headRepo.id !== run.repoId)
2847 return notFound();
2848 }
2849 // An outside agent opens a few pulls: each starts checks and a preview on the
2850 // owner's repository. Counted from the pull rows, one open at a time per token.
2851 const open = () =>
2852 openPull(ctx.app, ctx.auth.user!, repo, {
2853 title: str(input.title),
2854 body: str(input.body),
2855 baseBranch: str(input.base),
2856 headBranch: str(input.head),
2857 ...(headRepo ? { headRepo } : {}),
2858 // A person's deliberate yes to fixing a sealed report from a public branch.
2859 ...(input.confirmPublic === true ? { confirmPublic: true } : {}),
2860 ...(outside === undefined ? {} : { outsideAgent: true }),
2861 });
2862 // An outside token opens one pull at a time (the same turn a push's opens take),
2863 // its caps read inside the turn so the count cannot be raced.
2864 const opening =
2865 outside === undefined
2866 ? await open()
2867 : await inTurn(ctx.auth.user!.id, async () => {
2868 const capped = pullCapReached(ctx.app.db, repo.id, ctx.auth.user!.id, new Date());
2869 return capped ?? (await open());
2870 });
2871 if (typeof opening === "string") return tryAgain("rate_limited", 429, capWords(opening), 3600);
2872 const created = opening;
2873 if (!created.ok && created.error === "sealed_in_public")
2874 return apiError(
2875 "sealed_in_public",
2876 422,
2877 "this fixes a sealed report from a public branch: push it to your private repository (POST …/issues/<n>/private) and open the pull from there, or send confirmPublic: true",
2878 );
2879 if (!created.ok)
2880 return created.error === "origin_owner_only" ||
2881 created.error === "origin_refused" ||
2882 created.error === "origin_unreachable"
2883 ? originAware(created.error)
2884 : respondAccess(created.error, 422);
2885 if (proposal !== undefined)
2886 recordPullProposal(ctx.app.db, created.value.id, proposal, attested);
2887 return json(
2888 {
2889 ...withLabels(ctx, created.value),
2890 variantSiblings: variantSiblings(ctx.app.db, [created.value])[0] ?? [],
2891 ...(proposal
2892 ? { proposal: { child: proposal.child, origin: proposal.origin, ...(attested ? { attestation: attested } : {}) } }
2893 : {}),
2894 },
2895 201,
2896 );
2897 });
2898
2899 router.add("GET", "/api/v1/repos/:owner/:name/pulls/:number", async (ctx) => {
2900 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
2901 const found = timePhase(ctx.request, "pull", () => loadPull(ctx));
2902 if ("error" in found) return found.error;
2903 // `?diff=0` reads the pull without its diff, and skips computing it.
2904 const wantDiff = ctx.url.searchParams.get("diff");
2905 if (wantDiff !== null && wantDiff !== "0" && wantDiff !== "1")
2906 return apiError("invalid_diff", 422, "diff is 0 or 1");
2907 // A fork may have pushed since the pull opened; review what is being
2908 // proposed now, not the snapshot taken when it was.
2909 await timePhaseAsync(ctx.request, "head", () =>
2910 refreshPullHead(ctx.app, found.repo, found.pull),
2911 );
2912 // Include the diff so a reviewer (human or agent) reads the change without
2913 // a second round trip, and the review gate beside it so a client knows
2914 // whether merging is even on offer.
2915 const gate = { db: ctx.app.db, requireReview: found.repo.requireReview };
2916 const { status, diff } = await timePhaseAsync(ctx.request, "diff", async () => {
2917 const dir = await pullDirOf(ctx, found.repo, found.pull);
2918 return wantDiff === "0"
2919 ? { status: await pullStatus(dir, found.pull, gate), diff: undefined }
2920 : await pullDiff(dir, found.pull, gate);
2921 });
2922 const live = found.pull.state === "open" && found.pull.mergedAt === null;
2923 const checkStaleNow = await timePhaseAsync(
2924 ctx.request,
2925 "checks",
2926 async () =>
2927 live &&
2928 checkStale(
2929 checkSummary(ctx.app.db, found.pull.id, status.headOid).run,
2930 await baseTip(await pullDirOf(ctx, found.repo, found.pull), `refs/heads/${found.pull.baseBranch}`),
2931 ),
2932 );
2933 return timePhase(ctx.request, "render", () => {
2934 const hold = getHold(ctx.app.db, found.pull.id);
2935 const checked = checkSummary(ctx.app.db, found.pull.id, status.headOid).run;
2936 const text = JSON.stringify({
2937 ...withLabels(ctx, found.pull),
2938 check: checkWord(checked ?? undefined, status.headOid),
2939 checkStale: checkStaleNow,
2940 // The base tip the head's check merged with; null before any check
2941 // recorded one. Beside `checkStale` it names which main was tested.
2942 checkedAgainst: checked !== null && checked.baseOid !== "" ? checked.baseOid : null,
2943 // The approval and what it was given for; `current` is false once the head or the base
2944 // moved.
2945 approvedAt: status.reviews?.approval ?? null,
2946 variantSiblings: variantSiblings(ctx.app.db, [found.pull])[0] ?? [],
2947 ...(live ? { mergeable: status.mergeable, conflicts: status.conflicts } : {}),
2948 proposal: pullProposalOf(ctx.app.db, found.pull.id) ?? null,
2949 status,
2950 ...(diff === undefined ? {} : { diff }),
2951 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,
2956 });
2957 // Tagged by the exact bytes sent, after access was checked: a new head, verdict, review or
2958 // merge is never hidden behind a 304.
2959 const etag = weakEtag(text);
2960 const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" };
2961 if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers });
2962 return new Response(text, { headers: { "content-type": "application/json", ...headers } });
2963 });
2964 });
2965
2966 router.add(
2967 "PATCH",
2968 "/api/v1/repos/:owner/:name/pulls/:number",
2969 async (ctx) => {
2970 const denied = requireScope(ctx, "rw");
2971 if (denied) return denied;
2972 const found = loadPull(ctx);
2973 if ("error" in found) return found.error;
2974 const input = await body(ctx.request);
2975 // The same two halves as an issue's PATCH: words, then state.
2976 const text = textFrom(input);
2977 if (text === undefined) return json({ error: "invalid_text" }, 422);
2978 const wanted = input.state === undefined ? undefined : str(input.state);
2979 if (wanted !== undefined && wanted !== "open" && wanted !== "closed")
2980 return json({ error: "invalid_state" }, 422);
2981 // A pull has no reason to give: "parked" is the crew's word alone.
2982 if (input.reason !== undefined || input.into !== undefined)
2983 return json({ error: "invalid_reason" }, 422);
2984 if (
2985 wanted === undefined &&
2986 text.title === undefined &&
2987 text.body === undefined
2988 )
2989 return NOTHING_TO_CHANGE();
2990 if (text.title !== undefined || text.body !== undefined) {
2991 const edited = editIssue(
2992 ctx.app,
2993 ctx.auth.user,
2994 found.repo,
2995 found.pull,
2996 text,
2997 );
2998 if (!edited.ok)
2999 return edited.error === "taken_up"
3000 ? takenUp()
3001 : originAware(edited.error, 422);
3002 }
3003 if (wanted !== undefined) {
3004 const changed = await setIssueStateThrough(
3005 ctx.app,
3006 ctx.auth.user,
3007 found.repo,
3008 getPull(ctx.app.db, found.repo.id, found.pull.number)!,
3009 wanted,
3010 );
3011 if (!changed.ok) {
3012 // A planner told no learns the one rule it works by.
3013 if (
3014 changed.error === "forbidden" &&
3015 wanted === "closed" &&
3016 crewRole(ctx.app.db, found.repo.id, ctx.auth.user!.id) === "planner"
3017 )
3018 return apiError(
3019 "forbidden",
3020 403,
3021 PLANNER_REFUSALS.pull,
3022 );
3023 return originAware(changed.error, 409);
3024 }
3025 }
3026 return json(
3027 withLabels(ctx, getPull(ctx.app.db, found.repo.id, found.pull.number)!),
3028 );
3029 },
3030 );
3031
3032 // Hold a pull, or let it go (`actions/holds.ts`): a person who writes the
3033 // repository says "not this one yet", and no rule sends it to review or
3034 // lands it until it is released. A person's own merge is untouched.
3035 router.add(
3036 "PUT",
3037 "/api/v1/repos/:owner/:name/pulls/:number/hold",
3038 async (ctx) => {
3039 const denied = requireScope(ctx, "rw");
3040 if (denied) return denied;
3041 const found = loadPull(ctx);
3042 if ("error" in found) return found.error;
3043 const input = await body(ctx.request);
3044 if (input.until !== undefined && input.until !== "green")
3045 return respondAccess("bad_until", 422);
3046 const held = holdPull(
3047 ctx.app,
3048 ctx.auth.user,
3049 found.repo,
3050 found.pull,
3051 str(input.why),
3052 false,
3053 input.until === "green" ? "green" : undefined,
3054 );
3055 if (!held.ok)
3056 return respondAccess(held.error, held.error === "not_open" ? 409 : 422);
3057 return json({ held: true, hold: holdJson(held.value) });
3058 },
3059 );
3060 router.add(
3061 "DELETE",
3062 "/api/v1/repos/:owner/:name/pulls/:number/hold",
3063 (ctx) => {
3064 const denied = requireScope(ctx, "rw");
3065 if (denied) return denied;
3066 const found = loadPull(ctx);
3067 if ("error" in found) return found.error;
3068 const released = releasePull(
3069 ctx.app,
3070 ctx.auth.user,
3071 found.repo,
3072 found.pull,
3073 );
3074 if (!released.ok) return respondAccess(released.error, 422);
3075 return json({ held: false, released: released.value });
3076 },
3077 );
3078
3079 router.add(
3080 "POST",
3081 "/api/v1/repos/:owner/:name/pulls/:number/merge",
3082 async (ctx) => {
3083 const denied = requireScope(ctx, "rw");
3084 if (denied) return denied;
3085 const found = loadPull(ctx);
3086 if ("error" in found) return found.error;
3087 const input = await body(ctx.request);
3088 const strategy = str(input.strategy) === "squash" ? "squash" : "merge";
3089 const merged = await mergePull(
3090 ctx.app,
3091 ctx.auth.user,
3092 found.repo,
3093 found.pull,
3094 strategy,
3095 );
3096 if (!merged.ok) {
3097 if (typeof merged.error !== "string")
3098 return merged.error.kind === "guarded"
3099 ? json({ error: "guarded", message: guardedRefusal(merged.error.paths), paths: merged.error.paths }, 409)
3100 : merged.error.kind === "team_review_required"
3101 ? json({ error: merged.error.kind, message: teamHoldRefusal(merged.error.teams), teams: merged.error.teams }, 409)
3102 : json({ error: merged.error.kind }, 409);
3103 return originAware(merged.error, 409);
3104 }
3105 return json({ merged: true, ...merged.value });
3106 },
3107 );
3108
3109 // Land the author's commits up to `upTo` as their own merge commit (#9010).
3110 router.add(
3111 "POST",
3112 "/api/v1/repos/:owner/:name/pulls/:number/slices",
3113 async (ctx) => {
3114 const denied = requireScope(ctx, "rw");
3115 if (denied) return denied;
3116 const found = loadPull(ctx);
3117 if ("error" in found) return found.error;
3118 const input = await body(ctx.request);
3119 const landed = await landSlice(
3120 ctx.app,
3121 ctx.auth.user,
3122 found.repo,
3123 found.pull,
3124 str(input.upTo),
3125 );
3126 if (!landed.ok) {
3127 if (typeof landed.error !== "string")
3128 return json({ error: landed.error.kind }, 409);
3129 if (landed.error === "bad_slice" || landed.error === "sealed" || landed.error === "not_fork")
3130 return json({ error: landed.error }, 422);
3131 if (landed.error === "held") return json({ error: "held" }, 409);
3132 return originAware(landed.error, 409);
3133 }
3134 return json(landed.value);
3135 },
3136 );
3137
3138 router.add(
3139 "POST",
3140 "/api/v1/repos/:owner/:name/pulls/:number/comments",
3141 async (ctx) => {
3142 const denied = requireScope(ctx, "rw");
3143 if (denied) return denied;
3144 const found = loadPull(ctx);
3145 if ("error" in found) return found.error;
3146 const input = await body(ctx.request);
3147 const added = await addCommentThrough(
3148 ctx.app,
3149 ctx.auth.user,
3150 found.repo,
3151 found.pull,
3152 str(input.body),
3153 );
3154 if (!added.ok) return originAware(added.error);
3155 return json(added.value, 201);
3156 },
3157 );
3158
3159 // Attach a look: a picture a person took, at a stated width, with one line
3160 // saying what it shows (`actions/attach_look.ts`). The picture is base64
3161 // in the JSON body; the crew's own looks keep their path through the
3162 // preview.
3163 router.add(
3164 "POST",
3165 "/api/v1/repos/:owner/:name/pulls/:number/looks",
3166 async (ctx) => {
3167 const denied = requireScope(ctx, "rw");
3168 if (denied) return denied;
3169 const found = loadPull(ctx);
3170 if ("error" in found) return found.error;
3171 const input = await body(ctx.request);
3172 const attached = attachLook(
3173 ctx.app,
3174 ctx.auth.user,
3175 found.repo,
3176 found.pull,
3177 { width: str(input.width), note: str(input.says), image: str(input.image) },
3178 );
3179 if (!attached.ok)
3180 return respondAccess(
3181 attached.error,
3182 attached.error === "too_large"
3183 ? 413
3184 : attached.error === "not_open" || attached.error === "no_app"
3185 ? 409
3186 : 422,
3187 );
3188 const look = attached.value;
3189 return json(
3190 {
3191 id: look.id,
3192 width: look.kind,
3193 says: look.note,
3194 by: look.attachedBy,
3195 commit: look.commitOid,
3196 url: lookUrl(`/${found.repo.ownerName}/${found.repo.name}`, look),
3197 },
3198 201,
3199 );
3200 },
3201 );
3202
3203 // A pull's looks, newest first, from its own preview environment and only
3204 // the ones this reader may fetch as a picture (`looks/readable.ts`).
3205 router.add(
3206 "GET",
3207 "/api/v1/repos/:owner/:name/pulls/:number/looks",
3208 (ctx) => {
3209 const found = loadPull(ctx);
3210 if ("error" in found) return found.error;
3211 const items = pullLooks(ctx.app, found.repo, found.pull, ctx.auth.user);
3212 const fit = pullFit(ctx.app, found.repo, found.pull, ctx.auth.user);
3213 return json({ items, fit });
3214 },
3215 );
3216
3217 // A pull's review script (#13653): the steps that take a reviewer, person or agent, into the
3218 // preview at the place to test, each with the absolute address of its page.
3219 router.add("GET", "/api/v1/repos/:owner/:name/pulls/:number/review", (ctx) => {
3220 const found = loadPull(ctx);
3221 if ("error" in found) return found.error;
3222 return json({ items: reviewSteps(ctx.app, ctx.auth.user, found.repo, found.pull) });
3223 });
3224
3225 // Set it: a writer's, on an open pull; the steps replace the ones it had.
3226 router.add("PUT", "/api/v1/repos/:owner/:name/pulls/:number/review", async (ctx) => {
3227 const denied = requireScope(ctx, "rw");
3228 if (denied) return denied;
3229 const found = loadPull(ctx);
3230 if ("error" in found) return found.error;
3231 const input = await body(ctx.request);
3232 const set = setReviewSteps(ctx.app, ctx.auth.user, found.repo, found.pull, input.steps);
3233 if (!set.ok) {
3234 const e = set.error;
3235 if (e === "unauthorized" || e === "forbidden" || e === "not_found") return respondAccess(e, 422);
3236 return json({ error: e === "not_open" ? e : "invalid_steps", message: e === "not_open" ? "the pull is not open" : stepsWords(e) }, e === "not_open" ? 409 : 422);
3237 }
3238 return json({ items: reviewSteps(ctx.app, ctx.auth.user, found.repo, found.pull) });
3239 });
3240
3241 // Line-anchored review comments. The anchor is (path, side, line) in the
3242 // pull's current diff; the server takes the content hash, so a client never
3243 // handles one — and a later force-push marks the comment `outdated`.
3244 router.add(
3245 "GET",
3246 "/api/v1/repos/:owner/:name/pulls/:number/reviews",
3247 async (ctx) => {
3248 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
3249 const found = loadPull(ctx);
3250 if ("error" in found) return found.error;
3251 const marked = await timePhaseAsync(ctx.request, "reviews", async () => {
3252 const { diff } = await pullDiff(
3253 await pullDirOf(ctx, found.repo, found.pull),
3254 found.pull,
3255 );
3256 return withOutdated(
3257 readerMarked(
3258 ctx,
3259 found.repo.id,
3260 listReviewComments(ctx.app.db, found.pull.id),
3261 ),
3262 diff,
3263 );
3264 });
3265 return timePhase(ctx.request, "render", () =>
3266 json(
3267 marked.map(
3268 // The thread this comment belongs to, so a client can resolve it
3269 // without reassembling the key itself.
3270 (comment) => ({
3271 ...comment,
3272 anchor: anchorId(comment.path, comment.side, comment.line),
3273 }),
3274 ),
3275 ),
3276 );
3277 },
3278 );
3279
3280 router.add(
3281 "POST",
3282 "/api/v1/repos/:owner/:name/pulls/:number/reviews",
3283 async (ctx) => {
3284 const denied = requireScope(ctx, "rw");
3285 if (denied) return denied;
3286 const found = loadPull(ctx);
3287 if ("error" in found) return found.error;
3288 const input = await body(ctx.request);
3289 const side = input.side === "old" ? "old" : "new";
3290 const added = await addReview(
3291 ctx.app,
3292 ctx.auth.user,
3293 found.repo,
3294 found.pull,
3295 {
3296 body: str(input.body),
3297 path: str(input.path),
3298 line: Number(input.line),
3299 side,
3300 },
3301 );
3302 if (!added.ok) {
3303 // A verdict sent here is the call this route most often gets wrong.
3304 if (added.error === "bad_anchor" && input.state !== undefined)
3305 return apiError(
3306 "bad_anchor",
3307 422,
3308 `this route takes one line comment; a verdict goes to …/review-states as {"state","body","comments"}. ${ANCHOR_FORMAT}`,
3309 );
3310 if (added.error === "bad_anchor")
3311 return apiError("bad_anchor", 422, ANCHOR_FORMAT);
3312 return respondAccess(added.error, 422);
3313 }
3314 return json(added.value, 201);
3315 },
3316 );
3317
3318 // Review *states* — the verdicts. A sibling route rather than a mode of
3319 // `…/reviews`, because a line comment and a verdict are different things
3320 // with different rules, and one path that means two of them behind a query
3321 // parameter is the shape that gets called wrong.
3322 router.add(
3323 "GET",
3324 "/api/v1/repos/:owner/:name/pulls/:number/review-states",
3325 (ctx) => {
3326 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
3327 const found = loadPull(ctx);
3328 if ("error" in found) return found.error;
3329 const reviews = timePhase(ctx.request, "reviews", () =>
3330 readerMarked(ctx, found.repo.id, listReviews(ctx.app.db, found.pull.id)),
3331 );
3332 return timePhase(ctx.request, "render", () => json(reviews));
3333 },
3334 );
3335
3336 router.add(
3337 "POST",
3338 "/api/v1/repos/:owner/:name/pulls/:number/review-states",
3339 async (ctx) => {
3340 const denied = requireScope(ctx, "rw");
3341 if (denied) return denied;
3342 const found = loadPull(ctx);
3343 if ("error" in found) return found.error;
3344 const input = await body(ctx.request);
3345 const state = str(input.state);
3346 if (!isReviewState(state))
3347 return apiError(
3348 "invalid_state",
3349 422,
3350 "a review is approved, changes_requested, or commented",
3351 );
3352 const comments = reviewLines(input.comments);
3353 if (comments === undefined)
3354 return apiError(
3355 "invalid_comments",
3356 422,
3357 `comments is a list of {"path","line","side","body"}. ${ANCHOR_FORMAT}`,
3358 );
3359 const pass = passOf(input.ticks, input.left);
3360 if (pass === undefined)
3361 return apiError(
3362 "invalid_boxes",
3363 422,
3364 `ticks is a list of {"issue","box"} and left a list of {"issue","box","why"}, at most ${MAX_PASS} each; box counts the issue's unticked boxes from 1`,
3365 );
3366 const submitted = await submitReview(
3367 ctx.app,
3368 ctx.auth.user,
3369 found.repo,
3370 found.pull,
3371 { state, body: str(input.body), comments, pass },
3372 );
3373 if (!submitted.ok) {
3374 if (submitted.error === "self_review")
3375 return apiError(
3376 "self_review",
3377 422,
3378 "you cannot approve your own pull request",
3379 );
3380 if (submitted.error === "unseen_verdict")
3381 return apiError("unseen_verdict", 422, reviewWords.unseenVerdict);
3382 if (submitted.error === "unread_diff")
3383 return apiError("unread_diff", 422, reviewWords.unreadDiff);
3384 if (submitted.error === "looks_required")
3385 return apiError("looks_required", 422, reviewWords.looksRequired);
3386 if (submitted.error === "bad_anchor")
3387 return apiError(
3388 "bad_anchor",
3389 422,
3390 `nothing was posted: a comment's anchor is not in the diff. ${ANCHOR_FORMAT}`,
3391 );
3392 if (submitted.error === "too_many_lines")
3393 return apiError(
3394 "too_many_lines",
3395 422,
3396 `a review carries at most ${MAX_REVIEW_LINES} line comments`,
3397 );
3398 return originAware(submitted.error, 422);
3399 }
3400 return json(submitted.value, 201);
3401 },
3402 );
3403
3404 // Like or dislike one pull among its variant siblings; a dislike closes it
3405 // with a one-line reason.
3406 router.add(
3407 "POST",
3408 "/api/v1/repos/:owner/:name/pulls/:number/variant",
3409 async (ctx) => {
3410 const denied = requireScope(ctx, "rw");
3411 if (denied) return denied;
3412 const found = loadPull(ctx);
3413 if ("error" in found) return found.error;
3414 const input = await body(ctx.request);
3415 const answer = str(input.answer);
3416 if (answer !== "like" && answer !== "dislike")
3417 return apiError("invalid_answer", 422, ANSWER_WORDS);
3418 const voted = voteVariant(
3419 ctx.app,
3420 ctx.auth.user,
3421 found.repo,
3422 found.pull,
3423 answer,
3424 str(input.reason),
3425 );
3426 if (!voted.ok) {
3427 if (voted.error === "forbidden" || voted.error === "unauthorized")
3428 return respondAccess(voted.error, 422);
3429 return apiError(voted.error, 422, VOTE_NOT_RECORDED);
3430 }
3431 return json({ answer, closed: voted.value.closed }, 201);
3432 },
3433 );
3434
3435 // Let an origin fork's pull run here: a person who can write approves its
3436 // current head, and its check and preview start.
3437 router.add(
3438 "POST",
3439 "/api/v1/repos/:owner/:name/pulls/:number/approve-here",
3440 async (ctx) => {
3441 const denied = requireScope(ctx, "rw");
3442 if (denied) return denied;
3443 const found = loadPull(ctx);
3444 if ("error" in found) return found.error;
3445 const done = await approveToRun(
3446 ctx.app,
3447 ctx.auth.user,
3448 found.repo,
3449 found.pull,
3450 );
3451 if (!done.ok) {
3452 if (done.error === "self_review")
3453 return apiError(
3454 "self_review",
3455 422,
3456 "you cannot approve your own pull request",
3457 );
3458 if (done.error === "not_foreign")
3459 return apiError(
3460 "not_foreign",
3461 422,
3462 "this pull needs no approval to run",
3463 );
3464 if (done.error === "not_open")
3465 return apiError("not_open", 422, "this pull is closed");
3466 return respondAccess(done.error, 422);
3467 }
3468 return json(
3469 "id" in done.value ? done.value : { granted: true, ...done.value },
3470 201,
3471 );
3472 },
3473 );
3474
3475 // Review threads: every review comment sharing one anchor, and whether the
3476 // conversation is settled.
3477 router.add(
3478 "GET",
3479 "/api/v1/repos/:owner/:name/pulls/:number/threads",
3480 (ctx) => {
3481 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
3482 const found = loadPull(ctx);
3483 if ("error" in found) return found.error;
3484 const threads = timePhase(ctx.request, "threads", () => pullThreads(ctx.app, found.pull));
3485 return timePhase(ctx.request, "render", () => json(threads));
3486 },
3487 );
3488
3489 const thread = (resolved: boolean) => (ctx: Ctx) => {
3490 const denied = requireScope(ctx, "rw");
3491 if (denied) return denied;
3492 const found = loadPull(ctx);
3493 if ("error" in found) return found.error;
3494 const settledNow = resolveReviewThread(
3495 ctx.app,
3496 ctx.auth.user,
3497 found.repo,
3498 found.pull,
3499 ctx.params.anchor ?? "",
3500 resolved,
3501 );
3502 if (!settledNow.ok) return respondAccess(settledNow.error, 422);
3503 return json(settledNow.value);
3504 };
3505 router.add(
3506 "POST",
3507 "/api/v1/repos/:owner/:name/pulls/:number/threads/:anchor/resolve",
3508 thread(true),
3509 );
3510 router.add(
3511 "DELETE",
3512 "/api/v1/repos/:owner/:name/pulls/:number/threads/:anchor/resolve",
3513 thread(false),
3514 );
2609 pullRoutes(router);
35152610
35162611 // ── contributing to a repository you cannot push to ──────────────────
35172612 //
src/http/api/pulls.ts added +970
@@ -0,0 +1,970 @@
1 /**
2 * A pull request over the API: `GET` and `POST` `/api/v1/repos/:owner/:name/pulls`,
3 * one pull read and changed at `…/pulls/:number`, its hold, merge, slices,
4 * comments, looks, review script, line reviews, review states, variant vote,
5 * approval to run here and review threads; and the narrow proposal token a
6 * writer hands a child. Moved out of `api.ts` whole (#15352), route for route;
7 * the rules live in `actions/pulls.ts` and its neighbours.
8 */
9
10 import { pullWaitsFor } from "../../flow/waits_for.ts";
11 import { parseAttestation } from "../../core/attestation.ts";
12 import { reviewWords } from "../../actions/review_words.ts";
13 import { teamHoldRefusal } from "../../core/teams_words.ts";
14 import { guardedRefusal } from "../../crew/stranger.ts";
15 import { MAX_PASS, passOf } from "../../actions/box_pass.ts";
16 import { voteVariant } from "../../actions/variants.ts";
17 import { notePhase, takeSessionTime, timePhase, timePhaseAsync } from "../../core/route_timing.ts";
18 import { VOTE_NOT_RECORDED } from "../../actions/board_words.ts";
19 import { sealedScope } from "../../core/sealed.ts";
20 import {
21 addCommentThrough,
22 PLANNER_REFUSALS,
23 setIssueStateThrough,
24 } from "../../actions/issues.ts";
25 import {
26 addReview,
27 anchorId,
28 mergePull,
29 openPull,
30 pullThreads,
31 refreshPullHead,
32 resolveReviewThread,
33 submitReview,
34 approveToRun,
35 MAX_REVIEW_LINES,
36 type ReviewInput,
37 } from "../../actions/pulls.ts";
38 import { landSlice } from "../../actions/pull_slices.ts";
39 import { attachLook } from "../../actions/attach_look.ts";
40 import { reviewSteps, setReviewSteps } from "../../actions/review_steps.ts";
41 import { stepsWords } from "../../core/review_steps.ts";
42 import { lookUrl } from "../../core/looks.ts";
43 import { pullFit, pullLooks } from "../../looks/readable.ts";
44 import { holdPull, releasePull } from "../../actions/holds.ts";
45 import { getHold, type Hold } from "../../core/holds.ts";
46 import {
47 getPull,
48 listPulls,
49 variantSiblings,
50 pullDiff,
51 pullStatus,
52 pullMergeStates,
53 } from "../../core/pulls.ts";
54 import {
55 getRepo,
56 type Repo,
57 canWrite,
58 } from "../../core/repos.ts";
59 import {
60 isReviewState,
61 listReviewComments,
62 listReviews,
63 withOutdated,
64 } from "../../core/reviews.ts";
65 import { mintProposal } from "../../actions/proposal_tokens.ts";
66 import {
67 headInNamespace,
68 PROPOSAL_BODY_MAX,
69 pullProposalOf,
70 recordPullProposal,
71 } from "../../core/proposal_token.ts";
72 import { capWords, headInContribNamespace, inTurn, pullCapReached } from "../../core/contribute_token.ts";
73 import { takesOutside } from "../../actions/contribute_token.ts";
74 import { editIssue } from "../../actions/issues.ts";
75 import { appsRuntime, envsFor } from "../../apps/runtime.ts";
76 import { previewEnv } from "../../apps/data.ts";
77 import { checkWord } from "../../apps/check_word.ts";
78 import { getAppByRepo } from "../../core/apps.ts";
79 import { crewRole } from "../../core/agents.ts";
80 import {
81 checkSummary,
82 latestRunsForIssues,
83 } from "../../core/runs.ts";
84 import { checkStale } from "../../checks/stale.ts";
85 import { resolveOid } from "../../git/merge.ts";
86 import { refTip } from "../../git/read.ts";
87 import { holds, weakEtag } from "../etag.ts";
88 import { type Ctx, type Handler } from "../context.ts";
89 import {
90 apiError,
91 body,
92 boundedBody,
93 forbidden,
94 json,
95 notFound,
96 paged,
97 requireScope,
98 respondAccess,
99 str,
100 tryAgain,
101 } from "../respond.ts";
102 import type { Router } from "../router.ts";
103 import { ANSWER_WORDS } from "../../core/arg_words.ts";
104 import {
105 NOTHING_TO_CHANGE,
106 listQuery,
107 loadPull,
108 loadRepo,
109 originAware,
110 pullDirOf,
111 readerMarked,
112 takenUp,
113 textFrom,
114 withLabels,
115 withLabelsMany,
116 } from "../api.ts";
117
118 /**
119 * How a line comment is anchored, said the same way by every refusal of
120 * one — the sentence a reviewer reads to send it right the second time.
121 */
122 const ANCHOR_FORMAT =
123 'An anchor is {"path": a file in the pull\'s diff, "line": its line number, "side": "new" (the head\'s numbering, for added or kept lines) or "old" (the base\'s, for removed lines)}; the line must be inside one of the diff\'s hunks: in `@@ -a,b +c,d @@` the hunk\'s first line is c on the new side and a on the old. GET …/pulls/N returns the diff.';
124
125 /**
126 * A review's line comments as the API was sent them; undefined when they are not a list of objects.
127 */
128 function reviewLines(raw: unknown): ReviewInput[] | undefined {
129 if (raw === undefined || raw === null) return [];
130 // The cap is `submitReview`'s to refuse, by name (`too_many_lines`).
131 if (!Array.isArray(raw)) return undefined;
132 const out: ReviewInput[] = [];
133 for (const row of raw) {
134 if (typeof row !== "object" || row === null) return undefined;
135 const r = row as Record<string, unknown>;
136 out.push({
137 path: str(r.path),
138 line: Number(r.line),
139 side: r.side === "old" ? "old" : "new",
140 body: str(r.body),
141 });
142 }
143 return out;
144 }
145
146 /** A branch's tip from its ref file (no process); git is asked only when that cannot be read. */
147 const baseTip = async (dir: string, ref: string): Promise<string | undefined> =>
148 (await refTip(dir, ref)) ?? (await resolveOid(dir, ref));
149
150 /** A hold as the API says it: who, why and since when. */
151 const holdJson = (hold: Hold) => ({
152 by: hold.heldByName,
153 why: hold.why,
154 at: hold.heldAt,
155 ...(hold.until ? { until: hold.until } : {}),
156 });
157
158 export function pullRoutes(router: Router<Handler>): void {
159 // ── pull requests — so automation drives the review/merge loop ───────
160
161 router.add("GET", "/api/v1/repos/:owner/:name/pulls", async (ctx) => {
162 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
163 const repo = loadRepo(ctx);
164 if (!repo) return notFound();
165 const query = listQuery(ctx);
166 if (query instanceof Response) return query;
167 const pulls = timePhase(ctx.request, "list", () =>
168 listPulls(ctx.app.db, repo.id, {
169 ...query,
170 ...sealedScope(ctx.app.db, repo, ctx.auth.user),
171 }),
172 );
173 const states = await timePhaseAsync(ctx.request, "merge", async () =>
174 pullMergeStates(
175 await Promise.all(
176 pulls.map(async (p) => ({ dir: await pullDirOf(ctx, repo, p), pull: p })),
177 ),
178 ),
179 );
180 const items = timePhase(ctx.request, "labels", () => {
181 const siblings = variantSiblings(ctx.app.db, pulls);
182 // The check word and preview address the pull page shows, so a client
183 // lists "where to try it" without a request per pull.
184 const checks = latestRunsForIssues(ctx.app.db, pulls.map((p) => p.id));
185 // An address only where the pull page's preview card shows one: the
186 // environments `envsFor` hands this viewer (a private app shows none).
187 const record = getAppByRepo(ctx.app.db, repo.id);
188 const runtime = record === undefined ? undefined : appsRuntime(ctx.app);
189 const live = new Set(
190 record === undefined ? [] : envsFor(ctx.app, ctx.auth.user, record).map((e) => e.env),
191 );
192 return withLabelsMany(ctx, pulls).map((item, i) => ({
193 ...item,
194 author: item.originAuthor ?? item.authorName,
195 check: checkWord(checks.get(item.id), item.headOid),
196 preview:
197 record !== undefined && runtime !== undefined && item.state === "open" && item.mergedAt === null && live.has(previewEnv(item.number))
198 ? runtime.urlFor(record, previewEnv(item.number))
199 : null,
200 variantSiblings: siblings[i] ?? [],
201 ...(states[i] ?? {}),
202 }));
203 });
204 // The tag is of the exact bytes sent, so a new verdict, head or state is never hidden behind a
205 // 304; the page, state, limit, cursor and fields are in the body or the query that chose it.
206 return timePhase(ctx.request, "render", () => {
207 const text = JSON.stringify(paged(items, query.limit, (p) => p.number));
208 const etag = weakEtag(text);
209 const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" };
210 if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers });
211 return new Response(text, { headers: { "content-type": "application/json", ...headers } });
212 });
213 });
214
215 // A writer hands a child its own narrow credential for this repository
216 // (`core/proposal_token.ts`); the secret is shown once, as for any token.
217 router.add(
218 "POST",
219 "/api/v1/repos/:owner/:name/proposal-tokens",
220 async (ctx) => {
221 const denied = requireScope(ctx, "rw");
222 if (denied) return denied;
223 const repo = loadRepo(ctx);
224 if (!repo || !canWrite(ctx.app.db, repo, ctx.auth.user)) return notFound();
225 const input = await boundedBody(ctx.request, PROPOSAL_BODY_MAX);
226 if (input === "too_large")
227 return apiError("too_large", 413, `at most ${PROPOSAL_BODY_MAX} bytes`);
228 const minted = mintProposal(ctx.app, ctx.auth.user, repo, {
229 child: str(input.child),
230 origin: str(input.origin),
231 childRepo: str(input.childRepo),
232 });
233 if (!minted.ok)
234 return minted.error.code === "not_found" ? notFound() : apiError(minted.error.code, 422, minted.error.message);
235 return json(minted.value, 201);
236 },
237 );
238
239 router.add("POST", "/api/v1/repos/:owner/:name/pulls", async (ctx) => {
240 const denied = requireScope(ctx, "rw");
241 if (denied) return denied;
242 const repo = loadRepo(ctx);
243 if (!repo) return notFound();
244 // An outside agent's token opens a pull from its own contrib/<agent>/… branch of this
245 // repository, never from another repository, and never past what it was minted for.
246 const outside = ctx.auth.contribute;
247 if (outside !== undefined && (outside.repoId !== repo.id || !takesOutside(ctx.app, repo))) return forbidden();
248 // A proposal token's body is small, and its pull comes from a branch of
249 // its own child's namespace in this repository, never from another one.
250 const proposal = ctx.auth.proposal;
251 // The gate already pins a proposal token to its repository; this
252 // repeats it so the handler is safe on its own (defense in depth).
253 if (proposal !== undefined && proposal.repoId !== repo.id) return forbidden();
254 const input =
255 proposal === undefined
256 ? await body(ctx.request)
257 : await boundedBody(ctx.request, PROPOSAL_BODY_MAX);
258 if (input === "too_large")
259 return apiError("too_large", 413, `at most ${PROPOSAL_BODY_MAX} bytes`);
260 if (
261 outside !== undefined &&
262 (str(input.headRepo) !== "" || !headInContribNamespace(str(input.head), outside.namespace))
263 )
264 return apiError(
265 "invalid_head",
266 422,
267 `a contribute pull comes from a contrib/${outside.namespace}/… branch of this repository`,
268 );
269 if (
270 proposal !== undefined &&
271 (str(input.headRepo) !== "" ||
272 !headInNamespace(str(input.head), proposal.child))
273 )
274 return apiError(
275 "invalid_head",
276 422,
277 `a proposal pull comes from a child/${proposal.child}/… branch of this repository`,
278 );
279 // What the child says it proved: a verdict and a tree id, or nothing. Shown beside the
280 // pull, never admitted on (#13645); only a proposal may send one.
281 const attested = proposal === undefined ? undefined : parseAttestation(input.attestation);
282 if (attested === "invalid")
283 return apiError(
284 "invalid_attestation",
285 422,
286 "an attestation is { verdict: green|red|pending|none, tree: <40 or 64 hex> }",
287 );
288 // `headRepo: "owner/name"` proposes a fork's branch into this base.
289 let headRepo: Repo | undefined;
290 const headSpec = str(input.headRepo);
291 if (headSpec !== "") {
292 const [owner, name, ...rest] = headSpec.split("/");
293 headRepo =
294 owner && name && rest.length === 0
295 ? getRepo(ctx.app.db, owner, name)
296 : undefined;
297 if (!headRepo) return notFound();
298 // A crew run's head comes from its own two repositories, never another
299 // fork the crew member can read (defense in depth past the run gate).
300 const run = ctx.auth.run;
301 if (run !== undefined && headRepo.id !== run.forkId && headRepo.id !== run.repoId)
302 return notFound();
303 }
304 // An outside agent opens a few pulls: each starts checks and a preview on the
305 // owner's repository. Counted from the pull rows, one open at a time per token.
306 const open = () =>
307 openPull(ctx.app, ctx.auth.user!, repo, {
308 title: str(input.title),
309 body: str(input.body),
310 baseBranch: str(input.base),
311 headBranch: str(input.head),
312 ...(headRepo ? { headRepo } : {}),
313 // A person's deliberate yes to fixing a sealed report from a public branch.
314 ...(input.confirmPublic === true ? { confirmPublic: true } : {}),
315 ...(outside === undefined ? {} : { outsideAgent: true }),
316 });
317 // An outside token opens one pull at a time (the same turn a push's opens take),
318 // its caps read inside the turn so the count cannot be raced.
319 const opening =
320 outside === undefined
321 ? await open()
322 : await inTurn(ctx.auth.user!.id, async () => {
323 const capped = pullCapReached(ctx.app.db, repo.id, ctx.auth.user!.id, new Date());
324 return capped ?? (await open());
325 });
326 if (typeof opening === "string") return tryAgain("rate_limited", 429, capWords(opening), 3600);
327 const created = opening;
328 if (!created.ok && created.error === "sealed_in_public")
329 return apiError(
330 "sealed_in_public",
331 422,
332 "this fixes a sealed report from a public branch: push it to your private repository (POST …/issues/<n>/private) and open the pull from there, or send confirmPublic: true",
333 );
334 if (!created.ok)
335 return created.error === "origin_owner_only" ||
336 created.error === "origin_refused" ||
337 created.error === "origin_unreachable"
338 ? originAware(created.error)
339 : respondAccess(created.error, 422);
340 if (proposal !== undefined)
341 recordPullProposal(ctx.app.db, created.value.id, proposal, attested);
342 return json(
343 {
344 ...withLabels(ctx, created.value),
345 variantSiblings: variantSiblings(ctx.app.db, [created.value])[0] ?? [],
346 ...(proposal
347 ? { proposal: { child: proposal.child, origin: proposal.origin, ...(attested ? { attestation: attested } : {}) } }
348 : {}),
349 },
350 201,
351 );
352 });
353
354 router.add("GET", "/api/v1/repos/:owner/:name/pulls/:number", async (ctx) => {
355 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
356 const found = timePhase(ctx.request, "pull", () => loadPull(ctx));
357 if ("error" in found) return found.error;
358 // `?diff=0` reads the pull without its diff, and skips computing it.
359 const wantDiff = ctx.url.searchParams.get("diff");
360 if (wantDiff !== null && wantDiff !== "0" && wantDiff !== "1")
361 return apiError("invalid_diff", 422, "diff is 0 or 1");
362 // A fork may have pushed since the pull opened; review what is being
363 // proposed now, not the snapshot taken when it was.
364 await timePhaseAsync(ctx.request, "head", () =>
365 refreshPullHead(ctx.app, found.repo, found.pull),
366 );
367 // Include the diff so a reviewer (human or agent) reads the change without
368 // a second round trip, and the review gate beside it so a client knows
369 // whether merging is even on offer.
370 const gate = { db: ctx.app.db, requireReview: found.repo.requireReview };
371 const { status, diff } = await timePhaseAsync(ctx.request, "diff", async () => {
372 const dir = await pullDirOf(ctx, found.repo, found.pull);
373 return wantDiff === "0"
374 ? { status: await pullStatus(dir, found.pull, gate), diff: undefined }
375 : await pullDiff(dir, found.pull, gate);
376 });
377 const live = found.pull.state === "open" && found.pull.mergedAt === null;
378 const checkStaleNow = await timePhaseAsync(
379 ctx.request,
380 "checks",
381 async () =>
382 live &&
383 checkStale(
384 checkSummary(ctx.app.db, found.pull.id, status.headOid).run,
385 await baseTip(await pullDirOf(ctx, found.repo, found.pull), `refs/heads/${found.pull.baseBranch}`),
386 ),
387 );
388 return timePhase(ctx.request, "render", () => {
389 const hold = getHold(ctx.app.db, found.pull.id);
390 const checked = checkSummary(ctx.app.db, found.pull.id, status.headOid).run;
391 const text = JSON.stringify({
392 ...withLabels(ctx, found.pull),
393 check: checkWord(checked ?? undefined, status.headOid),
394 checkStale: checkStaleNow,
395 // The base tip the head's check merged with; null before any check
396 // recorded one. Beside `checkStale` it names which main was tested.
397 checkedAgainst: checked !== null && checked.baseOid !== "" ? checked.baseOid : null,
398 // The approval and what it was given for; `current` is false once the head or the base
399 // moved.
400 approvedAt: status.reviews?.approval ?? null,
401 variantSiblings: variantSiblings(ctx.app.db, [found.pull])[0] ?? [],
402 ...(live ? { mergeable: status.mergeable, conflicts: status.conflicts } : {}),
403 proposal: pullProposalOf(ctx.app.db, found.pull.id) ?? null,
404 status,
405 ...(diff === undefined ? {} : { diff }),
406 hold: hold === undefined ? null : holdJson(hold),
407 // Green and unlanded past six hours: what it waits for and the one action (#15803).
408 waitsFor: live
409 ? pullWaitsFor(ctx.app.db, found.repo, found.pull, { headOid: status.headOid, conflicts: status.conflicts?.length ?? 0 })
410 : null,
411 });
412 // Tagged by the exact bytes sent, after access was checked: a new head, verdict, review or
413 // merge is never hidden behind a 304.
414 const etag = weakEtag(text);
415 const headers = { etag, "cache-control": "private, no-cache", vary: "authorization, cookie" };
416 if (holds(ctx.request, etag)) return new Response(null, { status: 304, headers });
417 return new Response(text, { headers: { "content-type": "application/json", ...headers } });
418 });
419 });
420
421 router.add(
422 "PATCH",
423 "/api/v1/repos/:owner/:name/pulls/:number",
424 async (ctx) => {
425 const denied = requireScope(ctx, "rw");
426 if (denied) return denied;
427 const found = loadPull(ctx);
428 if ("error" in found) return found.error;
429 const input = await body(ctx.request);
430 // The same two halves as an issue's PATCH: words, then state.
431 const text = textFrom(input);
432 if (text === undefined) return json({ error: "invalid_text" }, 422);
433 const wanted = input.state === undefined ? undefined : str(input.state);
434 if (wanted !== undefined && wanted !== "open" && wanted !== "closed")
435 return json({ error: "invalid_state" }, 422);
436 // A pull has no reason to give: "parked" is the crew's word alone.
437 if (input.reason !== undefined || input.into !== undefined)
438 return json({ error: "invalid_reason" }, 422);
439 if (
440 wanted === undefined &&
441 text.title === undefined &&
442 text.body === undefined
443 )
444 return NOTHING_TO_CHANGE();
445 if (text.title !== undefined || text.body !== undefined) {
446 const edited = editIssue(
447 ctx.app,
448 ctx.auth.user,
449 found.repo,
450 found.pull,
451 text,
452 );
453 if (!edited.ok)
454 return edited.error === "taken_up"
455 ? takenUp()
456 : originAware(edited.error, 422);
457 }
458 if (wanted !== undefined) {
459 const changed = await setIssueStateThrough(
460 ctx.app,
461 ctx.auth.user,
462 found.repo,
463 getPull(ctx.app.db, found.repo.id, found.pull.number)!,
464 wanted,
465 );
466 if (!changed.ok) {
467 // A planner told no learns the one rule it works by.
468 if (
469 changed.error === "forbidden" &&
470 wanted === "closed" &&
471 crewRole(ctx.app.db, found.repo.id, ctx.auth.user!.id) === "planner"
472 )
473 return apiError(
474 "forbidden",
475 403,
476 PLANNER_REFUSALS.pull,
477 );
478 return originAware(changed.error, 409);
479 }
480 }
481 return json(
482 withLabels(ctx, getPull(ctx.app.db, found.repo.id, found.pull.number)!),
483 );
484 },
485 );
486
487 // Hold a pull, or let it go (`actions/holds.ts`): a person who writes the
488 // repository says "not this one yet", and no rule sends it to review or
489 // lands it until it is released. A person's own merge is untouched.
490 router.add(
491 "PUT",
492 "/api/v1/repos/:owner/:name/pulls/:number/hold",
493 async (ctx) => {
494 const denied = requireScope(ctx, "rw");
495 if (denied) return denied;
496 const found = loadPull(ctx);
497 if ("error" in found) return found.error;
498 const input = await body(ctx.request);
499 if (input.until !== undefined && input.until !== "green")
500 return respondAccess("bad_until", 422);
501 const held = holdPull(
502 ctx.app,
503 ctx.auth.user,
504 found.repo,
505 found.pull,
506 str(input.why),
507 false,
508 input.until === "green" ? "green" : undefined,
509 );
510 if (!held.ok)
511 return respondAccess(held.error, held.error === "not_open" ? 409 : 422);
512 return json({ held: true, hold: holdJson(held.value) });
513 },
514 );
515 router.add(
516 "DELETE",
517 "/api/v1/repos/:owner/:name/pulls/:number/hold",
518 (ctx) => {
519 const denied = requireScope(ctx, "rw");
520 if (denied) return denied;
521 const found = loadPull(ctx);
522 if ("error" in found) return found.error;
523 const released = releasePull(
524 ctx.app,
525 ctx.auth.user,
526 found.repo,
527 found.pull,
528 );
529 if (!released.ok) return respondAccess(released.error, 422);
530 return json({ held: false, released: released.value });
531 },
532 );
533
534 router.add(
535 "POST",
536 "/api/v1/repos/:owner/:name/pulls/:number/merge",
537 async (ctx) => {
538 const denied = requireScope(ctx, "rw");
539 if (denied) return denied;
540 const found = loadPull(ctx);
541 if ("error" in found) return found.error;
542 const input = await body(ctx.request);
543 const strategy = str(input.strategy) === "squash" ? "squash" : "merge";
544 const merged = await mergePull(
545 ctx.app,
546 ctx.auth.user,
547 found.repo,
548 found.pull,
549 strategy,
550 );
551 if (!merged.ok) {
552 if (typeof merged.error !== "string")
553 return merged.error.kind === "guarded"
554 ? json({ error: "guarded", message: guardedRefusal(merged.error.paths), paths: merged.error.paths }, 409)
555 : merged.error.kind === "team_review_required"
556 ? json({ error: merged.error.kind, message: teamHoldRefusal(merged.error.teams), teams: merged.error.teams }, 409)
557 : json({ error: merged.error.kind }, 409);
558 return originAware(merged.error, 409);
559 }
560 return json({ merged: true, ...merged.value });
561 },
562 );
563
564 // Land the author's commits up to `upTo` as their own merge commit (#9010).
565 router.add(
566 "POST",
567 "/api/v1/repos/:owner/:name/pulls/:number/slices",
568 async (ctx) => {
569 const denied = requireScope(ctx, "rw");
570 if (denied) return denied;
571 const found = loadPull(ctx);
572 if ("error" in found) return found.error;
573 const input = await body(ctx.request);
574 const landed = await landSlice(
575 ctx.app,
576 ctx.auth.user,
577 found.repo,
578 found.pull,
579 str(input.upTo),
580 );
581 if (!landed.ok) {
582 if (typeof landed.error !== "string")
583 return json({ error: landed.error.kind }, 409);
584 if (landed.error === "bad_slice" || landed.error === "sealed" || landed.error === "not_fork")
585 return json({ error: landed.error }, 422);
586 if (landed.error === "held") return json({ error: "held" }, 409);
587 return originAware(landed.error, 409);
588 }
589 return json(landed.value);
590 },
591 );
592
593 router.add(
594 "POST",
595 "/api/v1/repos/:owner/:name/pulls/:number/comments",
596 async (ctx) => {
597 const denied = requireScope(ctx, "rw");
598 if (denied) return denied;
599 const found = loadPull(ctx);
600 if ("error" in found) return found.error;
601 const input = await body(ctx.request);
602 const added = await addCommentThrough(
603 ctx.app,
604 ctx.auth.user,
605 found.repo,
606 found.pull,
607 str(input.body),
608 );
609 if (!added.ok) return originAware(added.error);
610 return json(added.value, 201);
611 },
612 );
613
614 // Attach a look: a picture a person took, at a stated width, with one line
615 // saying what it shows (`actions/attach_look.ts`). The picture is base64
616 // in the JSON body; the crew's own looks keep their path through the
617 // preview.
618 router.add(
619 "POST",
620 "/api/v1/repos/:owner/:name/pulls/:number/looks",
621 async (ctx) => {
622 const denied = requireScope(ctx, "rw");
623 if (denied) return denied;
624 const found = loadPull(ctx);
625 if ("error" in found) return found.error;
626 const input = await body(ctx.request);
627 const attached = attachLook(
628 ctx.app,
629 ctx.auth.user,
630 found.repo,
631 found.pull,
632 { width: str(input.width), note: str(input.says), image: str(input.image) },
633 );
634 if (!attached.ok)
635 return respondAccess(
636 attached.error,
637 attached.error === "too_large"
638 ? 413
639 : attached.error === "not_open" || attached.error === "no_app"
640 ? 409
641 : 422,
642 );
643 const look = attached.value;
644 return json(
645 {
646 id: look.id,
647 width: look.kind,
648 says: look.note,
649 by: look.attachedBy,
650 commit: look.commitOid,
651 url: lookUrl(`/${found.repo.ownerName}/${found.repo.name}`, look),
652 },
653 201,
654 );
655 },
656 );
657
658 // A pull's looks, newest first, from its own preview environment and only
659 // the ones this reader may fetch as a picture (`looks/readable.ts`).
660 router.add(
661 "GET",
662 "/api/v1/repos/:owner/:name/pulls/:number/looks",
663 (ctx) => {
664 const found = loadPull(ctx);
665 if ("error" in found) return found.error;
666 const items = pullLooks(ctx.app, found.repo, found.pull, ctx.auth.user);
667 const fit = pullFit(ctx.app, found.repo, found.pull, ctx.auth.user);
668 return json({ items, fit });
669 },
670 );
671
672 // A pull's review script (#13653): the steps that take a reviewer, person or agent, into the
673 // preview at the place to test, each with the absolute address of its page.
674 router.add("GET", "/api/v1/repos/:owner/:name/pulls/:number/review", (ctx) => {
675 const found = loadPull(ctx);
676 if ("error" in found) return found.error;
677 return json({ items: reviewSteps(ctx.app, ctx.auth.user, found.repo, found.pull) });
678 });
679
680 // Set it: a writer's, on an open pull; the steps replace the ones it had.
681 router.add("PUT", "/api/v1/repos/:owner/:name/pulls/:number/review", async (ctx) => {
682 const denied = requireScope(ctx, "rw");
683 if (denied) return denied;
684 const found = loadPull(ctx);
685 if ("error" in found) return found.error;
686 const input = await body(ctx.request);
687 const set = setReviewSteps(ctx.app, ctx.auth.user, found.repo, found.pull, input.steps);
688 if (!set.ok) {
689 const e = set.error;
690 if (e === "unauthorized" || e === "forbidden" || e === "not_found") return respondAccess(e, 422);
691 return json({ error: e === "not_open" ? e : "invalid_steps", message: e === "not_open" ? "the pull is not open" : stepsWords(e) }, e === "not_open" ? 409 : 422);
692 }
693 return json({ items: reviewSteps(ctx.app, ctx.auth.user, found.repo, found.pull) });
694 });
695
696 // Line-anchored review comments. The anchor is (path, side, line) in the
697 // pull's current diff; the server takes the content hash, so a client never
698 // handles one — and a later force-push marks the comment `outdated`.
699 router.add(
700 "GET",
701 "/api/v1/repos/:owner/:name/pulls/:number/reviews",
702 async (ctx) => {
703 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
704 const found = loadPull(ctx);
705 if ("error" in found) return found.error;
706 const marked = await timePhaseAsync(ctx.request, "reviews", async () => {
707 const { diff } = await pullDiff(
708 await pullDirOf(ctx, found.repo, found.pull),
709 found.pull,
710 );
711 return withOutdated(
712 readerMarked(
713 ctx,
714 found.repo.id,
715 listReviewComments(ctx.app.db, found.pull.id),
716 ),
717 diff,
718 );
719 });
720 return timePhase(ctx.request, "render", () =>
721 json(
722 marked.map(
723 // The thread this comment belongs to, so a client can resolve it
724 // without reassembling the key itself.
725 (comment) => ({
726 ...comment,
727 anchor: anchorId(comment.path, comment.side, comment.line),
728 }),
729 ),
730 ),
731 );
732 },
733 );
734
735 router.add(
736 "POST",
737 "/api/v1/repos/:owner/:name/pulls/:number/reviews",
738 async (ctx) => {
739 const denied = requireScope(ctx, "rw");
740 if (denied) return denied;
741 const found = loadPull(ctx);
742 if ("error" in found) return found.error;
743 const input = await body(ctx.request);
744 const side = input.side === "old" ? "old" : "new";
745 const added = await addReview(
746 ctx.app,
747 ctx.auth.user,
748 found.repo,
749 found.pull,
750 {
751 body: str(input.body),
752 path: str(input.path),
753 line: Number(input.line),
754 side,
755 },
756 );
757 if (!added.ok) {
758 // A verdict sent here is the call this route most often gets wrong.
759 if (added.error === "bad_anchor" && input.state !== undefined)
760 return apiError(
761 "bad_anchor",
762 422,
763 `this route takes one line comment; a verdict goes to …/review-states as {"state","body","comments"}. ${ANCHOR_FORMAT}`,
764 );
765 if (added.error === "bad_anchor")
766 return apiError("bad_anchor", 422, ANCHOR_FORMAT);
767 return respondAccess(added.error, 422);
768 }
769 return json(added.value, 201);
770 },
771 );
772
773 // Review *states* — the verdicts. A sibling route rather than a mode of
774 // `…/reviews`, because a line comment and a verdict are different things
775 // with different rules, and one path that means two of them behind a query
776 // parameter is the shape that gets called wrong.
777 router.add(
778 "GET",
779 "/api/v1/repos/:owner/:name/pulls/:number/review-states",
780 (ctx) => {
781 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
782 const found = loadPull(ctx);
783 if ("error" in found) return found.error;
784 const reviews = timePhase(ctx.request, "reviews", () =>
785 readerMarked(ctx, found.repo.id, listReviews(ctx.app.db, found.pull.id)),
786 );
787 return timePhase(ctx.request, "render", () => json(reviews));
788 },
789 );
790
791 router.add(
792 "POST",
793 "/api/v1/repos/:owner/:name/pulls/:number/review-states",
794 async (ctx) => {
795 const denied = requireScope(ctx, "rw");
796 if (denied) return denied;
797 const found = loadPull(ctx);
798 if ("error" in found) return found.error;
799 const input = await body(ctx.request);
800 const state = str(input.state);
801 if (!isReviewState(state))
802 return apiError(
803 "invalid_state",
804 422,
805 "a review is approved, changes_requested, or commented",
806 );
807 const comments = reviewLines(input.comments);
808 if (comments === undefined)
809 return apiError(
810 "invalid_comments",
811 422,
812 `comments is a list of {"path","line","side","body"}. ${ANCHOR_FORMAT}`,
813 );
814 const pass = passOf(input.ticks, input.left);
815 if (pass === undefined)
816 return apiError(
817 "invalid_boxes",
818 422,
819 `ticks is a list of {"issue","box"} and left a list of {"issue","box","why"}, at most ${MAX_PASS} each; box counts the issue's unticked boxes from 1`,
820 );
821 const submitted = await submitReview(
822 ctx.app,
823 ctx.auth.user,
824 found.repo,
825 found.pull,
826 { state, body: str(input.body), comments, pass },
827 );
828 if (!submitted.ok) {
829 if (submitted.error === "self_review")
830 return apiError(
831 "self_review",
832 422,
833 "you cannot approve your own pull request",
834 );
835 if (submitted.error === "unseen_verdict")
836 return apiError("unseen_verdict", 422, reviewWords.unseenVerdict);
837 if (submitted.error === "unread_diff")
838 return apiError("unread_diff", 422, reviewWords.unreadDiff);
839 if (submitted.error === "looks_required")
840 return apiError("looks_required", 422, reviewWords.looksRequired);
841 if (submitted.error === "bad_anchor")
842 return apiError(
843 "bad_anchor",
844 422,
845 `nothing was posted: a comment's anchor is not in the diff. ${ANCHOR_FORMAT}`,
846 );
847 if (submitted.error === "too_many_lines")
848 return apiError(
849 "too_many_lines",
850 422,
851 `a review carries at most ${MAX_REVIEW_LINES} line comments`,
852 );
853 return originAware(submitted.error, 422);
854 }
855 return json(submitted.value, 201);
856 },
857 );
858
859 // Like or dislike one pull among its variant siblings; a dislike closes it
860 // with a one-line reason.
861 router.add(
862 "POST",
863 "/api/v1/repos/:owner/:name/pulls/:number/variant",
864 async (ctx) => {
865 const denied = requireScope(ctx, "rw");
866 if (denied) return denied;
867 const found = loadPull(ctx);
868 if ("error" in found) return found.error;
869 const input = await body(ctx.request);
870 const answer = str(input.answer);
871 if (answer !== "like" && answer !== "dislike")
872 return apiError("invalid_answer", 422, ANSWER_WORDS);
873 const voted = voteVariant(
874 ctx.app,
875 ctx.auth.user,
876 found.repo,
877 found.pull,
878 answer,
879 str(input.reason),
880 );
881 if (!voted.ok) {
882 if (voted.error === "forbidden" || voted.error === "unauthorized")
883 return respondAccess(voted.error, 422);
884 return apiError(voted.error, 422, VOTE_NOT_RECORDED);
885 }
886 return json({ answer, closed: voted.value.closed }, 201);
887 },
888 );
889
890 // Let an origin fork's pull run here: a person who can write approves its
891 // current head, and its check and preview start.
892 router.add(
893 "POST",
894 "/api/v1/repos/:owner/:name/pulls/:number/approve-here",
895 async (ctx) => {
896 const denied = requireScope(ctx, "rw");
897 if (denied) return denied;
898 const found = loadPull(ctx);
899 if ("error" in found) return found.error;
900 const done = await approveToRun(
901 ctx.app,
902 ctx.auth.user,
903 found.repo,
904 found.pull,
905 );
906 if (!done.ok) {
907 if (done.error === "self_review")
908 return apiError(
909 "self_review",
910 422,
911 "you cannot approve your own pull request",
912 );
913 if (done.error === "not_foreign")
914 return apiError(
915 "not_foreign",
916 422,
917 "this pull needs no approval to run",
918 );
919 if (done.error === "not_open")
920 return apiError("not_open", 422, "this pull is closed");
921 return respondAccess(done.error, 422);
922 }
923 return json(
924 "id" in done.value ? done.value : { granted: true, ...done.value },
925 201,
926 );
927 },
928 );
929
930 // Review threads: every review comment sharing one anchor, and whether the
931 // conversation is settled.
932 router.add(
933 "GET",
934 "/api/v1/repos/:owner/:name/pulls/:number/threads",
935 (ctx) => {
936 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
937 const found = loadPull(ctx);
938 if ("error" in found) return found.error;
939 const threads = timePhase(ctx.request, "threads", () => pullThreads(ctx.app, found.pull));
940 return timePhase(ctx.request, "render", () => json(threads));
941 },
942 );
943
944 const thread = (resolved: boolean) => (ctx: Ctx) => {
945 const denied = requireScope(ctx, "rw");
946 if (denied) return denied;
947 const found = loadPull(ctx);
948 if ("error" in found) return found.error;
949 const settledNow = resolveReviewThread(
950 ctx.app,
951 ctx.auth.user,
952 found.repo,
953 found.pull,
954 ctx.params.anchor ?? "",
955 resolved,
956 );
957 if (!settledNow.ok) return respondAccess(settledNow.error, 422);
958 return json(settledNow.value);
959 };
960 router.add(
961 "POST",
962 "/api/v1/repos/:owner/:name/pulls/:number/threads/:anchor/resolve",
963 thread(true),
964 );
965 router.add(
966 "DELETE",
967 "/api/v1/repos/:owner/:name/pulls/:number/threads/:anchor/resolve",
968 thread(false),
969 );
970 }
test/api-pulls-module.test.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * The pull request routes live in `src/http/api/pulls.ts` (#15352), moved out of `api.ts` whole.
3 * The move keeps two things: `apiRoutes` still registers every one of them, in the place it
4 * did, and each answer still carries the security floor (`securityFloor` in
5 * `src/http/respond.ts`) — read here on a moved route's 200 and on its refusal.
6 */
7 import { afterAll, beforeAll, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { createApp, type App } from "../src/app.ts";
12 import { createRepo } from "../src/core/repos.ts";
13 import { apiRoutes } from "../src/http/api.ts";
14 import { pullRoutes } from "../src/http/api/pulls.ts";
15 import type { Handler } from "../src/http/context.ts";
16 import { Router } from "../src/http/router.ts";
17 import { serve, type Servers } from "../src/http/server.ts";
18 import { seedAdmin } from "./helpers/admin.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20
21 quietLogs();
22
23 let dataDir = "";
24 let app: App, servers: Servers;
25
26 beforeAll(async () => {
27 dataDir = await mkdtemp(join(tmpdir(), "forge-api-pulls-"));
28 app = createApp({ dataDir, port: 0 });
29 servers = await serve(app);
30 const admin = await seedAdmin(app, { username: "ada", email: "[email protected]", password: "correct-horse-battery" });
31 if (!admin.ok) throw new Error(admin.error);
32 const made = await createRepo(app.db, app.reposRoot, { ownerId: admin.value.id, name: "notes", visibility: "public" });
33 if (!made.ok) throw new Error(made.error);
34 });
35
36 afterAll(async () => {
37 servers?.stop();
38 app?.close();
39 await rm(dataDir, { recursive: true, force: true });
40 });
41
42 const routesOf = (add: (r: Router<Handler>) => void) => {
43 const r = new Router<Handler>();
44 add(r);
45 return r.routes().map((x) => `${x.method} ${x.pattern}`);
46 };
47
48 test("apiRoutes registers every pull route, as one run in its old place", () => {
49 const moved = routesOf(pullRoutes);
50 expect(moved.length).toBe(23);
51 expect(moved[0]).toBe("GET /api/v1/repos/:owner/:name/pulls");
52 const all = routesOf((r) => apiRoutes(r, () => false));
53 const at = all.indexOf(moved[0]!);
54 expect(all.slice(at, at + moved.length)).toEqual(moved);
55 // Still after the decisions read and before contributing, as in api.ts before the move.
56 expect(all[at - 1]).toBe("GET /api/v1/repos/:owner/:name/decisions");
57 expect(all[at + moved.length]).toBe("POST /api/v1/repos/:owner/:name/contribute");
58 });
59
60 const floor = (res: Response) => {
61 expect(res.headers.get("content-security-policy")).toContain("default-src");
62 expect(res.headers.get("x-content-type-options")).toBe("nosniff");
63 expect(res.headers.get("referrer-policy")).toBeTruthy();
64 };
65
66 test("a moved read answers with the security floor", async () => {
67 const res = await fetch(`${servers.url}/api/v1/repos/ada/notes/pulls`);
68 expect(res.status).toBe(200);
69 expect(res.headers.get("content-type")).toContain("application/json");
70 floor(res);
71 expect(await res.json()).toMatchObject({ items: [] });
72 });
73
74 test("a moved write's refusal answers with the security floor", async () => {
75 const res = await fetch(`${servers.url}/api/v1/repos/ada/notes/pulls/1/merge`, {
76 method: "POST",
77 headers: { origin: servers.url, "content-type": "application/json" },
78 body: "{}",
79 });
80 expect(res.status).toBe(401);
81 floor(res);
82 await res.body?.cancel();
83 });
test/landing-doors-review.test.ts +2 −2
@@ -60,8 +60,8 @@ interface Door {
6060 }
6161
6262 const DOORS: readonly Door[] = [
63 { name: "API merge", sites: ["src/http/api.ts:mergePull"], route: "post /api/v1/repos/{owner}/{name}/pulls/{number}/merge", way: { http: "api-merge" } },
64 { name: "API slices", sites: ["src/http/api.ts:landSlice"], route: "post /api/v1/repos/{owner}/{name}/pulls/{number}/slices", way: { http: "api-slices" } },
63 { name: "API merge", sites: ["src/http/api/pulls.ts:mergePull"], route: "post /api/v1/repos/{owner}/{name}/pulls/{number}/merge", way: { http: "api-merge" } },
64 { name: "API slices", sites: ["src/http/api/pulls.ts:landSlice"], route: "post /api/v1/repos/{owner}/{name}/pulls/{number}/slices", way: { http: "api-slices" } },
6565 { name: "MCP merge", sites: ["src/http/mcp/tools/merge.ts:mergePull"], tool: "merge", way: { http: "mcp-merge" } },
6666 { name: "MCP land_past_gate", sites: ["src/http/mcp/tools/land_past_gate.ts:landPastGate"], tool: "land_past_gate", way: { action: "mergePull", opts: { pastGate: true } } },
6767 { name: "web Merge button", sites: ["src/web/pages/pull.ts:mergePull"], way: { action: "mergePull" } },

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs