diff --git a/plugins/github-watcher/github.ts b/plugins/github-watcher/github.ts index b2598a65..45b3cfa8 100644 --- a/plugins/github-watcher/github.ts +++ b/plugins/github-watcher/github.ts @@ -17,6 +17,16 @@ export const dependabotAlertPath = (repo: string, number: number): string => `/r /** The create-label REST path for one repository. */ export const labelPath = (repo: string): string => `/repos/${repo}/labels`; +/** The create-issue REST path for one repository, and the sub-issue link path under a parent. */ +export const issuesPath = (repo: string): string => `/repos/${repo}/issues`; +export const subIssuesPath = (repo: string, parent: number): string => `/repos/${repo}/issues/${parent}/sub_issues`; + +/** The issue a REST create answered with: its database id (what a sub-issue link names), number and URL. */ +export function parseCreatedIssue(payload: unknown): { id: number; number: number; url: string | null } { + const parsed = z.object({ id: z.number(), number: z.number(), html_url: z.string().nullish() }).parse(payload); + return { id: parsed.id, number: parsed.number, url: parsed.html_url ?? null }; +} + /** * Whether a create-label response is GitHub's "this label already exists" * (a 422), which an idempotent create reports as `existed` rather than an diff --git a/plugins/github-watcher/server.test.ts b/plugins/github-watcher/server.test.ts index 48c4d70e..10a21580 100644 --- a/plugins/github-watcher/server.test.ts +++ b/plugins/github-watcher/server.test.ts @@ -38,7 +38,7 @@ const comment = (body: string, createdAt: string, who = "bob") => ({ author: { l // A GitHub whose GraphQL endpoint a test scripts: one repository with one // pull request, whose bb-managed label validates. function fakeGitHub() { - const state = { node: pullNode() as Record | null, fail: false, rejectSubIssues: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array>, openIssues: [] as Array>, searchIssues: [] as Array>, labels: { "acme/widgets": ["bb-managed"] } as Record, labelCreates: [] as string[], labelCreateStatus: 201, labelCreateMessage: "Validation Failed", dependabotAlerts: [] as unknown[], dependabotPage2: [] as unknown[], dependabotStatus: 200, dependabotMessage: "Forbidden", dependencyGraph: 1 as number | null, dependencyGraphFail: false, deployments: [] as unknown[], deploymentStatuses: {} as Record, files: {} as Record, commits: {} as Record, workflowRuns: [] as unknown[], workflowRun: null as unknown, jobs: [] as unknown[], compares: {} as Record, compareBases: {} as Record, defaultBranch: "main" }; + const state = { node: pullNode() as Record | null, fail: false, rejectSubIssues: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array>, openIssues: [] as Array>, searchIssues: [] as Array>, labels: { "acme/widgets": ["bb-managed"] } as Record, labelCreates: [] as string[], labelCreateStatus: 201, labelCreateMessage: "Validation Failed", issueCreates: [] as Array<{ repo: string; body: Record }>, subIssueLinks: [] as Array<{ repo: string; parent: number; body: unknown }>, issueCreateStatus: 201, issueCreateMessage: "Validation Failed", issueCreateNumber: 124, subIssueStatus: 200, subIssueMessage: "Validation Failed", dependabotAlerts: [] as unknown[], dependabotPage2: [] as unknown[], dependabotStatus: 200, dependabotMessage: "Forbidden", dependencyGraph: 1 as number | null, dependencyGraphFail: false, deployments: [] as unknown[], deploymentStatuses: {} as Record, files: {} as Record, commits: {} as Record, workflowRuns: [] as unknown[], workflowRun: null as unknown, jobs: [] as unknown[], compares: {} as Record, compareBases: {} as Record, defaultBranch: "main" }; const calls: Array<{ token: string; variables: Record }> = []; const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit) => { const token = ((init?.headers as Record).authorization ?? "").replace(/^Bearer /u, ""); @@ -93,6 +93,24 @@ function fakeGitHub() { state.labels[key] = [...(state.labels[key] ?? []), body.name]; return Response.json({ id: 1, name: body.name }, { status: 201 }); } + const subIssues = /\/repos\/([^/]+)\/([^/]+)\/issues\/(\d+)\/sub_issues(?:\?|$)/u.exec(u); + if (subIssues !== null && init?.method === "POST") { + if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); + const repo = `${subIssues[1]}/${subIssues[2]}`; + const body = JSON.parse(String(init.body)) as { sub_issue_id: number }; + state.subIssueLinks.push({ repo, parent: Number(subIssues[3]), body }); + if (state.subIssueStatus >= 400) return Response.json({ message: state.subIssueMessage }, { status: state.subIssueStatus }); + return Response.json({ id: 999, number: state.issueCreateNumber, sub_issue_id: body.sub_issue_id }); + } + const issueCreate = /\/repos\/([^/]+)\/([^/]+)\/issues(?:\?|$)/u.exec(u); + if (issueCreate !== null && init?.method === "POST") { + if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); + const repo = `${issueCreate[1]}/${issueCreate[2]}`; + const body = JSON.parse(String(init.body)) as Record; + state.issueCreates.push({ repo, body }); + if (state.issueCreateStatus >= 400) return Response.json({ message: state.issueCreateMessage }, { status: state.issueCreateStatus }); + return Response.json({ id: 999, number: state.issueCreateNumber, html_url: `https://github.com/${repo}/issues/${state.issueCreateNumber}` }, { status: 201 }); + } const dependabot = /\/repos\/([^/]+)\/([^/]+)\/dependabot\/alerts(?:\?|$)/u.exec(u); if (dependabot !== null) { if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 }); @@ -688,6 +706,48 @@ describe("stewards' source contract", () => { expect(await w.harness.callRpc("sourceBacklog", { team: "ENG" }, STEWARDS)).toEqual({ issues: [], unsupported: true, truncated: false, errors: [] }); }); + it("files a GitHub issue through sourceCreateIssue, refusing an unsigned description, a priority and anyone but the viewer (BB-360)", async () => { + const w = await setup(); + const out = await w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Add retries", description: "Calls fail once in a while.\n\n_— from bb thread thr_x_", labels: ["bb-managed"], assignee: "me" }, STEWARDS); + expect(out).toEqual({ id: "Acme/Widgets#124", key: "Acme/Widgets#124", url: "https://github.com/Acme/Widgets/issues/124" }); + expect(w.github.state.issueCreates).toEqual([{ repo: "Acme/Widgets", body: { title: "Add retries", body: "Calls fail once in a while.\n\n_— from bb thread thr_x_", labels: ["bb-managed"], assignees: ["dev"] } }]); + + // An unsigned description never reaches GitHub. + await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "x", description: "No signature" }, STEWARDS)).rejects.toThrow(/signature line/u); + expect(w.github.state.issueCreates).toHaveLength(1); + + // GitHub issues have no priority. + await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "x", description: "Hi\n\n_— from bb thread thr_x_", priority: "high" }, STEWARDS)).rejects.toThrow(/no priority/u); + + // Only the viewer's own login (me, @me or the login) may be assigned. + expect(await w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Mine", description: "Hi\n\n_— from bb thread thr_x_", assignee: "@me" }, STEWARDS)).toMatchObject({ key: "Acme/Widgets#124" }); + await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "x", description: "Hi\n\n_— from bb thread thr_x_", assignee: "someone" }, STEWARDS)).rejects.toThrow(/own login/u); + + // A parent is read before the create: it must be a same-repository issue. + w.github.state.node = issueNode(); + await w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "Acme/Widgets#7" }, STEWARDS); + expect(w.github.state.subIssueLinks).toEqual([{ repo: "Acme/Widgets", parent: 7, body: { sub_issue_id: 999 } }]); + const before = w.github.state.issueCreates.length; + await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "Other/Repo#7" }, STEWARDS)).rejects.toThrow(/same repository/u); + await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "nonsense" }, STEWARDS)).rejects.toThrow(/not a GitHub issue key/u); + w.github.state.node = pullNode({ number: 12 }); + await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "Acme/Widgets#12" }, STEWARDS)).rejects.toThrow(/pull request/u); + w.github.state.node = null; + await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "Acme/Widgets#7" }, STEWARDS)).rejects.toThrow(/does not exist/u); + expect(w.github.state.issueCreates).toHaveLength(before); + + // A unit that is not owner/repo is an error, not a silent create. + await expect(w.harness.callRpc("sourceCreateIssue", { unit: "widgets", title: "x", description: "Hi\n\n_— from bb thread thr_x_" }, STEWARDS)).rejects.toThrow(/not owner\/repo/u); + }); + + it("names the filed issue when a sub-issue link fails after the create (BB-360)", async () => { + const w = await setup(); + w.github.state.node = issueNode(); + w.github.state.subIssueStatus = 500; + await expect(w.harness.callRpc("sourceCreateIssue", { unit: "Acme/Widgets", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "Acme/Widgets#7" }, STEWARDS)).rejects.toThrow(/filed Acme\/Widgets#124 .*could not link it under Acme\/Widgets#7/u); + expect(w.github.state.issueCreates).toHaveLength(1); + }); + it("reads a repository's Dependabot alerts, naming a repository or a repo the token cannot read rather than failing", async () => { const w = await setup(); w.github.state.dependabotAlerts = [ diff --git a/plugins/github-watcher/server.ts b/plugins/github-watcher/server.ts index 00e0d9be..4804e65d 100644 --- a/plugins/github-watcher/server.ts +++ b/plugins/github-watcher/server.ts @@ -39,10 +39,12 @@ import { deploymentStatusesPath, deploymentsPath, graphql, + issuesPath, kindName, labelAlreadyExists, labelPath, parseCompare, + parseCreatedIssue, parseDefaultBranch, parseDependabotAlerts, parseDependencyGraphCount, @@ -64,13 +66,14 @@ import { parseWorkflowJobs, parseWorkflowRuns, refKey, + subIssuesPath, workflowRunJobsPath, workflowRunPath, workflowRunsPath, type Target, } from "./github.js"; import { createHooksLoop, HOOKS_URL_ENV, type Lease, type Rejection } from "./hooks-client.js"; -import { deploymentSchema, ringStewards, sourceContract, STEWARDS_PLUGIN_ID, workflowRunSchema, type AdoptableEntity, type Deployment, type EntitySnapshot, type SearchIssue, type WorkflowRun } from "./source-contract.js"; +import { deploymentSchema, ringStewards, signedBy, sourceContract, STEWARDS_PLUGIN_ID, workflowRunSchema, type AdoptableEntity, type Deployment, type EntitySnapshot, type SearchIssue, type WorkflowRun } from "./source-contract.js"; import { buildUsage, createRefusals, formatUsage, usageViewSchema, type InterestView } from "./usage.js"; import { compare, createCheckQueue, createWatchStore, initialCursors, snapshotOf, WATCH_MIGRATIONS, type WatchRow } from "./watch.js"; @@ -248,6 +251,28 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => }); } + /** + * One REST write with the token, for the issue create and its sub-issue + * link. A non-2xx answer throws with its status, like `restPage`; the + * token is re-read from gh on a 401 by `asDeveloper`. + */ + async function restWrite(path: string, body: unknown, signal: AbortSignal): Promise { + return asDeveloper(async (token) => { + const response = await deps.fetch(new URL(path, apiUrl), { + method: "POST", + headers: { accept: "application/vnd.github+json", authorization: `Bearer ${token}`, "user-agent": "bb-plugin-github", "x-github-api-version": "2022-11-28", "content-type": "application/json" }, + body: JSON.stringify(body), + signal, + }); + const payload: unknown = await response.json().catch(() => null); + if (!response.ok) { + const message = payload !== null && typeof payload === "object" && typeof (payload as { message?: unknown }).message === "string" ? (payload as { message: string }).message : ""; + throw new GitHubRequestError(`GitHub answered HTTP ${response.status}${message === "" ? "" : `: ${message}`}`, response.status); + } + return payload; + }); + } + /** * Create one label in one repository. A 422 `already_exists` is the label * already being there, which an idempotent create reports as `existed`; @@ -784,6 +809,46 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => throw new Error("sourceComment is a Linear write; the github source does not serve it"); }, + // BB-360: file an issue for the source-neutral ticket tools. The caller + // has already signed the description with the contract's signature line; + // an unsigned one is refused here. GitHub issues have no priority, so a + // priority is refused; a sub-issue's parent must be a same-repository + // issue; and the assignee is this server's own login (me, @me or the + // viewer) or none, never anyone else. + async sourceCreateIssue({ unit, title, description, labels, priority, parent, assignee }) { + if (signedBy(description) === null) throw new Error("an issue description must end with the bb thread signature line; nothing was filed"); + if (priority !== undefined) throw new Error("sourceCreateIssue has no priority on the github source; GitHub issues have no priority"); + const repo = parseRepo(unit); + if (repo === null) throw new Error(`${unit}: not owner/repo`); + const name = `${repo.owner}/${repo.name}`; + const viewer = parseViewer(await query(VIEWER_QUERY, {}, checkSignal())); + const who = assignee?.trim() ?? ""; + const self = who === "" || who.toLowerCase() === "me" || who.toLowerCase() === "@me" || who.toLowerCase() === `@${viewer.toLowerCase()}` || who.toLowerCase() === viewer.toLowerCase(); + if (!self) throw new Error(`sourceCreateIssue assigns only to this server's own login (${viewer}), not ${JSON.stringify(who)}`); + // Resolve the parent before any write, so a missing or non-issue + // parent changes nothing; a sub-issue is linked within one repository. + const parentRef = parent === undefined ? null : parseRef(parent); + if (parent !== undefined && parentRef === null) throw new Error(`parent ${JSON.stringify(parent)} is not a GitHub issue key like owner/repo#12`); + if (parentRef !== null && parentRef.repo.toLowerCase() !== name.toLowerCase()) throw new Error(`a GitHub sub-issue's parent must be in the same repository; ${parent} is not in ${name}`); + if (parentRef !== null) { + const target = await readTarget(parentRef, checkSignal()); + if (target === null) throw new Error(`parent ${parent} does not exist, or it is not visible to the signed-in GitHub user`); + if (target.kind !== "issue") throw new Error(`parent ${parent} is a pull request, not an issue; a sub-issue must be an issue`); + } + const body: Record = { title: title.trim(), body: description }; + if (labels.length > 0) body.labels = labels; + if (who !== "") body.assignees = [viewer]; + const created = parseCreatedIssue(await restWrite(issuesPath(name), body, checkSignal())); + if (parentRef !== null) { + try { + await restWrite(subIssuesPath(name, parentRef.number), { sub_issue_id: created.id }, checkSignal()); + } catch (error) { + throw new Error(`filed ${name}#${created.number}${created.url === null ? "" : ` (${created.url})`}, but could not link it under ${parent}: ${errorMessage(error)}`); + } + } + return { id: `${name}#${created.number}`, key: `${name}#${created.number}`, url: created.url }; + }, + // A repository's Dependabot alerts, read with the token through the // REST API. Each repository the token cannot read (no alert access, // alerts disabled, not visible) is named in `errors`; the rest are diff --git a/plugins/github-watcher/source-contract.ts b/plugins/github-watcher/source-contract.ts index 292f8aff..18018d7c 100644 --- a/plugins/github-watcher/source-contract.ts +++ b/plugins/github-watcher/source-contract.ts @@ -479,6 +479,30 @@ export const sourceContract = { input: z.object({ key: z.string().min(1).max(200), body: z.string().min(1).max(20_000) }), output: z.object({ ok: z.boolean(), url: z.string().nullable() }), }, + /** + * File a new issue in a unit: a Linear team key, or a GitHub owner/repo. + * The caller hands in a `description` that already carries the bb thread + * signature line (`signatureLine`), exactly as `sourceComment`'s body does; + * the source refuses an unsigned description, so a bug in the caller cannot + * file an unsigned issue. `priority` is a source capability (Linear's + * priority; a source with none refuses it), `parent` is the parent issue's + * key, and `assignee` names only this server's own login, or none: `me` + * always means the source's own login, and any other person is refused, + * because no steward assigns work to someone else. Additive and optional: a + * source that does not serve it is unavailable to the caller. + */ + sourceCreateIssue: { + input: z.object({ + unit: z.string().min(1).max(200), + title: z.string().min(1).max(500), + description: z.string().min(1).max(50_000), + labels: z.array(z.string().min(1).max(100)).max(50).default([]), + priority: z.enum(["none", "urgent", "high", "medium", "low"]).optional(), + parent: z.string().min(1).max(200).optional(), + assignee: z.string().min(1).max(200).optional(), + }), + output: z.object({ id: z.string(), key: z.string(), url: z.string().nullable() }), + }, /** * A team's whole open backlog, read-only: every open issue, unlabelled and * unassigned included. One team per call -- there is no all-teams mode -- diff --git a/plugins/linear/server.test.ts b/plugins/linear/server.test.ts index 5239126e..dca2e72e 100644 --- a/plugins/linear/server.test.ts +++ b/plugins/linear/server.test.ts @@ -396,6 +396,67 @@ describe("tools", () => { expect(await harness.callRpc("sourceComment", { key: "ENG-123", body: "Hi there\n\n_— from bb thread thr_x_" })).toEqual({ ok: true, url: "https://linear.app/c/2" }); }); + it("sourceCreateIssue files a signed issue, refusing an unsigned description and anyone but this server's own user (BB-360)", async () => { + const team = { + id: "t-eng", + key: "ENG", + name: "Engineering", + states: { nodes: [{ id: "s-todo", name: "Todo", type: "unstarted", position: 0 }] }, + labels: { nodes: [{ id: "l-bug", name: "Bug" }] }, + }; + let createInput: Record = {}; + let parentIssue: Record | null = issue(); + const { harness, linear } = await setup({ + token: "at-0", + linear: { + answer: (body) => { + if (body.query.startsWith("mutation($input: IssueCreateInput!)")) { + createInput = body.variables!.input as Record; + return { data: { issueCreate: { success: true, issue: { id: "uuid-124", identifier: "ENG-124", url: "https://linear.app/acme/issue/ENG-124" } } } }; + } + if (body.query.startsWith("query($key: String!) { teams")) return { data: { teams: { nodes: body.variables!.key === "ENG" ? [team] : [] }, issueLabels: { nodes: [] } } }; + if (body.query.startsWith("query($who: String!) { users")) return { data: { users: { nodes: [{ id: "u-other", name: "Other", displayName: "Other", email: "other@acme.test", active: true }] } } }; + if (body.query.startsWith("query($id: String!) { issue(id: $id) { id identifier labels")) return { data: { issue: parentIssue } }; + return { data: { issue: issue() } }; + }, + }, + }); + + const out = await harness.callRpc("sourceCreateIssue", { unit: "eng", title: "Add retries", description: "Calls fail once in a while.\n\n_— from bb thread thr_x_", labels: ["bug"], priority: "high" }); + expect(out).toEqual({ id: "uuid-124", key: "ENG-124", url: "https://linear.app/acme/issue/ENG-124" }); + expect(createInput).toMatchObject({ teamId: "t-eng", title: "Add retries", labelIds: ["l-bug"], priority: 2 }); + expect(createInput.description).toBe("Calls fail once in a while.\n\n_— from bb thread thr_x_"); + + // An unsigned description never reaches Linear. + const creates = () => linear.calls.filter((c) => c.body?.query.startsWith("mutation($input: IssueCreateInput!)")).length; + expect(creates()).toBe(1); + await expect(harness.callRpc("sourceCreateIssue", { unit: "ENG", title: "x", description: "No signature" })).rejects.toThrow(/signature line/u); + expect(creates()).toBe(1); + + // Assigning to anyone but this server's own user is refused before the write. + await expect(harness.callRpc("sourceCreateIssue", { unit: "ENG", title: "x", description: "Hi\n\n_— from bb thread thr_x_", assignee: "Other" })).rejects.toThrow(/own user/u); + expect(creates()).toBe(1); + + // This server's own user is accepted (the connected account is Jane ). + expect(await harness.callRpc("sourceCreateIssue", { unit: "ENG", title: "Mine", description: "Hi\n\n_— from bb thread thr_x_", assignee: "me" })).toMatchObject({ key: "ENG-124" }); + expect(createInput.assigneeId).toBe("u1"); + + // A parent issue is resolved and must be in the same team. + await harness.callRpc("sourceCreateIssue", { unit: "ENG", title: "Child", description: "Hi\n\n_— from bb thread thr_x_", parent: "ENG-123" }); + expect(createInput.parentId).toBe("uuid-1"); + + // Every refusal below happens before Linear is asked to file anything. + const before = creates(); + expect(before).toBe(3); + await expect(harness.callRpc("sourceCreateIssue", { unit: "ENG", title: "x", description: "Hi\n\n_— from bb thread thr_x_", labels: ["nope"] })).rejects.toThrow(/No label named "nope"/u); + await expect(harness.callRpc("sourceCreateIssue", { unit: "NOPE", title: "x", description: "Hi\n\n_— from bb thread thr_x_" })).rejects.toThrow(/No Linear team NOPE/u); + parentIssue = null; + await expect(harness.callRpc("sourceCreateIssue", { unit: "ENG", title: "x", description: "Hi\n\n_— from bb thread thr_x_", parent: "ENG-999" })).rejects.toThrow(/No Linear issue ENG-999/u); + parentIssue = issue({ identifier: "OPS-1", team: { key: "OPS", name: "Ops", states: { nodes: [{ id: "s-ops", name: "Todo", type: "unstarted", position: 0 }] } } }); + await expect(harness.callRpc("sourceCreateIssue", { unit: "ENG", title: "x", description: "Hi\n\n_— from bb thread thr_x_", parent: "OPS-1" })).rejects.toThrow(/must be filed in OPS/u); + expect(creates()).toBe(before); + }); + it("linear_comment signs the comment with the thread and reports the URL", async () => { const { tool, text, linear } = await setup({ token: "at-0", diff --git a/plugins/linear/server.ts b/plugins/linear/server.ts index e2840961..70038987 100644 --- a/plugins/linear/server.ts +++ b/plugins/linear/server.ts @@ -624,6 +624,10 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => // unsigned comment body. sourceUpdateIssue: (input) => sourceUpdateIssue(input), sourceComment: (input) => sourceComment(input), + // BB-360: file an issue through the source contract. The caller signs + // the description (as sourceComment's body is signed), and the assignee + // is this server's own user or none, never anyone else. + sourceCreateIssue: (input) => sourceCreateIssue(input), // Dependabot alerts are a GitHub thing; linear has none. Stewards only // asks github, so this is a plain answer rather than a throw. async sourceDependabotAlerts() { @@ -1588,6 +1592,51 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => return { ok: true, url: created.url }; } + // BB-360: file an issue for the source-neutral ticket tools. The caller + // has already signed the description with the contract's signature line + // (the same way sourceComment's body is signed); an unsigned one is + // refused here. The assignee is this server's own user or none: no steward + // assigns work to anyone else, so a value that resolves to another user is + // refused. + async function sourceCreateIssue(input: { unit: string; title: string; description: string; labels: string[]; priority?: "none" | "urgent" | "high" | "medium" | "low"; parent?: string; assignee?: string }) { + if (signedBy(input.description) === null) throw new Error("an issue description must end with the bb thread signature line; nothing was filed"); + const teamKey = input.unit.trim().toUpperCase(); + const where = await pick({ team: teamKey }, checkSignal()); + const team = parseTeam(await query(where.key, TEAM_QUERY, { key: teamKey }, checkSignal())); + if (team === null) throw new Error(`No Linear team ${teamKey}, or it is not visible to the connected user.`); + + const create: Record = { teamId: team.id, title: input.title.trim(), description: input.description }; + if (input.labels.length > 0) { + const found = findLabels(team.labels, input.labels); + if (found.missing.length > 0) { + const names = team.labels.map((l) => l.name); + throw new Error(`No label named ${found.missing.map((m) => JSON.stringify(m)).join(", ")} for team ${team.key}. Its labels: ${names.length > 0 ? names.join(", ") : "(none)"}.`); + } + create.labelIds = found.ids; + } + if (input.priority !== undefined) create.priority = PRIORITIES[input.priority]; + if (input.assignee !== undefined) { + const who = input.assignee.trim(); + if (who !== "") { + const self = who.toLowerCase() === "me" || who.toLowerCase() === where.user.name.toLowerCase() || (where.user.email !== null && who.toLowerCase() === where.user.email.toLowerCase()); + if (!self) { + const resolved = await resolveAssignee(where, who, checkSignal()); + if ("error" in resolved) throw new Error(resolved.error); + if (resolved.id !== where.user.id) throw new Error(`sourceCreateIssue assigns only to this server's own user (${where.user.name}), not ${JSON.stringify(who)}`); + } + create.assigneeId = where.user.id; + } + } + if (input.parent !== undefined) { + const parent = parseIssueRef(await query(where.key, ISSUE_REF_QUERY, { id: input.parent }, checkSignal())); + if (parent === null) throw notFound(input.parent, where); + if (parent.team.key !== team.key) throw new Error(`${parent.identifier} is in team ${parent.team.key}, so a sub-issue of it must be filed in ${parent.team.key}, not ${team.key}.`); + create.parentId = parent.id; + } + const created = parseIssueCreate(await query(where.key, ISSUE_CREATE, { input: create }, checkSignal())); + return { id: created.id, key: created.identifier, url: created.url }; + } + /** An issue as the search contract wants it: the description the caller matches the fingerprint line in. */ const searchIssueOf = (issue: Issue): SearchIssue => ({ id: issue.id, diff --git a/plugins/linear/source-contract.ts b/plugins/linear/source-contract.ts index 292f8aff..18018d7c 100644 --- a/plugins/linear/source-contract.ts +++ b/plugins/linear/source-contract.ts @@ -479,6 +479,30 @@ export const sourceContract = { input: z.object({ key: z.string().min(1).max(200), body: z.string().min(1).max(20_000) }), output: z.object({ ok: z.boolean(), url: z.string().nullable() }), }, + /** + * File a new issue in a unit: a Linear team key, or a GitHub owner/repo. + * The caller hands in a `description` that already carries the bb thread + * signature line (`signatureLine`), exactly as `sourceComment`'s body does; + * the source refuses an unsigned description, so a bug in the caller cannot + * file an unsigned issue. `priority` is a source capability (Linear's + * priority; a source with none refuses it), `parent` is the parent issue's + * key, and `assignee` names only this server's own login, or none: `me` + * always means the source's own login, and any other person is refused, + * because no steward assigns work to someone else. Additive and optional: a + * source that does not serve it is unavailable to the caller. + */ + sourceCreateIssue: { + input: z.object({ + unit: z.string().min(1).max(200), + title: z.string().min(1).max(500), + description: z.string().min(1).max(50_000), + labels: z.array(z.string().min(1).max(100)).max(50).default([]), + priority: z.enum(["none", "urgent", "high", "medium", "low"]).optional(), + parent: z.string().min(1).max(200).optional(), + assignee: z.string().min(1).max(200).optional(), + }), + output: z.object({ id: z.string(), key: z.string(), url: z.string().nullable() }), + }, /** * A team's whole open backlog, read-only: every open issue, unlabelled and * unassigned included. One team per call -- there is no all-teams mode -- diff --git a/plugins/stewards/contract.test.ts b/plugins/stewards/contract.test.ts index 151055a2..608b4c14 100644 --- a/plugins/stewards/contract.test.ts +++ b/plugins/stewards/contract.test.ts @@ -39,6 +39,22 @@ describe("source-contract.ts", () => { expect(sourceContract.sourceEnsureLabel.output.safeParse({ results: [{ unit: "ENG", status: "failed" }] }).success).toBe(false); }); + it("parses sourceCreateIssue, whose description already carries the signature line (BB-360)", () => { + const description = `Fix login.\n\n${signatureLine("thr_x")}`; + expect(sourceContract.sourceCreateIssue.input.parse({ unit: "ENG", title: "Fix login", description })).toEqual({ unit: "ENG", title: "Fix login", description, labels: [] }); + // A unit, a title and a signed description are required; priority is one of the five. + expect(sourceContract.sourceCreateIssue.input.safeParse({ unit: "ENG", title: "x" }).success).toBe(false); + expect(sourceContract.sourceCreateIssue.input.safeParse({ unit: "ENG", title: "x", description: "x", priority: "someday" }).success).toBe(false); + expect(sourceContract.sourceCreateIssue.input.parse({ unit: "acme/web", title: "x", description: "x", labels: ["bb-managed"], priority: "high", parent: "acme/web#1", assignee: "me" })).toMatchObject({ + labels: ["bb-managed"], + priority: "high", + parent: "acme/web#1", + assignee: "me", + }); + expect(sourceContract.sourceCreateIssue.output.parse({ id: "uuid-1", key: "ENG-1", url: null })).toEqual({ id: "uuid-1", key: "ENG-1", url: null }); + expect(sourceContract.sourceCreateIssue.output.safeParse({ id: "uuid-1", key: "ENG-1" }).success).toBe(false); + }); + it("parses sourceBacklog, telling a capped read, an empty backlog and an unsupported source apart (BB-331)", () => { const issue = { id: "uuid-1", diff --git a/plugins/stewards/source-contract.ts b/plugins/stewards/source-contract.ts index 292f8aff..18018d7c 100644 --- a/plugins/stewards/source-contract.ts +++ b/plugins/stewards/source-contract.ts @@ -479,6 +479,30 @@ export const sourceContract = { input: z.object({ key: z.string().min(1).max(200), body: z.string().min(1).max(20_000) }), output: z.object({ ok: z.boolean(), url: z.string().nullable() }), }, + /** + * File a new issue in a unit: a Linear team key, or a GitHub owner/repo. + * The caller hands in a `description` that already carries the bb thread + * signature line (`signatureLine`), exactly as `sourceComment`'s body does; + * the source refuses an unsigned description, so a bug in the caller cannot + * file an unsigned issue. `priority` is a source capability (Linear's + * priority; a source with none refuses it), `parent` is the parent issue's + * key, and `assignee` names only this server's own login, or none: `me` + * always means the source's own login, and any other person is refused, + * because no steward assigns work to someone else. Additive and optional: a + * source that does not serve it is unavailable to the caller. + */ + sourceCreateIssue: { + input: z.object({ + unit: z.string().min(1).max(200), + title: z.string().min(1).max(500), + description: z.string().min(1).max(50_000), + labels: z.array(z.string().min(1).max(100)).max(50).default([]), + priority: z.enum(["none", "urgent", "high", "medium", "low"]).optional(), + parent: z.string().min(1).max(200).optional(), + assignee: z.string().min(1).max(200).optional(), + }), + output: z.object({ id: z.string(), key: z.string(), url: z.string().nullable() }), + }, /** * A team's whole open backlog, read-only: every open issue, unlabelled and * unassigned included. One team per call -- there is no all-teams mode --