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

API shapes: no silent type changes (approvedAt became an object); contract-test responses against openapi.json #17945

opened this in answer to

Merged 22h 17m ago, live in production

scout/forge:scout/17944-api-shapes-no-silent-type-changes-approv → main 0 commits fork 1 thread · 1 unresolved

  • Merged. scout/17944-api-shapes-no-silent-type-changes-approv was merged into main as 1b196c6.

Review

Sign in to review this change.
10 files changed +106 −18
docs/features/api-shape-changes.md added +19
@@ -0,0 +1,19 @@
1 ---
2 topic: Agents: MCP, git, or the terminal
3 row: API shapes are a contract: a field never changes type, and changes are listed here
4 ---
5 # API shapes are a contract
6
7 A field in an API answer keeps its type. A richer value is a new field beside the old one; the old one stays what it was. `openapi.json` is the source of truth: `test/approval-base.test.ts` reads the pull detail answer against the schema the document declares (`test/support/conforms.ts`) and fails when they part. A route's tests add the same check as they gain samples.
8
9 ## Changes clients follow
10
11 - `GET /api/v1/repos/{owner}/{name}/pulls/{number}`: `approvedAt` is a date string or null again (it was briefly the object, #16761); the object `{at, head, base, current}` is the new field `approval`. A client that decoded the object reads `approval` instead.
12
13 ## Known bends, not yet changed
14
15 - `next_cursor` is a number on some lists and a string on others.
16 - `comments` is a count in lists and an array in an issue's detail.
17 - `/user/repos` answers a bare array where other lists answer `{items, next_cursor}`.
18
19 Each of these will be fixed as a new field or a version, never in place. Not done here: a `GET /api/v1/changes` feed; this page is the list for now. No terminal screen shows it: the terminal reads the same pull through `src/tui/screens/pull.ts`, which does not use `approvedAt`.
docs/features/approval-base.md +1 −1
@@ -7,7 +7,7 @@ row: An approval says what it was given for
77 An approval is recorded against the head and the base tip it was given for. When the base moves after it (another pull landed), the approval is still counted, and every door says the base moved.
88
99 - **Page:** the reviews chip in the merge box on the pull's Files step reads "the base moved since the approval" in red. Nothing is added while the approval is current.
10 - **API:** `GET /api/v1/repos/:owner/:name/pulls/:number` carries `approvedAt: { at, head, base, current }`, or `null` when no one's latest verdict approves. `base` is `null` for an approval given before the base was recorded; `current` is `false` once the head or the base moved.
10 - **API:** `GET /api/v1/repos/:owner/:name/pulls/:number` carries `approval: { at, head, base, current }` (and `approvedAt`, the date string of that approval), both `null` when no one's latest verdict approves. `base` is `null` for an approval given before the base was recorded; `current` is `false` once the head or the base moved.
1111 - **MCP:** `pulls` with a `repo` carries `movedSinceApproval` on each row; the card says "moved since approval".
1212 - **Inbox:** a green pull's "look" row, and a pull's "waiting" row, on `/asks` and the home's ask lines end "moved since approval" once the head or the base is no longer the one approved. The base is the one the stale-asks sweep last read (no git on the request); before a sweep has read it only the head is compared. One rule for the inbox and MCP: `src/core/approval_at.ts`.
1313 - **Terminal:** the pull screen's merge box adds "the base moved since the approval" after the approval count.
src/contract/openapi/routes/getApiV1ReposOwnerNamePullsNumber.ts +1 −1
@@ -1,4 +1,4 @@
11 import { ref } from "../schema_kit.ts";
22 import { REPO, type Route } from "../shared.ts";
33
4 export const route: Route = { method: "get", path: `${REPO}/pulls/{number}`, summary: "Read one pull with its diff and review gate", detail: "Read one pull with its diff and review gate (diff=0 leaves the diff out; a diff over 4 MiB of git text is left out too, and `diffTooLarge` {limitBytes, says} replaces it: read it at …/pulls/{number}/diff); `check` is the word for the head's check: green, red, running or none; `checkedAgainst` is the base tip that check merged with (null before one recorded it), `checkStale` says the base has moved since, and `approvedAt` is the standing approval {at, head, base, current} or null, current false once the head or the base moved, and `approvedAgainst` is the same approval as one string, \"<head7> against <base7>\" (the head alone for an approval from before bases were recorded, null with none); `waitsFor` is {cause, says, action, line} for an open pull green and unlanded over six hours, else null; the 200 carries a weak etag of the exact body, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body and the same etag until the head, a check verdict, a review or the state changes", auth: false, role: "anonymous", alsoStatus: [304], query: { diff: "string" }, response: ref("PullDetail"), refuses: [404] };
4 export const route: Route = { method: "get", path: `${REPO}/pulls/{number}`, summary: "Read one pull with its diff and review gate", detail: "Read one pull with its diff and review gate (diff=0 leaves the diff out; a diff over 4 MiB of git text is left out too, and `diffTooLarge` {limitBytes, says} replaces it: read it at …/pulls/{number}/diff); `check` is the word for the head's check: green, red, running or none; `checkedAgainst` is the base tip that check merged with (null before one recorded it), `checkStale` says the base has moved since, and `approvedAt` is when the standing approval was given (a date string, or null) and `approval` is that approval {at, head, base, current} or null, current false once the head or the base moved, and `approvedAgainst` is the same approval as one string, \"<head7> against <base7>\" (the head alone for an approval from before bases were recorded, null with none); `waitsFor` is {cause, says, action, line} for an open pull green and unlanded over six hours, else null; the 200 carries a weak etag of the exact body, cache-control private, no-cache and vary authorization, cookie, and a repeat sending If-None-Match gets 304 with no body and the same etag until the head, a check verdict, a review or the state changes", auth: false, role: "anonymous", alsoStatus: [304], query: { diff: "string" }, response: ref("PullDetail"), refuses: [404] };
src/contract/openapi/schemas/pull.ts +2 −1
@@ -64,7 +64,8 @@ const PULL_DETAIL: Schema = obj(
6464 check: words("green", "red", "running", "none"),
6565 checkStale: bool,
6666 checkedAgainst: orNull(str),
67 approvedAt: orNull(APPROVAL),
67 approvedAt: orNull(str),
68 approval: orNull(APPROVAL),
6869 approvedAgainst: orNull(str),
6970 variantSiblings: list(int),
7071 mergeable: bool,
src/core/approval_at.ts +1 −1
@@ -30,7 +30,7 @@ export function movedSinceApproval(
3030 /**
3131 * The approval in one string, "<head7> against <base7>": what it was given
3232 * for, readable in a line. An approval from before bases were recorded names
33 * its head alone; no approval is null. `approvedAt` carries the same facts as
33 * its head alone; no approval is null. `approval` carries the same facts as
3434 * an object; this is the form for a line of text.
3535 */
3636 export function approvedAgainst(approval: { head: string; base: string | null } | null | undefined): string | null {
src/http/api/pulls.ts +4 −1
@@ -409,9 +409,12 @@ export function pullRoutes(router: Router<Handler>): void {
409409 // The base tip the head's check merged with; null before any check
410410 // recorded one. Beside `checkStale` it names which main was tested.
411411 checkedAgainst: checked !== null && checked.baseOid !== "" ? checked.baseOid : null,
412 // When the standing approval was given: a date string, as it was before #16761. A field's
413 // type never changes (#17944); the richer record is `approval`.
414 approvedAt: status.reviews?.approval?.at ?? null,
412415 // The approval and what it was given for; `current` is false once the head or the base
413416 // moved.
414 approvedAt: status.reviews?.approval ?? null,
417 approval: status.reviews?.approval ?? null,
415418 // The same approval as one line, "<head7> against <base7>" (null with none).
416419 approvedAgainst: approvedAgainst(status.reviews?.approval),
417420 variantSiblings: variantSiblings(ctx.app.db, [found.pull])[0] ?? [],
test/approval-base.test.ts +18 −9
@@ -1,8 +1,10 @@
11 /**
22 * An approval is recorded against the head and the base tip it was given
33 * for, and stops being current when either moves: the API carries
4 * `approvedAt.base`, the pull page's reviews chip says when the base moved.
4 * `approval.base`, the pull page's reviews chip says when the base moved.
outdated

This header still says the API carries approvedAt.base; it is approval.base now.

55 */
6 import { openapi } from "../src/contract/openapi.ts";
7 import { declared, disagreements } from "./support/conforms.ts";
68 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
79 import { mkdtemp, rm } from "node:fs/promises";
810 import { tmpdir } from "node:os";
@@ -92,23 +94,30 @@ describe("approvedAt over the API and the page", () => {
9294 const number = opened.value.number;
9395 const path = `/api/v1/repos/alice/lib/pulls/${number}?diff=0`;
9496
95 expect((await (await get(path)).json() as { approvedAt: unknown }).approvedAt).toBeNull();
97 const none = (await (await get(path)).json()) as { approvedAt: unknown; approval: unknown };
98 expect(none.approvedAt).toBeNull();
99 expect(none.approval).toBeNull();
96100
97101 const pull = getPull(app.db, repo.id, number)!;
98102 const approved = await submitReview(app, bob, repo, pull, { state: "approved" });
99103 if (!approved.ok) throw new Error(String(approved.error));
100 const body = (await (await get(path)).json()) as { approvedAt: { head: string; base: string; current: boolean; at: string } };
101 expect(body.approvedAt.head).toBe(side.value.commitOid);
102 expect(body.approvedAt.base).toBe(first.value.commitOid);
103 expect(body.approvedAt.current).toBe(true);
104 const body = (await (await get(path)).json()) as { approvedAt: string; approval: { head: string; base: string; current: boolean; at: string } };
105 expect(body.approval.head).toBe(side.value.commitOid);
106 expect(body.approval.base).toBe(first.value.commitOid);
107 expect(body.approval.current).toBe(true);
108 expect(body.approvedAt).toBe(body.approval.at);
109 // The contract test: the answer matches what openapi.json declares for it (#17944).
110 const doc = openapi("https://forge.test", "test", "admin") as Record<string, unknown>;
111 const schema = declared(doc, "/api/v1/repos/{owner}/{name}/pulls/{number}", "get");
112 expect(disagreements(body, schema, doc)).toEqual([]);
104113
105114 expect(await (await get(`/alice/lib/pulls/${number}/files`)).text()).not.toContain("the base moved since the approval");
106115
107116 const moved = await commitToBranch(app, alice, repo, { message: "two", files: [{ path: "b.md", content: "b\n" }] });
108117 if (!moved.ok) throw new Error(JSON.stringify(moved.error));
109 const after = (await (await get(path)).json()) as { approvedAt: { head: string; base: string; current: boolean } };
110 expect(after.approvedAt.base).toBe(first.value.commitOid);
111 expect(after.approvedAt.current).toBe(false);
118 const after = (await (await get(path)).json()) as { approval: { head: string; base: string; current: boolean } };
119 expect(after.approval.base).toBe(first.value.commitOid);
120 expect(after.approval.current).toBe(false);
112121 expect(await (await get(`/alice/lib/pulls/${number}/files`)).text()).toContain("the base moved since the approval");
113122 }, 60_000);
114123 });
test/approval-moved-inbox.test.ts +4 −4
@@ -122,8 +122,8 @@ describe("the inbox row of an approved pull", () => {
122122 expect(await asks()).not.toContain("moved since approval");
123123 const body = await readPull();
124124 expect(body.approvedAgainst).toBe(`${pull.headOid.slice(0, 7)} against ${(await mainTip()).slice(0, 7)}`);
125 expect(body.approvedAt.current).toBe(true);
126 expect(body.approvedAt.head.slice(0, 7)).toBe(pull.headOid.slice(0, 7));
125 expect(body.approval.current).toBe(true);
126 expect(body.approval.head.slice(0, 7)).toBe(pull.headOid.slice(0, 7));
127127 againstThen = body.approvedAgainst;
128128 });
129129
@@ -136,7 +136,7 @@ describe("the inbox row of an approved pull", () => {
136136 const body = await readPull();
137137 expect(body.approvedAgainst).toBe(againstThen); // the approval is what it was
138138 expect(body.approvedAgainst).not.toContain(`against ${(await mainTip()).slice(0, 7)}`);
139 expect(body.approvedAt.current).toBe(false);
140 expect(body.approvedAt.head).toBe(pull.headOid);
139 expect(body.approval.current).toBe(false);
140 expect(body.approval.head).toBe(pull.headOid);
141141 }, 60_000);
142142 });
test/support/conforms.test.ts added +12
@@ -0,0 +1,12 @@
1 import { expect, test } from "bun:test";
2 import { disagreements } from "./conforms.ts";
3
4 const doc = { components: { schemas: {} } };
5 const schema = { type: "object", required: ["at"], properties: { at: { type: ["string", "null"] } } };
6
7 test("a field that changes type is named", () => {
8 expect(disagreements({ at: "2026-01-01" }, schema, doc)).toEqual([]);
9 expect(disagreements({ at: null }, schema, doc)).toEqual([]);
10 expect(disagreements({ at: { at: "x" } }, schema, doc)).toEqual(["$.at: is object, declared string|null"]);
11 expect(disagreements({}, schema, doc)).toEqual(["$.at: missing"]);
12 });
test/support/conforms.ts added +44
@@ -0,0 +1,44 @@
1 /**
2 * Does a JSON value match the schema openapi.json declares for it (#17944)? Only what the
3 * contract's own kit writes (`schema_kit.ts`): type (or a type list), enum, required, properties,
4 * items, anyOf and `$ref`. Properties not declared are allowed, as the contract says.
5 * Returns what disagrees, each as `path: why`; empty means it conforms.
6 */
7 type S = Record<string, unknown>;
8
9 const kind = (v: unknown): string => (v === null ? "null" : Array.isArray(v) ? "array" : Number.isInteger(v) ? "integer" : typeof v);
10
11 export function disagreements(value: unknown, schema: S, doc: S, at = "$"): string[] {
12 if (typeof schema.$ref === "string") {
13 const name = schema.$ref.replace("#/components/schemas/", "");
14 const target = ((doc.components as S).schemas as Record<string, S>)[name];
15 return target ? disagreements(value, target, doc, at) : [`${at}: unknown schema ${name}`];
16 }
17 if (Array.isArray(schema.anyOf)) {
18 const tries = (schema.anyOf as S[]).map((s) => disagreements(value, s, doc, at));
19 return tries.some((t) => t.length === 0) ? [] : tries[0]!;
20 }
21 const out: string[] = [];
22 const types = schema.type === undefined ? [] : ([] as string[]).concat(schema.type as string | string[]);
23 const k = kind(value);
24 if (types.length > 0 && !types.includes(k) && !(k === "integer" && types.includes("number"))) {
25 return [`${at}: is ${k}, declared ${types.join("|")}`];
26 }
27 if (Array.isArray(schema.enum) && !schema.enum.includes(value)) out.push(`${at}: ${JSON.stringify(value)} is not one of ${JSON.stringify(schema.enum)}`);
28 if (k === "object") {
29 const o = value as S;
30 for (const key of (schema.required as string[] | undefined) ?? []) if (!(key in o)) out.push(`${at}.${key}: missing`);
31 for (const [key, sub] of Object.entries((schema.properties as Record<string, S> | undefined) ?? {})) {
32 if (key in o) out.push(...disagreements(o[key], sub, doc, `${at}.${key}`));
33 }
34 }
35 if (k === "array" && schema.items) (value as unknown[]).forEach((v, i) => out.push(...disagreements(v, schema.items as S, doc, `${at}[${i}]`)));
36 return out;
37 }
38
39 /** The schema a route declares for its 200 JSON answer. */
40 export function declared(doc: S, path: string, method: string): S {
41 const op = ((doc.paths as S)[path] as S)[method] as S;
42 const ok = (op.responses as S)["200"] as S;
43 return ((ok.content as S)["application/json"] as S).schema as S;
44 }

Search
↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs