Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions plugins/github-watcher/github.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,12 @@ export function parseCreatedIssue(payload: unknown): { id: number; number: numbe
return { id: parsed.id, number: parsed.number, url: parsed.html_url ?? null };
}

/** The comment a REST create answered with: its URL, when GitHub returns one. */
export function parseCreatedComment(payload: unknown): { url: string | null } {
const parsed = z.object({ html_url: z.string().nullish() }).parse(payload);
return { 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
Expand Down
53 changes: 50 additions & 3 deletions plugins/github-watcher/server.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> | null, fail: false, rejectSubIssues: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array<Record<string, unknown>>, pullList: [] as unknown[], pullListStatus: 200, pullListMessage: "Forbidden", pullListRetryAfter: "120", openIssues: [] as Array<Record<string, unknown>>, searchIssues: [] as Array<Record<string, unknown>>, labels: { "acme/widgets": ["bb-managed"] } as Record<string, string[]>, labelCreates: [] as string[], labelCreateStatus: 201, labelCreateMessage: "Validation Failed", issueCreates: [] as Array<{ repo: string; body: Record<string, unknown> }>, 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<number, unknown[]>, files: {} as Record<string, string>, commits: {} as Record<string, string>, workflowRuns: [] as unknown[], workflowRun: null as unknown, jobs: [] as unknown[], compares: {} as Record<string, string>, compareBases: {} as Record<string, { base: string; mergeBase: string }>, defaultBranch: "main" };
const state = { node: pullNode() as Record<string, unknown> | null, fail: false, rejectSubIssues: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array<Record<string, unknown>>, pullList: [] as unknown[], pullListStatus: 200, pullListMessage: "Forbidden", pullListRetryAfter: "120", openIssues: [] as Array<Record<string, unknown>>, searchIssues: [] as Array<Record<string, unknown>>, labels: { "acme/widgets": ["bb-managed"] } as Record<string, string[]>, labelCreates: [] as string[], labelCreateStatus: 201, labelCreateMessage: "Validation Failed", issueCreates: [] as Array<{ repo: string; body: Record<string, unknown> }>, issuePatches: [] as Array<{ repo: string; number: number; body: Record<string, unknown> }>, commentCreates: [] as Array<{ repo: string; number: number; body: string }>, 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<number, unknown[]>, files: {} as Record<string, string>, commits: {} as Record<string, string>, workflowRuns: [] as unknown[], workflowRun: null as unknown, jobs: [] as unknown[], compares: {} as Record<string, string>, compareBases: {} as Record<string, { base: string; mergeBase: string }>, defaultBranch: "main" };
const calls: Array<{ token: string; variables: Record<string, unknown> }> = [];
const fetchImpl = vi.fn(async (url: string | URL, init?: RequestInit) => {
const token = ((init?.headers as Record<string, string>).authorization ?? "").replace(/^Bearer /u, "");
Expand Down Expand Up @@ -116,6 +116,23 @@ function fakeGitHub() {
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 commentCreate = /\/repos\/([^/]+)\/([^/]+)\/issues\/(\d+)\/comments(?:\?|$)/u.exec(u);
if (commentCreate !== null && init?.method === "POST") {
if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 });
const repo = `${commentCreate[1]}/${commentCreate[2]}`;
const number = Number(commentCreate[3]);
const body = JSON.parse(String(init.body)) as { body: string };
state.commentCreates.push({ repo, number, body: body.body });
return Response.json({ id: 1, html_url: `https://github.com/${repo}/issues/${number}#issuecomment-1` }, { status: 201 });
}
const issuePatch = /\/repos\/([^/]+)\/([^/]+)\/issues\/(\d+)(?:\?|$)/u.exec(u);
if (issuePatch !== null && init?.method === "PATCH") {
if (!state.valid(token)) return Response.json({ message: "Bad credentials" }, { status: 401 });
const repo = `${issuePatch[1]}/${issuePatch[2]}`;
const body = JSON.parse(String(init.body)) as Record<string, unknown>;
state.issuePatches.push({ repo, number: Number(issuePatch[3]), body });
return Response.json({ number: Number(issuePatch[3]) });
}
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 });
Expand Down Expand Up @@ -171,8 +188,8 @@ function fakeGitHub() {
}
if (`${v.owner}/${v.name}`.toLowerCase() !== "acme/widgets") return Response.json({ data: { repository: null }, errors: [{ type: "NOT_FOUND", message: "Could not resolve to a Repository" }] });
const number = typeof state.node?.number === "number" ? state.node.number : 12;
if (v.number !== number || state.node === null) return Response.json({ data: { repository: { nameWithOwner: "Acme/Widgets", issueOrPullRequest: null } }, errors: [{ type: "NOT_FOUND", message: "Could not resolve" }] });
return Response.json({ data: { repository: { nameWithOwner: "Acme/Widgets", defaultBranchRef: { name: state.defaultBranch }, issueOrPullRequest: state.node } } });
if (v.number !== number || state.node === null) return Response.json({ data: { viewer: { login: "dev" }, repository: { nameWithOwner: "Acme/Widgets", issueOrPullRequest: null } }, errors: [{ type: "NOT_FOUND", message: "Could not resolve" }] });
return Response.json({ data: { viewer: { login: "dev" }, repository: { nameWithOwner: "Acme/Widgets", defaultBranchRef: { name: state.defaultBranch }, issueOrPullRequest: state.node } } });
}) as unknown as typeof fetch;
return { fetchImpl, calls, state };
}
Expand Down Expand Up @@ -891,6 +908,36 @@ describe("stewards' source contract", () => {
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("comments on a GitHub issue through sourceComment, refusing an unsigned body (BB-360)", async () => {
const w = await setup();
const out = await w.harness.callRpc("sourceComment", { key: "Acme/Widgets#7", body: "On it.\n\n_— from bb thread thr_x_" }, STEWARDS);
expect(out).toEqual({ ok: true, url: "https://github.com/Acme/Widgets/issues/7#issuecomment-1" });
expect(w.github.state.commentCreates).toEqual([{ repo: "Acme/Widgets", number: 7, body: "On it.\n\n_— from bb thread thr_x_" }]);
// An unsigned body never reaches GitHub; a bad key is refused first.
await expect(w.harness.callRpc("sourceComment", { key: "Acme/Widgets#7", body: "No signature" }, STEWARDS)).rejects.toThrow(/signature line/u);
await expect(w.harness.callRpc("sourceComment", { key: "nonsense", body: "Hi\n\n_— from bb thread thr_x_" }, STEWARDS)).rejects.toThrow(/not a GitHub issue key/u);
expect(w.github.state.commentCreates).toHaveLength(1);
});

it("updates a GitHub issue through sourceUpdateIssue: labels, a status swap and the state (BB-360)", async () => {
const w = await setup();
w.github.state.node = issueNode({ labels: { nodes: [{ name: "bb-managed" }, { name: "status:todo" }] } });
const out = await w.harness.callRpc("sourceUpdateIssue", { key: "Acme/Widgets#7", addLabels: ["bug"], state: "status:in-progress", assignee: "me" }, STEWARDS);
expect(out).toMatchObject({ ok: true });
expect(w.github.state.issuePatches).toEqual([{ repo: "Acme/Widgets", number: 7, body: { labels: ["bb-managed", "bug", "status:in-progress"], assignees: ["dev"] } }]);
// Closing and reopening are the issue's own state, with no label swap.
await w.harness.callRpc("sourceUpdateIssue", { key: "Acme/Widgets#7", state: "closed" }, STEWARDS);
expect(w.github.state.issuePatches.at(-1)!.body).toEqual({ state: "closed", state_reason: "completed" });
// A not-planned close is expressible too.
await w.harness.callRpc("sourceUpdateIssue", { key: "Acme/Widgets#7", state: "closed (not planned)" }, STEWARDS);
expect(w.github.state.issuePatches.at(-1)!.body).toEqual({ state: "closed", state_reason: "not_planned" });
// Priority, relations and another assignee are refused, as the contract says.
await expect(w.harness.callRpc("sourceUpdateIssue", { key: "Acme/Widgets#7", priority: "high" }, STEWARDS)).rejects.toThrow(/no priority/u);
await expect(w.harness.callRpc("sourceUpdateIssue", { key: "Acme/Widgets#7", relations: [{ type: "blockedBy", issue: "Acme/Widgets#8" }] }, STEWARDS)).rejects.toThrow(/no relations/u);
await expect(w.harness.callRpc("sourceUpdateIssue", { key: "Acme/Widgets#7", assignee: "someone" }, STEWARDS)).rejects.toThrow(/own login/u);
await expect(w.harness.callRpc("sourceUpdateIssue", { key: "Acme/Widgets#7", state: "Done" }, STEWARDS)).rejects.toThrow(/no state/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();
Expand Down
70 changes: 61 additions & 9 deletions plugins/github-watcher/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ import {
labelAlreadyExists,
labelPath,
parseCompare,
parseCreatedComment,
parseCreatedIssue,
parseDefaultBranch,
parseDependabotAlerts,
Expand Down Expand Up @@ -276,10 +277,10 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
* 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<unknown> {
async function restWrite(path: string, body: unknown, signal: AbortSignal, method: "POST" | "PATCH" = "POST"): Promise<unknown> {
return asDeveloper(async (token) => {
const response = await deps.fetch(new URL(path, apiUrl), {
method: "POST",
method,
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,
Expand Down Expand Up @@ -1014,14 +1015,65 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) =>
return { issues: [], unsupported: true, truncated: false, errors: [] };
},

// BB-341: the backlog steward's triage writes are Linear writes; GitHub
// has no issue priority or relations and no signed-comment path here.
// Stewards only ever asks linear, so these are guards, not a path.
async sourceUpdateIssue() {
throw new Error("sourceUpdateIssue is a Linear write; the github source does not serve it");
// BB-360: the source-neutral ticket_update. GitHub issues carry labels
// and an open/closed state; a project's phases are `status:<phase>`
// labels, so setting one replaces the others. Priority, assignee and
// relations have no GitHub issue equivalent and are refused per field,
// as the contract documents; the assignee rule is this server's own
// login or none, exactly as sourceCreateIssue's.
async sourceUpdateIssue({ key, addLabels, priority, state, assignee, relations }) {
if (priority !== undefined) throw new Error("sourceUpdateIssue has no priority on the github source; GitHub issues have no priority");
if (relations.length > 0) throw new Error("sourceUpdateIssue has no relations on the github source; GitHub issues have no relations");
const ref = parseRefKey(key);
if (ref === null) throw new Error(`${key} is not a GitHub issue key like owner/repo#12`);
const snapshot = await readSnapshot(ref, checkSignal());
if (snapshot === null) throw new Error(`${key} does not exist, or it is not visible to the signed-in GitHub user`);
const body: Record<string, unknown> = {};
const changed: string[] = [];
const labels = new Set(snapshot.labels);
for (const label of addLabels) labels.add(label);
if (state !== undefined) {
if (state === "open" || state === "closed" || state === "closed (not planned)") {
body.state = state === "open" ? "open" : "closed";
// GitHub records why a close happened; `closed` is completed, the
// playbook's other terminal state is not planned.
if (state !== "open") body.state_reason = state === "closed (not planned)" ? "not_planned" : "completed";
changed.push(state === "open" ? "reopened" : state === "closed (not planned)" ? "closed as not planned" : "closed");
} else if (state.startsWith("status:")) {
for (const label of [...labels]) if (label.startsWith("status:")) labels.delete(label);
labels.add(state);
changed.push(`now ${state}`);
} else {
throw new Error(`sourceUpdateIssue has no state ${JSON.stringify(state)} on the github source; give open, closed, or a status:<phase> label`);
}
}
if (assignee !== undefined) {
const who = assignee.trim().toLowerCase();
if (who === "me" || who === "nobody") {
body.assignees = who === "me" ? [snapshot.viewer].filter((v): v is string => v !== null) : [];
changed.push(who === "me" ? `assigned to ${snapshot.viewer ?? "this server's login"}` : "unassigned");
} else if (snapshot.viewer !== null && who === snapshot.viewer.toLowerCase()) {
body.assignees = [snapshot.viewer];
changed.push(`assigned to ${snapshot.viewer}`);
} else {
throw new Error(`sourceUpdateIssue assigns only to this server's own login (${snapshot.viewer ?? "unknown"}), not ${JSON.stringify(assignee)}`);
}
}
if (addLabels.length > 0 || (state !== undefined && state.startsWith("status:"))) body.labels = [...labels];
if (Object.keys(body).length > 0) await restWrite(`${issuesPath(ref.repo)}/${ref.number}`, body, checkSignal(), "PATCH");
if (addLabels.length > 0) changed.push(`labels ${[...labels].join(", ")}`);
return { ok: true, changed };
},
async sourceComment() {
throw new Error("sourceComment is a Linear write; the github source does not serve it");
// BB-360: the source-neutral ticket_comment. The caller has already
// signed the body with the contract's signature line; an unsigned one is
// refused here, exactly as sourceCreateIssue refuses an unsigned
// description.
async sourceComment({ key, body }) {
if (signedBy(body) === null) throw new Error("a comment must end with the bb thread signature line; nothing was posted");
const ref = parseRefKey(key);
if (ref === null) throw new Error(`${key} is not a GitHub issue key like owner/repo#12`);
const created = parseCreatedComment(await restWrite(`${issuesPath(ref.repo)}/${ref.number}/comments`, { body }, checkSignal()));
return { ok: true, url: created.url };
},

// BB-360: file an issue for the source-neutral ticket tools. The caller
Expand Down
20 changes: 14 additions & 6 deletions plugins/github-watcher/source-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -462,18 +462,26 @@ export const sourceContract = {
}),
},
/**
* The backlog steward's one gated write (BB-341): add labels, set a
* priority, add relations. Stewards validates every field, the label
* vocabulary, the adoption check, the priority rule and the comment budget
* before it calls; the source only applies the plan. Additive and optional:
* a source that does not serve it is unavailable to the caller. A source
* that has no issue priority or relations (GitHub) answers with an error.
* A ticket write (BB-341, BB-360): add labels, set a priority, set the
* workflow state, set the assignee, add relations. Stewards validates every
* field, the label vocabulary, the adoption check, the priority rule and the
* comment budget before it calls; the source only applies the plan. Additive
* and optional: a source that does not serve it is unavailable to the
* caller, and a source that has no concept for one field answers with an
* error for that field (GitHub has no issue priority or relations).
* `state` is a workflow state's name on Linear; on GitHub it is `open`,
* `closed`, `closed (not planned)` or a `status:<phase>` label, which
* replaces the other status labels. `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.
*/
sourceUpdateIssue: {
input: z.object({
key: z.string().min(1).max(200),
addLabels: z.array(z.string().min(1).max(100)).max(50).default([]),
priority: z.enum(["none", "urgent", "high", "medium", "low"]).optional(),
state: z.string().min(1).max(60).optional(),
assignee: z.string().min(1).max(200).optional(),
relations: z.array(z.object({ type: z.enum(["blockedBy", "blocks", "related", "duplicate"]), issue: z.string().min(1).max(200) })).max(20).default([]),
}),
output: z.object({ ok: z.boolean(), changed: z.array(z.string()) }),
Expand Down
Loading
Loading