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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions plugins/github-watcher/source-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,15 @@ export const entitySnapshotSchema = z.object({
*/
children: z.array(snapshotChildSchema),
childrenTotal: z.number().int().nonnegative().optional(),
/**
* BB-385: the keys of the issues that block this one (this issue is
* `blockedBy` them), keeping only blockers still open. Optional and
* additive: the linear source reads relations and sends it, an empty array
* when nothing blocks the issue; github, which has no dependency relation,
* omits it. Absent means the source did not read relations, never that none
* block it, so a caller that needs the fact refuses rather than assumes.
*/
blockedBy: z.array(z.string()).optional(),
/**
* True when the source could not read the entity's parent and sub-issues
* (GitHub rejected the fields, or the relation read errored or was
Expand Down
21 changes: 21 additions & 0 deletions plugins/linear/linear.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -342,13 +342,34 @@ describe("what stewards reads", () => {
],
parent: { id: "uuid-100", key: "ENG-100" },
children: [{ id: "uuid-124", key: "ENG-124", title: "Add test", state: "Todo", stateType: "unstarted", labels: ["bb-managed"] }],
blockedBy: [],
linkedPulls: [{ url: "https://github.com/Acme/web/pull/42", key: "Acme/web#42" }],
pull: null,
viewer: "jane",
});
expect(parseSnapshotIssue({ data: { issue: null } })).toBeNull();
});

it("carries the open blockers from the inverse blocks relations (BB-385)", () => {
const blockers = {
...raw,
inverseRelations: {
nodes: [
{ id: "r1", type: "blocks", issue: { identifier: "ENG-70", state: { name: "In Progress", type: "started" } } },
// A completed or canceled blocker no longer blocks.
{ id: "r2", type: "blocks", issue: { identifier: "ENG-69", state: { name: "Done", type: "completed" } } },
{ id: "r3", type: "blocks", issue: { identifier: "ENG-68", state: { name: "Canceled", type: "canceled" } } },
// An unknown state counts as open, so nothing rides on an unread blocker.
{ id: "r4", type: "blocks", issue: { identifier: "ENG-67", state: null } },
// A non-blocks relation is not a blocker, and a duplicate is listed once.
{ id: "r5", type: "related", issue: { identifier: "ENG-66", state: { name: "Todo", type: "unstarted" } } },
{ id: "r6", type: "blocks", issue: { identifier: "ENG-70", state: { name: "In Progress", type: "started" } } },
],
},
};
expect(snapshotOfIssue(parseSnapshotIssue({ data: { issue: blockers } })!, null).blockedBy).toEqual(["ENG-70", "ENG-67"]);
});

it("orders linked pulls by attachment createdAt descending, regardless of the API's order (BB-316)", () => {
const attachments = {
nodes: [
Expand Down
29 changes: 28 additions & 1 deletion plugins/linear/linear.ts
Original file line number Diff line number Diff line change
Expand Up @@ -157,7 +157,7 @@ const commentSchema = z.object({
user: person,
});

const relationIssueSchema = z.object({ identifier: z.string(), state: z.object({ name: z.string() }).nullish() });
const relationIssueSchema = z.object({ identifier: z.string(), state: z.object({ name: z.string(), type: z.string().nullish() }).nullish() });
const relationSchema = z.object({ id: z.string(), type: z.string(), issue: relationIssueSchema.nullish(), relatedIssue: relationIssueSchema.nullish() });
export type IssueRelation = z.infer<typeof relationSchema>;

Expand Down Expand Up @@ -460,6 +460,7 @@ const SNAPSHOT_FIELDS =
"state { name type } team { id key } assignee { name displayName email } creator { name displayName email } " +
"labels { nodes { name } } parent { id identifier } " +
"children { nodes { id identifier title state { name type } labels { nodes { name } } } } " +
"inverseRelations { nodes { id type issue { identifier state { name type } } } } " +
`comments(last: ${SNAPSHOT_COMMENTS_MAX}) { nodes { id body createdAt url user { name displayName email } } } ` +
"attachments { nodes { url sourceType createdAt } }";

Expand Down Expand Up @@ -516,6 +517,10 @@ const snapshotIssueSchema = z.object({
),
})
.nullish(),
// BB-385: the inverse `blocks` relations, so a snapshot can name the open
// issues that block this one. The `Issue` query already reads them for the
// `linear_issue` tool; the snapshot query now reads them too.
inverseRelations: z.object({ nodes: z.array(relationSchema) }).nullish(),
comments: z.object({ nodes: z.array(commentSchema.extend({ id: z.string() })) }).nullish(),
attachments: z.object({ nodes: z.array(z.object({ url: z.string().nullish(), sourceType: z.string().nullish(), createdAt: z.string().nullish() })) }).nullish(),
});
Expand All @@ -535,6 +540,27 @@ export function pullKey(url: string): string | null {
return m === null ? null : `${m[1]}/${m[2]}#${m[3]}`;
}

/**
* BB-385: the open blockers of an issue, from its inverse relations. A
* `blocks` inverse relation names an issue that blocks this one; a blocker
* whose state type is completed or canceled no longer blocks. An unknown
* state counts as open, so a promotion never rides on a blocker it could not
* read.
*/
export function openBlockers(issue: SnapshotIssue): string[] {
const closed = new Set(["completed", "canceled"]);
const out: string[] = [];
for (const relation of issue.inverseRelations?.nodes ?? []) {
if (relation.type !== "blocks") continue;
const blocker = relation.issue;
if (blocker === null || blocker === undefined || blocker.identifier === "") continue;
const type = (blocker.state?.type ?? "").trim().toLowerCase();
if (closed.has(type)) continue;
if (!out.includes(blocker.identifier)) out.push(blocker.identifier);
}
return out;
}

/**
* The issue as stewards sees it. Comments are the newest fifty, oldest
* first; each body is clipped after its signature is read, so a long
Expand Down Expand Up @@ -593,6 +619,7 @@ export function snapshotOfIssue(issue: SnapshotIssue, viewer: string | null): En
stateType: c.state?.type ?? null,
labels: (c.labels?.nodes ?? []).map((l) => l.name),
})),
blockedBy: openBlockers(issue),
linkedPulls,
pull: null,
viewer,
Expand Down
9 changes: 9 additions & 0 deletions plugins/linear/source-contract.ts
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,15 @@ export const entitySnapshotSchema = z.object({
*/
children: z.array(snapshotChildSchema),
childrenTotal: z.number().int().nonnegative().optional(),
/**
* BB-385: the keys of the issues that block this one (this issue is
* `blockedBy` them), keeping only blockers still open. Optional and
* additive: the linear source reads relations and sends it, an empty array
* when nothing blocks the issue; github, which has no dependency relation,
* omits it. Absent means the source did not read relations, never that none
* block it, so a caller that needs the fact refuses rather than assumes.
*/
blockedBy: z.array(z.string()).optional(),
/**
* True when the source could not read the entity's parent and sub-issues
* (GitHub rejected the fields, or the relation read errored or was
Expand Down
15 changes: 14 additions & 1 deletion plugins/stewards/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,20 @@ install on a stock bb: one repository, no Linear, no hooks service.
[store.ts](store.ts)); the digest lists each write and counts the refusals.
The flag is re-read on every call, so turning it off refuses at once, and
a ticket, ledger or configuration that cannot be read refuses and writes
nothing. The `.bb` keys land in a later, owner-reviewed pull request.
nothing. Stage 3 adds a second opt-in, `backlog.promote: true`, and with it
the gated `backlog_promote { key }` tool ([backlog-promote.ts](backlog-promote.ts)):
it moves one ticket to Todo, adds the adoption label and assigns it to this
server, then the ordinary ticket steward adopts it. The plugin, not the
model, picks the ticket — the top-ordered ready-looking un-adopted Backlog
ticket, by the owner's priority and then oldest `createdAt` first, with the
key as a final tiebreak (Linear returns newest first, so the tiebreak is
explicit) — and ignores a `key` that is not that ticket. It refuses when Todo plus In Progress is at
or over `backlog.wipLimit`, never edits a description, cancels, closes or
changes a priority, and never promotes an adopted ticket, one in a
non-Backlog state, or one with an open `blockedBy` (the linear snapshot now
carries the open blocker keys). Each promotion is its own digest line; a
WIP-full or no-candidate refusal repeated for an unchanged reason collapses
to one. The `.bb` keys land in a later, owner-reviewed pull request.
- **The reconcile loop.** linear and github-watcher hold leases on the hooks
service for the project's teams and repos and for every bound entity, and ring this plugin
on a doorbell. A ring is debounced, the entity is snapshotted, compared with
Expand Down
216 changes: 216 additions & 0 deletions plugins/stewards/backlog-promote.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
import { describe, expect, it } from "vitest";
import {
backlogPromoteParamsSchema,
candidateEligible,
decidePromote,
hasOpenBlocker,
isAdopted,
isBacklogState,
isReadyLooking,
isTodoOrInProgress,
orderedCandidates,
promoteAcceptedDetail,
promotePlan,
promoteRefusedDetail,
wipCount,
type BacklogPromoteIssue,
type PromoteConfig,
type PromoteDetail,
} from "./backlog-promote.js";

const config = (over: Partial<PromoteConfig> = {}): PromoteConfig => ({
promote: true,
team: "BB",
wipLimit: 5,
label: "bb-managed",
adoptedLabels: ["bb-managed", "initiative"],
...over,
});

const issue = (over: Partial<BacklogPromoteIssue> = {}): BacklogPromoteIssue => ({
id: "uuid-1",
key: "BB-1",
unit: "BB",
title: "Fix login",
state: "Backlog",
stateType: "backlog",
labels: [],
assignees: [],
priority: null,
createdAt: "2026-10-01T00:00:00Z",
...over,
});

const detail = (over: Partial<PromoteDetail> = {}): PromoteDetail => ({ description: "Users cannot log in.", blockedBy: [], ...over });

const detailsOf = (entries: Array<[string, Partial<PromoteDetail>]>): Map<string, PromoteDetail> => new Map(entries.map(([key, over]) => [key, detail(over)]));

const decide = (over: Partial<Parameters<typeof decidePromote>[0]> = {}) => decidePromote({ params: {}, issues: [issue()], details: detailsOf([["BB-1", {}]]), config: config(), ...over });

const reason = (result: ReturnType<typeof decidePromote>): string => (result.ok ? "" : result.reason);

describe("the promotion opt-in and authority limits (BB-385)", () => {
it("refuses everything while backlog.promote is off", () => {
expect(reason(decide({ config: config({ promote: false }) }))).toMatch(/promote is off/u);
});

it("refuses a call carrying a description, state, assignee, cancel, close, label, priority or relation", () => {
for (const field of ["description", "state", "assignee", "cancel", "close", "addLabels", "priority", "relations"]) {
const raw = { key: "BB-1", [field]: "x" } as unknown as Parameters<typeof decidePromote>[0]["params"];
expect(reason(decide({ params: raw }))).toMatch(new RegExp(`may not carry ${field}`, "u"));
}
// The tool's own schema is strict, so the same call never parses.
expect(backlogPromoteParamsSchema.safeParse({ key: "BB-1", state: "Todo" }).success).toBe(false);
expect(backlogPromoteParamsSchema.safeParse({ key: "BB-1" }).success).toBe(true);
expect(backlogPromoteParamsSchema.safeParse({}).success).toBe(true);
});

it("plans exactly Todo, the adoption label and this server's own login", () => {
const result = decide();
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.plan).toEqual({ key: "BB-1", state: "Todo", addLabels: ["bb-managed"], assignee: "me" });
expect(result.candidate.key).toBe("BB-1");
}
expect(promotePlan(issue({ key: "BB-2" }), config())).toEqual({ key: "BB-2", state: "Todo", addLabels: ["bb-managed"], assignee: "me" });
});
});

describe("the WIP limit (BB-385)", () => {
const todo = (over: Partial<BacklogPromoteIssue> = {}) => issue({ key: `BB-${Math.random()}`, state: "Todo", stateType: "unstarted", ...over });
const inProgress = (over: Partial<BacklogPromoteIssue> = {}) => issue({ key: `BB-${Math.random()}`, state: "In Progress", stateType: "started", ...over });

it("counts only Todo and In Progress by name, not In Review or another started state", () => {
const issues = [todo(), inProgress(), issue({ state: "Backlog", stateType: "backlog" }), issue({ state: "Done", stateType: "completed" })];
expect(wipCount(issues, config())).toBe(2);
expect(isTodoOrInProgress(issue({ state: "Todo", stateType: "unstarted" }))).toBe(true);
expect(isTodoOrInProgress(issue({ state: "In Progress", stateType: "started" }))).toBe(true);
expect(isTodoOrInProgress(issue({ state: "Todo", stateType: null }))).toBe(true);
// In Review is a `started` state in the BB team, but it is not work in progress for the ceiling.
expect(isTodoOrInProgress(issue({ state: "In Review", stateType: "started" }))).toBe(false);
expect(isTodoOrInProgress(issue({ state: "Doing", stateType: "started" }))).toBe(false);
expect(isTodoOrInProgress(issue({ state: "Ready", stateType: "unstarted" }))).toBe(false);
expect(isTodoOrInProgress(issue({ state: "Backlog", stateType: "backlog" }))).toBe(false);
});

it("refuses at the ceiling and promotes below it", () => {
const atLimit = [todo(), inProgress(), todo(), inProgress(), todo()];
expect(reason(decide({ issues: atLimit, details: detailsOf([]), config: config({ wipLimit: 5 }) }))).toMatch(/WIP full/u);
const below = [todo(), inProgress(), todo(), inProgress()];
expect(decide({ issues: below, details: detailsOf([]), config: config({ wipLimit: 5 }) }).ok).toBe(false);
// Below the ceiling but with no candidate, the refusal is "no eligible candidate".
expect(reason(decide({ issues: below, details: detailsOf([]), config: config({ wipLimit: 5 }) }))).toBe("no eligible candidate");
});

it("counts only the watched team", () => {
expect(wipCount([todo({ unit: "OPS" }), todo({ unit: "BB" })], config())).toBe(1);
});
});

describe("the candidate rules (BB-385)", () => {
it("never picks a ticket that is not in Backlog", () => {
expect(isBacklogState(issue({ state: "Backlog", stateType: "backlog" }))).toBe(true);
expect(isBacklogState(issue({ state: "Backlog", stateType: null }))).toBe(true);
expect(isBacklogState(issue({ state: "Todo", stateType: "unstarted" }))).toBe(false);
// A non-Backlog ticket is not a candidate even when it is the only one.
expect(reason(decide({ issues: [issue({ state: "Todo", stateType: "unstarted" })], details: detailsOf([]) }))).toBe("no eligible candidate");
});

it("never picks an adopted ticket: an adoption label, an initiative or any assignee", () => {
expect(isAdopted(issue({ labels: ["bb-managed"] }), config())).toBe(true);
expect(isAdopted(issue({ labels: ["initiative"] }), config())).toBe(true);
expect(isAdopted(issue({ assignees: ["jane"] }), config())).toBe(true);
expect(isAdopted(issue(), config())).toBe(false);
expect(orderedCandidates([issue({ labels: ["bb-managed"] }), issue({ key: "BB-2", assignees: ["jane"] }), issue({ key: "BB-3" })], config()).map((i) => i.key)).toEqual(["BB-3"]);
});

it("never picks a ticket with an open blocker", () => {
expect(hasOpenBlocker(detail({ blockedBy: ["BB-9"] }))).toBe(true);
expect(hasOpenBlocker(detail({ blockedBy: [] }))).toBe(false);
// The only candidate is blocked, so nothing is promoted.
expect(reason(decide({ details: detailsOf([["BB-1", { blockedBy: ["BB-9"] }]]) }))).toBe("no eligible candidate");
// A blocked top ticket is skipped for the next ready-looking one.
const result = decide({
issues: [issue({ key: "BB-1" }), issue({ key: "BB-2" })],
details: detailsOf([
["BB-1", { blockedBy: ["BB-9"] }],
["BB-2", {}],
]),
});
expect(result.ok).toBe(true);
if (result.ok) expect(result.plan.key).toBe("BB-2");
});

it("requires a non-empty title and description, and skips a ticket that lacks one", () => {
expect(isReadyLooking(issue(), detail())).toBe(true);
expect(isReadyLooking(issue({ title: " " }), detail())).toBe(false);
expect(isReadyLooking(issue(), detail({ description: " " }))).toBe(false);
expect(isReadyLooking(issue(), detail({ description: null }))).toBe(false);
expect(candidateEligible(issue(), detail())).toBe(true);
// The top ticket is empty, so the next ready-looking one is promoted.
const result = decide({
issues: [issue({ key: "BB-1" }), issue({ key: "BB-2" })],
details: detailsOf([
["BB-1", { description: " " }],
["BB-2", {}],
]),
});
expect(result.ok).toBe(true);
if (result.ok) expect(result.plan.key).toBe("BB-2");
});

it("skips a candidate whose detail was not read, but promotes a later read one", () => {
const result = decide({
issues: [issue({ key: "BB-1" }), issue({ key: "BB-2" })],
details: detailsOf([["BB-2", {}]]),
});
expect(result.ok).toBe(true);
if (result.ok) expect(result.plan.key).toBe("BB-2");
});
});

describe("the ordering (BB-385)", () => {
it("orders by the owner's priority, then oldest first, and never changes priority", () => {
const issues = [
issue({ key: "BB-1", priority: "Low", createdAt: "2026-10-05T00:00:00Z" }),
issue({ key: "BB-2", priority: "Urgent", createdAt: "2026-10-06T00:00:00Z" }),
issue({ key: "BB-3", priority: null, createdAt: "2026-10-07T00:00:00Z" }),
// The source returns newest `createdAt` first (Linear's own order): the
// two High tickets are passed newest-first and must come out oldest-first.
issue({ key: "BB-4", priority: "High", createdAt: "2026-10-09T00:00:00Z" }),
issue({ key: "BB-5", priority: "Medium", createdAt: "2026-10-03T00:00:00Z" }),
issue({ key: "BB-6", priority: "High", createdAt: "2026-10-08T00:00:00Z" }),
];
expect(orderedCandidates(issues, config()).map((i) => i.key)).toEqual(["BB-2", "BB-6", "BB-4", "BB-5", "BB-1", "BB-3"]);
// The plan carries no priority, so a promotion never writes one.
const result = decide({ issues, details: detailsOf(issues.map((i) => [i.key, {}])) });
expect(result.ok).toBe(true);
if (result.ok) expect(result.plan).toEqual({ key: "BB-2", state: "Todo", addLabels: ["bb-managed"], assignee: "me" });
});

it("treats an unknown priority as unset rather than ranking above a hand-set one", () => {
const issues = [issue({ key: "BB-1", priority: "P0-ish" }), issue({ key: "BB-2", priority: "low" })];
expect(orderedCandidates(issues, config()).map((i) => i.key)).toEqual(["BB-2", "BB-1"]);
});
});

describe("the key hint (BB-385)", () => {
it("ignores a key that is not the top-ordered eligible ticket", () => {
const issues = [issue({ key: "BB-1", priority: "Urgent" }), issue({ key: "BB-2", priority: "Low" })];
const details = detailsOf([
["BB-1", {}],
["BB-2", {}],
]);
const result = decide({ params: { key: "BB-2" }, issues, details });
expect(result.ok).toBe(true);
if (result.ok) expect(result.plan.key).toBe("BB-1");
});
});

describe("the ledger entries (BB-385)", () => {
it("names the promoted ticket, the state, the label and the assignee", () => {
expect(promoteAcceptedDetail(issue({ key: "BB-1" }), { key: "BB-1" }, config())).toEqual({ state: "Todo", addLabels: ["bb-managed"], assignee: "me", requestedKey: "BB-1", promoted: "BB-1" });
expect(promoteRefusedDetail({ key: "BB-2" })).toEqual({ requestedKey: "BB-2" });
expect(promoteRefusedDetail({})).toEqual({ requestedKey: null });
});
});
Loading