From 219cc46b04afcc87e7a32be3c47c5d1dc6ac750a Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Wed, 18 Nov 2026 20:49:42 +0000 Subject: [PATCH 1/3] stewards: source-neutral ticket tools and skills (BB-360) Implements BB-360 PR 2 of 2. Registers ticket_file, ticket_read, ticket_search, ticket_comment, ticket_update and ticket_watch in stewards for steward and worker threads, each a thin dispatch over source-contract.ts by key shape (BB-123 is Linear, owner/repo#N is GitHub), and rewrites the stewards, build-tickets and pr-reviewer skills to the neutral names. - sourceUpdateIssue gains the optional state and assignee fields ticket_update needs; the three contract copies stay byte-identical. - ticket_file resolves a unit against the project's teams and repos and refuses without one when several are configured. - ticket_watch records the watching thread and the plugin's existing ring path wakes it; no new contract RPC. - GitHub's sourceUpdateIssue serves labels and the open/closed or status: state, and refuses priority, assignee and relations. - Every filed description and comment carries the signature line, pinned by a test that gate.ts never reads one as the owner's. Co-Authored-By: Claude Sonnet 5.5 --- plugins/github-watcher/server.test.ts | 30 +- plugins/github-watcher/server.ts | 54 ++- plugins/github-watcher/source-contract.ts | 20 +- plugins/linear/server.test.ts | 26 ++ plugins/linear/server.ts | 26 +- plugins/linear/source-contract.ts | 20 +- plugins/stewards/README.md | 11 +- plugins/stewards/config.test.ts | 14 +- plugins/stewards/contract.test.ts | 13 + plugins/stewards/server.test.ts | 137 +++++- plugins/stewards/server.ts | 44 +- plugins/stewards/skill.test.ts | 31 +- .../stewards/skills/build-tickets/SKILL.md | 33 +- plugins/stewards/skills/pr-reviewer/SKILL.md | 6 +- plugins/stewards/skills/stewards/SKILL.md | 65 ++- plugins/stewards/source-contract.ts | 20 +- plugins/stewards/templates.ts | 77 ++-- plugins/stewards/test-world.ts | 22 +- plugins/stewards/ticket-tools.test.ts | 127 ++++++ plugins/stewards/ticket-tools.ts | 403 ++++++++++++++++++ 20 files changed, 1005 insertions(+), 174 deletions(-) create mode 100644 plugins/stewards/ticket-tools.test.ts create mode 100644 plugins/stewards/ticket-tools.ts diff --git a/plugins/github-watcher/server.test.ts b/plugins/github-watcher/server.test.ts index 184937db..f6671038 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>, pullList: [] as unknown[], pullListStatus: 200, pullListMessage: "Forbidden", pullListRetryAfter: "120", 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 state = { node: pullNode() as Record | null, fail: false, rejectSubIssues: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array>, pullList: [] as unknown[], pullListStatus: 200, pullListMessage: "Forbidden", pullListRetryAfter: "120", 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 }>, issuePatches: [] as Array<{ repo: string; number: number; 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, ""); @@ -116,6 +116,14 @@ 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 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; + 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 }); @@ -171,8 +179,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 }; } @@ -891,6 +899,22 @@ 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("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" }); + // 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(); diff --git a/plugins/github-watcher/server.ts b/plugins/github-watcher/server.ts index 9a7debc1..588766e4 100644 --- a/plugins/github-watcher/server.ts +++ b/plugins/github-watcher/server.ts @@ -276,10 +276,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 { + async function restWrite(path: string, body: unknown, signal: AbortSignal, method: "POST" | "PATCH" = "POST"): Promise { 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, @@ -1014,11 +1014,51 @@ 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:` + // 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 = {}; + 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") { + body.state = state; + changed.push(state === "closed" ? "closed" : "reopened"); + } 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: 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"); diff --git a/plugins/github-watcher/source-contract.ts b/plugins/github-watcher/source-contract.ts index 33a7447a..3f00f68e 100644 --- a/plugins/github-watcher/source-contract.ts +++ b/plugins/github-watcher/source-contract.ts @@ -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` or a `status:` 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()) }), diff --git a/plugins/linear/server.test.ts b/plugins/linear/server.test.ts index 4a8c8ed0..dbe81893 100644 --- a/plugins/linear/server.test.ts +++ b/plugins/linear/server.test.ts @@ -396,6 +396,32 @@ 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("sourceUpdateIssue sets the workflow state and the assignee, refusing another person (BB-360)", async () => { + const ref = issue(); + let lastInput: Record = {}; + const { harness } = await setup({ + token: "at-0", + linear: { + answer: (body) => { + if (body.query.startsWith("mutation($id: String!, $input: IssueUpdateInput!)")) { + lastInput = body.variables!.input as Record; + return { data: { issueUpdate: { success: true, issue: { identifier: "ENG-123", state: { name: "Done" }, assignee: { name: "Jane", displayName: "jane", email: "jane@acme.test" }, labels: { nodes: [] }, priority: 0 } } } }; + } + 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 }] } } }; + return { data: { issue: ref, issueLabels: { nodes: [] } } }; + }, + }, + }); + const out = (await harness.callRpc("sourceUpdateIssue", { key: "ENG-123", state: "Done", assignee: "me" })) as { ok: boolean; changed: string[] }; + expect(out.ok).toBe(true); + expect(lastInput).toMatchObject({ stateId: "s-done", assigneeId: "u1" }); + expect(out.changed).toContain("now Done"); + expect(out.changed).toContain("assigned to jane"); + // Another person is refused before the write; a state the team lacks too. + await expect(harness.callRpc("sourceUpdateIssue", { key: "ENG-123", assignee: "Other" })).rejects.toThrow(/own user/u); + await expect(harness.callRpc("sourceUpdateIssue", { key: "ENG-123", state: "Nope" })).rejects.toThrow(/no state named/u); + }); + 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", diff --git a/plugins/linear/server.ts b/plugins/linear/server.ts index c8a73315..3ab09c2e 100644 --- a/plugins/linear/server.ts +++ b/plugins/linear/server.ts @@ -1541,7 +1541,7 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => // check, the priority rule and the comment budget -- so this only applies // the plan. A label or related key that does not exist is an error that // changes nothing. - async function sourceUpdateIssue(input: { key: string; addLabels: string[]; priority?: "none" | "urgent" | "high" | "medium" | "low"; relations: Array<{ type: RelationType; issue: string }> }) { + async function sourceUpdateIssue(input: { key: string; addLabels: string[]; priority?: "none" | "urgent" | "high" | "medium" | "low"; state?: string; assignee?: string; relations: Array<{ type: RelationType; issue: string }> }) { const where = await forIssue(input.key, undefined, checkSignal()); const ref = parseIssueRef(await query(where.key, ISSUE_REF_QUERY, { id: input.key }, checkSignal())); if (ref === null) throw notFound(input.key, where); @@ -1568,10 +1568,34 @@ export function createLinearPlugin(deps: LinearPluginDeps): (bb: BbPluginApi) => } if (input.priority !== undefined) update.priority = PRIORITIES[input.priority]; + // BB-360: the source-neutral `ticket_update` writes a workflow state by + // name and an assignee (this server's own user, or none); both are + // resolved before the mutation, so a bad name changes nothing. + if (input.state !== undefined) { + const target = findState(ref.team.states, input.state); + if (target === null) { + const names = [...ref.team.states].sort((a, b) => a.position - b.position).map((s) => `${s.name} (${s.type})`); + throw new Error(`Team ${ref.team.key} has no state named ${JSON.stringify(input.state)}. Its states: ${names.join(", ")}.`); + } + update.stateId = target.id; + } + if (input.assignee !== undefined) { + if (input.assignee.trim().toLowerCase() === "nobody") { + update.assigneeId = null; + } else { + const resolved = await resolveAssignee(where, input.assignee, checkSignal()); + if ("error" in resolved) throw new Error(resolved.error); + if (resolved.id !== where.user.id) throw new Error(`sourceUpdateIssue assigns only to this server's own user (${where.user.name}), not ${JSON.stringify(input.assignee)}`); + update.assigneeId = resolved.id; + } + } + if (Object.keys(update).length > 0) { const updated = parseIssueUpdate(await query(where.key, ISSUE_UPDATE, { id: ref.id, input: update }, checkSignal())); if (update.labelIds !== undefined) changed.push(updated.labels.length === 0 ? "no labels" : `labels ${updated.labels.join(", ")}`); if (input.priority !== undefined) changed.push(`priority ${updated.priority === null ? input.priority : (PRIORITY_NAMES[updated.priority] ?? String(updated.priority))}`); + if (input.state !== undefined) changed.push(`now ${updated.state ?? input.state}`); + if (input.assignee !== undefined) changed.push(updated.assignee === null ? "unassigned" : `assigned to ${updated.assignee}`); } for (const relation of relations) { parseIssueRelationCreate(await query(where.key, ISSUE_RELATION_CREATE, { input: relationCreateInput({ type: relation.type, issueId: relation.id }, ref.id) }, checkSignal())); diff --git a/plugins/linear/source-contract.ts b/plugins/linear/source-contract.ts index 33a7447a..3f00f68e 100644 --- a/plugins/linear/source-contract.ts +++ b/plugins/linear/source-contract.ts @@ -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` or a `status:` 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()) }), diff --git a/plugins/stewards/README.md b/plugins/stewards/README.md index ba282b4a..fd42e638 100644 --- a/plugins/stewards/README.md +++ b/plugins/stewards/README.md @@ -204,9 +204,10 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. flight already, so two tickets going ready in the same minute schedule against each other rather than racing to In Progress. `bb stewards show` prints what a binding touches and overlaps; the project steward's wake lists - both for every binding. Everything else is the tools every thread has: `linear_*`, `gh`, - and `bb thread spawn` / `tell` for workers, which stewards recognizes as - workers by their lifecycle owner. + both for every binding. Everything else is the tools every thread has: the + source-neutral `ticket_*` tools, `linear_*` for Linear-specific features, + `gh` for pull requests, and `bb thread spawn` / `tell` for workers, which + stewards recognizes as workers by their lifecycle owner. - **Lifecycle.** A terminal state gets a wrap-up turn with its workers still running. The steward either ends the binding there, or keeps it open to follow through (`steward_report { followThrough }`) on what the state @@ -563,7 +564,7 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run. and the steward is then woken with it framed as the owner's confirmation. A vague "sure" releases nothing and is re-asked once. The three intents in BB-11 use tools stewards already have: "build this" is - `linear_update_issue` (label and Todo), "halt work" is a hold plus a move + `ticket_update` (label and Todo), "halt work" is a hold plus a move to Backlog, and a redirect is `steward_update { guidance }`. A steward may put its own binding on hold for this, but only its parent or the project steward lifts a hold. @@ -936,7 +937,7 @@ GitHub target the issue gets `bb-managed`, `status:todo` and a other severity's ticket raises the owner's adoption decision, kept by the plugin until answered, with one overdue reminder). A GitHub filing target (`ops.team`, or a role's `team`, an `owner/repo` in `repos.json`) files with -`gh issue create`, assigned to this server's GitHub login, and reads state, +`ticket_file`, assigned to this server's GitHub login, and reads state, dedup and auto-adoption through the github source exactly as a Linear team does through linear; `bb stewards check --create-labels` creates the `priority:` labels its `autoAdopt` names in the filing repo (and diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index d99dfd94..38d8e60c 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -661,17 +661,15 @@ describe("the GitHub issue playbook (BB-234)", () => { expect(parsed.value).toMatchObject({ kind: "ticket", source: "github" }); expect(Object.keys(parsed.value.phases)).toEqual(["open", "status:todo", "status:in-progress", "status:in-review"]); expect(parsed.value.terminal).toEqual(["closed", "closed (completed)", "closed (not planned)", "closed (duplicate)"]); - // GitHub sub-issues (BB-250): create-sub-issue is in `may`, the promote rule is set, - // and the status:todo phase carries the attach commands. + // GitHub sub-issues (BB-250, BB-360): create-sub-issue is in `may`, the + // promote rule is set, and the status:todo phase files a child through the + // source-neutral ticket_file, naming the parent. expect(parsed.value.may).toContain("create-sub-issue"); expect(parsed.value.promote).toBe("A sub-issue that needs more than one pull request, its own approval, or work in a repo the parent does not touch."); const todo = phaseInstructions(parsed.value, "status:todo")!; - expect(todo).toContain("sub_issues"); - // The child is assigned to this server's login, so a later `bb-managed` promotion can adopt it, - // and its number is printed so the steward can name it and re-attach it later. - expect(todo).toContain("--assignee @me"); - expect(todo).toContain('echo "filed child #$n"'); - expect(phaseInstructions(parsed.value, "status:in-review")).toMatch(/gh issue\s+close/u); + expect(todo).toContain("ticket_file { unit, title, description, parent }"); + expect(todo).toMatch(/real sub-issue/u); + expect(phaseInstructions(parsed.value, "status:in-review")).toMatch(/ticket_update \{ key, state: "closed" \}/u); expect(phaseInstructions(parsed.value, "open")).toMatch(/Add `status:todo`/u); expect(phaseInstructions(parsed.value, "status:in-progress")).toContain("no `Fixes #N`"); }); diff --git a/plugins/stewards/contract.test.ts b/plugins/stewards/contract.test.ts index dd958221..172d470b 100644 --- a/plugins/stewards/contract.test.ts +++ b/plugins/stewards/contract.test.ts @@ -93,6 +93,19 @@ describe("source-contract.ts", () => { expect(sourceContract.sourceCreateIssue.output.safeParse({ id: "uuid-1", key: "ENG-1" }).success).toBe(false); }); + it("parses sourceUpdateIssue's ticket fields, state and assignee included (BB-360)", () => { + expect(sourceContract.sourceUpdateIssue.input.parse({ key: "ENG-1" })).toEqual({ key: "ENG-1", addLabels: [], relations: [] }); + expect(sourceContract.sourceUpdateIssue.input.parse({ key: "ENG-1", addLabels: ["auth"], priority: "high", state: "Done", assignee: "me", relations: [{ type: "blockedBy", issue: "ENG-2" }] })).toMatchObject({ + addLabels: ["auth"], + priority: "high", + state: "Done", + assignee: "me", + relations: [{ type: "blockedBy", issue: "ENG-2" }], + }); + expect(sourceContract.sourceUpdateIssue.input.safeParse({ key: "ENG-1", priority: "someday" }).success).toBe(false); + expect(sourceContract.sourceUpdateIssue.output.parse({ ok: true, changed: ["now Done"] })).toEqual({ ok: true, changed: ["now Done"] }); + }); + 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/server.test.ts b/plugins/stewards/server.test.ts index ea9a830c..c925d4a7 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -244,12 +244,16 @@ describe("a Linear ticket steward", () => { const [project, steward] = t.spawns.map((x) => x.id); const tools = async (id: string) => (await t.harness.behavior.resolveAgentConfiguration(makePluginAgentConfigurationContext({ thread: { id, title: null, parentThreadId: null, sourceThreadId: null } }))).tools.map((x) => x.name); - expect(await tools(steward!)).toEqual(["steward_report", "steward_update"]); - expect(await tools(project!)).toEqual(["steward_update"]); + // The tools read in registration order, and the ticket tools (BB-360) are + // registered before worker_park and steward_report. + const ticketTools = ["ticket_file", "ticket_read", "ticket_search", "ticket_comment", "ticket_update", "ticket_watch"]; + expect(await tools(steward!)).toEqual([...ticketTools, "steward_report", "steward_update"]); + expect(await tools(project!)).toEqual([...ticketTools, "steward_update"]); expect(await tools("thr_other")).toEqual([]); - // BB-329: a worker gets exactly one plugin tool, its own park call. + // BB-329: a worker gets exactly one plugin tool, its own park call, and + // the source-neutral ticket tools (BB-360). await t.created("thr_w1", steward!, "ENG-12: Implement"); - expect(await tools("thr_w1")).toEqual(["worker_park"]); + expect(await tools("thr_w1")).toEqual([...ticketTools, "worker_park"]); const report = await t.tool("steward_report", { phase: "Todo", summary: "Specifying.", nextAction: "Post acceptance criteria", actor: "steward", requeueAfter: "1d" }, steward!); expect(report.error).toBe(false); @@ -12253,13 +12257,14 @@ describe("the backlog triage writes (BB-341)", () => { const tools = async (t: Awaited>, id: string) => (await t.harness.behavior.resolveAgentConfiguration(makePluginAgentConfigurationContext({ thread: { id, title: null, parentThreadId: null, sourceThreadId: null } }))).tools.map((x) => x.name); it("is offered only when backlog.triage is true, and absent writes nothing", async () => { + const ticketTools = ["ticket_file", "ticket_read", "ticket_search", "ticket_comment", "ticket_update", "ticket_watch"]; const off = await triaging({ triage: false }); - expect(await tools(off.t, "thr_backlog")).toEqual(["steward_report", "steward_update"]); + expect(await tools(off.t, "thr_backlog")).toEqual([...ticketTools, "steward_report", "steward_update"]); expect((await off.t.tool("backlog_triage", { key: "BB-1", addLabels: ["bug"] }, "thr_backlog")).error).toBe(true); expect(off.t.linearWrites).toEqual([]); const on = await triaging({ triage: true }); - expect(await tools(on.t, "thr_backlog")).toEqual(["backlog_triage", "steward_report", "steward_update"]); + expect(await tools(on.t, "thr_backlog")).toEqual(["backlog_triage", ...ticketTools, "steward_report", "steward_update"]); }); it("writes labels, a priority and a signed comment through linear, and records each in the ledger", async () => { @@ -18203,3 +18208,123 @@ describe("playbook refreshes (BB-328 Part 2)", () => { expect(t.hooks.store.playbookRefreshes("p1")[0]!.state).toBe("pr_open"); }); }); + +// BB-360: the source-neutral ticket tools. One test per tool proving the +// dispatch goes to the source the key names, and ticket_file's unit rule. +describe("the source-neutral ticket tools (BB-360)", () => { + /** A project with a Linear steward already spawned, so the tools have a thread. */ + const withSteward = async () => { + const t = await setup(); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + return { t, steward: t.spawns[1]!.id }; + }; + const githubTicket = (over: Partial = {}) => githubIssue({ id: "acme/web#3", key: "acme/web#3", url: "https://github.com/acme/web/issues/3", parent: null, children: [], ...over }); + + it("ticket_read dispatches to the source the key names", async () => { + const { t, steward } = await withSteward(); + t.entities.set("acme/web#3", githubTicket()); + t.rpcCalls.length = 0; + const linear = await t.tool("ticket_read", { key: "ENG-12" }, steward); + expect(linear.error).toBe(false); + expect(linear.text).toContain("ENG-12"); + expect(t.rpcCalls).toContainEqual(expect.objectContaining({ pluginId: "linear", method: "sourceSnapshot", input: { id: "ENG-12" } })); + t.rpcCalls.length = 0; + const github = await t.tool("ticket_read", { key: "acme/web#3" }, steward); + expect(github.error).toBe(false); + expect(github.text).toContain("acme/web#3"); + expect(t.rpcCalls).toContainEqual(expect.objectContaining({ pluginId: "github-watcher", method: "sourceSnapshot", input: { id: "acme/web#3" } })); + // A key that names no system is refused, never guessed. + expect((await t.tool("ticket_read", { key: "not-a-key" }, steward)).error).toBe(true); + }); + + it("ticket_search fans out over the project's units, per source", async () => { + const { t, steward } = await withSteward(); + t.entities.set("acme/web#3", githubTicket({ title: "Web login", description: "login on web" })); + t.rpcCalls.length = 0; + const out = await t.tool("ticket_search", { query: "login" }, steward); + expect(out.error).toBe(false); + expect(t.rpcCalls.some((c) => c.method === "sourceSearchIssues" && c.pluginId === "linear")).toBe(true); + expect(t.rpcCalls.some((c) => c.method === "sourceSearchIssues" && c.pluginId === "github-watcher")).toBe(true); + // Naming units narrows to them. + t.rpcCalls.length = 0; + await t.tool("ticket_search", { query: "login", units: ["ENG"] }, steward); + expect(t.rpcCalls.some((c) => c.method === "sourceSearchIssues" && c.pluginId === "github-watcher")).toBe(false); + expect((await t.tool("ticket_search", { query: "login", units: ["OTHER"] }, steward)).error).toBe(true); + }); + + it("ticket_comment signs the body and dispatches to the source the key names", async () => { + const { t, steward } = await withSteward(); + t.entities.set("acme/web#3", githubTicket()); + t.linearWrites.length = 0; + const linear = await t.tool("ticket_comment", { key: "ENG-12", body: "On it." }, steward); + expect(linear.error).toBe(false); + const write = t.linearWrites.find((w) => w.method === "sourceComment")!; + expect(write.input.key).toBe("ENG-12"); + expect(String(write.input.body)).toContain(`_— from bb thread ${steward}_`); + t.rpcCalls.length = 0; + t.linearWrites.length = 0; + const github = await t.tool("ticket_comment", { key: "acme/web#3", body: "On it." }, steward); + expect(github.error).toBe(false); + expect(t.rpcCalls.some((c) => c.method === "sourceComment" && c.pluginId === "github-watcher")).toBe(true); + expect(t.linearWrites.find((w) => w.method === "sourceComment")!.input.key).toBe("acme/web#3"); + }); + + it("ticket_update passes the fields the source carries, by key shape", async () => { + const { t, steward } = await withSteward(); + t.entities.set("acme/web#3", githubTicket()); + t.linearWrites.length = 0; + const linear = await t.tool("ticket_update", { key: "ENG-12", labels: ["auth"], priority: "high", state: "Done", assignee: "me", relations: [{ type: "blockedBy", issue: "ENG-13" }] }, steward); + expect(linear.error).toBe(false); + expect(t.linearWrites.find((w) => w.method === "sourceUpdateIssue")!.input).toMatchObject({ key: "ENG-12", addLabels: ["auth"], priority: "high", state: "Done", assignee: "me", relations: [{ type: "blockedBy", issue: "ENG-13" }] }); + // A GitHub key dispatches to github-watcher, where labels and a status + // label work and the source refuses the fields GitHub has no concept for. + t.rpcCalls.length = 0; + const github = await t.tool("ticket_update", { key: "acme/web#3", labels: ["auth"], state: "status:in-progress" }, steward); + expect(github.error).toBe(false); + expect(t.rpcCalls.some((c) => c.method === "sourceUpdateIssue" && c.pluginId === "github-watcher")).toBe(true); + // An assignee other than this server's own login is refused in the tool. + expect((await t.tool("ticket_update", { key: "ENG-12", assignee: "sam" }, steward)).error).toBe(true); + }); + + it("ticket_file resolves the unit, signs the description, and refuses an unknown or missing unit", async () => { + const { t, steward } = await withSteward(); + // The project lists several units: ENG, acme/bb and acme/web. + const refused = await t.tool("ticket_file", { title: "New", description: "Body" }, steward); + expect(refused.error).toBe(true); + expect(refused.text).toMatch(/several units/u); + expect(refused.text).toContain("ENG"); + expect(refused.text).toContain("acme/web"); + expect((await t.tool("ticket_file", { unit: "OTHER", title: "New", description: "Body" }, steward)).error).toBe(true); + // A Linear unit files through linear, with the signed description. + t.linearWrites.length = 0; + const linear = await t.tool("ticket_file", { unit: "ENG", title: "New", description: "Body", assignee: "me" }, steward); + expect(linear.error).toBe(false); + const write = t.linearWrites.find((w) => w.method === "sourceCreateIssue")!; + expect(write.input.unit).toBe("ENG"); + expect(String(write.input.description)).toContain(`_— from bb thread ${steward}_`); + // A GitHub unit files through github-watcher. + t.rpcCalls.length = 0; + const github = await t.tool("ticket_file", { unit: "acme/web", title: "New", description: "Body" }, steward); + expect(github.error).toBe(false); + expect(t.rpcCalls.some((c) => c.method === "sourceCreateIssue" && c.pluginId === "github-watcher")).toBe(true); + // An assignee other than this server's own login is refused in the tool. + expect((await t.tool("ticket_file", { unit: "ENG", title: "New", description: "Body", assignee: "sam" }, steward)).error).toBe(true); + }); + + it("ticket_watch leases the entity and the ring wakes the watching thread", async () => { + const { t, steward } = await withSteward(); + t.entities.set("acme/web#3", githubTicket()); + const out = await t.tool("ticket_watch", { key: "acme/web#3" }, steward); + expect(out.error).toBe(false); + expect(out.text).toContain("acme/web#3"); + await t.flush(); + const interest = t.rpcCalls.filter((c) => c.method === "sourceSetInterest" && c.pluginId === "github-watcher").at(-1)!; + expect((interest.input as { entities: string[] }).entities).toContain("acme/web#3"); + // A ring on the watched entity wakes the thread, through the same path a binding uses. + t.sends.length = 0; + t.entities.set("acme/web#3", githubTicket({ title: "Changed" })); + await t.ring("github", "acme/web#3"); + expect(t.sends.some((s) => s.threadId === steward && s.text.includes("acme/web#3 changed"))).toBe(true); + }); +}); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 09b787c0..72d7fd4a 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -133,6 +133,7 @@ import { } from "./source-contract.js"; import { DEPLOY_STATES, allDeployed, applyDeployment, applyDeploymentRead, applyWorkflowRun, awaitingOnRepo, deploymentLines, deploymentReportSchema, isFinalDeploymentState, matchesTarget, matchesWorkflow, mergedPulls, pickWatch, recordMerged, reportDeployment, targetKeyOf, timeOut, timeoutsDue } from "./deploy.js"; import { backlogTriageParamsSchema, decideTriage, planIsEmpty, type BacklogWrite, type TriageConfig, type TriageTicket } from "./backlog-triage.js"; +import { TICKET_TOOL_NAMES, createTicketWatches, registerTicketTools, ticketUnits } from "./ticket-tools.js"; import { evaluateCarries, liveAtMergeVerdict, matchCarriesRule, noRuleNoted, type CarriesReader } from "./carries.js"; import { ACTORS, MIGRATIONS, ESCALATED_NEED_KINDS, NEEDS_KINDS, RESOLUTION_KINDS, createStore, needChoices, newId, type Assumption, type Binding, type DepsDecision, type DivergenceRow, type Escalation, type Fingerprint, type PlaybookRefresh, type StandupNoteRow, type StandupRow, type StandupTranscriptEntry, type Lesson, type Need, type Observed, type Question, type ReadyState, type Store, type WaitDivergenceRow, type WakeRetry, type Worker } from "./store.js"; import { hasLessonAnchor, landLessonInstruction, lessonAnchor, lessonLandingMark, planLessonTransitions, planValidations, retiredLessonAnchor, withLessonAnchor } from "./lessons.js"; @@ -2174,6 +2175,9 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P readCounts.sourceCall(); return rpc(SOURCE_PLUGIN_IDS[source], method, input, outputSchema); }; + // BB-360: the tickets a thread asked to watch (`ticket_watch`). One KV row + // per watcher; the ring path reads it and wakes the thread. + const ticketWatches = createTicketWatches(bb.storage.kv); // BB-354: whether this server can send a Slack DM, read from the Slack // plugin's own `status` RPC. A missing plugin, a method that predates it or @@ -3864,10 +3868,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // while its stop turn is still running: the doorbell has nothing to wake. const off = new Set([...configs.values()].filter((c) => c.value !== null && !c.value.enabled).map((c) => c.value!.projectId)); const open = store.open().filter((b) => !off.has(b.projectId)); + // BB-360: the tickets a thread asked to watch (`ticket_watch`) join the + // bindings' entities, so the source leases them and rings the plugin on + // a change; the ring path then wakes the watching thread. + const watched = await ticketWatches.interest(); const sets: Record = { linear: { units: [...new Set(projects.flatMap((p) => p.file.linear.teams))].sort(), - entities: [...new Set(open.filter((b) => b.source === "linear").map((b) => b.entityId))].sort(), + entities: [...new Set([...open.filter((b) => b.source === "linear").map((b) => b.entityId), ...watched.linear])].sort(), dependabot: [], deployment: [], }, @@ -3878,6 +3886,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P ...open.filter((b) => b.source === "github").map((b) => b.entityId), ...open.flatMap((b) => leasedPulls(b)), ...open.flatMap((b) => waitedPullKeys(b)), + ...watched.github, ]), ].sort(), // Every repo the project watches for Dependabot alerts. A server @@ -7666,6 +7675,12 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P /** A ring from a source: look at the binding(s) it concerns, or consider adopting. */ async function onRing(source: Source, id: string): Promise { + // BB-360: a thread that watched this entity with `ticket_watch` is woken + // here, through the same ring path a binding is. The watch row is the + // truth; the ring only says the entity may have changed. + for (const w of await ticketWatches.watchers(source, id)) { + await sendTo(w.threadId, `Ticket ${w.key} changed. Read it with ticket_read and carry on.`); + } const bound = store.byEntity(source, id); // Ring every binding of the entity, not only the one `byEntity` picks: // the open binding owns it and reconciles the doorbell, and an ended one @@ -11929,7 +11944,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // steers a binding: the steward saving the user's instructions, a parent // or the project steward deciding an escalation, setting priority, holds // and models, or approving a spec. Everything else a steward does, it does - // with the tools every thread has: linear_*, gh, and `bb thread` for + // with the source-neutral ticket tools (BB-360), gh, and `bb thread` for // workers. type Role = { kind: "steward"; binding: Binding } | { kind: "project"; projectId: string } | null; @@ -11961,11 +11976,11 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // landed yet, counts; the tool itself refuses anything else. const worker = store.worker(context.thread.id) !== null; const parent = context.thread.parentThreadId !== null && store.byThread(context.thread.parentThreadId) !== null; - return worker || parent ? { tools: ["worker_park"], skills: [...STEWARDS_SKILLS] } : { tools: [], skills: [...STEWARDS_SKILLS] }; + return worker || parent ? { tools: ["worker_park", ...TICKET_TOOL_NAMES], skills: [...STEWARDS_SKILLS] } : { tools: [], skills: [...STEWARDS_SKILLS] }; } if (role.kind === "project") { return { - tools: ["steward_update"], + tools: ["steward_update", ...TICKET_TOOL_NAMES], skills: [...STEWARDS_SKILLS], instructions: "You are this project's steward. Decide escalations from the project's own guidance (AGENTS.md, architecture and design docs); only the project's big decisions go to the user. Read status with `bb stewards list` and `bb stewards show `; steer with steward_update. Do not do a binding's work yourself: when an ended binding left work undone, reopen its entity so its steward resumes. Read the stewards skill for the protocol.", @@ -11981,7 +11996,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P // turning it off refuses at once even before the selection refreshes. const backlogTriage = target?.kind === "backlog" && configs.get(b.projectId)?.value?.file.backlog?.triage === true; return { - tools: backlogTriage ? ["steward_report", "steward_update", "backlog_triage"] : ["steward_report", "steward_update"], + tools: backlogTriage ? ["steward_report", "steward_update", "backlog_triage", ...TICKET_TOOL_NAMES] : ["steward_report", "steward_update", ...TICKET_TOOL_NAMES], skills: [...STEWARDS_SKILLS], instructions: `You are the ops steward watching ${JSON.stringify(b.entityKey)} (binding ${b.id}, playbook ${JSON.stringify(b.playbook)}), and your thread id is ${context.thread.id}. ` + @@ -11995,7 +12010,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }; } return { - tools: ["steward_report", "steward_update"], + tools: ["steward_report", "steward_update", ...TICKET_TOOL_NAMES], skills: [...STEWARDS_SKILLS], instructions: `You are the steward of ${JSON.stringify(b.entityKey)} (binding ${b.id}, a ${b.kind} binding under playbook ${JSON.stringify(b.playbook)}), and your thread id is ${context.thread.id}. ` + @@ -12362,6 +12377,23 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P }), }); + // BB-360: the source-neutral ticket tools, registered for steward and + // worker threads beside steward_report/steward_update/worker_park. They + // are one thin dispatch over the source contract by key shape; the watch + // registry is the one piece that is the plugin's own, woken by the ring + // path. + registerTicketTools(bb, { + sourceRpc, + snapshot, + project: async (projectId) => { + const config = await loadConfig(projectId); + return config === null ? null : { units: ticketUnits(config.file, config.repos), viewer: { linear: config.linearLogin, github: config.githubLogin } }; + }, + watches: ticketWatches, + pushInterest, + log: (message) => bb.log.warn(`stewards: ${message}`), + }); + /** * BB-329: the worker's own park. One additive argument: the worker says * what it ended its turn waiting on, and the plugin keeps its row diff --git a/plugins/stewards/skill.test.ts b/plugins/stewards/skill.test.ts index 4b55ac5c..e71cd8fc 100644 --- a/plugins/stewards/skill.test.ts +++ b/plugins/stewards/skill.test.ts @@ -49,17 +49,30 @@ describe("the shipped pr-reviewer skill's product ack (BB-207)", () => { }); // BB-250: a GitHub ticket steward files a child as a native sub-issue, so the -// create command assigns it to this server's login (a GitHub issue is adopted -// only when the login is an assignee) and the attach uses the REST endpoint. +// source assigns it to this server's login (a GitHub issue is adopted only +// when the login is an assignee). BB-360 moved the step to `ticket_file`. const stewardsSkill = readFileSync(fileURLToPath(new URL("./skills/stewards/SKILL.md", import.meta.url)), "utf8"); +const onboardingSkill = readFileSync(fileURLToPath(new URL("./skills/onboarding/SKILL.md", import.meta.url)), "utf8"); -describe("the shipped stewards skill's GitHub child filing (BB-250)", () => { - it("carries the create-and-attach commands and assigns the child to this server's login", () => { - expect(stewardsSkill).toContain("### Filing a child on GitHub"); - expect(stewardsSkill).toContain("repos/{owner}/{repo}/issues/{parent}/sub_issues"); - expect(stewardsSkill).toContain("--assignee @me"); - expect(stewardsSkill).toContain('echo "filed child #$n"'); - expect(stewardsSkill).toContain("-F sub_issue_id="); +describe("the shipped stewards skill's child filing (BB-250, BB-360)", () => { + it("files a child through the source-neutral ticket_file, naming the parent", () => { + expect(stewardsSkill).toContain("### Filing a child"); + expect(stewardsSkill).toContain("ticket_file { unit, title, description, parent }"); + expect(stewardsSkill).toMatch(/native sub-issue/u); + expect(stewardsSkill).toMatch(/assigns the\nchild to this server's login/u); + }); +}); + +// BB-360: the shipped skills take every ticket step through the source-neutral +// tools. `linear_*` stays only for a Linear @bb session reply, which has no +// neutral equivalent, and `gh` stays for pull requests. +describe("the shipped skills' source-neutral ticket steps (BB-360)", () => { + it("names no linear_* tool or gh issue for a ticket step", () => { + for (const text of [stewardsSkill, buildTicketsSkill, skill, onboardingSkill]) { + expect(text).not.toMatch(/gh issue/u); + const linear = [...new Set(text.match(/linear_[a-z_]+/gu) ?? [])].filter((t) => t !== "linear_session_reply"); + expect(linear).toEqual([]); + } }); }); diff --git a/plugins/stewards/skills/build-tickets/SKILL.md b/plugins/stewards/skills/build-tickets/SKILL.md index 138e3e47..6643c371 100644 --- a/plugins/stewards/skills/build-tickets/SKILL.md +++ b/plugins/stewards/skills/build-tickets/SKILL.md @@ -49,24 +49,22 @@ The ticket's state is how the team sees progress: | In Review | A PR is open; the reviewer thread and, in the owner lane, a human are reviewing it. | | Done | Merged and deployed; the steward sets it once the deployment source confirms it. | -On a **GitHub issue** the same states are the status labels `status:todo`, -`status:in-progress` and `status:in-review`, swapped with `gh issue edit ---add-label/--remove-label`; the terminal state is the issue closed, and only -the steward closes it. +Move the ticket's state with `ticket_update { key, state }`. On Linear that is +a workflow state name. On a GitHub issue the state is a `status:` +label (`status:todo`, `status:in-progress`, `status:in-review`) or `closed`: +`ticket_update` swaps the status label, and `closed` closes the issue. Only +the steward closes a GitHub issue. A worker never sets **Done**. The steward sets it, which ends the steward's binding and archives the steward's thread, once every pull request is merged and the project's deployment source confirms it is live. End at merge. -`linear_comment` and `linear_update_issue` sign what you write; do not add -a signature line to Linear comments yourself. On a GitHub issue, comment with -`gh issue comment`, move state by swapping the status label with `gh issue -edit --add-label/--remove-label`, and close with `gh issue close`. Everything -you post with `gh` ends with `_— from bb thread ${BB_THREAD_ID:?}_`: the -shell's `:?` makes the command fail when `BB_THREAD_ID` is unset, rather than -writing a signature with no thread id, which the plugin would read as the -owner's own words. +`ticket_comment` and `ticket_update` sign for you; add no signature to what +you pass them. `gh` stays for pull requests: everything you post with `gh` +ends with `_— from bb thread ${BB_THREAD_ID:?}_`: the shell's `:?` makes the +command fail when `BB_THREAD_ID` is unset, rather than writing a signature +with no thread id, which the plugin would read as the owner's own words. ## Build @@ -171,9 +169,8 @@ Sibling PR: --comment ""`, -and it waits for the same deployment confirmation. +not by you. Leave the ticket's state to the steward. A GitHub issue is +closed with `ticket_update { key, state: "closed" }` and a closing +`ticket_comment`, and it waits for the same deployment confirmation. A docs-only or host-side change builds nothing, and host-side material still has to be applied on the host by hand: say so in your final message. diff --git a/plugins/stewards/skills/pr-reviewer/SKILL.md b/plugins/stewards/skills/pr-reviewer/SKILL.md index 78512307..c884d920 100644 --- a/plugins/stewards/skills/pr-reviewer/SKILL.md +++ b/plugins/stewards/skills/pr-reviewer/SKILL.md @@ -91,7 +91,7 @@ Everything below is shared. In both modes the marker carries The spawn prompt names the repository, the PR number, the ticket key, its title and acceptance criteria, and the author thread id. If the prompt is -missing the acceptance criteria, read them from the ticket (`linear_issue`) +missing the acceptance criteria, read them from the ticket (`ticket_read`) or the PR body and say in your review that you did. A Dependabot version-update PR, or a worker's replacement for one (the project's `deps-prs` playbook), has no ticket: the PR body is the spec, the criteria @@ -112,7 +112,7 @@ worker that spawned you. `gh api repos//pulls//comments`): do not repeat what an existing `Claude Code Review` or the previous round already said, but do check whether the author acted on it. Read any Linear ticket the - title or body names (`linear_issue`). + title or body names (`ticket_read`). 2. **Judge substantial, and the referenced ticket's spec.** Do this before the rebase push, the tests or the lane classification, and from the diff (`gh pr diff`), never from the pull request body. Read the review @@ -125,7 +125,7 @@ worker that spawned you. threshold. Read the list from the playbook, not from memory. **A playbook with no `substantial` list has not opted in: nothing is substantial, so mark `substantial=no spec=no` and skip the Product section.** Then look - for a ticket the title or body references, read it (`linear_issue`) and + for a ticket the title or body references, read it (`ticket_read`) and find its binding with `bb stewards show `: it has an approved spec when its `Ready:` line names an approval. A pull request whose referenced ticket has an approved spec cites it and is not re-asked, however large diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 638cabf8..f6518d02 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -221,20 +221,18 @@ Two tools are yours; everything else you do with the tools every thread has. The worker playbooks tell a worker never to open one, so a worker that does has ignored its task; when you cannot answer the question yourself, tell the user. -- **Act as the user, signed.** `linear_comment`, `linear_update_issue` and - `linear_create_issue` sign for you: add no signature to what you pass - them. On a GitHub issue, comment with `gh issue comment`, move the state - by swapping the status label with `gh issue edit --add-label/--remove-label`, - and close with `gh issue close`; sign every `gh` body by hand. With `gh`, - end what you write with +- **Act as the user, signed.** `ticket_comment`, `ticket_update` and + `ticket_file` sign for you: add no signature to what you pass them. + `ticket_update { key, state }` moves the state: a Linear workflow state + name, or on a GitHub issue a `status:` label or `closed`. `gh` stays + for pull requests; sign every `gh` body by hand, ending it with `_— from bb thread _`. Your thread id is in the wake and in `$BB_THREAD_ID`; never take it from your workspace's path, which names the project steward. The playbook's `may` list is what you may do. - **A phase keyed on a label.** A playbook phase keyed `label:` is entered by adding that label and leaving the workflow state where it is; a present label matching such a key wins over the state-keyed phase. Add the - label with the source's own tooling (`gh issue edit --add-label ` on a - GitHub issue; the Linear label on a Linear issue). github-watcher's + label with `ticket_update { key, labels: [name] }`. github-watcher's synthesised `status:*` state is unchanged, so a GitHub playbook may key on either form. - **Comments, not description edits.** Start a spec comment with @@ -466,26 +464,15 @@ Two tools are yours; everything else you do with the tools every thread has. reaches it. A report that needs nobody is marked read, so the sidebar's unread dot means "needs you"; a report that needs you is left unread. -### Filing a child on GitHub +### Filing a child -A GitHub child is attached as a native sub-issue of its parent in the same -action, so the parent's snapshot lists it. Create the child assigned to this -server's login (so a later `bb-managed` promotion can adopt it), keep its -number, and attach it, keeping a `Part of #{parent}` line in the body for a -reader: - -``` -n=$(gh issue create --repo {owner}/{repo} --title "…" --body "Part of #{parent} - -…" --assignee @me | grep -oE '[0-9]+$') -echo "filed child #$n" -gh api -X POST repos/{owner}/{repo}/issues/{parent}/sub_issues -F sub_issue_id=$(gh api repos/{owner}/{repo}/issues/$n --jq .id) -``` - -`echo` prints the child's number. `-F` sends the numeric id as an integer. A -child missing from the parent's next wake under Sub-issues is re-attached -with the attach command, using the child's number in place of `$n`, not -re-filed. +A child is filed with `ticket_file { unit, title, description, parent }`; the +source attaches it to the parent in the same action, so the parent's snapshot +lists it. On GitHub that is a native sub-issue, and the source assigns the +child to this server's login so a later `bb-managed` promotion can adopt it; +on Linear the parent must be in the same team. Keep a `Part of ` +line in the description for a reader. A child missing from the parent's next +wake under Sub-issues is re-filed, not attached by hand. ## If you are an ops steward @@ -509,9 +496,8 @@ comment on its ticket saying it resolved, never a close from here. **Defaults.** Put every problem's fingerprint in the ticket description on a line of its own, ``Fingerprint: `` ``. The wake names the filing -target and its source: a Linear team, where you file with -`linear_create_issue` and assign with `assignee: "me"`, or a GitHub repo, -where you file with `gh issue create` and assign with `--assignee `. +target and its source: a Linear team key or a GitHub owner/repo, filed with +`ticket_file { unit, title, description, labels, priority, assignee: "me" }`. Assign every ticket you file to this server's owner for that source and to no one else; when the wake says the login cannot be read, file it unassigned rather than guessing. A ticket already assigned to someone else is classified @@ -519,20 +505,19 @@ and commented on, never reassigned. A recurrence is a comment on its ticket, never a second ticket. Before you file, the plugin searches the filing target's source for the exact `Fingerprint:` line and reports a hit as Recurring or Returned; if the wake says dedup is unavailable, search the -target yourself (`linear_search`, or `gh issue list --search`) for that -fingerprint before filing. +target yourself (`ticket_search`) for that fingerprint before filing. On a **GitHub** target there is no priority or due-date field. Put the fingerprint on its own line and, for a dependency deadline, a `Due: YYYY-MM-DD` line beside it. Add the labels the wake names: for a priority or severity `autoAdopt` names, `bb-managed`, `status:todo` and `priority:`, so adoption picks the issue up; for any other, no label, -and the plugin files the owner's adoption decision instead. Sign every `gh` -body by hand with `_— from bb thread _`. +and the plugin files the owner's adoption decision instead. `ticket_file` +and `ticket_comment` sign for you; add no signature to what you pass them. -- **New:** file one ticket per problem with `linear_create_issue`, or with - `gh issue create` on a GitHub target: pod and container, since when, the - evidence quoted, your diagnosis, a priority, and the fingerprint line. +- **New:** file one ticket per problem with `ticket_file`: pod and container, + since when, the evidence quoted, your diagnosis, a priority, and the + fingerprint line. Raise one `decision` escalation for the tickets of the turn: "Filed BB-N (high): …. Recommend adopting." A priority the wake says `ops.autoAdopt` covers you label and move to Todo (Linear) or add `bb-managed`, @@ -723,8 +708,8 @@ comments, moves it — you are woken with the change: if it answers the escalation, record it with `guidance` + `resolve`; if not, leave it open. An ops steward's `decision` escalation is a ticket it filed about production: adopt it when the project's guidance says it is worth working -(add the label, move it to Todo with `linear_update_issue`; a ticket steward -picks it up), or decline with a reason, then resolve the escalation. +(add the label and move it to its Todo phase with `ticket_update`; a ticket +steward picks it up), or decline with a reason, then resolve the escalation. Everything you ask the user is a record. Forwarding a non-approval escalation to them makes a question for it, carrying the escalation's @@ -802,7 +787,7 @@ and where the record disagrees with your memory, the record is right. You do not ended binding left work undone, reopen its entity so its steward resumes. An `@bb` mention on an issue with no steward comes to you, under the same -rules: act through `linear_update_issue` and `steward_update`, and end with +rules: act through `ticket_update` and `steward_update`, and end with exactly one `linear_session_reply`. A mention from someone other than the owner never reaches you until the owner confirms it by id. diff --git a/plugins/stewards/source-contract.ts b/plugins/stewards/source-contract.ts index 33a7447a..3f00f68e 100644 --- a/plugins/stewards/source-contract.ts +++ b/plugins/stewards/source-contract.ts @@ -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` or a `status:` 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()) }), diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index c31538d5..92b61664 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -205,26 +205,24 @@ You steward one GitHub issue until it is closed. You decide and delegate; you do not write code yourself. Workers implement, fix CI and answer review comments. -The issue's state is its status label: swap \`status:todo\`, -\`status:in-progress\` and \`status:in-review\` with \`gh issue edit ---add-label/--remove-label\` as the work moves. An issue with no status label -reads \`open\`; a closed one reads \`closed (completed)\` or \`closed (not -planned)\`. Decide what you can from the issue and the project's own guidance -(AGENTS.md, architecture and design docs in the repos). Escalate only what -that guidance does not settle. - -Everything you write on the issue is a comment, signed by hand: end the body -of \`gh issue comment --body-file -\` with -\`_— from bb thread $BB_THREAD_ID_\`. Edit the description only once the -scope has changed and the change is settled, and then say in a comment what -changed and why. Start a spec comment with "**Spec:**" so it counts toward -the spec an approval is pinned to. +The issue's state is its status label: move it with +\`ticket_update { key, state: "status:in-progress" }\` (and the like) as the +work moves. An issue with no status label reads \`open\`; a closed one reads +\`closed (completed)\` or \`closed (not planned)\`. Decide what you can from +the issue and the project's own guidance (AGENTS.md, architecture and design +docs in the repos). Escalate only what that guidance does not settle. + +Everything you write on the issue is a comment through \`ticket_comment\`, +which signs for you. Edit the description only once the scope has changed and +the change is settled, and then say in a comment what changed and why. Start +a spec comment with "**Spec:**" so it counts toward the spec an approval is +pinned to. ## open -An issue with no status label reads \`open\`. Add \`status:todo\` -(\`gh issue edit --add-label status:todo\`) so the work has a state to move -through, then specify it against the ready checklist. Work out what you can — +An issue with no status label reads \`open\`. Add \`status:todo\` with +\`ticket_update { key, labels: ["status:todo"] }\` so the work has a state to +move through, then specify it against the ready checklist. Work out what you can — acceptance criteria, affected repos, a plan — from the code and the project's docs, and post it as spec comments. Ask only what you cannot work out, as a decision escalation, one question at a time. Report the checklist on every @@ -237,9 +235,9 @@ the project steward (the files overlap work in flight), wait for that too: it holds you behind that work, or stacks you on a pull request still being built, and the hold lifts itself when the work lands or that pull request opens, or it tells you to start. Otherwise, or once approved and scheduled, -move the issue to \`status:in-progress\` (remove \`status:todo\`, add -\`status:in-progress\`). A new spec needs approval again, and is asked for the -same way. +move the issue to \`status:in-progress\` with +\`ticket_update { key, state: "status:in-progress" }\`. A new spec needs +approval again, and is asked for the same way. ## status:todo @@ -260,24 +258,12 @@ move the issue to \`status:in-progress\` (remove \`status:todo\`, add \`status:in-progress\`). A new spec needs approval again, and is asked for the same way. -A GitHub issue can have native sub-issues, so file a child as a real -sub-issue of its parent in the same action, keeping a \`Part of #{parent}\` -line in the body for a reader. Create the child assigned to this server's -login (so a later \`bb-managed\` promotion can adopt it), keep its number, and -attach it: - -\`\`\` -n=$(gh issue create --repo {owner}/{repo} --title "…" --body "Part of #{parent} - -…" --assignee @me | grep -oE '[0-9]+$') -echo "filed child #$n" -gh api -X POST repos/{owner}/{repo}/issues/{parent}/sub_issues -F sub_issue_id=$(gh api repos/{owner}/{repo}/issues/$n --jq .id) -\`\`\` - -\`echo\` prints the child's number. \`-F\` sends the numeric id as an -integer. A child missing from the parent's next wake under Sub-issues is -re-attached with the attach command, using the child's number in place of -\`$n\`, not re-filed. +File a child as a real sub-issue of its parent with +\`ticket_file { unit, title, description, parent }\`, keeping a +\`Part of #{parent}\` line in the description for a reader. The source +attaches it to the parent in the same action and assigns it to this server's +login, so a later \`bb-managed\` promotion can adopt it. A child missing from +the parent's next wake under Sub-issues is re-filed, not attached by hand. ## status:in-progress @@ -290,8 +276,8 @@ body, and stop when checks pass". The pull request must NOT use a GitHub closing keyword — no \`Fixes #N\`, \`Closes #N\` or \`Resolves #N\` — so GitHub does not close the issue at merge; you close it yourself once the merge is deployed. When the pull requests are ready, request review and move the issue -to \`status:in-review\` (remove \`status:in-progress\`, add -\`status:in-review\`). +to \`status:in-review\` with \`ticket_update { key, state: +"status:in-review" }\`. ${SECRET_REQUEST} @@ -307,10 +293,9 @@ plugin posts one signed nudge naming the requested reviewer; if a second budget passes it files the owner's **Review it yourself / Reassign / Keep waiting** decide item, and Keep waiting resets the budget once. ${WAIT_SLACK_GUIDANCE} When every linked pull request is merged and the project's -deployment source confirms the merge is live, close the issue with \`gh issue -close --comment ""\` (use -\`--reason not planned\` when the issue will not be done), and end with -steward_report. Until the deployment confirms it, the work is merged, not +deployment source confirms the merge is live, close the issue with +\`ticket_update { key, state: "closed" }\` and a \`ticket_comment\` saying +what shipped and where it is live, and end with steward_report. Until the deployment confirms it, the work is merged, not done: do not close the issue early. ${buildBlocker("the issue")} @@ -528,7 +513,7 @@ trace, or the fenced alert content) quoted; your diagnosis, the likely cause and what would confirm it; and a priority: urgent when users cannot work, high when a service is degraded or an error hits many users, medium otherwise. Search the team for an open ticket about the same problem first -(linear_search), and comment there instead of filing a second one. +(ticket_search), and comment there instead of filing a second one. ${OPS_QUESTIONS} @@ -605,7 +590,7 @@ comment there, never a second ticket. A ticket you file says: the repository and ecosystem; each alert's package, severity, GHSA id and fixed version; the manifest path; the priority and due date from the SLA; and the fingerprint lines. Search the team for an open -ticket about the same repository and ecosystem first (linear_search), and +ticket about the same repository and ecosystem first (ticket_search), and comment there instead of filing a second one. A fixed or dismissed alert is trimmed from its ticket's list; a ticket with no alerts left is moved to Done with a comment saying why. diff --git a/plugins/stewards/test-world.ts b/plugins/stewards/test-world.ts index 11b78e22..a356d904 100644 --- a/plugins/stewards/test-world.ts +++ b/plugins/stewards/test-world.ts @@ -6,7 +6,7 @@ import { readdirSync } from "node:fs"; import { createFakePluginHost, makeThreadResponse } from "@get-bb/plugin-sdk/testing"; import { PROJECT_FILE, playbookPath } from "./config.js"; import { createStewardsPlugin, SECRET_SETTING_NAMES, testHooks, type StewardsDeps } from "./server.js"; -import { SOURCE_PLUGIN_IDS, sourceContract, type EntitySnapshot } from "./source-contract.js"; +import { SOURCE_PLUGIN_IDS, signedBy, sourceContract, type EntitySnapshot } from "./source-contract.js"; import { GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, projectFileTemplate } from "./templates.js"; /** The skills bb registers for this plugin: each directory under `skills/` (package.json `bb.skills`). */ @@ -290,7 +290,10 @@ export function world() { else if (args.method === "repoSet") out = { repos, primary, layout, error: null }; else if (args.method === "sourceSnapshot") { if (snapshotErrors.has(String(input.id))) throw new Error("Linear rate limited the read"); - const entity = entities.get(String(input.id)) ?? null; + // The real source accepts a Linear key as well as its UUID; the fake + // resolves the key too, so a ticket_* test can read by key. + const wanted = String(input.id); + const entity = entities.get(wanted) ?? [...entities.values()].find((e) => e.key.toLowerCase() === wanted.toLowerCase()) ?? null; // BB-322: the real source's snapshot carries the pull request's changed // files; the test world keeps them beside the entity. Merge them so the // assessment's decide-list mark reads the same files `pullChangedFiles` @@ -331,8 +334,8 @@ export function world() { ? { issues: [], unsupported: false, truncated: false, errors: [backlogError] } : { issues: backlog.filter((i) => String(i.unit).toUpperCase() === team), unsupported: false, truncated: backlogTruncated, errors: [] }; } else if (args.method === "sourceUpdateIssue") { - // The real linear validates the input; the fake does too, and remembers - // every write so a test can assert what was sent (BB-341). + // The real sources validate the input; the fake does too, and remembers + // every write so a test can assert what was sent (BB-341, BB-360). sourceContract.sourceUpdateIssue.input.parse(input); linearWrites.push({ method: args.method, input }); if (linearWriteError !== null) throw new Error(linearWriteError); @@ -342,6 +345,17 @@ export function world() { linearWrites.push({ method: args.method, input }); if (linearWriteError !== null) throw new Error(linearWriteError); out = { ok: true, url: "https://linear.app/acme/comment/1" }; + } else if (args.method === "sourceCreateIssue") { + // The real sources validate the input and refuse an unsigned description + // (BB-360); the fake does both so a ticket_file test proves the signing. + sourceContract.sourceCreateIssue.input.parse(input); + if (signedBy(String(input.description)) === null) throw new Error("an issue description must end with the bb thread signature line; nothing was filed"); + linearWrites.push({ method: args.method, input }); + if (linearWriteError !== null) throw new Error(linearWriteError); + const source = args.pluginId === SOURCE_PLUGIN_IDS.github ? "github" : "linear"; + const unit = String(input.unit); + const key = source === "github" ? `${unit}#1` : `${unit}-1`; + out = { id: `${source}-new`, key, url: source === "github" ? `https://github.com/${unit}/issues/1` : `https://linear.app/acme/issue/${key}` }; } else if (args.method === "sourceValidate") { // The real plugins validate the input; an empty label was once accepted here and rejected there. sourceContract.sourceValidate.input.parse(input); diff --git a/plugins/stewards/ticket-tools.test.ts b/plugins/stewards/ticket-tools.test.ts new file mode 100644 index 00000000..770c679f --- /dev/null +++ b/plugins/stewards/ticket-tools.test.ts @@ -0,0 +1,127 @@ +// BB-360: the pure half of the source-neutral ticket tools, and the one gate +// pin: a body `ticket_comment` writes is signed, so gate.ts never reads it as +// the owner's approval or spec comment. +import type { PluginKvStorage } from "@get-bb/plugin-sdk"; +import { describe, expect, it } from "vitest"; +import { issue } from "./fixtures.js"; +import { ownerApproval } from "./gate.js"; +import { signedBy } from "./source-contract.js"; +import { assigneeAllowed, createTicketWatches, formatSearchHit, formatTicket, parseTicketKey, resolveFileUnit, signedTicketBody, sourceOfTicketKey, ticketUnits } from "./ticket-tools.js"; + +const memoryKv = (): PluginKvStorage => { + const rows = new Map(); + return { + async get(key: string) { + return rows.get(key) as T | undefined; + }, + async set(key: string, value: unknown) { + rows.set(key, value); + }, + async delete(key: string) { + rows.delete(key); + }, + async list(prefix?: string) { + return [...rows.keys()].filter((k) => prefix === undefined || k.startsWith(prefix)).sort(); + }, + }; +}; + +describe("the ticket key shape names the source (BB-360)", () => { + it("reads a Linear key as linear and a GitHub reference as github", () => { + expect(sourceOfTicketKey("BB-123")).toBe("linear"); + expect(sourceOfTicketKey("ENG-1")).toBe("linear"); + expect(sourceOfTicketKey("acme/web#12")).toBe("github"); + expect(sourceOfTicketKey("https://github.com/acme/web/issues/12")).toBe("github"); + expect(sourceOfTicketKey("acme/web/pull/12")).toBe("github"); + expect(sourceOfTicketKey("not a ticket")).toBeNull(); + }); + + it("canonicalizes a GitHub reference to owner/repo#N and leaves a Linear key as its own id", () => { + expect(parseTicketKey("BB-123")).toEqual({ source: "linear", id: "BB-123", key: "BB-123" }); + expect(parseTicketKey("https://github.com/acme/web/issues/12")).toEqual({ source: "github", id: "acme/web#12", key: "acme/web#12" }); + expect(parseTicketKey("nope")).toBeNull(); + }); +}); + +describe("ticket_file's unit rule (BB-360)", () => { + const units = ticketUnits({ linear: { teams: ["ENG", "OPS"] } }, ["acme/web"]); + + it("defaults to the only configured unit", () => { + expect(resolveFileUnit(ticketUnits({ linear: { teams: ["ENG"] } }, []), undefined)).toEqual({ ok: true, unit: { source: "linear", unit: "ENG" } }); + }); + + it("refuses without a unit when several are configured, naming them", () => { + const out = resolveFileUnit(units, undefined); + expect(out.ok).toBe(false); + if (!out.ok) { + expect(out.error).toContain("ENG"); + expect(out.error).toContain("OPS"); + expect(out.error).toContain("acme/web"); + expect(out.error).toMatch(/name the one/u); + } + }); + + it("resolves a named unit to its source, ignoring case", () => { + expect(resolveFileUnit(units, "acme/web")).toEqual({ ok: true, unit: { source: "github", unit: "acme/web" } }); + expect(resolveFileUnit(units, "eng")).toEqual({ ok: true, unit: { source: "linear", unit: "ENG" } }); + }); + + it("refuses a unit the project does not list", () => { + const out = resolveFileUnit(units, "OTHER"); + expect(out.ok).toBe(false); + if (!out.ok) expect(out.error).toContain("OTHER"); + }); +}); + +describe("the assignee rule (BB-360)", () => { + it("accepts me, nobody and this server's own login, and refuses anyone else", () => { + expect(assigneeAllowed("me", ["jane"])).toBe(true); + expect(assigneeAllowed("nobody", ["jane"])).toBe(true); + expect(assigneeAllowed("jane", ["Jane"])).toBe(true); + expect(assigneeAllowed("sam", ["jane"])).toBe(false); + }); +}); + +describe("ticket_read's render (BB-360)", () => { + it("shows the ticket's facts without naming the system", () => { + const text = formatTicket(issue({ labels: ["bb-managed"], priority: "High", parent: { id: "uuid-1", key: "ENG-1" } })); + expect(text).toContain("ENG-12: Fix login"); + expect(text).toContain("Todo · ENG"); + expect(text).toContain("labels: bb-managed"); + expect(text).toContain("priority: High"); + expect(text).toContain("parent: ENG-1"); + // The facts name no system; the URL, of course, spells one. + expect(text).not.toContain("Linear"); + }); + + it("renders a search hit on one line", () => { + expect(formatSearchHit({ id: "uuid-12", key: "ENG-12", title: "Fix login", description: null, state: "Todo", stateType: "unstarted", unit: "ENG", assignee: "Jane" })).toBe("ENG-12 Todo @Jane Fix login [ENG]"); + }); +}); + +describe("the ticket watch registry (BB-360)", () => { + it("records a watcher per thread and reports the watched ids per source", async () => { + const watches = createTicketWatches(memoryKv()); + await watches.add("thr_a", { source: "linear", id: "uuid-12", key: "ENG-12" }); + await watches.add("thr_b", { source: "linear", id: "uuid-12", key: "ENG-12" }); + await watches.add("thr_a", { source: "github", id: "acme/web#3", key: "acme/web#3" }); + expect((await watches.watchers("linear", "uuid-12")).map((w) => w.threadId).sort()).toEqual(["thr_a", "thr_b"]); + expect((await watches.watchers("github", "acme/web#3")).map((w) => w.threadId)).toEqual(["thr_a"]); + expect(await watches.interest()).toEqual({ linear: ["uuid-12"], github: ["acme/web#3"] }); + await watches.remove("thr_a", "linear", "uuid-12"); + expect((await watches.watchers("linear", "uuid-12")).map((w) => w.threadId)).toEqual(["thr_b"]); + }); +}); + +describe("the gate reads a ticket_comment body as signed (BB-360)", () => { + it("signs the body and never lets it count as the owner's approval", () => { + const body = signedTicketBody("thr_agent", "Approved — go ahead."); + expect(signedBy(body)).toBe("thr_agent"); + // The snapshot the source builds from that body carries `signedBy`; the + // owner's own approval reader must skip it, exactly as gate.ts does. + const entity = issue({ + comments: [{ id: "c1", author: "Jane", did: "commented", body, createdAt: "2026-10-02T00:00:00Z", url: null, signedBy: signedBy(body) }], + }); + expect(ownerApproval(entity).approved).toBe(false); + }); +}); diff --git a/plugins/stewards/ticket-tools.ts b/plugins/stewards/ticket-tools.ts new file mode 100644 index 00000000..a907a503 --- /dev/null +++ b/plugins/stewards/ticket-tools.ts @@ -0,0 +1,403 @@ +// BB-360: the source-neutral ticket tools, registered for steward and worker +// threads. Each is a thin dispatch over `source-contract.ts` by the shape of +// the key it is given: `BB-123` is Linear, `owner/repo#N` is GitHub. Nothing +// here names a system in its output; the per-source differences that remain +// (what a source cannot do) are the source's own errors, surfaced verbatim. +// +// The tools keep the validations stewards already does: a filed description +// and a comment body are signed with the contract's `signatureLine` before +// they are sent, the source refuses an unsigned body and an assignee other +// than this server's own login, and `ticket_file` resolves its unit against +// the project's own teams and repos, defaulting only when there is exactly +// one. +// +// `ticket_watch` is the one tool that is not a contract dispatch: it records +// the watching thread beside the entity id and the plugin's existing ring +// path (`stewardsRing`) wakes it, so no source-contract RPC is needed. +import type { BbPluginApi, PluginKvStorage } from "@get-bb/plugin-sdk"; +import { z } from "zod"; +import { signatureLine, sourceContract, type EntitySnapshot, type SearchIssue, type Source } from "./source-contract.js"; + +/** The tools this module registers, in the order they read in a thread's tool list. */ +export const TICKET_TOOL_NAMES = ["ticket_file", "ticket_read", "ticket_search", "ticket_comment", "ticket_update", "ticket_watch"] as const; +export type TicketToolName = (typeof TICKET_TOOL_NAMES)[number]; + +/** Linear's issue key, `ENG-123`. */ +const LINEAR_KEY = /^[A-Za-z][A-Za-z0-9]*-\d+$/u; + +const GH_NAME = "[A-Za-z0-9_.-]+"; +// Every way a person writes a GitHub issue or pull request: a URL, an +// owner/repo/issues/N path, or owner/repo#N. +const GH_FORMS = [ + new RegExp(`^(?:https?://)?(?:www\\.)?github\\.com/(${GH_NAME})/(${GH_NAME})/(?:pulls?|issues?)/(\\d+)(?:[/?#].*)?$`, "u"), + new RegExp(`^(${GH_NAME})/(${GH_NAME})/(?:pulls?|issues?)/(\\d+)$`, "u"), + new RegExp(`^(${GH_NAME})/(${GH_NAME})#(\\d+)$`, "u"), +]; + +/** A GitHub reference from any of its forms, or null. */ +function parseGitHubRef(input: string): { repo: string; number: number } | null { + const s = input.trim(); + for (const form of GH_FORMS) { + const m = form.exec(s); + if (m === null) continue; + const number = Number(m[3]); + if (!Number.isInteger(number) || number <= 0) return null; + return { repo: `${m[1]}/${m[2]}`, number }; + } + return null; +} + +/** A ticket key resolved to the source it names and the id a source reads it by. */ +export type TicketKey = { source: "linear" | "github"; id: string; key: string }; + +/** The source a key names, by its shape alone; null when it is neither shape. */ +export function sourceOfTicketKey(key: string): "linear" | "github" | null { + const trimmed = key.trim(); + if (LINEAR_KEY.test(trimmed)) return "linear"; + if (parseGitHubRef(trimmed) !== null) return "github"; + return null; +} + +/** + * Resolve a ticket key. A Linear key is both its own id and its own key; a + * GitHub reference is canonicalized to `owner/repo#N`, which is the id the + * source's snapshot and ring path use. + */ +export function parseTicketKey(key: string): TicketKey | null { + const trimmed = key.trim(); + const source = sourceOfTicketKey(trimmed); + if (source === null) return null; + const ref = parseGitHubRef(trimmed); + if (ref === null) return { source, id: trimmed, key: trimmed }; + const canonical = `${ref.repo}#${ref.number}`; + return { source, id: canonical, key: canonical }; +} + +/** One unit a ticket may be filed in: a Linear team key, or a GitHub owner/repo. */ +export type TicketUnit = { source: "linear" | "github"; unit: string }; + +/** The project's units as filing targets: its Linear teams, then its GitHub repos. */ +export function ticketUnits(file: { linear: { teams: string[] } }, repos: readonly string[]): TicketUnit[] { + return [...file.linear.teams.map((unit): TicketUnit => ({ source: "linear", unit })), ...repos.map((unit): TicketUnit => ({ source: "github", unit }))]; +} + +const listUnits = (units: readonly TicketUnit[]): string => (units.length === 0 ? "none" : units.map((u) => u.unit).join(", ")); + +export type UnitResolution = { ok: true; unit: TicketUnit } | { ok: false; error: string }; + +/** + * Resolve the unit `ticket_file` files into: the named one when given, the + * only configured one when there is exactly one, and a refusal naming the + * units when several are configured and none was named. + */ +export function resolveFileUnit(units: readonly TicketUnit[], requested: string | undefined): UnitResolution { + const name = (requested ?? "").trim(); + if (name !== "") { + const found = units.find((u) => u.unit.toLowerCase() === name.toLowerCase()); + return found === undefined + ? { ok: false, error: `${JSON.stringify(name)} is not one of this project's units (${listUnits(units)}); file in one of those.` } + : { ok: true, unit: found }; + } + if (units.length === 0) return { ok: false, error: "This project lists no Linear team or GitHub repo to file in." }; + if (units.length === 1) return { ok: true, unit: units[0]! }; + return { ok: false, error: `This project lists several units (${listUnits(units)}); name the one to file in with unit.` }; +} + +/** Whether an assignee value names this server's own login, `me`, or `nobody` (clear). */ +export function assigneeAllowed(value: string, own: readonly (string | null)[]): boolean { + const v = value.trim().toLowerCase(); + if (v === "" || v === "me" || v === "nobody") return true; + return own.some((login) => login !== null && login.trim().toLowerCase() === v); +} + +/** The text a `ticket_read` returns: the facts a steward acts on, no system named. */ +export function formatTicket(entity: EntitySnapshot): string { + const lines: string[] = [`${entity.key}: ${entity.title ?? "(untitled)"}`]; + lines.push(`${entity.state}${entity.unit === "" ? "" : ` · ${entity.unit}`}${entity.url === null ? "" : ` · ${entity.url}`}`); + if (entity.labels.length > 0) lines.push(`labels: ${entity.labels.join(", ")}`); + if (entity.assignees.length > 0) lines.push(`assignees: ${entity.assignees.join(", ")}`); + if (entity.priority !== null) lines.push(`priority: ${entity.priority}`); + if (entity.parent !== null) lines.push(`parent: ${entity.parent.key}`); + if (entity.description !== null && entity.description.trim() !== "") lines.push("", entity.description.trim()); + if (entity.comments.length > 0) { + lines.push("", `comments (${entity.comments.length}, newest last):`); + for (const c of entity.comments) lines.push(`- ${c.author} (${c.did})${c.signedBy === null ? "" : ` [bb thread ${c.signedBy}]`}: ${c.body.replace(/\s+/gu, " ").trim().slice(0, 400)}`); + } + return lines.join("\n"); +} + +/** One line per search hit. */ +export function formatSearchHit(issue: SearchIssue): string { + return `${issue.key} ${issue.state}${issue.assignee === null ? "" : ` @${issue.assignee}`} ${issue.title ?? "(untitled)"}${issue.unit === "" ? "" : ` [${issue.unit}]`}`; +} + +// ---- the watch registry ------------------------------------------------------ +// +// One KV row per (source, entity id, thread): the row is the truth, and the +// plugin's existing `stewardsRing` path reads it to wake the thread. Storing +// one row per watcher means an add or a remove is a single write, never a +// read-modify-write of a shared list. + +const WATCH_PREFIX = "ticket-watch/"; +const watchKey = (source: string, id: string, threadId: string): string => `${WATCH_PREFIX}${source}/${id}/${threadId}`; + +export type TicketWatcher = { threadId: string; key: string }; + +export interface TicketWatches { + add(threadId: string, ref: { source: Source; id: string; key: string }): Promise; + remove(threadId: string, source: Source, id: string): Promise; + /** Every thread watching this entity, with the key to show it. */ + watchers(source: Source, id: string): Promise; + /** The watched entity ids per source, for the interest set the sources lease on. */ + interest(): Promise<{ linear: string[]; github: string[] }>; +} + +export function createTicketWatches(kv: PluginKvStorage): TicketWatches { + return { + async add(threadId, ref) { + await kv.set(watchKey(ref.source, ref.id, threadId), { key: ref.key }); + }, + async remove(threadId, source, id) { + await kv.delete(watchKey(source, id, threadId)); + }, + async watchers(source, id) { + const prefix = `${WATCH_PREFIX}${source}/${id}/`; + const out: TicketWatcher[] = []; + for (const key of await kv.list(prefix)) { + const stored = await kv.get<{ key?: unknown }>(key); + out.push({ threadId: key.slice(prefix.length), key: typeof stored?.key === "string" ? stored.key : id }); + } + return out; + }, + async interest() { + const linear = new Set(); + const github = new Set(); + for (const key of await kv.list(WATCH_PREFIX)) { + const rest = key.slice(WATCH_PREFIX.length); + const first = rest.indexOf("/"); + const last = rest.lastIndexOf("/"); + if (first < 0 || last <= first) continue; + const source = rest.slice(0, first); + const id = rest.slice(first + 1, last); + if (source === "linear") linear.add(id); + else if (source === "github") github.add(id); + } + return { linear: [...linear], github: [...github] }; + }, + }; +} + +// ---- registration ------------------------------------------------------------ + +/** What the calling thread's project offers the ticket tools. */ +export type TicketProject = { units: TicketUnit[]; viewer: { linear: string | null; github: string | null } }; + +export interface TicketToolDeps { + /** One source-contract call, to the plugin that serves the source. */ + sourceRpc: (source: Source, method: string, input: unknown, outputSchema: z.ZodType) => Promise; + /** One fresh entity read through the contract. */ + snapshot: (source: Source, id: string) => Promise; + /** The calling thread's project: its filing units and this server's own logins. */ + project: (projectId: string) => Promise; + /** The watch registry the ring path wakes from. */ + watches: TicketWatches; + /** Ask the plugin to re-send the interest set, after a watch is added. */ + pushInterest: () => void; + log: (message: string) => void; +} + +const errorMessage = (error: unknown): string => (error instanceof Error ? error.message : String(error)); +const toolError = (error: unknown) => ({ content: [{ type: "text" as const, text: errorMessage(error) }], isError: true }); + +/** Sign a body the way `ticket_file` and `ticket_comment` do: the contract's signature line, on its own, last. */ +export const signedTicketBody = (threadId: string, body: string): string => `${body.trimEnd()}\n\n${signatureLine(threadId)}`; + +const badKey = (key: string): Error => + new Error(`${JSON.stringify(key)} is not a ticket key. Give a Linear key such as BB-123, or a GitHub issue as owner/repo#12 or its URL.`); + +/** Register the six source-neutral ticket tools. The role selection decides who sees them. */ +export function registerTicketTools(bb: BbPluginApi, deps: TicketToolDeps): void { + const sign = signedTicketBody; + + bb.agents.registerTool({ + name: "ticket_file", + description: + "File a new ticket. Give a unit (a Linear team key such as ENG, or a GitHub owner/repo) when the project lists more than one; with a single unit it is the default. The description is signed for you. On GitHub there is no priority; a Linear ticket may carry one. The assignee is this server's own login or nobody.", + presentation: { label: { pending: "Filing a ticket", completed: "Filed a ticket" } }, + parameters: z.object({ + unit: z.string().trim().min(1).max(200).optional().describe("The unit to file in: a Linear team key or a GitHub owner/repo. Omit when the project lists exactly one."), + title: z.string().trim().min(1).max(500).describe("The ticket's title."), + description: z.string().trim().min(1).max(50_000).describe("The ticket's description, in Markdown. Do not sign it; the plugin signs it."), + labels: z.array(z.string().trim().min(1).max(100)).max(50).optional().describe("Label names to add."), + priority: z.enum(["none", "urgent", "high", "medium", "low"]).optional().describe("The priority. A source with no priority (GitHub) refuses it."), + parent: z.string().trim().min(1).max(200).optional().describe("The parent ticket's key, to file this as a child."), + assignee: z.string().trim().min(1).max(200).optional().describe("'me' for this server's own login, or 'nobody'. Any other person is refused."), + }), + async execute(input, { threadId, projectId }) { + try { + const project = await deps.project(projectId); + if (project === null) return toolError(new Error("This thread's project has no readable stewards configuration.")); + const resolved = resolveFileUnit(project.units, input.unit); + if (!resolved.ok) return toolError(new Error(resolved.error)); + if (input.assignee !== undefined && !assigneeAllowed(input.assignee, [project.viewer.linear, project.viewer.github])) { + return toolError(new Error(`assignee accepts only this server's own login (${project.viewer.linear ?? project.viewer.github ?? "me"}) or 'nobody', not ${JSON.stringify(input.assignee)}.`)); + } + const out = await deps.sourceRpc( + resolved.unit.source, + "sourceCreateIssue", + { + unit: resolved.unit.unit, + title: input.title, + description: sign(threadId, input.description), + labels: input.labels ?? [], + ...(input.priority === undefined ? {} : { priority: input.priority }), + ...(input.parent === undefined ? {} : { parent: input.parent }), + ...(input.assignee === undefined ? {} : { assignee: input.assignee }), + }, + sourceContract.sourceCreateIssue.output, + ); + return `Filed ${out.key}${out.url === null ? "" : `: ${out.url}`}`; + } catch (error) { + return toolError(error); + } + }, + }); + + bb.agents.registerTool({ + name: "ticket_read", + description: + "Read one ticket by key: a Linear key such as BB-123, or a GitHub issue as owner/repo#12 or its URL. Returns its title, state, unit, labels, assignees, priority, parent, description and latest comments.", + presentation: { label: { pending: "Reading a ticket", completed: "Read a ticket" } }, + parameters: z.object({ key: z.string().trim().min(1).max(300).describe("The ticket key: BB-123, or owner/repo#12.") }), + async execute({ key }) { + try { + const ref = parseTicketKey(key); + if (ref === null) return toolError(badKey(key)); + const entity = await deps.snapshot(ref.source, ref.id); + return entity === null ? toolError(new Error(`No ticket ${ref.key}, or it is not visible to this server.`)) : formatTicket(entity); + } catch (error) { + return toolError(error); + } + }, + }); + + bb.agents.registerTool({ + name: "ticket_search", + description: + "Find tickets by free text. Searches every unit the project lists, or only the units named. Returns one line per ticket, newest first.", + presentation: { label: { pending: "Searching tickets", completed: "Searched tickets" } }, + parameters: z.object({ + query: z.string().trim().min(1).max(500).describe("Free text over titles and descriptions."), + units: z.array(z.string().trim().min(1).max(200)).max(100).optional().describe("The units to search: Linear team keys or GitHub owner/repos. Omit for every unit the project lists."), + }), + async execute({ query, units }, { projectId }) { + try { + const project = await deps.project(projectId); + if (project === null) return toolError(new Error("This thread's project has no readable stewards configuration.")); + let selected = project.units; + if (units !== undefined && units.length > 0) { + const wanted = units.map((u) => u.trim().toLowerCase()); + const missing = units.filter((u) => !project.units.some((x) => x.unit.toLowerCase() === u.trim().toLowerCase())); + if (missing.length > 0) return toolError(new Error(`${missing.map((u) => JSON.stringify(u)).join(", ")} ${missing.length === 1 ? "is" : "are"} not among this project's units (${listUnits(project.units)}).`)); + selected = project.units.filter((u) => wanted.includes(u.unit.toLowerCase())); + } + const bySource = new Map<"linear" | "github", string[]>(); + for (const u of selected) bySource.set(u.source, [...(bySource.get(u.source) ?? []), u.unit]); + const found: SearchIssue[] = []; + for (const [source, sourceUnits] of bySource) { + const out = await deps.sourceRpc(source, "sourceSearchIssues", { units: sourceUnits, query, limit: 20 }, sourceContract.sourceSearchIssues.output); + found.push(...out.issues); + } + return found.length === 0 ? `No tickets match ${JSON.stringify(query)}.` : found.map(formatSearchHit).join("\n"); + } catch (error) { + return toolError(error); + } + }, + }); + + bb.agents.registerTool({ + name: "ticket_comment", + description: "Add a comment to a ticket by key. The comment is signed for you; do not sign it yourself.", + presentation: { label: { pending: "Commenting on a ticket", completed: "Commented on a ticket" } }, + parameters: z.object({ + key: z.string().trim().min(1).max(300).describe("The ticket key: BB-123, or owner/repo#12."), + body: z.string().trim().min(1).max(20_000).describe("The comment, in Markdown. Do not sign it; the plugin signs it."), + }), + async execute({ key, body }, { threadId }) { + try { + const ref = parseTicketKey(key); + if (ref === null) return toolError(badKey(key)); + const out = await deps.sourceRpc(ref.source, "sourceComment", { key: ref.key, body: sign(threadId, body) }, sourceContract.sourceComment.output); + return `Commented on ${ref.key}${out.url === null ? "" : `: ${out.url}`}`; + } catch (error) { + return toolError(error); + } + }, + }); + + bb.agents.registerTool({ + name: "ticket_update", + description: + "Change a ticket by key: add labels, set a priority, set the workflow state, set the assignee, or add relations ({ type, issue } with type blockedBy, blocks, related or duplicate). Give only the fields to change. A source that does not support a field returns its own error, as the GitHub source does for this write. The assignee is this server's own login or nobody.", + presentation: { label: { pending: "Updating a ticket", completed: "Updated a ticket" } }, + parameters: z.object({ + key: z.string().trim().min(1).max(300).describe("The ticket key: BB-123, or owner/repo#12."), + state: z.string().trim().min(1).max(60).optional().describe("A workflow state name, matched ignoring case (a source with states)."), + labels: z.array(z.string().trim().min(1).max(100)).max(50).optional().describe("Label names to add."), + priority: z.enum(["none", "urgent", "high", "medium", "low"]).optional().describe("The priority. A source with no priority refuses it."), + assignee: z.string().trim().min(1).max(200).optional().describe("'me' for this server's own login, or 'nobody' to clear. Any other person is refused."), + relations: z + .array(z.object({ type: z.enum(["blockedBy", "blocks", "related", "duplicate"]), issue: z.string().trim().min(1).max(200) })) + .max(20) + .optional() + .describe("Relations to add."), + }), + async execute(input, { projectId }) { + try { + const ref = parseTicketKey(input.key); + if (ref === null) return toolError(badKey(input.key)); + const project = await deps.project(projectId); + if (input.assignee !== undefined && (project === null || !assigneeAllowed(input.assignee, [project.viewer.linear, project.viewer.github]))) { + return toolError(new Error(`assignee accepts only this server's own login${project === null ? "" : ` (${project.viewer.linear ?? project.viewer.github ?? "me"})`} or 'nobody', not ${JSON.stringify(input.assignee)}.`)); + } + const out = await deps.sourceRpc( + ref.source, + "sourceUpdateIssue", + { + key: ref.key, + addLabels: input.labels ?? [], + ...(input.state === undefined ? {} : { state: input.state }), + ...(input.priority === undefined ? {} : { priority: input.priority }), + ...(input.assignee === undefined ? {} : { assignee: input.assignee }), + relations: input.relations ?? [], + }, + sourceContract.sourceUpdateIssue.output, + ); + return `${ref.key}: ${out.changed.length === 0 ? "no change" : out.changed.join("; ")}.`; + } catch (error) { + return toolError(error); + } + }, + }); + + bb.agents.registerTool({ + name: "ticket_watch", + description: + "Watch a ticket by key and end the turn rather than polling: this thread is messaged when the ticket changes. The source's own ring path fires the wake, so it works wherever the project's source is connected; a source that only polls wakes on its next poll.", + presentation: { label: { pending: "Watching a ticket", completed: "Watching a ticket" } }, + parameters: z.object({ key: z.string().trim().min(1).max(300).describe("The ticket key: BB-123, or owner/repo#12.") }), + async execute({ key }, { threadId }) { + try { + const ref = parseTicketKey(key); + if (ref === null) return toolError(badKey(key)); + const entity = await deps.snapshot(ref.source, ref.id); + if (entity === null) return toolError(new Error(`No ticket ${ref.key}, or it is not visible to this server.`)); + await deps.watches.add(threadId, { source: entity.source, id: entity.id, key: entity.key }); + deps.pushInterest(); + return `Watching ${entity.key}. This thread will be messaged when it changes; end the turn rather than polling.`; + } catch (error) { + return toolError(error); + } + }, + }); +} From 1e468dd86565ab2f4706faa237d70b4c43d2fef6 Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Wed, 18 Nov 2026 21:06:49 +0000 Subject: [PATCH 2/3] stewards: fix the ticket_* review round (BB-360) Addresses the four blockers from round 1. - github-watcher serves sourceComment (signed only), so ticket_comment works on a GitHub key; tested on its harness. - ticket_watch is one-shot: the row is dropped when it fires, the thread is woken with send (never unarchived), a deleted thread's watches are forgotten, and the interest set is refreshed; tested. - The child step files with assignee: "me", a link failure re-links the named child rather than filing a second one, and a not-planned close is expressible as state: "closed (not planned)". - The state vocabulary is stated once in ticket_update's description and the state parameter, and the steps just say ticket_update { key, state }. Co-Authored-By: Claude Sonnet 5.5 --- plugins/github-watcher/github.ts | 6 ++++ plugins/github-watcher/server.test.ts | 27 +++++++++++++++-- plugins/github-watcher/server.ts | 22 ++++++++++---- plugins/github-watcher/source-contract.ts | 4 +-- plugins/linear/source-contract.ts | 4 +-- plugins/stewards/config.test.ts | 4 +-- plugins/stewards/server.test.ts | 17 +++++++++-- plugins/stewards/server.ts | 24 ++++++++++++--- plugins/stewards/skill.test.ts | 4 +-- .../stewards/skills/build-tickets/SKILL.md | 12 ++++---- plugins/stewards/skills/stewards/SKILL.md | 17 ++++++----- plugins/stewards/source-contract.ts | 4 +-- plugins/stewards/templates.ts | 29 ++++++++++--------- plugins/stewards/ticket-tools.ts | 10 +++++-- 14 files changed, 130 insertions(+), 54 deletions(-) diff --git a/plugins/github-watcher/github.ts b/plugins/github-watcher/github.ts index 9ce75650..3df0f482 100644 --- a/plugins/github-watcher/github.ts +++ b/plugins/github-watcher/github.ts @@ -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 diff --git a/plugins/github-watcher/server.test.ts b/plugins/github-watcher/server.test.ts index f6671038..af2b53be 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>, pullList: [] as unknown[], pullListStatus: 200, pullListMessage: "Forbidden", pullListRetryAfter: "120", 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 }>, issuePatches: [] as Array<{ repo: string; number: number; 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 state = { node: pullNode() as Record | null, fail: false, rejectSubIssues: false, valid: (token: string) => token.startsWith("gho_"), openPulls: [] as Array>, pullList: [] as unknown[], pullListStatus: 200, pullListMessage: "Forbidden", pullListRetryAfter: "120", 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 }>, issuePatches: [] as Array<{ repo: string; number: number; body: Record }>, 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, 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, ""); @@ -116,6 +116,15 @@ 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 }); @@ -899,6 +908,17 @@ 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" }] } }); @@ -907,7 +927,10 @@ describe("stewards' source contract", () => { 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" }); + 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); diff --git a/plugins/github-watcher/server.ts b/plugins/github-watcher/server.ts index 588766e4..9b811ac2 100644 --- a/plugins/github-watcher/server.ts +++ b/plugins/github-watcher/server.ts @@ -44,6 +44,7 @@ import { labelAlreadyExists, labelPath, parseCompare, + parseCreatedComment, parseCreatedIssue, parseDefaultBranch, parseDependabotAlerts, @@ -1032,9 +1033,12 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => const labels = new Set(snapshot.labels); for (const label of addLabels) labels.add(label); if (state !== undefined) { - if (state === "open" || state === "closed") { - body.state = state; - changed.push(state === "closed" ? "closed" : "reopened"); + 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); @@ -1060,8 +1064,16 @@ export function createGitHubPlugin(deps: GitHubPluginDeps): (bb: BbPluginApi) => 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 diff --git a/plugins/github-watcher/source-contract.ts b/plugins/github-watcher/source-contract.ts index 3f00f68e..f1219423 100644 --- a/plugins/github-watcher/source-contract.ts +++ b/plugins/github-watcher/source-contract.ts @@ -470,8 +470,8 @@ export const sourceContract = { * 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` or a `status:` label, which replaces the other status - * labels. `assignee` names only this server's own login, or none: `me` + * `closed`, `closed (not planned)` or a `status:` 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. */ diff --git a/plugins/linear/source-contract.ts b/plugins/linear/source-contract.ts index 3f00f68e..f1219423 100644 --- a/plugins/linear/source-contract.ts +++ b/plugins/linear/source-contract.ts @@ -470,8 +470,8 @@ export const sourceContract = { * 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` or a `status:` label, which replaces the other status - * labels. `assignee` names only this server's own login, or none: `me` + * `closed`, `closed (not planned)` or a `status:` 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. */ diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index 38d8e60c..d884ed5c 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -667,9 +667,9 @@ describe("the GitHub issue playbook (BB-234)", () => { expect(parsed.value.may).toContain("create-sub-issue"); expect(parsed.value.promote).toBe("A sub-issue that needs more than one pull request, its own approval, or work in a repo the parent does not touch."); const todo = phaseInstructions(parsed.value, "status:todo")!; - expect(todo).toContain("ticket_file { unit, title, description, parent }"); + expect(todo).toContain('ticket_file { unit, title, description, parent, assignee: "me" }'); expect(todo).toMatch(/real sub-issue/u); - expect(phaseInstructions(parsed.value, "status:in-review")).toMatch(/ticket_update \{ key, state: "closed" \}/u); + expect(phaseInstructions(parsed.value, "status:in-review")).toMatch(/ticket_update \{ key, state \}/u); expect(phaseInstructions(parsed.value, "open")).toMatch(/Add `status:todo`/u); expect(phaseInstructions(parsed.value, "status:in-progress")).toContain("no `Fixes #N`"); }); diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index c925d4a7..9ff60797 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -18312,9 +18312,11 @@ describe("the source-neutral ticket tools (BB-360)", () => { expect((await t.tool("ticket_file", { unit: "ENG", title: "New", description: "Body", assignee: "sam" }, steward)).error).toBe(true); }); - it("ticket_watch leases the entity and the ring wakes the watching thread", async () => { + it("ticket_watch leases the entity, the ring wakes the thread once, and the watch ends", async () => { const { t, steward } = await withSteward(); - t.entities.set("acme/web#3", githubTicket()); + // Unlabelled, so the ring never adopts it and the interest set is the watch's alone. + const watched = githubTicket({ labels: [], state: "open", assignees: [] }); + t.entities.set("acme/web#3", watched); const out = await t.tool("ticket_watch", { key: "acme/web#3" }, steward); expect(out.error).toBe(false); expect(out.text).toContain("acme/web#3"); @@ -18323,8 +18325,17 @@ describe("the source-neutral ticket tools (BB-360)", () => { expect((interest.input as { entities: string[] }).entities).toContain("acme/web#3"); // A ring on the watched entity wakes the thread, through the same path a binding uses. t.sends.length = 0; - t.entities.set("acme/web#3", githubTicket({ title: "Changed" })); + t.entities.set("acme/web#3", { ...watched, title: "Changed" }); await t.ring("github", "acme/web#3"); expect(t.sends.some((s) => s.threadId === steward && s.text.includes("acme/web#3 changed"))).toBe(true); + // The watch is one-shot: a second change does not message the thread + // again, and the entity leaves the interest set. + t.sends.length = 0; + t.entities.set("acme/web#3", { ...watched, title: "Changed again" }); + await t.ring("github", "acme/web#3"); + expect(t.sends.some((s) => s.threadId === steward && s.text.includes("acme/web#3 changed"))).toBe(false); + await t.flush(); + const after = t.rpcCalls.filter((c) => c.method === "sourceSetInterest" && c.pluginId === "github-watcher").at(-1)!; + expect((after.input as { entities: string[] }).entities).not.toContain("acme/web#3"); }); }); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 72d7fd4a..61506e64 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -7676,10 +7676,18 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P /** A ring from a source: look at the binding(s) it concerns, or consider adopting. */ async function onRing(source: Source, id: string): Promise { // BB-360: a thread that watched this entity with `ticket_watch` is woken - // here, through the same ring path a binding is. The watch row is the - // truth; the ring only says the entity may have changed. - for (const w of await ticketWatches.watchers(source, id)) { - await sendTo(w.threadId, `Ticket ${w.key} changed. Read it with ticket_read and carry on.`); + // here, through the same ring path a binding is. The watch is one-shot: + // it is dropped once it fires, so a later change does not message the + // thread again (a re-watch asks for another wake). `send`, not `sendTo`, + // so waking a watcher never unarchives a thread. + const watching = await ticketWatches.watchers(source, id); + if (watching.length > 0) { + for (const w of watching) { + await send(w.threadId, `Ticket ${w.key} changed. Read it with ticket_read and carry on.`); + await ticketWatches.remove(w.threadId, source, id); + } + // The entity may leave the interest set now no one watches it. + pushInterest(); } const bound = store.byEntity(source, id); // Ring every binding of the entity, not only the one `byEntity` picks: @@ -10156,6 +10164,14 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P pushInterest(); }), ); + // BB-360: a deleted thread's ticket watches are forgotten, so its id does + // not stay in the interest set forever. + bb.events.on("thread.deleted", ({ thread }) => { + void ticketWatches + .removeThread(thread.id) + .then(() => pushInterest()) + .catch((error) => bb.log.warn(`stewards: could not forget ${thread.id}'s ticket watches: ${errorMessage(error)}`)); + }); // ---- @bb mentions ---------------------------------------------------------------------------------- // diff --git a/plugins/stewards/skill.test.ts b/plugins/stewards/skill.test.ts index e71cd8fc..46514ba9 100644 --- a/plugins/stewards/skill.test.ts +++ b/plugins/stewards/skill.test.ts @@ -57,9 +57,9 @@ const onboardingSkill = readFileSync(fileURLToPath(new URL("./skills/onboarding/ describe("the shipped stewards skill's child filing (BB-250, BB-360)", () => { it("files a child through the source-neutral ticket_file, naming the parent", () => { expect(stewardsSkill).toContain("### Filing a child"); - expect(stewardsSkill).toContain("ticket_file { unit, title, description, parent }"); + expect(stewardsSkill).toContain('ticket_file { unit, title, description, parent, assignee: "me" }'); expect(stewardsSkill).toMatch(/native sub-issue/u); - expect(stewardsSkill).toMatch(/assigns the\nchild to this server's login/u); + expect(stewardsSkill).toMatch(/assigns the\s+child to this server's login/u); }); }); diff --git a/plugins/stewards/skills/build-tickets/SKILL.md b/plugins/stewards/skills/build-tickets/SKILL.md index 6643c371..4cfd7828 100644 --- a/plugins/stewards/skills/build-tickets/SKILL.md +++ b/plugins/stewards/skills/build-tickets/SKILL.md @@ -49,11 +49,9 @@ The ticket's state is how the team sees progress: | In Review | A PR is open; the reviewer thread and, in the owner lane, a human are reviewing it. | | Done | Merged and deployed; the steward sets it once the deployment source confirms it. | -Move the ticket's state with `ticket_update { key, state }`. On Linear that is -a workflow state name. On a GitHub issue the state is a `status:` -label (`status:todo`, `status:in-progress`, `status:in-review`) or `closed`: -`ticket_update` swaps the status label, and `closed` closes the issue. Only -the steward closes a GitHub issue. +Move the ticket's state with `ticket_update { key, state }`; the tool's +`state` names the source's own vocabulary. Only the steward closes a GitHub +issue. A worker never sets **Done**. The steward sets it, which ends the steward's binding and archives the steward's thread, once every pull request is @@ -422,8 +420,8 @@ merge stages a restart, say so in your final message. Do not move the ticket to **Done**: the steward closes it once every pull request is merged and deployed, and it is woken by the deployment source, not by you. Leave the ticket's state to the steward. A GitHub issue is -closed with `ticket_update { key, state: "closed" }` and a closing -`ticket_comment`, and it waits for the same deployment confirmation. +closed with `ticket_update { key, state }` and a closing `ticket_comment`, +and it waits for the same deployment confirmation. A docs-only or host-side change builds nothing, and host-side material still has to be applied on the host by hand: say so in your final message. diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index f6518d02..310c357d 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -223,8 +223,8 @@ Two tools are yours; everything else you do with the tools every thread has. tell the user. - **Act as the user, signed.** `ticket_comment`, `ticket_update` and `ticket_file` sign for you: add no signature to what you pass them. - `ticket_update { key, state }` moves the state: a Linear workflow state - name, or on a GitHub issue a `status:` label or `closed`. `gh` stays + `ticket_update { key, state }` moves the state; the tool's `state` names + the source's own vocabulary. `gh` stays for pull requests; sign every `gh` body by hand, ending it with `_— from bb thread _`. Your thread id is in the wake and in `$BB_THREAD_ID`; never take it from your workspace's path, which names the @@ -466,13 +466,16 @@ Two tools are yours; everything else you do with the tools every thread has. ### Filing a child -A child is filed with `ticket_file { unit, title, description, parent }`; the -source attaches it to the parent in the same action, so the parent's snapshot -lists it. On GitHub that is a native sub-issue, and the source assigns the +A child is filed with +`ticket_file { unit, title, description, parent, assignee: "me" }`; the source +attaches it to the parent in the same action, so the parent's snapshot lists +it. On GitHub that is a native sub-issue, and `assignee: "me"` assigns the child to this server's login so a later `bb-managed` promotion can adopt it; on Linear the parent must be in the same team. Keep a `Part of ` -line in the description for a reader. A child missing from the parent's next -wake under Sub-issues is re-filed, not attached by hand. +line in the description for a reader. If the source reports it filed the child +but could not link it (the error names the child's key), do not file a second +one: on GitHub, re-link that child with +`gh api -X POST repos/{owner}/{repo}/issues/{parent}/sub_issues -F sub_issue_id=`. ## If you are an ops steward diff --git a/plugins/stewards/source-contract.ts b/plugins/stewards/source-contract.ts index 3f00f68e..f1219423 100644 --- a/plugins/stewards/source-contract.ts +++ b/plugins/stewards/source-contract.ts @@ -470,8 +470,8 @@ export const sourceContract = { * 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` or a `status:` label, which replaces the other status - * labels. `assignee` names only this server's own login, or none: `me` + * `closed`, `closed (not planned)` or a `status:` 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. */ diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index 92b61664..980f5992 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -205,9 +205,9 @@ You steward one GitHub issue until it is closed. You decide and delegate; you do not write code yourself. Workers implement, fix CI and answer review comments. -The issue's state is its status label: move it with -\`ticket_update { key, state: "status:in-progress" }\` (and the like) as the -work moves. An issue with no status label reads \`open\`; a closed one reads +The issue's state is its status label: move it with \`ticket_update { key, +state }\` (the tool's \`state\` names the source's vocabulary) as the work +moves. An issue with no status label reads \`open\`; a closed one reads \`closed (completed)\` or \`closed (not planned)\`. Decide what you can from the issue and the project's own guidance (AGENTS.md, architecture and design docs in the repos). Escalate only what that guidance does not settle. @@ -235,9 +235,8 @@ the project steward (the files overlap work in flight), wait for that too: it holds you behind that work, or stacks you on a pull request still being built, and the hold lifts itself when the work lands or that pull request opens, or it tells you to start. Otherwise, or once approved and scheduled, -move the issue to \`status:in-progress\` with -\`ticket_update { key, state: "status:in-progress" }\`. A new spec needs -approval again, and is asked for the same way. +move the issue to \`status:in-progress\` with \`ticket_update { key, state }\`. +A new spec needs approval again, and is asked for the same way. ## status:todo @@ -259,11 +258,14 @@ move the issue to \`status:in-progress\` (remove \`status:todo\`, add same way. File a child as a real sub-issue of its parent with -\`ticket_file { unit, title, description, parent }\`, keeping a +\`ticket_file { unit, title, description, parent, assignee: "me" }\`, keeping a \`Part of #{parent}\` line in the description for a reader. The source -attaches it to the parent in the same action and assigns it to this server's -login, so a later \`bb-managed\` promotion can adopt it. A child missing from -the parent's next wake under Sub-issues is re-filed, not attached by hand. +attaches it to the parent in the same action and, with \`assignee: "me"\`, +assigns it to this server's login, so a later \`bb-managed\` promotion can +adopt it. If the source reports it filed the child but could not link it (the +error names the child's key), re-link that child with +\`gh api -X POST repos/{owner}/{repo}/issues/{parent}/sub_issues -F sub_issue_id=\`, +not a second child. ## status:in-progress @@ -276,8 +278,7 @@ body, and stop when checks pass". The pull request must NOT use a GitHub closing keyword — no \`Fixes #N\`, \`Closes #N\` or \`Resolves #N\` — so GitHub does not close the issue at merge; you close it yourself once the merge is deployed. When the pull requests are ready, request review and move the issue -to \`status:in-review\` with \`ticket_update { key, state: -"status:in-review" }\`. +to \`status:in-review\` with \`ticket_update { key, state }\`. ${SECRET_REQUEST} @@ -294,8 +295,8 @@ budget passes it files the owner's **Review it yourself / Reassign / Keep waiting** decide item, and Keep waiting resets the budget once. ${WAIT_SLACK_GUIDANCE} When every linked pull request is merged and the project's deployment source confirms the merge is live, close the issue with -\`ticket_update { key, state: "closed" }\` and a \`ticket_comment\` saying -what shipped and where it is live, and end with steward_report. Until the deployment confirms it, the work is merged, not +\`ticket_update { key, state }\` and a \`ticket_comment\` saying what shipped +and where it is live, and end with steward_report. Until the deployment confirms it, the work is merged, not done: do not close the issue early. ${buildBlocker("the issue")} diff --git a/plugins/stewards/ticket-tools.ts b/plugins/stewards/ticket-tools.ts index a907a503..7a4f3275 100644 --- a/plugins/stewards/ticket-tools.ts +++ b/plugins/stewards/ticket-tools.ts @@ -146,6 +146,8 @@ export type TicketWatcher = { threadId: string; key: string }; export interface TicketWatches { add(threadId: string, ref: { source: Source; id: string; key: string }): Promise; remove(threadId: string, source: Source, id: string): Promise; + /** Forget every watch a thread holds, when the thread is archived or deleted. */ + removeThread(threadId: string): Promise; /** Every thread watching this entity, with the key to show it. */ watchers(source: Source, id: string): Promise; /** The watched entity ids per source, for the interest set the sources lease on. */ @@ -160,6 +162,10 @@ export function createTicketWatches(kv: PluginKvStorage): TicketWatches { async remove(threadId, source, id) { await kv.delete(watchKey(source, id, threadId)); }, + async removeThread(threadId) { + const suffix = `/${threadId}`; + for (const key of await kv.list(WATCH_PREFIX)) if (key.endsWith(suffix)) await kv.delete(key); + }, async watchers(source, id) { const prefix = `${WATCH_PREFIX}${source}/${id}/`; const out: TicketWatcher[] = []; @@ -338,11 +344,11 @@ export function registerTicketTools(bb: BbPluginApi, deps: TicketToolDeps): void bb.agents.registerTool({ name: "ticket_update", description: - "Change a ticket by key: add labels, set a priority, set the workflow state, set the assignee, or add relations ({ type, issue } with type blockedBy, blocks, related or duplicate). Give only the fields to change. A source that does not support a field returns its own error, as the GitHub source does for this write. The assignee is this server's own login or nobody.", + "Change a ticket by key: add labels, set a priority, set the state, set the assignee, or add relations ({ type, issue } with type blockedBy, blocks, related or duplicate). Give only the fields to change; a source that has no concept for a field returns its own error. `state` is the source's own vocabulary: a Linear workflow state name, or on GitHub `open`, `closed`, `closed (not planned)` or a `status:` label, which replaces the other status labels. `priority` is Linear's (GitHub has none). The assignee is this server's own login or nobody.", presentation: { label: { pending: "Updating a ticket", completed: "Updated a ticket" } }, parameters: z.object({ key: z.string().trim().min(1).max(300).describe("The ticket key: BB-123, or owner/repo#12."), - state: z.string().trim().min(1).max(60).optional().describe("A workflow state name, matched ignoring case (a source with states)."), + state: z.string().trim().min(1).max(60).optional().describe("The state: a Linear workflow state name, or on GitHub `open`, `closed`, `closed (not planned)` or a `status:` label."), labels: z.array(z.string().trim().min(1).max(100)).max(50).optional().describe("Label names to add."), priority: z.enum(["none", "urgent", "high", "medium", "low"]).optional().describe("The priority. A source with no priority refuses it."), assignee: z.string().trim().min(1).max(200).optional().describe("'me' for this server's own login, or 'nobody' to clear. Any other person is refused."), From 969a97054d1892d4e86495eff3f37b722ed1f00f Mon Sep 17 00:00:00 2001 From: Dylan Trotter Date: Wed, 18 Nov 2026 21:13:26 +0000 Subject: [PATCH 3/3] stewards: use GitHub's numeric id when re-linking a child (BB-360) Review round 2 suggestion: the sub-issue link needs the numeric REST id, which the source's error does not carry, so look it up from the child's number with `gh api repos/{owner}/{repo}/issues/ --jq .id`. Co-Authored-By: Claude Sonnet 5.5 --- plugins/stewards/skills/stewards/SKILL.md | 4 +++- plugins/stewards/templates.ts | 4 ++-- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 310c357d..5d9f2f18 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -475,7 +475,9 @@ on Linear the parent must be in the same team. Keep a `Part of ` line in the description for a reader. If the source reports it filed the child but could not link it (the error names the child's key), do not file a second one: on GitHub, re-link that child with -`gh api -X POST repos/{owner}/{repo}/issues/{parent}/sub_issues -F sub_issue_id=`. +`gh api -X POST repos/{owner}/{repo}/issues/{parent}/sub_issues -F sub_issue_id=$(gh api repos/{owner}/{repo}/issues/ --jq .id)`, +using the child's number `` from the error (GitHub's link wants the numeric +REST id, not the number). ## If you are an ops steward diff --git a/plugins/stewards/templates.ts b/plugins/stewards/templates.ts index 980f5992..6e9e07a1 100644 --- a/plugins/stewards/templates.ts +++ b/plugins/stewards/templates.ts @@ -264,8 +264,8 @@ attaches it to the parent in the same action and, with \`assignee: "me"\`, assigns it to this server's login, so a later \`bb-managed\` promotion can adopt it. If the source reports it filed the child but could not link it (the error names the child's key), re-link that child with -\`gh api -X POST repos/{owner}/{repo}/issues/{parent}/sub_issues -F sub_issue_id=\`, -not a second child. +\`gh api -X POST repos/{owner}/{repo}/issues/{parent}/sub_issues -F sub_issue_id=$(gh api repos/{owner}/{repo}/issues/ --jq .id)\`, +using the child's number \`\` from the error, not a second child. ## status:in-progress