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

GET …/issues/{number}?comments=N answers only the last N comments and says how many there are #4075

Parked opened this
Closed without merging

scout/forge:scout/3364-get-issues-number-comments-n-answers-onl → main 9 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
8 files changed +105 −25
README.md +1 −1
@@ -208,7 +208,7 @@ runs no check and no preview until a writer approves its head or lets it run
208208 (**Let it run here**, which is not a review; a new push waits again), and a bare push to `child/…` starts none. A pull
209209 opened with it says "proposed by child … from …" on every tab of the pull's
210210 page, in the terminal's pull view, and as `proposal` in the pull's JSON
211 (`GET …/pulls/:number`, and MCP's `pull` tool). `GET …/pulls/:number?diff=0` reads the pull without its diff (and skips computing it); `diff` is `0` or `1`, default `1`, and anything else answers 422. `GET …/issues?fields=brief` lists issues with only number, kind, title, state, labels, assignee, author, originAuthor, authorIsAgent, createdAt and updatedAt (and `untrusted` where it applies); no bodies or comments. `fields` is `brief` or left out, and anything else answers 422 `invalid_fields`.
211 (`GET …/pulls/:number`, and MCP's `pull` tool). `GET …/pulls/:number?diff=0` reads the pull without its diff (and skips computing it); `diff` is `0` or `1`, default `1`, and anything else answers 422. `GET …/issues?fields=brief` lists issues with only number, kind, title, state, labels, assignee, author, originAuthor, authorIsAgent, createdAt and updatedAt (and `untrusted` where it applies); no bodies or comments. `fields` is `brief` or left out, and anything else answers 422 `invalid_fields`. `GET …/issues/:number?comments=N` answers only the newest N comments, oldest first, plus `commentCount` with the total; N is 0 to 200, anything else answers 422 `invalid_comments`, and without the parameter the answer is unchanged. MCP's `issue` tool takes the same optional `comments` argument.
212212
213213 ### Proposing to a parent forge
214214
docs/MCP.md +1 −1
@@ -32,7 +32,7 @@ for a tunnel and a forge that sleeps.
3232 | `repo` | `{ repo }`: one repository's description, visibility, autonomy, `audience { level, sentence }` and `provenance` (where a migrated one came from, `null` when hidden), the same as `GET /api/v1/repos/:owner/:name` | |
3333 | `tell` | a sentence becomes an issue, a builder is picked, a run starts on the crew's next tick | yes |
3434 | `say` | speak on an issue or a pull; a working builder hears it as its next step | yes |
35 | `issue` | `{ repo, number }`: one issue's title, state, closeReason, body, labels, assignee, comments (author, authorIsAgent, body, at) and blockedBy/blocks, as `GET …/issues/:number`; a sealed one you cannot see is not found | |
35 | `issue` | `{ repo, number, comments? }`: one issue's title, state, closeReason, body, labels, assignee, comments (author, authorIsAgent, body, at) and blockedBy/blocks, as `GET …/issues/:number`; `comments` (0 to 200) keeps only the newest that many, with `commentCount` the total; a sealed one you cannot see is not found | |
3636 | `pull` | `{ repo, number }`: a pull's title, state, head and base, and for an open pull whether it merges into the base's current head (`mergeable`) and the paths that stop it (`conflicts`), and `check: { state, baseOid }`: the latest check's state and the base tip it was merged with (empty when it merged nothing); `mergeable` and `conflicts` are the same fields as `GET …/pulls/:number`, `check` is `state` and `run.baseOid` from `GET …/pulls/:number/checks` | |
3737 | `edit` | a new title or body for an issue or a pull: its author's, or a writer's; an agent edits only what it wrote | yes |
3838 | `pulls` | `{ repo, state?, limit? }`: a repository's pulls, newest first, one brief line each: `number`, `title`, `author`, `head`, `check` (state), `approvals`, `changesRequested`, `mergeable` (null once closed); `state` open (default) or closed, `limit` 1-50 (default 20); no bodies, no diffs | no |
src/contract/openapi.ts +31 −16
@@ -15,8 +15,8 @@ interface Route {
1515 readonly auth: boolean;
1616 /** A JSON body's fields, when it takes one. */
1717 readonly body?: Readonly<Record<string, string>>;
18 /** The query parameters its handler reads, by name and type. */
19 readonly query?: Readonly<Record<string, string>>;
18 /** The query parameters its handler reads: a type, or a description with its JSON schema. */
19 readonly query?: Readonly<Record<string, string | { readonly description: string; readonly schema: Record<string, unknown> }>>;
2020 /** The success status, when it is not 200. */
2121 readonly status?: number;
2222 /** The refusals it answers, by stable `error` code. */
@@ -73,7 +73,6 @@ export const ROUTES: readonly Route[] = [
7373 auth: true,
7474 body: { title: "string", body: "string" },
7575 },
76 { method: "get", path: `${REPO}/issues/{number}`, summary: "Read one issue with its comments", auth: false },
7776 {
7877 method: "patch",
7978 path: `${REPO}/issues/{number}`,
@@ -82,6 +81,18 @@ export const ROUTES: readonly Route[] = [
8281 body: { state: "string", reason: "string", into: "integer" },
8382 },
8483 { method: "get", path: `${REPO}/pulls/{number}`, summary: "Read one pull with its diff and review gate (diff=0 leaves the diff out)", auth: false, query: { diff: "string" } },
84 {
85 method: "get",
86 path: `${REPO}/issues/{number}`,
87 summary: "Read one issue with its comments",
88 auth: false,
89 query: {
90 comments: {
91 description: "Answer only the newest N comments and `commentCount` with the total",
92 schema: { type: "integer", minimum: 0, maximum: 200 },
93 },
94 },
95 },
8596 {
8697 method: "post",
8798 path: `${REPO}/issues/{number}/comments`,
@@ -161,19 +172,23 @@ export function openapi(origin: string, version: string): Record<string, unknown
161172 required: true,
162173 schema: { type: m[1] === "number" || m[1] === "blocker" ? "integer" : "string" },
163174 }));
164 const query = Object.entries(r.query ?? {}).map(([name, t]) => ({
165 name,
166 in: "query",
167 required: false,
168 schema:
169 name === "state"
170 ? { type: "string", enum: ["open", "closed", "all"] }
171 : name === "fields"
172 ? { type: "string", enum: ["brief"] }
173 : name === "diff"
174 ? { type: "string", enum: ["0", "1"], default: "1" }
175 : schema(t),
176 }));
175 const query = Object.entries(r.query ?? {}).map(([name, t]) =>
176 typeof t === "string"
177 ? {
178 name,
179 in: "query",
180 required: false,
181 schema:
182 name === "state"
183 ? { type: "string", enum: ["open", "closed", "all"] }
184 : name === "fields"
185 ? { type: "string", enum: ["brief"] }
186 : name === "diff"
187 ? { type: "string", enum: ["0", "1"], default: "1" }
188 : schema(t),
189 }
190 : { name, in: "query", required: false, description: t.description, schema: t.schema },
191 );
177192 (paths[r.path] ??= {})[r.method] = {
178193 operationId: `${r.method}${r.path.replace(/[^A-Za-z0-9]+(.)?/g, (_, c: string | undefined) => (c ?? "").toUpperCase())}`,
179194 summary: r.summary,
src/http/api.ts +8 −5
@@ -3225,7 +3225,13 @@ export function apiRoutes(router: Router<Handler>): void {
32253225 // shape, marked `kind: "pull"`, with the path where its diff lives (#3299).
32263226 const found = loadConversation(ctx);
32273227 if ("error" in found) return found.error;
3228 const asked = ctx.url.searchParams.get("comments");
3229 if (asked !== null && (!/^\d{1,3}$/.test(asked) || Number(asked) > 200))
3230 return apiError("invalid_comments", 422, "comments is a whole number from 0 to 200");
3231 const last = asked === null ? null : Number(asked);
32283232 const { repo, issue } = found;
3233 const all = listComments(ctx.app.db, issue.id);
3234 const shown = last === null ? all : last === 0 ? [] : all.slice(-last);
32293235 return json({
32303236 ...withLabels(ctx, issue),
32313237 ...(issue.kind === "pull"
@@ -3233,11 +3239,8 @@ export function apiRoutes(router: Router<Handler>): void {
32333239 pull: `/api/v1/repos/${repo.ownerName}/${repo.name}/pulls/${issue.number}`,
32343240 }
32353241 : {}),
3236 comments: readerMarked(
3237 ctx,
3238 found.repo.id,
3239 listComments(ctx.app.db, found.issue.id),
3240 ),
3242 comments: readerMarked(ctx, repo.id, shown),
3243 ...(last === null ? {} : { commentCount: all.length }),
32413244 });
32423245 });
32433246
src/http/mcp.ts +11 −2
@@ -710,12 +710,13 @@ const TOOLS: readonly Tool[] = [
710710 {
711711 name: "issue",
712712 description:
713 "Read one issue: title, state, closeReason, body, labels, assignee, comments (author, agent or not, body, time), `blockedBy`, `blocks`. A crew agent sees `untrusted: true` on text by non-writers, as in the REST API. Sealed or private issues you cannot see are not found.",
713 "Read one issue: title, state, closeReason, body, labels, assignee, its comments (author, whether the author is an agent, body, time), and `blockedBy` and `blocks` (what it waits for, and what waits for it). Text written by someone who cannot write the repository carries `untrusted: true`, as in GET /api/v1/repos/:owner/:name/issues/:number (shown to a crew agent only). A sealed or private issue you cannot see is not found. `comments` (0 to 200) answers only the newest that many comments, oldest first, plus `commentCount` with the total.",
714714 inputSchema: {
715715 type: "object",
716716 properties: {
717717 repo: REPO_ARG,
718718 number: { type: "integer", minimum: 1 },
719 comments: { type: "integer", minimum: 0, maximum: 200 },
719720 },
720721 required: ["repo", "number"],
721722 },
@@ -734,6 +735,12 @@ const TOOLS: readonly Tool[] = [
734735 !mayView(ctx.app.db, repo, issue, user)
735736 )
736737 return bad("not_found", `no issue #${String(n)}`);
738 const asked = args["comments"];
739 if (
740 asked !== undefined &&
741 (typeof asked !== "number" || !Number.isInteger(asked) || asked < 0 || asked > 200)
742 )
743 return bad("invalid_comments", "comments is a whole number from 0 to 200");
737744 const db = ctx.app.db;
738745 // Marked only for a crew agent, as the API does: to anyone else the
739746 // mark would say which commenters cannot write.
@@ -742,7 +749,8 @@ const TOOLS: readonly Tool[] = [
742749 items: readonly T[],
743750 ): (T & { untrusted?: string })[] =>
744751 marking ? markReaders(db, repo, items) : [...items];
745 const comments = mark(listComments(db, issue.id));
752 const every = listComments(db, issue.id);
753 const comments = mark(asked === undefined ? every : asked === 0 ? [] : every.slice(-asked));
746754 const authors = getUsersByIds(db, [...new Set(comments.map((c) => c.authorId))]);
747755 const deps = dependenciesOf(db, issue.id);
748756 const brief = (i: typeof issue) => ({
@@ -773,6 +781,7 @@ const TOOLS: readonly Tool[] = [
773781 at: c.createdAt,
774782 ...flag(c),
775783 })),
784 ...(asked === undefined ? {} : { commentCount: every.length }),
776785 blockedBy: deps.blockedBy.filter(seen).map(brief),
777786 blocks: deps.blocks.filter(seen).map(brief),
778787 });
test/api-reader-marks.test.ts +33
@@ -348,3 +348,36 @@ describe("every other place a builder or a decider reads a reader's words", () =
348348 expect(got.comments[0].untrusted).toBe(READER);
349349 });
350350 });
351
352 describe("reading an issue with only its newest comments", () => {
353 test("comments=N answers the last N in time order and the total", async () => {
354 const issue = ok(openIssue(app, alice, repo, { title: "Long thread", body: "x" }));
355 for (let i = 1; i <= 30; i++) ok(addComment(app, alice, repo, issue, `c${i}`));
356 const res = await fetch(
357 `${servers.url}/api/v1/repos/alice/square/issues/${issue.number}?comments=5`,
358 { headers: { authorization: `Bearer ${botToken}` } },
359 );
360 const body = (await res.json()) as any;
361 expect(body.commentCount).toBe(30);
362 expect(body.comments.map((c: any) => c.body)).toEqual(["c26", "c27", "c28", "c29", "c30"]);
363 const none = (await (await fetch(
364 `${servers.url}/api/v1/repos/alice/square/issues/${issue.number}?comments=0`,
365 )).json()) as any;
366 expect(none.comments).toEqual([]);
367 expect(none.commentCount).toBe(30);
368 const all = (await (await fetch(
369 `${servers.url}/api/v1/repos/alice/square/issues/${issue.number}`,
370 )).json()) as any;
371 expect(all.comments.length).toBe(30);
372 expect(all.commentCount).toBeUndefined();
373 });
374
375 test("anything but 0 to 200 is a 422", async () => {
376 for (const bad of ["abc", "-1", "201", "1.5", ""]) {
377 const res = await fetch(
378 `${servers.url}/api/v1/repos/alice/square/issues/${issueNumber}?comments=${bad}`,
379 );
380 expect(res.status).toBe(422);
381 }
382 });
383 });
test/mcp.test.ts +12
@@ -492,6 +492,18 @@ describe("the forge over MCP", () => {
492492 const other = (await tool(rw, "issue", { repo: "alice/game", number: first.number })).value;
493493 expect(other.blocks.map((b: any) => b.number)).toEqual([waiting.number]);
494494
495 // comments=N keeps the newest N, oldest first, and counts them all.
496 const last = (await tool(rw, "issue", { repo: "alice/game", number: waiting.number, comments: 1 })).value;
497 expect(last.comments.map((c: any) => c.body)).toEqual(["two"]);
498 expect(last.commentCount).toBe(2);
499 const none = (await tool(rw, "issue", { repo: "alice/game", number: waiting.number, comments: 0 })).value;
500 expect([none.comments, none.commentCount]).toEqual([[], 2]);
501 expect(read.commentCount).toBeUndefined();
502 for (const bad of [-1, 201, 1.5, "2"])
503 expect((await tool(rw, "issue", { repo: "alice/game", number: waiting.number, comments: bad })).error).toContain(
504 "invalid_comments",
505 );
506
495507 // Not found: no such number, and a pull's number is not an issue's.
496508 expect((await tool(rw, "issue", { repo: "alice/game", number: 9999 })).error).toContain("not_found");
497509 const branched = await commitToBranch(app, alice, game, {
test/openapi.test.ts +8
@@ -47,6 +47,14 @@ test("the map, plan and dependency routes are described", () => {
4747 expect(del.parameters.find((p: any) => p.name === "blocker").schema.type).toBe("integer");
4848 });
4949
50 test("reading one issue names the comments query parameter and its bound", () => {
51 const doc = openapi("https://f.test", "1") as any;
52 const params = doc.paths["/api/v1/repos/{owner}/{name}/issues/{number}"].get.parameters;
53 const comments = params.find((p: any) => p.name === "comments");
54 expect(comments.in).toBe("query");
55 expect(comments.schema.maximum).toBe(200);
56 });
57
5058 test("listing issues and pulls is described with the query the handlers read", () => {
5159 const doc = openapi("https://f.test", "1") as any;
5260 const R = "/api/v1/repos/{owner}/{name}";

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs