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

Issues: a route to assign an issue to a person or an agent #18285

opened this in answer to

Its check is red, 19h 45m ago

check failed: 1 of 2244 tests — "listing issues and pulls is described with the query the handlers read"

scout/forge:scout/18256-issues-a-route-to-assign-an-issue-to-a-p → main 3 commits fork

Review

Sign in to review this change.
11 files changed +144 −12
docs/features/api-list-filters.md +2 −1
@@ -13,9 +13,10 @@ GET /api/v1/repos/OWNER/NAME/pulls?labels=bug
1313 ```
1414
1515 - **`labels=a,b`** keeps the items carrying every label named (AND), each by name (case-insensitive) or id. It works on both lists and combines with `label=`, `author=` and `state=`. More than 20 names is a 422 `invalid_labels`.
16 - **`assignee=name`** (issues only) keeps the issues assigned to that account (case-insensitive); `assignee=me` is the caller's own, a 401 when signed out. The terminal's issue list does the same with `o`, and the MCP `issues` tool takes `assignee`. `POST …/issues` takes `assignee` too, to file an issue already assigned; across every repository, `GET /api/v1/user/assigned` is the caller's list.
1617 - **`milestone=N`** (issues only) keeps the issues beneath issue N: everything it waits for, directly or through others. This is the tree the milestone page counts. The walk never passes through the plan's furniture (pillar umbrellas, the Later umbrella, the gate), and the sealed scope still applies to what it finds.
1718 - **`milestone=` refuses** with a 422 `invalid_milestone` when N is not a whole number, is not an issue of this repository the caller can see (a pull's number included), or is the **Later umbrella or the Later gate**. The plan counts as Later everything that waits behind the gate, which runs the other way through the graph from Later's own links, so a walk of Later's links would come up short of the plan. Read deferred work from `GET /api/v1/repos/OWNER/NAME/map` instead.
18 - **Any other parameter is a 422 `unknown_parameter`.** Its `message` names what the list does not read, and `accepted` lists what it does: `state, label, labels, author, cursor, limit`, plus `fields, milestone` on the issue list. `fields=a,b` (see [fields](api-fields.md)) is read before this check, on both lists.
19 - **Any other parameter is a 422 `unknown_parameter`.** Its `message` names what the list does not read, and `accepted` lists what it does: `state, label, labels, author, cursor, limit`, plus `fields, milestone, assignee` on the issue list. `fields=a,b` (see [fields](api-fields.md)) is read before this check, on both lists.
1920
2021 **This breaks clients that send extra parameters.** Before, the forge ignored a parameter it did not read. A typo such as `?lables=bug`, or a filter the forge does not have such as `?milestone=` on pulls, returned the whole list as if it were filtered. Now the same request is a 422. A client that adds its own parameters (a cache-buster such as `?_=123`, tracking tags) must drop them for these two lists. `?page=` and `?offset=` keep their own 400 `invalid_query` (see [the API reference](api-reference.md)).
2122
src/contract/openapi/routes/getApiV1ReposOwnerNameIssues.ts +1 −1
@@ -1,3 +1,3 @@
11 import { ISSUE_ITEM_KEYS, LIST_QUERY, REPO, type Route } from "../shared.ts";
22
3 export const route: Route = { method: "get", path: `${REPO}/issues`, summary: "List a repository's issues", detail: "List a repository's issues; the repository's standing direction issue carries standing: true and is the one open issue counts.openIssues leaves out; fields=brief leaves out bodies and comments, any other fields value is a 422 invalid_fields; the 200 carries a weak etag of the page and cache-control private, no-cache (it varies by reader), and a repeat sending If-None-Match gets 304 with no body; milestone=N lists the tree beneath issue N, refusing the Later umbrella and gate, whose deferred count is the map's; labels=a,b keeps issues carrying every one", auth: false, role: "anonymous", alsoStatus: [304], itemKeys: ISSUE_ITEM_KEYS, query: { ...LIST_QUERY, fields: "string", milestone: "integer" }, refusals: { invalid_limit: "limit is not a whole number from 1 to 200 (422)", invalid_cursor: "cursor is not the next_cursor of a previous page (422)", invalid_state: "state is not open, closed or all (422)", unknown_parameter: "a parameter this list does not read (422)", invalid_labels: "over 20 labels (422)", invalid_milestone: "milestone is not an issue of this repository the caller can see, or is the Later umbrella or gate (422)" }, refuses: [404] };
3 export const route: Route = { method: "get", path: `${REPO}/issues`, summary: "List a repository's issues", detail: "List a repository's issues; the repository's standing direction issue carries standing: true and is the one open issue counts.openIssues leaves out; fields=brief leaves out bodies and comments, any other fields value is a 422 invalid_fields; the 200 carries a weak etag of the page and cache-control private, no-cache (it varies by reader), and a repeat sending If-None-Match gets 304 with no body; milestone=N lists the tree beneath issue N, refusing the Later umbrella and gate, whose deferred count is the map's; labels=a,b keeps issues carrying every one; assignee=<username> keeps those assigned to that account and assignee=me those assigned to the caller (401 when signed out)", auth: false, role: "anonymous", alsoStatus: [304], itemKeys: ISSUE_ITEM_KEYS, query: { ...LIST_QUERY, fields: "string", milestone: "integer", assignee: "string" }, refusals: { invalid_limit: "limit is not a whole number from 1 to 200 (422)", invalid_cursor: "cursor is not the next_cursor of a previous page (422)", invalid_state: "state is not open, closed or all (422)", unknown_parameter: "a parameter this list does not read (422)", invalid_labels: "over 20 labels (422)", invalid_milestone: "milestone is not an issue of this repository the caller can see, or is the Later umbrella or gate (422)" }, refuses: [404] };
src/contract/openapi/routes/postApiV1ReposOwnerNameIssues.ts +7 −2
@@ -3,9 +3,14 @@ import { REPO, type Route } from "../shared.ts";
33 export const route: Route = {
44 method: "post",
55 path: `${REPO}/issues`,
6 summary: "Open an issue",
6 summary: "Open an issue, optionally assigned",
7 detail: "Open an issue (rw scope); `assignee` is a username, or null or left out for nobody, through the same check as PUT …/assignee; an unknown name is refused before anything is filed, and an assignment the check refuses leaves the issue filed with `assignRefused` naming why",
78 auth: true,
89 role: "member",
9 body: { title: "string", body: "string" },
10 body: { title: "string", body: "string", assignee: "string" },
11 refusals: {
12 invalid_assignee: "`assignee` is neither a username nor null (422)",
13 no_such_user: "`assignee` names no account (422)",
14 },
1015 refuses: [401, 404],
1116 };
src/http/api/issues.ts +24 −3
@@ -7,7 +7,8 @@
77
88 import { cursorRefusal, limitRefusal } from "../../contract/page_query.ts";
99 import { parseLimit } from "../../contract/page_query.ts";
10 import { markQuestion } from "../../actions/issues.ts";
10 import { getUserByName } from "../../core/users.ts";
11 import { assignIssue, markQuestion } from "../../actions/issues.ts";
1112 import { parseQuestion } from "../../core/issues.ts";
1213 import { mayReadRuns } from "../../actions/runs.ts";
1314 import { costField, issueCostFor } from "../../core/issue_cost.ts";
@@ -190,13 +191,21 @@ export function issueRoutes(router: Router<Handler>): void {
190191 const fields = ctx.url.searchParams.get("fields");
191192 if (fields !== null && fields !== "brief")
192193 return apiError("invalid_fields", 422, "fields must be brief, or left out");
193 const query = listQuery(ctx, ["fields", "milestone"]);
194 const query = listQuery(ctx, ["fields", "milestone", "assignee"]);
194195 if (query instanceof Response) return query;
196 // `assignee=me` is the caller's own list; a name is a username.
197 const assigneeParam = ctx.url.searchParams.get("assignee");
198 if (assigneeParam === "me") {
199 const denied = requireScope(ctx, "ro");
200 if (denied) return denied;
201 }
202 const assignee = assigneeParam === "me" ? ctx.auth.user!.username : assigneeParam;
195203 const beneath = milestoneScope(ctx, repo);
196204 if (beneath instanceof Response) return beneath;
197205 const listed = timePhase(ctx.request, "list", () =>
198206 listIssues(ctx.app.db, repo.id, {
199207 ...query,
208 ...(assignee ? { assignee } : {}),
200209 ...(beneath !== undefined ? { beneath } : {}),
201210 kind: "issue",
202211 ...sealedScope(ctx.app.db, repo, ctx.auth.user),
@@ -233,6 +242,13 @@ export function issueRoutes(router: Router<Handler>): void {
233242 if (!repo) return notFound();
234243 const input = await body(ctx.request);
235244 const got = parse(NEW_ISSUE, input);
245 // An assignee at creation: a username, or null/left out for nobody.
246 // Named wrongly it is refused before anything is filed.
247 const named = input.assignee;
248 if (named !== undefined && named !== null && typeof named !== "string")
249 return apiError("invalid_assignee", 422, "assignee must be a username or null");
250 const assignee = typeof named === "string" && named !== "" ? getUserByName(ctx.app.db, named) : null;
251 if (assignee === undefined) return apiError("no_such_user", 422, `no account named ${named}`);
236252 const created = await openIssueThrough(ctx.app, ctx.auth.user, repo, {
237253 title: str(input.title),
238254 body: str(input.body),
@@ -240,7 +256,12 @@ export function issueRoutes(router: Router<Handler>): void {
240256 ...(input.sealed === true ? { sealed: true } : {}),
241257 });
242258 if (!created.ok) return originAware(created.error);
243 return json(withLabels(ctx, created.value), 201);
259 if (assignee === null) return json(withLabels(ctx, created.value), 201);
260 // The issue is filed either way; a refused assignment is told beside it.
261 const assigned = assignIssue(ctx.app, ctx.auth.user, repo, created.value, assignee);
262 return assigned.ok
263 ? json(withLabels(ctx, assigned.value), 201)
264 : json({ ...withLabels(ctx, created.value), assignRefused: assigned.error }, 201);
244265 });
245266
246267 // The plan a crew run keeps on its issue: replaced whole at each update (#8707).
src/http/mcp/tools/issues.ts +6 −3
@@ -12,7 +12,7 @@ import { good, bad, limitArg, type Tool, REPO_ARG, repoArg, isAnswer } from "../
1212
1313 export const tool: Tool = {
1414 name: "issues",
15 doc: "`{ repo, state?, label?, author?, limit?, cursor? }`: a repository's issues, newest first, as `{ items, next_cursor }` like `GET …/issues?fields=brief`: `number`, `title`, `state`, `labels`, `assignee`, `author`, `authorIsAgent`, `createdAt`, `updatedAt`, and `untrusted: true` on text from someone who cannot write, `standing: true` on the repository's direction issue (the one open issue no count of open issues includes); `state` open (default), closed or all, `label` a name, `author` a username, `limit` 1-200 (default 50), `cursor` the last `next_cursor`; a sealed issue you cannot see is left out, a repository you cannot read is not found; draws the `ui://forge/issues` card: state, pillar and what each waits on",
15 doc: "`{ repo, state?, label?, author?, limit?, cursor? }`: a repository's issues, newest first, as `{ items, next_cursor }` like `GET …/issues?fields=brief`: `number`, `title`, `state`, `labels`, `assignee`, `author`, `authorIsAgent`, `createdAt`, `updatedAt`, and `untrusted: true` on text from someone who cannot write, `standing: true` on the repository's direction issue (the one open issue no count of open issues includes); `state` open (default), closed or all, `label` a name, `author` a username, `assignee` a username or `me`, `limit` 1-200 (default 50), `cursor` the last `next_cursor`; a sealed issue you cannot see is left out, a repository you cannot read is not found; draws the `ui://forge/issues` card: state, pillar and what each waits on",
1616 description: "A repo's issues by state, label and author, newest first, paged.",
1717 inputSchema: {
1818 type: "object",
@@ -21,6 +21,7 @@ export const tool: Tool = {
2121 state: { type: "string", enum: ["open", "closed", "all"] },
2222 label: { type: "string" },
2323 author: { type: "string" },
24 assignee: { type: "string" },
2425 limit: { type: "integer", minimum: 1, maximum: 200 },
2526 cursor: { type: "string" },
2627 },
@@ -49,8 +50,9 @@ export const tool: Tool = {
4950 };
5051 const label = text("label");
5152 const author = text("author");
52 if (label instanceof Error || author instanceof Error)
53 return bad("invalid", "`label` and `author` are names");
53 const assignee = text("assignee");
54 if (label instanceof Error || author instanceof Error || assignee instanceof Error)
55 return bad("invalid", "`label`, `author` and `assignee` are names");
5456 const db = ctx.app.db;
5557 const rows = listIssues(db, repo.id, {
5658 state,
@@ -59,6 +61,7 @@ export const tool: Tool = {
5961 ...(cursor === undefined ? {} : { cursor }),
6062 ...(label === undefined ? {} : { label }),
6163 ...(author === undefined ? {} : { author }),
64 ...(assignee === undefined ? {} : { assignee: assignee === "me" ? user.username : assignee }),
6265 ...sealedScope(db, repo, user),
6366 });
6467 // Marked as `issue` marks: only for a crew agent, or the forge's own agent
src/tui/screens/issues.ts +12 −1
@@ -3,7 +3,7 @@
33 * an issue with a diff and the list of them differs only in what a row's
44 * state badge can say.
55 *
6 * Filters compose the way the API's do: state segment, label, author, and a
6 * Filters compose the way the API's do: state segment, label, author, assignee (`o`), and a
77 * text search, all folded into the one `issues()` question the `RepoSource`
88 * answers — so the same screen lists what we hold and what another forge
99 * holds, and the TUI can never show a set the JSON surface could not.
@@ -78,6 +78,7 @@ export function issuesScreen(
7878 let segment = 0;
7979 let label: string | undefined;
8080 let mine = false;
81 let onMe = false;
8182 const state = new ListState();
8283 const search = new Filter();
8384 const repo = localRepo(src);
@@ -165,6 +166,7 @@ export function issuesScreen(
165166 state: STATES[segment]!,
166167 ...(label === undefined ? {} : { label }),
167168 ...(mine && f.user ? { author: f.user.username } : {}),
169 ...(onMe && f.user ? { assignee: f.user.username } : {}),
168170 ...(at === undefined ? {} : { cursor: at }),
169171 limit: PAGE,
170172 });
@@ -274,6 +276,7 @@ export function issuesScreen(
274276 binding(["l"], "label"),
275277 ...(stops() > 0 ? [binding(["P"], "pillar")] : []),
276278 binding(["a"], mine ? "all authors" : "only mine"),
279 binding(["o"], onMe ? "all assignees" : "assigned to me"),
277280 ...(mayWrite() ? [binding(["c"], `new ${noun}`)] : []),
278281 ...(kind === "issue" && repo !== undefined ? [binding(["m"], "plan"), binding(["h"], "held")] : []),
279282 binding(["/"], "search"),
@@ -312,6 +315,7 @@ export function issuesScreen(
312315 const chips = [
313316 label === undefined ? "" : `label:${label}`,
314317 mine ? "author:me" : "",
318 onMe ? "assignee:me" : "",
315319 pillar === 0 ? "" : `pillar:${stopTag()}`,
316320 pillar !== 0 && more ? "(more not loaded)" : "",
317321 ]
@@ -401,6 +405,13 @@ export function issuesScreen(
401405 runAsync(ctx, reload);
402406 return true;
403407 }
408 if (e.key === "o") {
409 onMe = !onMe;
410 counted.clear();
411 cursor = undefined;
412 runAsync(ctx, reload);
413 return true;
414 }
404415 if (e.key === "P" && stops() > 0) {
405416 pillar = (pillar + 1) % (stops() + 1);
406417 state.clamp(shown().length);
src/view/local.ts +1
@@ -314,6 +314,7 @@ export function localSource(
314314 ...sealedScope(app.db, repo, actor),
315315 ...(query.label === undefined ? {} : { label: query.label }),
316316 ...(query.author === undefined ? {} : { author: query.author }),
317 ...(query.assignee === undefined ? {} : { assignee: query.assignee }),
317318 ...(query.query === undefined ? {} : { query: query.query }),
318319 ...(Number.isInteger(cursor) && cursor > 0 ? { cursor } : {}),
319320 });
src/view/origin.ts +2
@@ -568,6 +568,8 @@ function matches(item: IssueSummary, query: IssueQuery): boolean {
568568 item.authorName.toLowerCase() !== query.author.toLowerCase()
569569 )
570570 return false;
571 // An origin's summaries carry no assignee, so a list of someone's own is empty, not unfiltered.
572 if (query.assignee !== undefined) return false;
571573 if (
572574 query.query !== undefined &&
573575 query.query.trim() !== "" &&
src/view/source.ts +5
@@ -232,6 +232,11 @@ export interface IssueQuery {
232232 readonly state: "open" | "closed" | "all";
233233 readonly label?: string;
234234 readonly author?: string;
235 /**
236 * A username: only what is assigned to them (a mirror's origin names no assignee here, so it
237 * lists none).
238 */
239 readonly assignee?: string;
235240 readonly query?: string;
236241 readonly cursor?: string;
237242 readonly limit?: number;
test/api-issue-assignee.test.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * An issue is assigned at creation and listed by assignee: `POST …/issues` and
3 * `GET …/issues?assignee=` (#18256).
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { createRepo } from "../src/actions/repos.ts";
11 import { createToken } from "../src/core/tokens.ts";
12 import { createUser } from "../src/core/users.ts";
13 import { serve, type Servers } from "../src/http/server.ts";
14
15 describe("assignee at creation and as a list filter", () => {
16 let dataDir: string;
17 let app: App;
18 let servers: Servers;
19 let alice: string;
20 const base = () => `${servers.url}/api/v1/repos/alice/game/issues`;
21 const post = (payload: unknown) =>
22 fetch(base(), {
23 method: "POST",
24 headers: { authorization: `Bearer ${alice}`, "content-type": "application/json" },
25 body: JSON.stringify(payload),
26 });
27 const list = (query: string, token: string | null = alice) =>
28 fetch(`${base()}${query}`, { headers: token === null ? {} : { authorization: `Bearer ${token}` } });
29
30 beforeAll(async () => {
31 dataDir = await mkdtemp(join(tmpdir(), "forge-api-issue-assignee-"));
32 app = createApp({ dataDir, port: 0 });
33 servers = await serve(app);
34 const seed = { origin: "seed", trusted: true, password: "a-good-passphrase" } as const;
35 const first = await createUser(app.db, { ...seed, username: "alice", email: "[email protected]", adminIfFirst: true });
36 const second = await createUser(app.db, { ...seed, username: "bob", email: "[email protected]" });
37 if (!first.ok || !second.ok) throw new Error("seed failed");
38 const a = first.value;
39 alice = createToken(app.db, a.id, "a", "rw").token;
40 const made = await createRepo(app, a, { name: "game", visibility: "public" });
41 if (!made.ok) throw new Error(String(made.error));
42 }, 30_000);
43
44 afterAll(async () => {
45 servers.stop();
46 app.close();
47 await rm(dataDir, { recursive: true, force: true });
48 });
49
50 test("an issue is filed assigned, and unassigned when no assignee is named", async () => {
51 const mine = await post({ title: "Owner: renew the cert", assignee: "alice" });
52 expect(mine.status).toBe(201);
53 expect(((await mine.json()) as { assigneeName: string }).assigneeName).toBe("alice");
54 const nobody = await post({ title: "Loose end", assignee: null });
55 expect(nobody.status).toBe(201);
56 expect(((await nobody.json()) as { assigneeName: string | null }).assigneeName).toBeNull();
57 });
58
59 test("a bad assignee is refused before anything is filed", async () => {
60 const before = ((await (await list("?state=all")).json()) as { items: unknown[] }).items.length;
61 const ghost = await post({ title: "x", assignee: "nobody-here" });
62 expect(ghost.status).toBe(422);
63 expect(((await ghost.json()) as { error: string }).error).toBe("no_such_user");
64 const odd = await post({ title: "x", assignee: 7 });
65 expect(odd.status).toBe(422);
66 expect(((await odd.json()) as { error: string }).error).toBe("invalid_assignee");
67 const after = ((await (await list("?state=all")).json()) as { items: unknown[] }).items.length;
68 expect(after).toBe(before);
69 });
70
71 test("assignee=me lists the caller's, assignee=name lists that account's", async () => {
72 const titles = async (q: string) =>
73 ((await (await list(q)).json()) as { items: { title: string }[] }).items.map((i) => i.title);
74 expect(await titles("?assignee=me")).toEqual(["Owner: renew the cert"]);
75 expect(await titles("?assignee=ALICE")).toEqual(["Owner: renew the cert"]);
76 expect(await titles("?assignee=bob")).toEqual([]);
77 expect((await titles("")).length).toBe(2);
78 });
79
80 test("assignee=me needs somebody signed in", async () => {
81 expect((await list("?assignee=me", null)).status).toBe(401);
82 });
83 });
test/api-list-query.test.ts +1 −1
@@ -129,7 +129,7 @@ test("an unknown parameter is a 422 that names the accepted ones", async () => {
129129 expect(res.status).toBe(422);
130130 expect(res.body.error).toBe("unknown_parameter");
131131 expect(res.body.message).toContain('"nonsense"');
132 expect(res.body.accepted).toEqual(["state", "label", "labels", "author", "cursor", "limit", "fields", "milestone"]);
132 expect(res.body.accepted).toEqual(["state", "label", "labels", "author", "cursor", "limit", "fields", "milestone", "assignee"]);
133133 const pulls = await list("milestone=1", "pulls");
134134 expect(pulls.status).toBe(422);
135135 expect(pulls.body.accepted).not.toContain("milestone");

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

Keyboard shortcuts

Docs