diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index dba94dcf..84c78cdc 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -1012,7 +1012,7 @@ deployment: # where a merge is confirmed live (BB-53); omi - Stewards are children of their parent steward, or of the project steward when they have none, with parent notifications off (§4), so bb's thread tree nests each under its parent. bb does not re-parent a live thread when its - parent ends: a child spawned under a goal that later ends stays under it + parent ends: a child spawned under an initiative that later ends stays under it visually, even though the binding's `parentBindingId` moved up (`endBinding`). The sidebar's own list (§21) derives the same nesting from each binding's `parentKey`, one level deep, so the two views agree. Who reports to whom is in diff --git a/plugins/stewards/config.test.ts b/plugins/stewards/config.test.ts index 75f85520..c0330d1d 100644 --- a/plugins/stewards/config.test.ts +++ b/plugins/stewards/config.test.ts @@ -368,16 +368,16 @@ describe("playbooks", () => { }); it("keys a phase on a label with `label:`, keeping it out of the states (BB-248)", () => { - const withLabel = parsePlaybook(LINEAR_TICKETS.replace(" In Progress: { stage: build, stuck: 2d }", ' In Progress: { stage: build, stuck: 2d }\n "label:goal:awaiting-outcome": { stage: build, stuck: 120d }'), "linear-tickets"); + const withLabel = parsePlaybook(LINEAR_TICKETS.replace(" In Progress: { stage: build, stuck: 2d }", ' In Progress: { stage: build, stuck: 2d }\n "label:initiative:awaiting-outcome": { stage: build, stuck: 120d }'), "linear-tickets"); if (!withLabel.ok) throw new Error(withLabel.error); const p = withLabel.value; - expect(labelPhaseName("label:goal:awaiting-outcome")).toBe("goal:awaiting-outcome"); + expect(labelPhaseName("label:initiative:awaiting-outcome")).toBe("initiative:awaiting-outcome"); expect(labelPhaseName("In Progress")).toBeNull(); - expect(playbookLabels(p)).toEqual(["goal:awaiting-outcome"]); - expect(playbookStates(p)).not.toContain("label:goal:awaiting-outcome"); + expect(playbookLabels(p)).toEqual(["initiative:awaiting-outcome"]); + expect(playbookStates(p)).not.toContain("label:initiative:awaiting-outcome"); expect(playbookStates(p)).toContain("In Progress"); // phaseOf still resolves the label key itself, for a binding's stored phase. - expect(phaseOf(p, "label:goal:awaiting-outcome")).toMatchObject({ name: "label:goal:awaiting-outcome", stage: "build" }); + expect(phaseOf(p, "label:initiative:awaiting-outcome")).toMatchObject({ name: "label:initiative:awaiting-outcome", stage: "build" }); // A `label:` key with no name is refused; a state-only playbook has no label keys. expect(parsePlaybook(LINEAR_TICKETS.replace(" In Progress: { stage: build, stuck: 2d }", ' In Progress: { stage: build, stuck: 2d }\n "label:": { stage: build }'), "linear-tickets")).toMatchObject({ ok: false }); const plain = parsePlaybook(LINEAR_TICKETS, "linear-tickets"); @@ -846,29 +846,29 @@ describe("project-level ticket watches (BB-246)", () => { const file = (tickets: unknown) => parseProjectFile(JSON.stringify({ version: 1, tickets })); const playbooks = () => { const tickets = parsePlaybook(LINEAR_TICKETS, "linear-tickets"); - const goals = parsePlaybook(LINEAR_TICKETS.replace("name: linear-tickets", "name: goals"), "goals"); + const initiative = parsePlaybook(LINEAR_TICKETS.replace("name: linear-tickets", "name: initiative"), "initiative"); const prs = parsePlaybook(GITHUB_PRS, "github-prs"); - if (!tickets.ok || !goals.ok || !prs.ok) throw new Error("playbook parse failed"); + if (!tickets.ok || !initiative.ok || !prs.ok) throw new Error("playbook parse failed"); return new Map([ ["linear-tickets", tickets.value], - ["goals", goals.value], + ["initiative", initiative.value], ["github-prs", prs.value], ]); }; it("parses a tickets list, defaulting match, and refuses a bad shape", () => { - const parsed = file([{ match: { labels: ["docs"], title: "Docs: *" }, playbook: "goals" }, { playbook: "linear-tickets" }]); + const parsed = file([{ match: { labels: ["docs"], title: "Docs: *" }, playbook: "initiative" }, { playbook: "linear-tickets" }]); if (!parsed.ok) throw new Error(parsed.error); expect(parsed.value.tickets).toEqual([ - { match: { labels: ["docs"], title: "Docs: *" }, playbook: "goals" }, + { match: { labels: ["docs"], title: "Docs: *" }, playbook: "initiative" }, { match: {}, playbook: "linear-tickets" }, ]); const empty = parseProjectFile(JSON.stringify({ version: 1 })); if (!empty.ok) throw new Error(empty.error); expect(empty.value.tickets).toEqual([]); - expect(file([{ match: { labels: [] }, playbook: "goals" }])).toMatchObject({ ok: false }); + expect(file([{ match: { labels: [] }, playbook: "initiative" }])).toMatchObject({ ok: false }); expect(file([{ match: { labels: ["docs"] } }])).toMatchObject({ ok: false }); - expect(file([{ match: { bogus: true }, playbook: "goals" }])).toMatchObject({ ok: false }); + expect(file([{ match: { bogus: true }, playbook: "initiative" }])).toMatchObject({ ok: false }); // A near-miss key is still refused by the strict project file. expect(parseProjectFile(JSON.stringify({ version: 1, ticket: [] }))).toMatchObject({ ok: false }); }); @@ -887,15 +887,15 @@ describe("project-level ticket watches (BB-246)", () => { }); it("reports a ticket watch playbook that did not parse from the loader's error, once", () => { - const parsed = file([{ playbook: "goals" }]); + const parsed = file([{ playbook: "initiative" }]); if (!parsed.ok) throw new Error(parsed.error); - const problems = ticketWatchProblems(parsed.value, new Map(), new Map([["goals", "stewards/playbooks/goals.md: the front matter is not YAML"]])); - expect(problems).toEqual([expect.stringMatching(/tickets\[0\].*"goals".*not YAML/u)]); + const problems = ticketWatchProblems(parsed.value, new Map(), new Map([["initiative", "stewards/playbooks/initiative.md: the front matter is not YAML"]])); + expect(problems).toEqual([expect.stringMatching(/tickets\[0\].*"initiative".*not YAML/u)]); }); it("names a ticket watch by its playbook", () => { - const parsed = file([{ playbook: "goals" }]); + const parsed = file([{ playbook: "initiative" }]); if (!parsed.ok) throw new Error(parsed.error); - expect(parsed.value.tickets.map((w) => ticketWatchId(w))).toEqual(["goals@ticket"]); + expect(parsed.value.tickets.map((w) => ticketWatchId(w))).toEqual(["initiative@ticket"]); }); }); diff --git a/plugins/stewards/config.ts b/plugins/stewards/config.ts index 47ce5c1f..efa3146d 100644 --- a/plugins/stewards/config.ts +++ b/plugins/stewards/config.ts @@ -20,14 +20,15 @@ export const playbookPath = (name: string) => `${STEWARDS_DIR}/playbooks/${name} export const DEFAULT_LABEL = "bb-managed"; /** - * The label a goal ticket carries besides the adoption label, and the playbook - * that stewards it (BB-243). A ticket is a goal when it carries the label or - * runs under the playbook: the project steward's wake and digest read a goal's - * progress from the `**Met:**` comments, and the playbook name is known even - * before the first snapshot, so an unread history reads `unknown`, never `0`. + * The label an initiative ticket carries besides the adoption label, and the + * playbook that stewards it (BB-243). A ticket is an initiative when it + * carries the label or runs under the playbook: the project steward's wake and + * digest read an initiative's progress from the `**Met:**` comments, and the + * playbook name is known even before the first snapshot, so an unread history + * reads `unknown`, never `0`. */ -export const GOAL_LABEL = "goal"; -export const GOAL_PLAYBOOK = "goal"; +export const INITIATIVE_LABEL = "initiative"; +export const INITIATIVE_PLAYBOOK = "initiative"; /** * Authors whose pull requests the dependency watch adopts under deps-prs diff --git a/plugins/stewards/github.ts b/plugins/stewards/github.ts index ef628a0e..33c2d32b 100644 --- a/plugins/stewards/github.ts +++ b/plugins/stewards/github.ts @@ -77,8 +77,14 @@ export interface GithubWriter { * changes-requested review, where the owner's own pull request cannot. */ review(repo: string, number: number, event: "APPROVE" | "REQUEST_CHANGES" | "COMMENT", body: string): Promise; - /** Squash-merge the pull request, with the given commit title and message; returns the merge commit sha when GitHub reports one. */ - squashMerge(repo: string, number: number, title: string, body: string): Promise<{ sha: string | null }>; + /** + * Squash-merge the pull request, with the given commit title and message; + * returns the merge commit sha when GitHub reports one. `sha` is the head + * the caller judged: GitHub refuses with 409 "Head branch was modified" + * when the head moved, so an unattended merge never lands a push whose + * checks have not run (BB-257). + */ + squashMerge(repo: string, number: number, title: string, body: string, sha?: string | null): Promise<{ sha: string | null }>; /** * A pull request's title and body, for the squash merge commit (BB-193). * Null when GitHub has no readable title, or when the read fails; the caller @@ -156,8 +162,8 @@ export function createGhWriter(token: TokenReader = createGhTokenReader(), doFet async review(repo, number, event, body) { await request("POST", `/repos/${repo}/pulls/${number}/reviews`, { event, body }); }, - async squashMerge(repo, number, title, body) { - const response = await request("PUT", `/repos/${repo}/pulls/${number}/merge`, { merge_method: "squash", commit_title: title, commit_message: body }); + async squashMerge(repo, number, title, body, headSha) { + const response = await request("PUT", `/repos/${repo}/pulls/${number}/merge`, { merge_method: "squash", commit_title: title, commit_message: body, ...(headSha === undefined || headSha === null || headSha === "" ? {} : { sha: headSha }) }); const merged = (await response.json().catch(() => null)) as { sha?: unknown } | null; const sha = merged?.sha; return { sha: typeof sha === "string" && sha !== "" ? sha : null }; diff --git a/plugins/stewards/reconcile.test.ts b/plugins/stewards/reconcile.test.ts index 20cd497c..196134b1 100644 --- a/plugins/stewards/reconcile.test.ts +++ b/plugins/stewards/reconcile.test.ts @@ -20,7 +20,7 @@ const reviews = (() => { const ctx = { own: new Set(["thr_s", "thr_w"]), stewardThreadId: "thr_s", approved: false, cursor: "2026-10-01T12:00:00Z", workerInFlight: false }; const actionable = (cs: Array<{ text: string; actionable: boolean }>) => cs.filter((c) => c.actionable).map((c) => c.text); -const LABEL_PHASE = '\n "label:goal:awaiting-outcome": { stage: build, stuck: 120d }'; +const LABEL_PHASE = '\n "label:initiative:awaiting-outcome": { stage: build, stuck: 120d }'; const labelledTickets = (() => { const p = parsePlaybook(LINEAR_TICKETS.replace(" In Progress: { stage: build, stuck: 2d }", ` In Progress: { stage: build, stuck: 2d }${LABEL_PHASE}`), "linear-tickets"); if (!p.ok) throw new Error(p.error); @@ -34,23 +34,23 @@ const labelledGithubIssues = (() => { describe("phaseAndStage keys a phase on a present label (BB-248)", () => { it("selects a matching label phase ahead of the state, on Linear", () => { - expect(phaseAndStage(labelledTickets, "In Progress", ["bb-managed", "goal:awaiting-outcome"])).toEqual({ phase: "label:goal:awaiting-outcome", stage: "build" }); + expect(phaseAndStage(labelledTickets, "In Progress", ["bb-managed", "initiative:awaiting-outcome"])).toEqual({ phase: "label:initiative:awaiting-outcome", stage: "build" }); // The label match ignores case. - expect(phaseAndStage(labelledTickets, "In Progress", ["Goal:Awaiting-Outcome"])).toEqual({ phase: "label:goal:awaiting-outcome", stage: "build" }); + expect(phaseAndStage(labelledTickets, "In Progress", ["Initiative:Awaiting-Outcome"])).toEqual({ phase: "label:initiative:awaiting-outcome", stage: "build" }); // No such label, or no labels at all: the state decides, as today. expect(phaseAndStage(labelledTickets, "In Progress", ["bb-managed"])).toEqual({ phase: "In Progress", stage: "build" }); expect(phaseAndStage(labelledTickets, "In Progress")).toEqual({ phase: "In Progress", stage: "build" }); }); it("selects it on a GitHub entity too, over the synthesised status state", () => { - expect(phaseAndStage(labelledGithubIssues, "status:in-progress", ["bb-managed", "goal:awaiting-outcome"])).toEqual({ phase: "label:goal:awaiting-outcome", stage: "build" }); + expect(phaseAndStage(labelledGithubIssues, "status:in-progress", ["bb-managed", "initiative:awaiting-outcome"])).toEqual({ phase: "label:initiative:awaiting-outcome", stage: "build" }); // A present status label is still a state, and decides when no label phase matches. expect(phaseAndStage(labelledGithubIssues, "status:in-progress", ["bb-managed", "status:in-progress"])).toEqual({ phase: "status:in-progress", stage: "build" }); }); it("resolves the stored label phase for stuckDue", () => { - expect(phaseAndStage(labelledTickets, "In Progress", ["goal:awaiting-outcome"]).phase).toBe("label:goal:awaiting-outcome"); - expect(stuckDue({ advancedAt: 1_000, createdAt: 0, phase: "label:goal:awaiting-outcome" }, labelledTickets, [], 1_000 + 120 * 86_400_000)).toBe(120 * 86_400_000); + expect(phaseAndStage(labelledTickets, "In Progress", ["initiative:awaiting-outcome"]).phase).toBe("label:initiative:awaiting-outcome"); + expect(stuckDue({ advancedAt: 1_000, createdAt: 0, phase: "label:initiative:awaiting-outcome" }, labelledTickets, [], 1_000 + 120 * 86_400_000)).toBe(120 * 86_400_000); }); }); @@ -503,29 +503,29 @@ describe("lifecycle", () => { }); }); -// BB-243: a goal is a ticket routed to the `goal` playbook. All three endings -// (reached, superseded, retired) are the goal closing; a child's merge is not -// one, so the binding carries on. The fixture is a fake goal, never the pilot's. -describe("goal endings (BB-243)", () => { - const goal = (() => { - const p = parsePlaybook(GITHUB_ISSUES.replace("name: github-issues", "name: goal").replace("approval: project", "approval: user"), "goal"); +// BB-243: an initiative is a ticket routed to the `initiative` playbook. All three endings +// (reached, superseded, retired) are the initiative closing; a child's merge is not +// one, so the binding carries on. The fixture is a fake initiative, never the pilot's. +describe("initiative endings (BB-243)", () => { + const initiative = (() => { + const p = parsePlaybook(GITHUB_ISSUES.replace("name: github-issues", "name: initiative").replace("approval: project", "approval: user"), "initiative"); if (!p.ok) throw new Error(p.error); return p.value; })(); const open = { kind: "ticket" as const, endedAt: null, endReason: null, manualDetach: false, ending: null }; - it("ends the binding when the goal is reached, superseded or retired, and never on a child merge", () => { + it("ends the binding when the initiative is reached, superseded or retired, and never on a child merge", () => { // Reached: every criterion met, the owner closes it as completed. - expect(lifecycle(open, goal, issue({ state: "closed (completed)" }), "bb-managed").kind).toBe("terminal"); + expect(lifecycle(open, initiative, issue({ state: "closed (completed)" }), "bb-managed").kind).toBe("terminal"); // Retired: the owner closes it as not planned. - expect(lifecycle(open, goal, issue({ state: "closed (not planned)" }), "bb-managed").kind).toBe("terminal"); - // Superseded: a successor is filed and this goal is closed with a Revision comment. - const superseded = issue({ state: "closed", comments: [comment({ id: "r1", author: "Jane", body: "**Revision:** superseded by Goal: file the 2027 claim." })] }); - expect(lifecycle(open, goal, superseded, "bb-managed").kind).toBe("terminal"); - // A child merging does not close the goal, so the binding carries on. - expect(lifecycle(open, goal, issue({ state: "status:in-progress" }), "bb-managed").kind).toBe("continue"); - // An ended goal stays ended while it is closed, whatever an earlier digest said. - expect(lifecycle({ ...open, endedAt: 1, endReason: "terminal" }, goal, issue({ state: "closed" }), "bb-managed").kind).toBe("stay-ended"); + expect(lifecycle(open, initiative, issue({ state: "closed (not planned)" }), "bb-managed").kind).toBe("terminal"); + // Superseded: a successor is filed and this initiative is closed with a Revision comment. + const superseded = issue({ state: "closed", comments: [comment({ id: "r1", author: "Jane", body: "**Revision:** superseded by Initiative: file the 2027 claim." })] }); + expect(lifecycle(open, initiative, superseded, "bb-managed").kind).toBe("terminal"); + // A child merging does not close the initiative, so the binding carries on. + expect(lifecycle(open, initiative, issue({ state: "status:in-progress" }), "bb-managed").kind).toBe("continue"); + // An ended initiative stays ended while it is closed, whatever an earlier digest said. + expect(lifecycle({ ...open, endedAt: 1, endReason: "terminal" }, initiative, issue({ state: "closed" }), "bb-managed").kind).toBe("stay-ended"); }); }); diff --git a/plugins/stewards/server.test.ts b/plugins/stewards/server.test.ts index 015709a8..80156138 100644 --- a/plugins/stewards/server.test.ts +++ b/plugins/stewards/server.test.ts @@ -116,6 +116,8 @@ function world() { let pullNumber = 0; let createPullError: string | null = null; let mergePullError: string | null = null; + /** When set, the pull request's head moves during `pullDetails`, so the merge PUT sees a stale head and GitHub refuses with 409 (BB-257). */ + let moveHeadOnMerge = false; /** A forced failure for `github.dispatchWorkflow`, to exercise the best-effort dispatch after a merge (BB-216). */ let mergeDispatchError: string | null = null; /** A forced failure for `github.pullDetails`, to exercise the merge title fallback (BB-193). */ @@ -132,9 +134,20 @@ function world() { review: async (repo: string, number: number, event: "APPROVE" | "REQUEST_CHANGES" | "COMMENT", body: string) => { githubReviews.push({ repo, number, event, body }); }, - squashMerge: async (repo: string, number: number, title: string, body: string) => { + squashMerge: async (repo: string, number: number, title: string, body: string, sha?: string | null) => { if (mergePullError !== null) throw new Error(mergePullError); + const key = `${repo}#${number}`; + const e = entities.get(key); + // The real PUT names the head the caller judged; GitHub refuses with 409 + // when the head moved (BB-257). + if (sha !== undefined && sha !== null && sha !== "" && e !== undefined && e.pull !== null && e.pull.headSha !== sha) { + throw new Error(`PUT /repos/${repo}/pulls/${number}/merge failed: 409 {"message":"Head branch was modified. Review and try the merge again."}`); + } githubMerges.push({ repo, number, title, body }); + // The real merge changes the pull request's state; the fake must too, or + // the plugin's own gate-met merge (BB-257) and the reconcile it + // schedules would merge the same open snapshot again in a loop. + if (e !== undefined && e.pull !== null) entities.set(key, { ...e, state: "merged", pull: { ...e.pull, merged: true, mergeCommit: "c".repeat(40) } }); return { sha: "c".repeat(40) }; }, // The real writer reads the pull request's title and body from GitHub; the @@ -144,6 +157,9 @@ function world() { if (pullDetailsError !== null) throw new Error(pullDetailsError); const entity = entities.get(`${repo}#${number}`); if (entity === undefined || entity.title === null || entity.title.trim() === "") return null; + // A push between the look and the merge: the head the plugin judged is + // no longer the head, so the merge PUT must be refused (BB-257). + if (moveHeadOnMerge && entity.pull !== null) entities.set(`${repo}#${number}`, { ...entity, pull: { ...entity.pull, headSha: "ddddddd4" } }); return { title: entity.title, body: entity.description ?? "" }; }, files: async (repo: string, number: number) => { @@ -494,7 +510,7 @@ function world() { }, }; let now = Date.parse("2026-10-14T15:00:00Z"); - return { files, writes, writtenContent, fileContents, repos, primary, entities, projectList, dependabotAlerts, sourceDeployments, sourceFiles, sourceCommits, sourceRuns, sourceCompares, labelEnsureCalls, labelsEnsured, labelEnsureFailures, setLabelEnsureUnavailable: (value: boolean) => { labelEnsureUnavailable = value; }, setPushUnavailable: (value: boolean) => { pushUnavailable = value; }, setLabelEnsureThrow: (value: string | null) => { labelEnsureThrow = value; }, setLayout: (value: "primary" | "directory") => { layout = value; primary = value === "directory" ? null : { dir: "bb", url: "https://github.com/acme/bb.git" }; }, viewers, setLinearMine: (teams: Array<{ unit: string; name: string }>) => { linearMine = teams; }, setMissingStates: (source: "linear" | "github", unit: string, states: string[]) => { missingStates.set(`${source}:${unit.toLowerCase()}`, states); }, setMissingLabel: (source: "linear" | "github", unit: string, labels: string[]) => { missingLabels.set(`${source}:${unit.toLowerCase()}`, labels); }, rpcCalls, githubTrees, githubBranchProtection, githubLabels, setSnapshotError: (id: string, fail: boolean) => { if (fail) snapshotErrors.add(id); else snapshotErrors.delete(id); }, setSearchUnsupported: (value: boolean) => { searchUnsupported = value; }, setSearchError: (value: string | null) => { searchError = value; }, setCreatePullError: (value: string | null) => { createPullError = value; }, setMergePullError: (value: string | null) => { mergePullError = value; }, setPullDetailsError: (value: string | null) => { pullDetailsError = value; }, setRetryConflict: (value: boolean) => { retryConflict = value; }, setRetryQueued: (value: boolean) => { retryQueued = value; }, threads, deletes, sections, usage, metadata, spawns, sends, retries, retryEvents, queuedDeletes, userTurns, githubComments, githubReviews, githubMerges, githubPulls, githubClosedPulls, githubDefaultBranches, githubFiles, githubFileContents, githubDispatches, setMergeDispatchError: (value: string | null) => { mergeDispatchError = value; }, github, sdk, uiPreferences, uiPreferencesWrites, now: () => now, advance: (ms: number) => (now += ms) }; + return { files, writes, writtenContent, fileContents, repos, primary, entities, projectList, dependabotAlerts, sourceDeployments, sourceFiles, sourceCommits, sourceRuns, sourceCompares, labelEnsureCalls, labelsEnsured, labelEnsureFailures, setLabelEnsureUnavailable: (value: boolean) => { labelEnsureUnavailable = value; }, setPushUnavailable: (value: boolean) => { pushUnavailable = value; }, setLabelEnsureThrow: (value: string | null) => { labelEnsureThrow = value; }, setLayout: (value: "primary" | "directory") => { layout = value; primary = value === "directory" ? null : { dir: "bb", url: "https://github.com/acme/bb.git" }; }, viewers, setLinearMine: (teams: Array<{ unit: string; name: string }>) => { linearMine = teams; }, setMissingStates: (source: "linear" | "github", unit: string, states: string[]) => { missingStates.set(`${source}:${unit.toLowerCase()}`, states); }, setMissingLabel: (source: "linear" | "github", unit: string, labels: string[]) => { missingLabels.set(`${source}:${unit.toLowerCase()}`, labels); }, rpcCalls, githubTrees, githubBranchProtection, githubLabels, setSnapshotError: (id: string, fail: boolean) => { if (fail) snapshotErrors.add(id); else snapshotErrors.delete(id); }, setSearchUnsupported: (value: boolean) => { searchUnsupported = value; }, setSearchError: (value: string | null) => { searchError = value; }, setCreatePullError: (value: string | null) => { createPullError = value; }, setMergePullError: (value: string | null) => { mergePullError = value; }, setMoveHeadOnMerge: (value: boolean) => { moveHeadOnMerge = value; }, setPullDetailsError: (value: string | null) => { pullDetailsError = value; }, setRetryConflict: (value: boolean) => { retryConflict = value; }, setRetryQueued: (value: boolean) => { retryQueued = value; }, threads, deletes, sections, usage, metadata, spawns, sends, retries, retryEvents, queuedDeletes, userTurns, githubComments, githubReviews, githubMerges, githubPulls, githubClosedPulls, githubDefaultBranches, githubFiles, githubFileContents, githubDispatches, setMergeDispatchError: (value: string | null) => { mergeDispatchError = value; }, github, sdk, uiPreferences, uiPreferencesWrites, now: () => now, advance: (ms: number) => (now += ms) }; } async function setup(extra: Partial = {}, settings: Record = {}, seedProvider?: string | null | "fail-list" | "fail-set", seedNavigation?: string | null | "fail-list" | "fail-set") { @@ -872,21 +888,21 @@ describe("a Linear ticket steward", () => { const t = await setup(); t.files[playbookPath("linear-tickets")] = LINEAR_TICKETS.replace( " In Progress: { stage: build, stuck: 2d }", - ' In Progress: { stage: build, stuck: 2d }\n "label:goal:awaiting-outcome": { stage: spec, stuck: 120d }', - ).replace("## In Review", "## label:goal:awaiting-outcome\n\nWait for the outcome.\n\n## In Review"); + ' In Progress: { stage: build, stuck: 2d }\n "label:initiative:awaiting-outcome": { stage: spec, stuck: 120d }', + ).replace("## In Review", "## label:initiative:awaiting-outcome\n\nWait for the outcome.\n\n## In Review"); t.entities.set("uuid-12", issue()); await t.ring("linear", "uuid-12"); const steward = t.spawns[1]!.id; expect(t.hooks.store.find("ENG-12", "p1")!.phase).toBe("Todo"); t.sends.length = 0; // The label moves the phase; the state stays `Todo`. - t.entities.set("uuid-12", issue({ labels: ["bb-managed", "goal:awaiting-outcome"] })); + t.entities.set("uuid-12", issue({ labels: ["bb-managed", "initiative:awaiting-outcome"] })); await t.ring("linear", "uuid-12"); - expect(t.hooks.store.find("ENG-12", "p1")!.phase).toBe("label:goal:awaiting-outcome"); + expect(t.hooks.store.find("ENG-12", "p1")!.phase).toBe("label:initiative:awaiting-outcome"); const wakes = t.sends.filter((s) => s.threadId === steward); expect(wakes).toHaveLength(1); - expect(wakes[0]!.text).toMatch(/Phase: Todo → label:goal:awaiting-outcome/u); - expect(wakes[0]!.text).toContain("### label:goal:awaiting-outcome"); + expect(wakes[0]!.text).toMatch(/Phase: Todo → label:initiative:awaiting-outcome/u); + expect(wakes[0]!.text).toContain("### label:initiative:awaiting-outcome"); expect(wakes[0]!.text).toContain("Wait for the outcome."); }); @@ -2607,43 +2623,43 @@ describe("escalations delivered once, updates safe to retry", () => { }); }); -// BB-243: a goal is a ticket under the `goal` playbook. All three endings -// (reached, superseded, retired) are the goal closing; a child's merge is not -// one, so the binding carries on. The fixture is a fake goal, never the pilot's. -describe("goal endings end the binding (BB-243)", () => { - const GOAL = LINEAR_TICKETS.replace("name: linear-tickets", "name: goal"); - async function goalBinding() { +// BB-243: an initiative is a ticket under the `initiative` playbook. All three endings +// (reached, superseded, retired) are the initiative closing; a child's merge is not +// one, so the binding carries on. The fixture is a fake initiative, never the pilot's. +describe("initiative endings end the binding (BB-243)", () => { + const INITIATIVE = LINEAR_TICKETS.replace("name: linear-tickets", "name: initiative"); + async function initiativeBinding() { const t = await setup(); const file = JSON.parse(t.files[PROJECT_FILE]!) as { playbooks?: Record }; - file.playbooks = { ticket: "goal" }; + file.playbooks = { ticket: "initiative" }; t.files[PROJECT_FILE] = JSON.stringify(file); - t.files[playbookPath("goal")] = GOAL; - t.entities.set("uuid-12", issue({ labels: ["bb-managed", "goal"], state: "In Progress", stateType: "started" })); + t.files[playbookPath("initiative")] = INITIATIVE; + t.entities.set("uuid-12", issue({ labels: ["bb-managed", "initiative"], state: "In Progress", stateType: "started" })); await t.ring("linear", "uuid-12"); return { t, steward: t.spawns[1]!.id }; } - const closeGoal = async (t: Awaited>["t"], steward: string, state: string, stateType: string) => { - t.entities.set("uuid-12", issue({ labels: ["bb-managed", "goal"], state, stateType })); + const closeInitiative = async (t: Awaited>["t"], steward: string, state: string, stateType: string) => { + t.entities.set("uuid-12", issue({ labels: ["bb-managed", "initiative"], state, stateType })); await t.ring("linear", "uuid-12"); await t.tool("steward_report", { phase: state, summary: "Ending.", nextAction: "Nothing", actor: "steward" }, steward); await t.idle(steward); }; it("ends on reached (Done), and not on a child merge", async () => { - const { t, steward } = await goalBinding(); - expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "goal", endedAt: null }); - // A child merging does not close the goal, so the binding carries on. - t.entities.set("uuid-12", issue({ labels: ["bb-managed", "goal"], state: "In Progress", stateType: "started", linkedPulls: [{ url: "https://github.com/acme/web/pull/7", key: "acme/web#7" }] })); + const { t, steward } = await initiativeBinding(); + expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "initiative", endedAt: null }); + // A child merging does not close the initiative, so the binding carries on. + t.entities.set("uuid-12", issue({ labels: ["bb-managed", "initiative"], state: "In Progress", stateType: "started", linkedPulls: [{ url: "https://github.com/acme/web/pull/7", key: "acme/web#7" }] })); await t.ring("linear", "uuid-12"); expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ endedAt: null }); // Reached: Done ends the binding once the wrap-up turn is over. - await closeGoal(t, steward, "Done", "completed"); + await closeInitiative(t, steward, "Done", "completed"); expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ endedAt: expect.any(Number), endReason: "terminal" }); }); it("ends on retired (Canceled)", async () => { - const { t, steward } = await goalBinding(); - await closeGoal(t, steward, "Canceled", "canceled"); + const { t, steward } = await initiativeBinding(); + await closeInitiative(t, steward, "Canceled", "canceled"); expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ endedAt: expect.any(Number), endReason: "terminal" }); }); }); @@ -3528,29 +3544,29 @@ describe("check --create-labels (BB-236)", () => { // BB-248: a playbook phase keyed `label:` is checked as a label, not as // a missing workflow state, on Linear and GitHub alike. describe("check on a `label:` phase key (BB-248)", () => { - const withLabel = (text: string, stateLine: string) => text.replace(stateLine, `${stateLine}\n "label:goal:awaiting-outcome": { stage: build, stuck: 120d }`); + const withLabel = (text: string, stateLine: string) => text.replace(stateLine, `${stateLine}\n "label:initiative:awaiting-outcome": { stage: build, stuck: 120d }`); it("checks a Linear label phase key as a label, not a missing workflow state", async () => { const t = await setup(); t.files[playbookPath("linear-tickets")] = withLabel(LINEAR_TICKETS, " In Progress: { stage: build, stuck: 2d }"); - t.setMissingLabel("linear", "ENG", ["goal:awaiting-outcome"]); + t.setMissingLabel("linear", "ENG", ["initiative:awaiting-outcome"]); const check = await t.harness.behavior.runCli(["check", "--project", "p1"]); expect(check.exitCode).toBe(1); - expect(check.stdout).toMatch(/problem: linear: ENG has no label goal:awaiting-outcome/u); - expect(check.stdout).not.toMatch(/has no state (?:label:)?goal:awaiting-outcome/u); + expect(check.stdout).toMatch(/problem: linear: ENG has no label initiative:awaiting-outcome/u); + expect(check.stdout).not.toMatch(/has no state (?:label:)?initiative:awaiting-outcome/u); // The label is read through the source's single-label field, with no states. const calls = t.rpcCalls.filter((c) => c.method === "sourceValidate" && c.pluginId === "linear"); - expect(calls.some((c) => c.input.label === "goal:awaiting-outcome" && (c.input.states as string[]).length === 0)).toBe(true); + expect(calls.some((c) => c.input.label === "initiative:awaiting-outcome" && (c.input.states as string[]).length === 0)).toBe(true); }); it("checks a GitHub repo label phase key the same way", async () => { const t = await setup(); t.files[playbookPath("github-issues")] = withLabel(GITHUB_ISSUES, " status:in-progress: { stage: build, stuck: 2d }"); - t.setMissingLabel("github", "acme/web", ["goal:awaiting-outcome"]); + t.setMissingLabel("github", "acme/web", ["initiative:awaiting-outcome"]); const check = await t.harness.behavior.runCli(["check", "--project", "p1"]); expect(check.exitCode).toBe(1); - expect(check.stdout).toMatch(/problem: github: acme\/web has no label goal:awaiting-outcome/u); - expect(check.stdout).not.toMatch(/has no state (?:label:)?goal:awaiting-outcome/u); + expect(check.stdout).toMatch(/problem: github: acme\/web has no label initiative:awaiting-outcome/u); + expect(check.stdout).not.toMatch(/has no state (?:label:)?initiative:awaiting-outcome/u); }); it("is silent when the label exists, and existing playbooks are unchanged", async () => { @@ -3558,7 +3574,7 @@ describe("check on a `label:` phase key (BB-248)", () => { t.files[playbookPath("linear-tickets")] = withLabel(LINEAR_TICKETS, " In Progress: { stage: build, stuck: 2d }"); const check = await t.harness.behavior.runCli(["check", "--project", "p1"]); expect(check.exitCode).toBe(0); - expect(check.stdout).not.toMatch(/goal:awaiting-outcome/u); + expect(check.stdout).not.toMatch(/initiative:awaiting-outcome/u); }); }); @@ -4033,28 +4049,28 @@ describe("role-owned pull watches (BB-164)", () => { // issue's labels and title, before the kind's default. The first watch wins; // with none, adoption is unchanged. It is the mirror of the pull watches. describe("project-level ticket watches (BB-246)", () => { - const GOALS = LINEAR_TICKETS.replace("name: linear-tickets", "name: goals"); - const GITHUB_GOALS = GITHUB_ISSUES.replace("name: github-issues", "name: goals"); + const INITIATIVES = LINEAR_TICKETS.replace("name: linear-tickets", "name: initiatives"); + const GITHUB_INITIATIVES = GITHUB_ISSUES.replace("name: github-issues", "name: initiatives"); const project = (tickets: unknown) => JSON.stringify({ version: 1, linear: { teams: ["ENG"] }, tickets }); it("adopts a labelled, assigned Linear ticket matching a watch under its playbook, and records the watch", async () => { const t = await setup({ timing: { debounceMs: 1, nightlyStaggerMs: 0, configTtlMs: 0 } }); - t.files[PROJECT_FILE] = project([{ match: { labels: ["docs"], title: "docs: *" }, playbook: "goals" }]); - t.files[playbookPath("goals")] = GOALS; + t.files[PROJECT_FILE] = project([{ match: { labels: ["docs"], title: "docs: *" }, playbook: "initiatives" }]); + t.files[playbookPath("initiatives")] = INITIATIVES; t.entities.set("uuid-12", issue({ labels: ["bb-managed", "docs"], title: "Docs: rewrite" })); await t.ring("linear", "uuid-12"); const b = t.hooks.store.find("ENG-12", "p1")!; - expect(b).toMatchObject({ kind: "ticket", playbook: "goals", adoptedBy: "goals@ticket", endedAt: null }); + expect(b).toMatchObject({ kind: "ticket", playbook: "initiatives", adoptedBy: "initiatives@ticket", endedAt: null }); expect(b.threadId).not.toBeNull(); // The title glob matched ignoring case, and `list` names the watch. const list = await t.harness.behavior.runCli(["list", "--project", "p1"]); - expect(list.stdout).toMatch(/adopted by goals@ticket/u); + expect(list.stdout).toMatch(/adopted by initiatives@ticket/u); }); it("adopts a ticket matching no watch under the kind's default playbook, as before", async () => { const t = await setup({ timing: { debounceMs: 1, nightlyStaggerMs: 0, configTtlMs: 0 } }); - t.files[PROJECT_FILE] = project([{ match: { labels: ["docs"] }, playbook: "goals" }]); - t.files[playbookPath("goals")] = GOALS; + t.files[PROJECT_FILE] = project([{ match: { labels: ["docs"] }, playbook: "initiatives" }]); + t.files[playbookPath("initiatives")] = INITIATIVES; t.entities.set("uuid-12", issue({ labels: ["bb-managed"], title: "Fix login" })); await t.ring("linear", "uuid-12"); expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "linear-tickets", adoptedBy: null }); @@ -4063,19 +4079,19 @@ describe("project-level ticket watches (BB-246)", () => { it("takes the first matching watch, so order decides", async () => { const t = await setup({ timing: { debounceMs: 1, nightlyStaggerMs: 0, configTtlMs: 0 } }); t.files[PROJECT_FILE] = project([ - { match: { labels: ["docs"] }, playbook: "goals" }, + { match: { labels: ["docs"] }, playbook: "initiatives" }, { match: { title: "Docs: *" }, playbook: "linear-tickets" }, ]); - t.files[playbookPath("goals")] = GOALS; + t.files[playbookPath("initiatives")] = INITIATIVES; t.entities.set("uuid-12", issue({ labels: ["bb-managed", "docs"], title: "Docs: rewrite" })); await t.ring("linear", "uuid-12"); - expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "goals", adoptedBy: "goals@ticket" }); + expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "initiatives", adoptedBy: "initiatives@ticket" }); }); it("matches every named label ignoring case, and falls through when one is missing", async () => { const t = await setup({ timing: { debounceMs: 1, nightlyStaggerMs: 0, configTtlMs: 0 } }); - t.files[PROJECT_FILE] = project([{ match: { labels: ["Docs", "v2"] }, playbook: "goals" }]); - t.files[playbookPath("goals")] = GOALS; + t.files[PROJECT_FILE] = project([{ match: { labels: ["Docs", "v2"] }, playbook: "initiatives" }]); + t.files[playbookPath("initiatives")] = INITIATIVES; // Missing `v2`: no match, so the default. t.entities.set("uuid-12", issue({ labels: ["bb-managed", "DOCS"] })); await t.ring("linear", "uuid-12"); @@ -4083,17 +4099,17 @@ describe("project-level ticket watches (BB-246)", () => { // Both present, ignoring case: the watch. t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", labels: ["bb-managed", "docs", "V2"] })); await t.ring("linear", "uuid-13"); - expect(t.hooks.store.find("ENG-13", "p1")).toMatchObject({ playbook: "goals" }); + expect(t.hooks.store.find("ENG-13", "p1")).toMatchObject({ playbook: "initiatives" }); }); it("adopts a labelled, assigned GitHub issue matching a watch under its playbook", async () => { const t = await setup({ timing: { debounceMs: 1, nightlyStaggerMs: 0, configTtlMs: 0 } }); - t.files[PROJECT_FILE] = project([{ match: { labels: ["docs"] }, playbook: "goals" }]); + t.files[PROJECT_FILE] = project([{ match: { labels: ["docs"] }, playbook: "initiatives" }]); t.files[playbookPath("github-issues")] = GITHUB_ISSUES; - t.files[playbookPath("goals")] = GITHUB_GOALS; + t.files[playbookPath("initiatives")] = GITHUB_INITIATIVES; t.entities.set("acme/web#14", githubIssue({ id: "acme/web#14", key: "acme/web#14", labels: ["bb-managed", "status:todo", "docs"] })); await t.ring("github", "acme/web#14"); - expect(t.hooks.store.find("acme/web#14", "p1")).toMatchObject({ source: "github", playbook: "goals", adoptedBy: "goals@ticket" }); + expect(t.hooks.store.find("acme/web#14", "p1")).toMatchObject({ source: "github", playbook: "initiatives", adoptedBy: "initiatives@ticket" }); }); it("adopts nothing when the matched watch's playbook is missing or not a ticket playbook", async () => { @@ -4112,15 +4128,15 @@ describe("project-level ticket watches (BB-246)", () => { it("does not re-route an adopted binding when the watch's label changes", async () => { const t = await setup({ timing: { debounceMs: 1, nightlyStaggerMs: 0, configTtlMs: 0 } }); - t.files[PROJECT_FILE] = project([{ match: { labels: ["docs"] }, playbook: "goals" }]); - t.files[playbookPath("goals")] = GOALS; + t.files[PROJECT_FILE] = project([{ match: { labels: ["docs"] }, playbook: "initiatives" }]); + t.files[playbookPath("initiatives")] = INITIATIVES; t.entities.set("uuid-12", issue({ labels: ["bb-managed", "docs"] })); await t.ring("linear", "uuid-12"); - expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "goals" }); + expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "initiatives" }); // Removing the watch's label leaves the playbook alone; the label still holds it. t.entities.set("uuid-12", issue({ labels: ["bb-managed"] })); await t.ring("linear", "uuid-12"); - expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "goals", endedAt: null }); + expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "initiatives", endedAt: null }); // A ticket adopted under the default does not switch when the label arrives. t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", labels: ["bb-managed"] })); await t.ring("linear", "uuid-13"); @@ -4132,22 +4148,22 @@ describe("project-level ticket watches (BB-246)", () => { it("keeps an adopted ticket's playbook after its watch is removed, until the playbook file itself goes", async () => { const t = await setup({ timing: { debounceMs: 1, nightlyStaggerMs: 0, configTtlMs: 0 } }); - t.files[PROJECT_FILE] = project([{ match: { labels: ["docs"] }, playbook: "goals" }]); - t.files[playbookPath("goals")] = GOALS; + t.files[PROJECT_FILE] = project([{ match: { labels: ["docs"] }, playbook: "initiatives" }]); + t.files[playbookPath("initiatives")] = INITIATIVES; t.entities.set("uuid-12", issue({ labels: ["bb-managed", "docs"] })); await t.ring("linear", "uuid-12"); - expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "goals", adoptedBy: "goals@ticket" }); - // The watch is removed, but `goals.md` remains: the binding keeps running + expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "initiatives", adoptedBy: "initiatives@ticket" }); + // The watch is removed, but `initiatives.md` remains: the binding keeps running // under it, and `check` reports no problem for the removed watch. t.files[PROJECT_FILE] = project([]); t.hooks.forgetConfigs(); await t.ring("linear", "uuid-12"); - expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "goals", endedAt: null }); + expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ playbook: "initiatives", endedAt: null }); const check = await t.harness.behavior.runCli(["check", "--project", "p1"]); - expect(check.stdout).not.toMatch(/goals/u); + expect(check.stdout).not.toMatch(/initiatives/u); // With the playbook file gone too, and no last-good copy, it ends. - delete t.files[playbookPath("goals")]; - await t.bb.storage.kv.delete("good/p1/playbook/goals"); + delete t.files[playbookPath("initiatives")]; + await t.bb.storage.kv.delete("good/p1/playbook/initiatives"); t.hooks.forgetConfigs(); await t.ring("linear", "uuid-12"); expect(t.hooks.store.find("ENG-12", "p1")).toMatchObject({ endedAt: expect.any(Number), endReason: "unconfigured" }); @@ -4161,12 +4177,12 @@ describe("project-level ticket watches (BB-246)", () => { expect(check.stdout).toMatch(/tickets\[0\].*"gone".*does not exist/); expect(check.stdout).toMatch(/tickets\[1\].*"github-prs" is a pr playbook, not a ticket playbook/); // A project with a valid ticket watch names it and passes. - t.files[PROJECT_FILE] = project([{ playbook: "goals" }]); - t.files[playbookPath("goals")] = GOALS; + t.files[PROJECT_FILE] = project([{ playbook: "initiatives" }]); + t.files[playbookPath("initiatives")] = INITIATIVES; t.hooks.forgetConfigs(); const good = await t.harness.behavior.runCli(["check", "--project", "p1"]); expect(good.exitCode).toBe(0); - expect(good.stdout).toMatch(/tickets: goals@ticket/u); + expect(good.stdout).toMatch(/tickets: initiatives@ticket/u); }); }); @@ -6744,7 +6760,7 @@ describe("needs you items", () => { expect(t.sends.filter((s) => s.threadId === steward).at(-1)!.text).toMatch(/## 5\. What changed since your last turn[\s\S]*approved ENG-12's spec on the Stewards page: Looks good/u); }); - it("files approve-pr in the owner lane; Approve posts a review on a teammate's pull request and the merge item follows", async () => { + it("files approve-pr in the owner lane; Approve posts a review on a teammate's pull request and the plugin merges", async () => { const t = await withPull([marker]); const b = t.binding(); // The user's lane is filed on the page at once, with no project-steward @@ -6766,12 +6782,12 @@ describe("needs you items", () => { expect(t.githubReviews).toEqual([{ repo: "acme/web", number: 7, event: "APPROVE", body: "" }]); expect(t.githubComments).toEqual([]); expect(t.hooks.store.need(need.id)!.status).toBe("done"); - // The snapshot now shows the owner's approval, so the merge item is filed. + // The snapshot now shows the owner's approval, so the plugin merges it. t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); await t.flush(); expect(t.hooks.store.openNeeds(b.id).find((n) => n.kind === "approve-pr")).toBeUndefined(); - expect(t.hooks.store.openNeeds(b.id).find((n) => n.kind === "merge")).toBeDefined(); - expect((await board()).needs.find((n) => n.kind === "merge")).toMatchObject({ url: "https://github.com/acme/web/pull/7", entityUrl: "https://linear.app/acme/issue/ENG-12" }); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); + expect(t.githubMerges).toEqual([{ repo: "acme/web", number: 7, title: "Add login retry (#7)", body: "Retries login." }]); }); it("keeps the comment convention when the pull request is the signed-in account's own (BB-118)", async () => { @@ -6967,13 +6983,15 @@ describe("needs you items", () => { expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); }); - it("files the merge need for the owner's own pull request (BB-170)", async () => { + it("merges the owner's own pull request when its playbook permits merge (BB-170)", async () => { const t = await setup(); t.entities.set("acme/web#7", pull({ labels: ["bb-managed"], author: "jane", comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); await t.ring("github", "acme/web#7"); const b = t.hooks.store.find("acme/web#7")!; expect(b.kind).toBe("pr"); - expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(true); + // github-prs' `may` includes merge, so the plugin takes the step itself. + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); + expect(t.githubMerges).toHaveLength(1); }); it("files the merge need for a dependabot[bot] pull request (BB-170)", async () => { @@ -7128,31 +7146,148 @@ describe("needs you items", () => { expect(closed.resolution).not.toMatch(/not waiting for an owner approval/u); }); - it("files merge only when the gate is met and no worker runs, and the page action merges through gh", async () => { - const t = await withPull([marker, owner]); + it("merges a gate-met ticket binding itself and files no Merge item", async () => { + const t = await withPull([marker]); const b = t.binding(); - const need = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "merge")!; - expect(need).toMatchObject({ what: "Merge acme/web#7", filedBy: "plugin" }); - const res = await t.harness.callRpc("stewardsNeedAction", { needId: need.id, action: "merge" }, client); - expect(res).toMatchObject({ ok: true, message: expect.stringMatching(/Merged/u) }); + expect(t.githubMerges).toEqual([]); + // The owner approves: the next look merges and wakes the steward with the + // merge note, and files no Merge item. + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); expect(t.githubMerges).toHaveLength(1); expect(t.githubMerges[0]).toMatchObject({ repo: "acme/web", number: 7, title: "Add login retry (#7)", body: "Retries login." }); expect(t.githubComments.at(-1)!.body).toMatch(/Merged: owner-reviewed lane, reviewer approved aaaaaaa, checks green, approved by the owner/u); - expect(t.hooks.store.need(need.id)!.status).toBe("done"); await t.flush(); - expect(t.sends.filter((s) => s.threadId === t.steward).at(-1)!.text).toMatch(/What changed[\s\S]*merged from the Stewards page/u); + expect(t.sends.filter((s) => s.threadId === t.steward).some((s) => /What changed[\s\S]*merged by the plugin/u.test(s.text))).toBe(true); }); - it("refuses the merge when a worker is still running", async () => { - const t = await withPull([marker, owner]); + it("does not merge a gate-met stacked pull request; it files the Merge item for a person (BB-257)", async () => { + const t = await withPull([marker]); const b = t.binding(); - await t.created("thr_w1", t.steward, "ENG-12: Implement"); - const need = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "merge")!; - const res = await t.harness.callRpc("stewardsNeedAction", { needId: need.id, action: "merge" }, client); - expect(res).toMatchObject({ ok: false, message: expect.stringMatching(/Worker thr_w1 is mid-turn/u) }); + // The pull request's base is another pull request's branch, not the repo's + // default branch. A person or worker merges it into its parent; the plugin + // must not squash it into a branch that may already be merged and dead. + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "bb/bb-256-parent", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toEqual([]); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.filedBy === "plugin")).toBe(true); + }); + + it("merges a gate-met pull request once its base is the default branch again", async () => { + const t = await withPull([marker]); + const b = t.binding(); + // Stacked first: the plugin files the item. Retargeted to `main`: the next + // look merges and closes the item through the shared path. + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "bb/bb-256-parent", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toEqual([]); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { base: "main", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toHaveLength(1); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); + }); + + it("does not merge while a worker is still running", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t.entities.set("acme/web#7", pull({}, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + const steward = t.spawns[1]!.id; + // The worker is in flight when the owner approves, so the plugin holds the + // merge for a later look rather than racing the worker. + await t.created("thr_w1", steward, "ENG-12: Implement"); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + await t.flush(); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); expect(t.githubMerges).toEqual([]); }); + it("merges a dependabot pull request under a deps-prs playbook that permits merge", async () => { + const t = await setup(); + t.files[PROJECT_FILE] = JSON.stringify({ version: 1, linear: { teams: ["ENG"] } }); + // The updated `.bb` playbook adds `merge`; until it lands the shipped + // template omits it and the plugin keeps filing the Merge item. + t.files[playbookPath("deps-prs")] = DEPS_PRS.replace("may: [comment, request-review, escalate, spawn-worker]", "may: [comment, request-review, escalate, spawn-worker, merge]"); + t.entities.set("acme/web#9", pull({ id: "acme/web#9", key: "acme/web#9", url: "https://github.com/acme/web/pull/9", title: "deps: bump the npm group", author: "dependabot[bot]", labels: [] }, { head: "dependabot/npm/group", headAuthor: "dependabot[bot]" })); + await t.hooks.sweep(); + await t.flush(); + const b = t.hooks.store.find("acme/web#9")!; + expect(b).toMatchObject({ kind: "pr", playbook: "deps-prs" }); + const noReview = comment({ id: "r1", author: "jane", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); + t.entities.set("acme/web#9", pull({ id: "acme/web#9", key: "acme/web#9", url: "https://github.com/acme/web/pull/9", title: "deps: bump the npm group", author: "dependabot[bot]", labels: [], comments: [noReview] }, { head: "dependabot/npm/group", headAuthor: "dependabot[bot]", checks: { state: "success", failing: [] } })); + await t.ring("github", "acme/web#9"); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); + expect(t.githubMerges).toHaveLength(1); + }); + + it("records a refused merge once, does not retry the same gate, and merges after the head moves", async () => { + const t = await withPull([marker]); + const b = t.binding(); + t.setMergePullError("Pull request is not mergeable: the merge conflict must be resolved"); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + // One attempt, noted on the binding and raised once to the steward. + expect(t.githubMerges).toEqual([]); + const stuck = t.hooks.store.openEscalations(b.id).filter((x) => x.kind === "stuck"); + expect(stuck).toHaveLength(1); + expect(stuck[0]!.headSha).toBe("aaaaaaa1"); + expect(t.sends.filter((s) => s.threadId === t.steward).some((s) => /could not merge acme\/web#7/u.test(s.text))).toBe(true); + // A second look at the same gate does not retry or re-raise. + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toEqual([]); + expect(t.hooks.store.openEscalations(b.id).filter((x) => x.kind === "stuck")).toHaveLength(1); + // A new head is a new attempt; with the refusal cleared, it merges. + t.setMergePullError(null); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] }, headSha: "bbbbbbb2" })); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toHaveLength(1); + }); + + it("does not merge while stewards are paused; it files the plugin's Merge item instead", async () => { + const t = await withPull([marker]); + const b = t.binding(); + await (t.hooks.settings as unknown as { experimental_set(values: Record): Promise }).experimental_set({ paused: true }); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toEqual([]); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.filedBy === "plugin")).toBe(true); + }); + + it("waits for the next look when the head moves between the look and the merge", async () => { + const t = await withPull([marker]); + const b = t.binding(); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); + // A push lands after the gate is judged and before the merge PUT: GitHub + // refuses with 409, and the plugin waits for the next look rather than + // raising a stuck refusal (BB-257). + t.setMoveHeadOnMerge(true); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toEqual([]); + expect(t.hooks.store.openEscalations(b.id).some((x) => x.kind === "stuck")).toBe(false); + // The head is stable on the next look, so it merges. + t.setMoveHeadOnMerge(false); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toHaveLength(1); + }); + + it("does not read a 409 in the pull request's URL path as a head-moved refusal", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t.entities.set("acme/web#7", pull({ comments: [marker] }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + // A conflict refusal whose URL path happens to contain 409, but whose + // status is 405: it must be recorded and raised, not silently retried. + t.setMergePullError("PUT /repos/acme/web/pulls/409/merge failed: 405 Base branch was modified. Review and try the merge again."); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toEqual([]); + expect(t.hooks.store.openEscalations(b.id).some((x) => x.kind === "stuck")).toBe(true); + }); + it("records a project-steward approval bound to the head sha; ticket and worker threads are refused (BB-30)", async () => { const t = await withPull([marker]); const b = t.binding(); @@ -7644,7 +7779,12 @@ describe("needs you items", () => { await t.tool("steward_update", { binding: "ENG-12", forward: esc.id }, t.project); const first = await board(); expect(first.needs).toEqual([expect.objectContaining({ kind: "approve-pr", key: "ENG-12", url: "https://github.com/acme/web/pull/7", actionable: true, why: null })]); - // Once the owner approves, a merge item appears; a running worker makes it not actionable. + // A steward-filed Merge item (a refused merge) is the owner's to press; a + // running worker makes it not actionable, a finished one does not. + const b = t.binding(); + t.hooks.store.fileNeed({ bindingId: b.id, kind: "merge", url: "https://github.com/acme/web/pull/7", what: "Merge acme/web#7", how: null, filedBy: "steward" }); + // The gate is met on the next look; the steward's own item blocks the + // plugin's merge, so the item is actionable. t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); await t.ring("linear", "uuid-12"); expect((await board()).needs.find((n) => n.kind === "merge")).toMatchObject({ actionable: true, why: null }); @@ -7687,16 +7827,22 @@ describe("needs you items", () => { }); it("a finished worker does not block a steward-filed merge item; a running one does (BB-175)", async () => { - const t = await withPull([marker, owner]); - const b = t.binding(); - // The plugin filed its own item; make it the steward's, as it is when a - // worker could not merge and handed the item to a person. - t.hooks.store.closeNeedByKey(b.id, "merge", "https://github.com/acme/web/pull/7", "the worker handed it to the steward"); + const t = await setup(); + t.entities.set("uuid-12", issue({ linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); + t.entities.set("acme/web#7", pull({ comments: [marker] }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12")!; + const steward = t.spawns[1]!.id; + // A worker could not merge and handed the item to a person; the plugin + // leaves it alone. The owner then approves, which would otherwise merge. t.hooks.store.fileNeed({ bindingId: b.id, kind: "merge", url: "https://github.com/acme/web/pull/7", what: "Merge acme/web#7", how: null, filedBy: "steward" }); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); + // The gate is met, but the steward's own item blocks the plugin's merge. + await t.ring("linear", "uuid-12"); const board = async () => ((await t.harness.callRpc("stewardsBoard", { projectId: "p1" })) as { board: { needs: Array<{ kind: string; actionable: boolean; why: string | null }> } }).board; // A running worker's turn can race a push: the item is not actionable and // the shared merge path refuses. - await t.created("thr_w1", t.steward, "ENG-12: Implement"); + await t.created("thr_w1", steward, "ENG-12: Implement"); expect((await board()).needs.find((n) => n.kind === "merge")).toMatchObject({ actionable: false }); const refused = await t.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"]); expect(refused.exitCode).toBe(1); @@ -7712,8 +7858,12 @@ describe("needs you items", () => { }); it("the not-actionable reason names the running worker (BB-175)", async () => { - const t = await withPull([marker, owner]); + const t = await withPull([marker]); const b = t.binding(); + t.hooks.store.fileNeed({ bindingId: b.id, kind: "merge", url: "https://github.com/acme/web/pull/7", what: "Merge acme/web#7", how: null, filedBy: "steward" }); + // The gate is met, but the steward's own item blocks the plugin's merge. + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); await t.created("thr_w1", t.steward, "ENG-12: Implement"); const board = async () => ((await t.harness.callRpc("stewardsBoard", { projectId: "p1" })) as { board: { needs: Array<{ kind: string; actionable: boolean; why: string | null }> } }).board; expect((await board()).needs.find((n) => n.kind === "merge")).toMatchObject({ actionable: false, why: "worker thr_w1 is mid-turn" }); @@ -7782,12 +7932,13 @@ describe("needs you items", () => { expect(t.hooks.store.openNeeds(b().id).some((n) => n.kind === "approve-spec")).toBe(false); expect(t.hooks.store.find("ENG-12")!.ready.approval!.specHash).not.toBe(firstHash); - // The user approves the pull request on the page; the merge item follows. + // The user approves the pull request on the page; the plugin merges it. const pr = t.hooks.store.openNeeds(b().id).find((n) => n.kind === "approve-pr")!; await t.harness.callRpc("stewardsNeedAction", { needId: pr.id, action: "approve" }, client); t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); await t.flush(); - expect(kinds()).toEqual(["configure", "configure", "configure", "merge", "provide-secret"]); + expect(kinds()).toEqual(["configure", "configure", "configure", "provide-secret"]); + expect(t.githubMerges).toHaveLength(1); // The user does the three external steps and provides the secret. for (const n of t.hooks.store.openNeeds(b().id).filter((x) => x.kind === "configure" || x.kind === "provide-secret")) { @@ -7796,10 +7947,9 @@ describe("needs you items", () => { } await t.flush(); const all = t.hooks.store.needs(b().id, true); - expect(all.map((n) => n.kind).sort()).toEqual(["approve-pr", "approve-spec", "configure", "configure", "configure", "merge", "provide-secret"]); + expect(all.map((n) => n.kind).sort()).toEqual(["approve-pr", "approve-spec", "configure", "configure", "configure", "provide-secret"]); expect(all.filter((n) => n.status === "done").map((n) => n.kind).sort()).toEqual(["approve-pr", "approve-spec", "configure", "configure", "configure", "provide-secret"]); - expect(all.find((n) => n.kind === "merge")!.status).toBe("open"); - expect(t.hooks.store.openNeeds(b().id).map((n) => n.kind)).toEqual(["merge"]); + expect(t.hooks.store.openNeeds(b().id)).toEqual([]); expect(project).toBeDefined(); }); @@ -8070,26 +8220,26 @@ describe("needs you items", () => { }); it("does not re-ask the coverage question when a closed item is refiled for the same escalation", async () => { - const t = await withPull([marker]); + const t = await withPull([]); const b = t.binding(); t.advance(1000); const esc = t.hooks.store.escalate({ bindingId: b.id, kind: "decision", question: "Include SSO?", meanwhile: "Wait.", route: "user", recommendation: null, projectId: "p1" }); t.advance(1000); - // The owner approves and checks are green: the merge item is filed, and the - // pair is asked once. - t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); + // The reviewer approves: the owner's approve-pr item is filed, and the pair + // is asked once. + t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "success", failing: [] } })); await t.ring("github", "acme/web#7"); const asked = () => t.sends.filter((s) => s.threadId === t.project && /a gate item was filed on ENG-12/u.test(s.text)); expect(asked()).toHaveLength(1); - // Checks go red: the merge item closes. Green again: it is refiled with a + // The reviewer round goes away: the item closes. Back: it is refiled with a // new id, but the pair was already asked for this escalation. t.advance(1000); - t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "failure", failing: ["test"] } })); + t.entities.set("acme/web#7", pull({}, { checks: { state: "success", failing: [] } })); await t.ring("github", "acme/web#7"); t.advance(1000); - t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); + t.entities.set("acme/web#7", pull({ comments: [marker] }, { checks: { state: "success", failing: [] } })); await t.ring("github", "acme/web#7"); - expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(true); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "approve-pr")).toBe(true); expect(asked()).toHaveLength(1); expect(t.hooks.store.escalation(esc.id)!.status).toBe("open"); }); @@ -8142,7 +8292,10 @@ describe("needs you items", () => { t.entities.set("acme/web#8", pull({ id: "acme/web#8", key: "acme/web#8", url: "https://github.com/acme/web/pull/8", title: "Fix login", comments: [marker, owner] }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] } })); await t.ring("linear", "uuid-12"); const b = t.hooks.store.find("ENG-12")!; - expect(t.hooks.store.openNeeds(b.id).filter((n) => n.kind === "merge").map((n) => n.url)).toEqual(["https://github.com/acme/web/pull/8"]); + // #8 belongs to ENG-12 and its gate is met, so the plugin merges it; #7 is + // only mentioned, so it files nothing and is not merged. + expect(t.githubMerges.map((m) => `${m.repo}#${m.number}`)).toEqual(["acme/web#8"]); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "approve-pr" && n.url === "https://github.com/acme/web/pull/7")).toBe(false); expect(t.hooks.store.openEscalations(b.id).some((x) => x.kind === "approval" && x.url === "https://github.com/acme/web/pull/7")).toBe(false); }); @@ -8177,7 +8330,9 @@ describe("needs you items", () => { await t.ring("linear", "uuid-13"); const a = t.hooks.store.find("ENG-12")!; const b = t.hooks.store.find("ENG-13")!; - expect(t.hooks.store.openNeeds(a.id).some((n) => n.kind === "merge" && n.url === "https://github.com/acme/web/pull/7")).toBe(true); + // ENG-12 owns #7 and merges it; ENG-13 only cross-references it. + expect(t.githubMerges.map((m) => `${m.repo}#${m.number}`)).toEqual(["acme/web#7"]); + expect(t.hooks.store.openNeeds(a.id).some((n) => n.kind === "merge")).toBe(false); expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "approve-pr")).toBe(false); expect(t.hooks.store.openEscalations(b.id).some((x) => x.kind === "approval")).toBe(false); @@ -8194,8 +8349,7 @@ describe("needs you items", () => { await t.created("thr_w1", steward, "ENG-12: Implement", { branchName: "retry" }); t.hooks.store.setWorker("thr_w1", "stopped", null); await t.ring("linear", "uuid-12"); - const b = t.hooks.store.find("ENG-12")!; - expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.url === "https://github.com/acme/web/pull/7")).toBe(true); + expect(t.githubMerges.map((m) => `${m.repo}#${m.number}`)).toEqual(["acme/web#7"]); }); it("BB-239: a worker's final message that names the pull request owns it on a foreign branch", async () => { @@ -8207,8 +8361,7 @@ describe("needs you items", () => { await t.created("thr_w1", steward, "ENG-12: Implement", { branchName: "retry" }); t.hooks.store.setWorker("thr_w1", "stopped", "Opened https://github.com/acme/web/pull/7 for review."); await t.ring("linear", "uuid-12"); - const b = t.hooks.store.find("ENG-12")!; - expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.url === "https://github.com/acme/web/pull/7")).toBe(true); + expect(t.githubMerges.map((m) => `${m.repo}#${m.number}`)).toEqual(["acme/web#7"]); }); it("BB-239: a title that names the ticket owns the pull request on a foreign branch", async () => { @@ -8216,8 +8369,7 @@ describe("needs you items", () => { t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started", linkedPulls: [{ key: "acme/web#7", url: "https://github.com/acme/web/pull/7" }] })); t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", title: "Fix login (ENG-12)", comments: [marker, owner] }, { head: "feature/other", checks: { state: "success", failing: [] } })); await t.ring("linear", "uuid-12"); - const b = t.hooks.store.find("ENG-12")!; - expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.url === "https://github.com/acme/web/pull/7")).toBe(true); + expect(t.githubMerges.map((m) => `${m.repo}#${m.number}`)).toEqual(["acme/web#7"]); }); it("BB-239: a GitHub issue's title number owns only a pull request in the issue's repo", async () => { @@ -8230,8 +8382,7 @@ describe("needs you items", () => { t.entities.set("acme/web#7", pull({ id: "acme/web#7", key: "acme/web#7", url: "https://github.com/acme/web/pull/7", unit: "acme/web", title: "Fix login (#14)", comments: [marker, owner] }, { head: "feature/other", checks: { state: "success", failing: [] } })); t.entities.set("acme/other#14", pull({ id: "acme/other#14", key: "acme/other#14", url: "https://github.com/acme/other/pull/14", unit: "acme/other", title: "Fix login (#14)", comments: [marker, owner] }, { head: "feature/other", checks: { state: "success", failing: [] } })); await t.ring("github", "acme/web#14"); - const b = t.hooks.store.find("acme/web#14", "p1")!; - expect(t.hooks.store.openNeeds(b.id).filter((n) => n.kind === "merge").map((n) => n.url)).toEqual(["https://github.com/acme/web/pull/7"]); + expect(t.githubMerges.map((m) => `${m.repo}#${m.number}`)).toEqual(["acme/web#7"]); }); // BB-256: a steward can hold its own merge behind another binding. While the @@ -8264,16 +8415,21 @@ describe("needs you items", () => { }); it("files no plugin Merge item while it stands, closes an open one, and leaves a steward-filed one alone", async () => { - const t = await withPull([marker, owner]); + const t = await withPull([marker]); const b = t.binding(); - const pluginNeed = t.hooks.store.openNeeds(b.id).find((n) => n.kind === "merge")!; - expect(pluginNeed.filedBy).toBe("plugin"); + // A plugin-filed Merge item from an earlier look, and the gate met. + const pluginNeed = t.hooks.store.fileNeed({ bindingId: b.id, kind: "merge", url: "https://github.com/acme/web/pull/7", what: "Merge acme/web#7", how: null, filedBy: "plugin" }); + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); t.entities.set("uuid-13", issue({ id: "uuid-13", key: "ENG-13", title: "Blocker" })); await t.ring("linear", "uuid-13"); const report = await t.tool("steward_report", waitReport("ENG-13 to be Done", ["ENG-13"]), t.steward); expect(report.error, report.text).toBe(false); expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual(["ENG-13"]); expect(t.hooks.store.need(pluginNeed.id)).toMatchObject({ status: "done", resolution: "held behind ENG-13" }); + // The hold stands with the gate met: no merge and no plugin item. + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toEqual([]); + expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.filedBy === "plugin")).toBe(false); // The row shows as held, not "needs you", with the steward's wait text. const sidebar = (await t.harness.callRpc("stewardsSidebar", { projectId: "p1" })) as { bindings: Array<{ key: string; needsUser: boolean; hold: string | null; holdBehind: string[] }> }; expect(sidebar.bindings.find((x) => x.key === "ENG-12")).toMatchObject({ needsUser: false, hold: "ENG-13 to be Done", holdBehind: ["ENG-13"] }); @@ -8289,14 +8445,18 @@ describe("needs you items", () => { expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.filedBy === "plugin")).toBe(false); }); - it("lifts when the target merges, notes it, wakes the steward, and files the Merge item on the next look", async () => { - const t = await withPull([marker, owner]); + it("lifts when the target merges, notes it, wakes the steward, and merges on the next look", async () => { + const t = await withPull([marker]); const b = t.binding(); blockedPull(t); await t.ring("github", "acme/web#8"); expect(t.hooks.store.find("acme/web#8")!.kind).toBe("pr"); await t.tool("steward_report", waitReport("acme/web#8", ["acme/web#8"]), t.steward); expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual(["acme/web#8"]); + // The gate is met, but the hold stands: no merge. + t.entities.set("acme/web#7", pull({ comments: [marker, owner] }, { checks: { state: "success", failing: [] } })); + await t.ring("linear", "uuid-12"); + expect(t.githubMerges).toEqual([]); expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(false); const wakes = t.sends.filter((s) => s.threadId === t.steward).length; // The target merges: the hold clears and the steward is woken with the note. @@ -8304,9 +8464,10 @@ describe("needs you items", () => { await t.ring("github", "acme/web#8"); expect(t.hooks.store.find("ENG-12")!.mergeBehind).toEqual([]); expect(t.sends.filter((s) => s.threadId === t.steward).length).toBeGreaterThan(wakes); - expect(t.sends.filter((s) => s.threadId === t.steward).at(-1)!.text).toMatch(/Merge hold lifted: acme\/web#8, which it waited behind, reached merged\./u); - // The next look files the Merge item again, so a stuck loop still surfaces. - expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge" && n.filedBy === "plugin")).toBe(true); + expect(t.sends.filter((s) => s.threadId === t.steward).some((s) => /Merge hold lifted: acme\/web#8, which it waited behind, reached merged\./u.test(s.text))).toBe(true); + // The next look merges the pull request, so a stuck loop still surfaces. + await t.ring("linear", "uuid-12"); + expect(t.githubMerges.map((m) => `${m.repo}#${m.number}`)).toEqual(["acme/web#7"]); }); }); }); @@ -12781,7 +12942,7 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { const reviewMarkerApprover = (lane: string, approver: string, id = "m1") => comment({ id, author: "trotterdylan", body: ``, signedBy: "thr_reviewer", createdAt: "2026-10-14T16:00:00Z" }); /** A bound ticket with one linked pull request, observed. */ - async function withPull(comments: ReturnType[], over: { repo?: string; number?: number; pullOver?: Record; entityOver?: Record; files?: string[]; project?: Record } = {}) { + async function withPull(comments: ReturnType[], over: { repo?: string; number?: number; pullOver?: Record; entityOver?: Record; files?: string[]; project?: Record; noReconcileGate?: boolean } = {}) { const repo = over.repo ?? "acme/web"; const number = over.number ?? 7; const key = `${repo}#${number}`; @@ -12790,9 +12951,14 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { t.entities.set("uuid-12", issue({ linkedPulls: [{ key, url: `https://github.com/${repo}/pull/${number}` }] })); // The worker branch convention names the ticket, so the linked pull // belongs to it rather than merely mentioning it (BB-239). - t.entities.set(key, pull({ id: key, key, url: `https://github.com/${repo}/pull/${number}`, unit: repo, comments, ...over.entityOver }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] }, ...over.pullOver })); + const buildPull = (cs: ReturnType[]) => pull({ id: key, key, url: `https://github.com/${repo}/pull/${number}`, unit: repo, comments: cs, ...over.entityOver }, { head: "bb/eng-12-retry", checks: { state: "success", failing: [] }, ...over.pullOver }); + // A test of the CLI or the page's own merge path needs a gate-met pull + // request the plugin has not already merged (BB-257): it rings with the + // gate unmet, then sets the marker without a reconcile. + t.entities.set(key, buildPull(over.noReconcileGate === true ? [] : comments)); if (over.files !== undefined) t.githubFiles.set(key, over.files); await t.ring("linear", "uuid-12"); + if (over.noReconcileGate === true) t.entities.set(key, buildPull(comments)); const [project, steward] = t.spawns.map((x) => x.id) as [string, string]; return { ...t, project, steward, key, binding: () => t.hooks.store.find("ENG-12")! }; } @@ -12911,11 +13077,10 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { }); it("merges through --project from a thread in another project (BB-214)", async () => { - const t = await withPull([reviewMarker("no-review")]); + const t = await withPull([reviewMarker("no-review")], { noReconcileGate: true }); const own = t.hooks.store.create({ projectId: "p2", source: "linear", entityId: "uuid-20", entityKey: "ENG-20", url: null, title: "Other", kind: "ticket", playbook: "linear-tickets", playbookVersion: "v1", parentBindingId: null, phase: "Todo", stage: "spec" }); t.hooks.store.patch(own.id, { threadId: "thr_p2" }); const b = t.binding(); - expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(true); const merged = await t.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"], { threadId: "thr_p2", projectId: "p2" }); expect(merged.exitCode).toBe(0); expect(t.githubMerges).toEqual([{ repo: "acme/web", number: 7, title: "Add login retry (#7)", body: "Retries login." }]); @@ -13041,16 +13206,15 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { expect(refused.stdout).toMatch(/The gate is not met: no reviewer round yet/u); expect(unmet.githubMerges).toEqual([]); - const busy = await withPull([reviewMarker("no-review")]); + const busy = await withPull([reviewMarker("no-review")], { noReconcileGate: true }); await busy.created("thr_w1", busy.steward, "ENG-12: Implement"); const running = await busy.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"]); expect(running.exitCode).toBe(1); expect(running.stdout).toMatch(/Worker thr_w1 is mid-turn/u); expect(busy.githubMerges).toEqual([]); - const t = await withPull([reviewMarker("no-review")]); + const t = await withPull([reviewMarker("no-review")], { noReconcileGate: true }); const b = t.binding(); - expect(t.hooks.store.openNeeds(b.id).some((n) => n.kind === "merge")).toBe(true); const merged = await t.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"]); expect(merged.exitCode).toBe(0); expect(merged.stdout).toMatch(/Merged: no-review lane, reviewer approved aaaaaaa, checks green/u); @@ -13064,7 +13228,7 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { }); it("lets the owning worker merge through the CLI while it is still in flight (BB-134)", async () => { - const t = await withPull([reviewMarker("no-review")]); + const t = await withPull([reviewMarker("no-review")], { noReconcileGate: true }); await t.created("thr_w1", t.steward, "ENG-12: Implement"); const merged = await t.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"], { threadId: "thr_w1", projectId: "p1" }); expect(merged.exitCode).toBe(0); @@ -13073,7 +13237,7 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { it("dispatches the configured workflow once after a merge, through the CLI and the page, and says so (BB-216)", async () => { const project = { version: 1, linear: { teams: ["ENG"] }, mergeDispatch: [{ repo: "acme/web", workflow: "bb-server.yaml", workflowRepo: "bitcomplete/bb-gate", ref: "main", inputs: { only_if_moved: "true" } }] }; - const t = await withPull([reviewMarker("no-review")], { project }); + const t = await withPull([reviewMarker("no-review")], { project, noReconcileGate: true }); const merged = await t.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"]); expect(merged.exitCode).toBe(0); expect(t.githubDispatches).toEqual([{ repo: "bitcomplete/bb-gate", workflow: "bb-server.yaml", ref: "main", inputs: { only_if_moved: "true" } }]); @@ -13081,8 +13245,9 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { expect(t.githubComments.at(-1)!.body).toMatch(/dispatched bb-server\.yaml on bitcomplete\/bb-gate@main/u); // The Stewards page's Merge item takes the same shared path. - const page = await withPull([reviewMarker("no-review")], { project }); + const page = await withPull([reviewMarker("no-review")], { project, noReconcileGate: true }); const b = page.binding(); + page.hooks.store.fileNeed({ bindingId: b.id, kind: "merge", url: "https://github.com/acme/web/pull/7", what: "Merge acme/web#7", how: null, filedBy: "plugin" }); const need = page.hooks.store.openNeeds(b.id).find((n) => n.kind === "merge")!; const res = await page.harness.callRpc("stewardsNeedAction", { needId: need.id, action: "merge" }, { experimental_caller: { kind: "client" } }); expect(res).toMatchObject({ ok: true }); @@ -13091,7 +13256,7 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { it("reads the ref from the workflow repo's default branch when the entry names none (BB-216)", async () => { const project = { version: 1, linear: { teams: ["ENG"] }, mergeDispatch: [{ repo: "acme/web", workflow: "build.yaml", workflowRepo: "acme/infra", inputs: { only_if_moved: "true" } }] }; - const t = await withPull([reviewMarker("no-review")], { project }); + const t = await withPull([reviewMarker("no-review")], { project, noReconcileGate: true }); t.githubDefaultBranches.set("acme/infra", "trunk"); const merged = await t.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"]); expect(merged.exitCode).toBe(0); @@ -13099,7 +13264,7 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { }); it("dispatches nothing when the project configures no mergeDispatch, so the merge path is unchanged (BB-216)", async () => { - const t = await withPull([reviewMarker("no-review")]); + const t = await withPull([reviewMarker("no-review")], { noReconcileGate: true }); const merged = await t.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"]); expect(merged.exitCode).toBe(0); expect(t.githubDispatches).toEqual([]); @@ -13108,7 +13273,7 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { it("reports a failed dispatch but still merges (BB-216)", async () => { const project = { version: 1, linear: { teams: ["ENG"] }, mergeDispatch: [{ repo: "acme/web", workflow: "bb-server.yaml", workflowRepo: "bitcomplete/bb-gate", ref: "main", inputs: { only_if_moved: "true" } }] }; - const t = await withPull([reviewMarker("no-review")], { project }); + const t = await withPull([reviewMarker("no-review")], { project, noReconcileGate: true }); t.setMergeDispatchError("workflow dispatch refused: 403"); const merged = await t.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"]); expect(merged.exitCode).toBe(0); @@ -13121,7 +13286,7 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { it("carries the pull request's title and body into the squash merge, and falls back to the key when they cannot be read (BB-193)", async () => { // The happy path: GitHub's own squash subject, with the PR body as the // message, and no "Merged:" summary in the commit. - const t = await withPull([reviewMarker("no-review")]); + const t = await withPull([reviewMarker("no-review")], { noReconcileGate: true }); const merged = await t.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"]); expect(merged.exitCode).toBe(0); expect(t.githubMerges).toEqual([{ repo: "acme/web", number: 7, title: "Add login retry (#7)", body: "Retries login." }]); @@ -13129,14 +13294,14 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { // A read that fails falls back to the old placeholder rather than refusing // a merge whose gate is met. - const failed = await withPull([reviewMarker("no-review")]); + const failed = await withPull([reviewMarker("no-review")], { noReconcileGate: true }); failed.setPullDetailsError("GitHub rate limited the read"); const failedMerge = await failed.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"]); expect(failedMerge.exitCode).toBe(0); expect(failed.githubMerges).toEqual([{ repo: "acme/web", number: 7, title: "Merge acme/web#7", body: "Merged: no-review lane, reviewer approved aaaaaaa, checks green." }]); // A pull request GitHub reports with no title falls back the same way. - const untitled = await withPull([reviewMarker("no-review")], { entityOver: { title: null } }); + const untitled = await withPull([reviewMarker("no-review")], { entityOver: { title: null }, noReconcileGate: true }); const untitledMerge = await untitled.harness.behavior.runCli(["merge", "acme/web#7", "--project", "p1"]); expect(untitledMerge.exitCode).toBe(0); expect(untitled.githubMerges).toEqual([{ repo: "acme/web", number: 7, title: "Merge acme/web#7", body: "Merged: no-review lane, reviewer approved aaaaaaa, checks green." }]); @@ -13157,7 +13322,7 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { }); it("carries the restart note only when one guidance paragraph names the repo, says restart and makes an every-merge claim", async () => { - const withNote = await withPull([reviewMarker("no-review")], { repo: "bitcomplete/bb-plugins" }); + const withNote = await withPull([reviewMarker("no-review")], { repo: "bitcomplete/bb-plugins", noReconcileGate: true }); // The real `.bb/AGENTS.md` shape ("Who merges"): all three in one paragraph. withNote.files["AGENTS.md"] = "The lane decides who approves, not what ships. **Any merge to `bb-plugins` `main`, docs included, moves the pin**, builds a new `bb-server` image and stages a restart for every developer.\n"; const merged = await withNote.harness.behavior.runCli(["merge", "bitcomplete/bb-plugins#7", "--project", "p1"]); @@ -13166,7 +13331,7 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { // A devbox-shaped paragraph names the repo and says "restart" but makes no // every-merge claim, so no note: the false positive the reviewer found. - const devbox = await withPull([reviewMarker("no-review")], { repo: "bitcomplete/devbox" }); + const devbox = await withPull([reviewMarker("no-review")], { repo: "bitcomplete/devbox", noReconcileGate: true }); devbox.files["AGENTS.md"] = "## Change classification\n\nA change to `devbox/host/**` is production infrastructure. A merge rebuilds the `bb-server` image and restarts every developer's server.\n"; const devboxMerged = await devbox.harness.behavior.runCli(["merge", "bitcomplete/devbox#7", "--project", "p1"]); expect(devboxMerged.exitCode).toBe(0); @@ -13174,7 +13339,7 @@ describe("the reviewer role and the gate and merge commands (BB-133)", () => { // The repo named in one paragraph and "restart" in another, in the same // section, is not the project saying a merge to that repo restarts servers. - const split = await withPull([reviewMarker("no-review")], { repo: "bitcomplete/bb-gate" }); + const split = await withPull([reviewMarker("no-review")], { repo: "bitcomplete/bb-gate", noReconcileGate: true }); split.files["AGENTS.md"] = "## Shipping a plugin change\n\nLanding on `bb-gate` main is not instant; the pin is rewritten.\n\nEvery developer's server will restart when a staged image lands.\n"; const splitMerged = await split.harness.behavior.runCli(["merge", "bitcomplete/bb-gate#7", "--project", "p1"]); expect(splitMerged.exitCode).toBe(0); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 5ed7ab30..bece2646 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -127,7 +127,7 @@ import { advanceStall, hasLiveWakeSource, parseUntil, type WakeSourceInput } fro import { PROJECT_CHANGED } from "./channels.js"; import { LINEAR_TICKETS, PLAYBOOK_TEMPLATES, projectFileTemplate } from "./templates.js"; import type { DeploymentTarget } from "./config.js"; -import { PROJECT_STEWARD_INTRO, choicesNote, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerFinishNote, workerQuestion, workerReportedError, workerWaiting, workflowRunLine, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; +import { PROJECT_STEWARD_INTRO, bindingMayMerge, choicesNote, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatSentryWake, formatSessionWake, formatWake, spawnCommand, workerFinishNote, workerQuestion, workerReportedError, workerWaiting, workflowRunLine, type DigestRecords, type PendingRequest, type WakeReason, type WorkerQuestion } from "./wake.js"; import { KNOWN_PLAYBOOKS, buildSurvey, formatSurvey, surveyWantedPaths, type Available, type SurveyBb, type SurveyLinear, type SurveyRepoInput, type SurveyReport } from "./survey.js"; export { MULTI_REPO_ENVIRONMENT_PROVIDER_ID, MULTI_REPO_PLUGIN_ID }; @@ -4001,7 +4001,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P if (b.scheduleAsked.length > 0) clear.scheduleAsked = []; if (Object.keys(clear).length > 0) b = store.patch(b.id, clear); } - const approvalEvents = await syncNeeds(b, observed, playbook, workerInFlight); + const approvalEvents = await syncNeeds(b, observed, playbook, workerInFlight, changes); // BB-203: write the status the plugin observed itself, without a steward // turn, before the wake, so the page and sidebar are current within one // refetch. Checks fold into the phrase; approved, merged and deployed @@ -6804,7 +6804,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P * every look, so the page only offers a button while it is true. The * `approve-pr` half lives in approvals.ts (BB-153). */ - async function syncNeeds(b: Binding, observed: Observed, playbook: Playbook, workerInFlight: boolean): Promise { + async function syncNeeds(b: Binding, observed: Observed, playbook: Playbook, workerInFlight: boolean, changes: Change[] = []): Promise { // BB-203: an `approve-pr` item this call closes because an approval is // present is a mechanical status event. The page and project-steward // paths write it at once; this catches an approval observed on GitHub. @@ -6888,16 +6888,59 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P const keys = mergeHoldKeys(b); store.closeNeed(open.id, `held behind ${(keys.length > 0 ? keys : b.mergeBehind).join(", ")}`); } + } else if (store.openNeeds(b.id).some((n) => n.kind === "merge" && n.url === url && n.filedBy !== "plugin")) { + // A steward-filed Merge item is a hand-off to a person (a worker + // whose permission system refused the merge, or a refused plugin + // merge): leave it alone and do not merge over it (BB-170/BB-257). } else if (!workerInFlight) { - store.fileNeed({ - bindingId: b.id, - kind: "merge", - url, - what: `Merge ${pull.key}`, - how: `The lane gate is met${g.lane === null ? "" : ` (${g.lane})`}. Merge squash-merges through the server's gh login and posts the merge comment.`, - data: { sha: g.headSha }, - filedBy: "plugin", - }); + const ref = parsePullRef(pull.url ?? pull.key) ?? parsePullRef(url); + // Pause stewards is the kill switch: while it is on, the plugin + // files the item a person can press but never merges (BB-257). + const paused = (await settings.get()).paused; + // BB-257: only the repository's default branch. A stacked pull + // request's base is another pull request's branch, which may + // already be merged and left dead; the plugin must not squash-merge + // into it (that is how #290/#291/#293 were stranded). A stacked + // pull request keeps the plugin-filed Merge item and a person or + // worker merges it into its parent. + if (bindingMayMerge(b, playbook) && ref !== null && !paused && (await pullBaseIsDefault(ref, pull))) { + // BB-257: the plugin takes the step the Merge item used to ask a + // person for. A refusal for this exact gate is recorded on the + // binding and not retried until the head or a gate input changes. + if (mergeRefusalFor(b, g) === null) { + const result = await mergePullRequest(b, ref, pull, "by the plugin"); + if (result.ok) { + // The note goes into this look's changes as well as the + // binding, so the wake that clears `pending` still carries + // it; a merge found by the next look reads the same as a + // worker's merge (BB-257). + const note = `${pull.key} was merged by the plugin. ${result.summary}`; + store.note(b.id, note); + changes.push({ text: note, actionable: true }); + scheduleReconcile(b.id); + } else if (isHeadMovedRefusal(result.message)) { + // A push landed between the look and the merge. GitHub + // refused it with 409; the next look judges the new head. + bb.log.warn(`stewards: plugin merge of ${pull.key} raced a push; waiting for the next look`); + } else if (result.message.startsWith("GitHub refused the merge:")) { + await raiseMergeRefusal(b, pull, g, result.message, changes); + } else { + // The gate or a worker changed between the look and the + // merge: file nothing and let the next look decide. + bb.log.warn(`stewards: plugin merge of ${pull.key} not attempted: ${result.message}`); + } + } + } else { + store.fileNeed({ + bindingId: b.id, + kind: "merge", + url, + what: `Merge ${pull.key}`, + how: `The lane gate is met${g.lane === null ? "" : ` (${g.lane})`}. Merge squash-merges through the server's gh login and posts the merge comment.`, + data: { sha: g.headSha }, + filedBy: "plugin", + }); + } } } else { store.closeNeedByKey(b.id, "merge", url, `The gate is not met: ${g.missing ?? "unknown"}.`); @@ -7779,6 +7822,84 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P return lines; } + /** + * GitHub's refusal when the head moved between the look and the merge + * (409 "Head branch was modified", BB-257): the next look judges the new + * head, so it is a wait, not a `stuck` refusal. + */ + function isHeadMovedRefusal(message: string): boolean { + // The status after "failed: ", never a bare "409": the pull request's + // URL path carries its number, so PR #409 would otherwise be read as a + // head-moved refusal and silently retried on every look (BB-257). + return /failed: 409\b/u.test(message) || /Head branch was modified/iu.test(message); + } + + /** + * Whether a pull request targets its repository's default branch + * (BB-257). A stacked pull request's base is another pull request's + * branch, which may already be merged and dead; the plugin must not + * auto-merge into it, because the change would be off the default branch + * with no one involved. A stacked pull request keeps the plugin-filed + * Merge item and a person or worker merges it into its parent. A read of + * the default branch that fails is not the default (fail closed), so the + * item is filed. + */ + async function pullBaseIsDefault(ref: { repo: string; number: number }, pull: EntitySnapshot): Promise { + const base = pull.pull?.base ?? null; + if (base === null || base === "") return false; + const def = await github.defaultBranch(ref.repo).catch(() => null); + return def !== null && def === base; + } + + /** + * The key a refused merge is recorded against (BB-257): the head sha and + * the reviewer marker and lane that made the gate met. A refusal under the + * same key is not retried, so a conflict or branch protection is one + * escalation per refusal, not one per look; a push or a new review round + * changes the key and a fresh attempt follows. + */ + function mergeAttemptKey(g: ReturnType): string { + return [g.headSha ?? "", markerKey(g.marker) ?? "", g.lane ?? ""].join("|"); + } + + /** + * The refusal already recorded for this gate, if any: a merge the plugin + * attempted and GitHub refused, kept as a `stuck` escalation on the + * binding. Its presence stops a retry loop; the head or a gate input + * changing makes a new key, so the next look attempts again. + */ + function mergeRefusalFor(b: Binding, g: ReturnType): Escalation | null { + const key = mergeAttemptKey(g); + return store.escalations(b.id, 50).find((x) => x.kind === "stuck" && x.data.mergeRefusal === true && x.data.mergeKey === key) ?? null; + } + + /** + * Record a merge the plugin attempted and GitHub refused (BB-257): one + * note on the binding and one `stuck` escalation to the steward, both + * carrying the head sha and the gate key, so a repeated look does not + * retry or re-raise. + */ + async function raiseMergeRefusal(b: Binding, pull: EntitySnapshot, g: ReturnType, message: string, changes: Change[]): Promise { + const key = mergeAttemptKey(g); + const note = `The plugin could not merge ${pull.key}: ${message}`; + store.note(b.id, note); + changes.push({ text: note, actionable: true }); + const x = store.escalate({ + bindingId: b.id, + kind: "stuck", + question: `Could not merge ${pull.key}: ${message}`, + context: `The lane gate was met, so the plugin attempted the merge itself (BB-257), and GitHub refused it. Resolve the conflict or the branch protection and push; the plugin retries when the head sha or a gate input changes, or retry once the cause is fixed with \`bb stewards merge ${pull.key}\`. GitHub said: ${message}`, + meanwhile: "The plugin does not retry the same gate; the pull request stays open.", + route: nextRoute(b, null), + recommendation: null, + url: pull.url ?? pull.key, + headSha: g.headSha, + data: { mergeRefusal: true, mergeKey: key }, + projectId: b.projectId, + }); + await deliver(b, x); + } + /** * The one merge path the Stewards page's Merge button and `bb stewards * merge` share: recompute the gate with the project's approval records @@ -7823,7 +7944,7 @@ export function createStewardsPlugin(deps: StewardsDeps): (bb: BbPluginApi) => P } let mergeSha: string | null = null; try { - ({ sha: mergeSha } = await github.squashMerge(ref.repo, ref.number, commitTitle, commitBody)); + ({ sha: mergeSha } = await github.squashMerge(ref.repo, ref.number, commitTitle, commitBody, gate.headSha)); } catch (error) { return { ok: false, message: `GitHub refused the merge: ${errorMessage(error)}` }; } diff --git a/plugins/stewards/skills/stewards/SKILL.md b/plugins/stewards/skills/stewards/SKILL.md index 43b962c8..55f040ca 100644 --- a/plugins/stewards/skills/stewards/SKILL.md +++ b/plugins/stewards/skills/stewards/SKILL.md @@ -427,16 +427,17 @@ body by hand with `_— from bb thread _`. - **No logs** (the wake says so): diagnose from status and events, and say in the ticket that logs were not available. -## If you are a goal steward - -You own a **goal**: an outcome with acceptance criteria and no fixed set of -children. You file and sequence the children yourself, revise the outcome as -signals arrive, and stay open until the outcome is reached, the goal is -superseded, or the owner retires it. The goal is a ticket carrying the -adoption label and the `goal` label, assigned to this server's owner, and -routed to the `goal` playbook; its children are native sub-issues on both -sources. The project steward's wake and digest count your progress from the -`**Met:**` comments, so write them as you go. +## If you are an initiative steward + +You own an **initiative**: an outcome with acceptance criteria and no fixed +set of children. You file and sequence the children yourself, revise the +outcome as signals arrive, and stay open until the outcome is reached, the +initiative is superseded, or the owner retires it. The initiative is a ticket +carrying the adoption label and the `initiative` label, assigned to this +server's owner, and routed to the `initiative` playbook; its children are +native sub-issues on both sources. An initiative here is a labelled issue, +not a Linear Initiative. The project steward's wake and digest count your +progress from the `**Met:**` comments, so write them as you go. **The description holds only what the owner approves**, under fixed headings: `## Outcome` (one paragraph: what is true when this is done), @@ -448,8 +449,8 @@ who gives feedback and where, validators, the calendar, external events), and criterion in the description: progress is counted from `Met:` comments, not from ticked boxes. -**Comment prefixes.** Every comment you write on the goal starts with one of -these, so the history reads as a record: +**Comment prefixes.** Every comment you write on the initiative starts with +one of these, so the history reads as a record: - `**Revision:**` explains each description edit: what changed in the outcome or criteria, and which signal prompted it. @@ -458,7 +459,7 @@ these, so the history reads as a record: - `**Note:**` for anything else worth recording. **The outcome evolves, under approval.** The outcome paragraph and the -criteria are the spec, and the `goal` playbook's ready gate is +criteria are the spec, and the `initiative` playbook's ready gate is `approval: user`, so the owner approves them — not you and not the project steward. When a signal warrants a change — a stakeholder's feedback, a child's result, a validator, a date passing, an external event — edit the @@ -473,34 +474,35 @@ comment. Comments from anyone other than the owner are information until the owner confirms them: mention people to ask them, and fold their input into the next revision rather than acting on it. -**You drive.** On every wake, reread the goal, its signals and its children -(listed in the wake). File the next child for the first unmet, approved -criterion that has no open child: an ordinary labelled sub-issue, with a -`**Child:**` comment on the goal naming the criterion it serves. One child -per step, in dependency order, one layer ahead of what has merged; at most -two or three open at a time; never a child for an unapproved criterion. When -you cannot derive the next step, the ticket steward's rules apply: escalate -only what the guidance does not settle, one question per reply, record each +**You drive.** On every wake, reread the initiative, its signals and its +children (listed in the wake). File the next child for the first unmet, +approved criterion that has no open child: an ordinary labelled sub-issue, +with a `**Child:**` comment on the initiative naming the criterion it +serves. One child per step, in dependency order, one layer ahead of what has +merged; at most two or three open at a time; never a child for an unapproved +criterion. When you cannot derive the next step, the ticket steward's rules +apply: escalate only what the guidance does not settle, one question per +reply, record each ask, never repeat an open one. Where a wrong answer is reversible, record an assumption with `steward_update { assume: { text, context } }` and proceed, letting the next revision confirm it; ask only when the wrong answer is irreversible or blocks everything. A `(check: …)` criterion is judged by you from a child's output, not run by the plugin. Once the remaining criteria wait on an outcome (a -filed claim, a cycle run), add the `goal:awaiting-outcome` label and report -the wait; the label phase is what parks you, not a state change. +filed claim, a cycle run), add the `initiative:awaiting-outcome` label and +report the wait; the label phase is what parks you, not a state change. -**Three endings.** The binding ends when the goal closes, never on a merge -of a child. +**Three endings.** The binding ends when the initiative closes, never on a +merge of a child. -- **Reached:** every criterion is met. Ask the owner to close the goal, +- **Reached:** every criterion is met. Ask the owner to close the initiative, naming the `**Met:**` comments in one closing comment, and take the wrap-up turn. -- **Superseded:** a revision changes the outcome so far that a new goal is -filed. Close this goal with a `**Revision:**` comment pointing at the -successor, so the successor carries the outcome and this record says why it -ended. -- **Retired:** the owner closes the goal as not planned. Take the wrap-up -turn and end; do not reopen it yourself. +- **Superseded:** a revision changes the outcome so far that a new initiative +is filed. Close this initiative with a `**Revision:**` comment pointing at +the successor, so the successor carries the outcome and this record says why +it ended. +- **Retired:** the owner closes the initiative as not planned. Take the +wrap-up turn and end; do not reopen it yourself. ## If you are the project steward diff --git a/plugins/stewards/wake.test.ts b/plugins/stewards/wake.test.ts index e80f9345..00c9ff90 100644 --- a/plugins/stewards/wake.test.ts +++ b/plugins/stewards/wake.test.ts @@ -7,7 +7,7 @@ import { comment, issue, pull } from "./fixtures.js"; import { gateState } from "./reconcile.js"; import { MIGRATIONS, RESOLUTION_KINDS, createStore } from "./store.js"; import { DEPS_PRS, GITHUB_PRS, GITHUB_REVIEWS, LINEAR_TICKETS, OPS_WATCH, DEPS_ALERTS, PLAYBOOK_TEMPLATES } from "./templates.js"; -import { STANDING_RULES, BRIEF_PREFIX, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatRecords, formatWake, goalProgress, goalProgressFlag, spawnCommand, workerFinishNote, workerQuestion, type DigestRecords, type WakeInput } from "./wake.js"; +import { STANDING_RULES, BRIEF_PREFIX, formatBrief, formatDepsWake, formatOpsWake, formatProjectWake, formatRecords, formatWake, initiativeProgress, initiativeProgressFlag, spawnCommand, workerFinishNote, workerQuestion, type DigestRecords, type WakeInput } from "./wake.js"; import { BRIEF_MAX_CHARS } from "./server.js"; import type { OpsFinding } from "./ops.js"; import type { DepsFinding } from "./deps.js"; @@ -385,6 +385,16 @@ describe("the nightly prompt", () => { expect(STANDING_RULES.join("\n")).toMatch(/even when the ticket or spec says the owner produces or seals it by hand/u); }); + it("carries the rule that the plugin merges a gate-met pull request (BB-257)", () => { + const rules = STANDING_RULES.join("\n"); + expect(rules).toMatch(/The plugin merges once the lane gate is met/u); + expect(rules).toMatch(/targets the default branch/u); + expect(rules).toMatch(/a ticket binding always does/u); + expect(rules).toMatch(/`may` includes `merge`/u); + expect(rules).toMatch(/stacked pull request/u); + expect(rules).toMatch(/Do not file a Merge item/u); + }); + it("carries the merge hold rule and its line (BB-256)", () => { expect(STANDING_RULES.join("\n")).toMatch(/do not merge before X is Done/u); expect(STANDING_RULES.join("\n")).toMatch(/mergeBehind/u); @@ -728,7 +738,7 @@ describe("the ops and deps wake classification lines (BB-136)", () => { }); }); -describe("goal progress (BB-243)", () => { +describe("initiative progress (BB-243)", () => { const description = [ "## Outcome", "", @@ -744,21 +754,21 @@ describe("goal progress (BB-243)", () => { "", "The progress file.", ].join("\n"); - const goal = (over: Partial = {}) => issue({ labels: ["bb-managed", "goal"], description, ...over }); + const initiative = (over: Partial = {}) => issue({ labels: ["bb-managed", "initiative"], description, ...over }); const met = (text: string, id = text) => comment({ id, body: `**Met:** ${text}` }); it("counts distinct Met: comments against the description's criteria", () => { const { s, bind } = world(); - const b = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: goal({ comments: [met("Scope memo approved (owner)"), met("Expenses gathered (check: npm run expenses)")] }), pulls: [] } }); - expect(goalProgress(b)).toEqual({ met: 2, criteria: 3, capped: false }); - expect(goalProgressFlag(b)).toBe("goal met 2/3"); + const b = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: initiative({ comments: [met("Scope memo approved (owner)"), met("Expenses gathered (check: npm run expenses)")] }), pulls: [] } }); + expect(initiativeProgress(b)).toEqual({ met: 2, criteria: 3, capped: false }); + expect(initiativeProgressFlag(b)).toBe("criteria 2/3"); }); it("counts a criterion once when its Met: comment repeats", () => { const { s, bind } = world(); - const b = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: goal({ comments: [met("Scope memo approved (owner)", "c1"), met("scope memo approved (owner)", "c2")] }), pulls: [] } }); - expect(goalProgress(b)).toEqual({ met: 1, criteria: 3, capped: false }); - expect(goalProgressFlag(b)).toBe("goal met 1/3"); + const b = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: initiative({ comments: [met("Scope memo approved (owner)", "c1"), met("scope memo approved (owner)", "c2")] }), pulls: [] } }); + expect(initiativeProgress(b)).toEqual({ met: 1, criteria: 3, capped: false }); + expect(initiativeProgressFlag(b)).toBe("criteria 1/3"); }); it("counts the criteria a signed, evidenced Met: comment names, never above the checklist", () => { @@ -766,62 +776,62 @@ describe("goal progress (BB-243)", () => { const signed = (id: string, text: string) => comment({ id, body: `**Met:** ${text}\n\n_— from bb thread thr_steward_` }); const b = s.patch(bind("ENG-12").id, { lastSnapshot: { - entity: goal({ + entity: initiative({ comments: [signed("c1", "Scope memo approved (owner)"), signed("c2", "Scope memo approved — see docs/memo.md"), signed("c3", "Expenses gathered (check: npm run expenses)"), signed("c4", "Claim filed (owner)")], }), pulls: [], }, }); - expect(goalProgress(b)).toEqual({ met: 3, criteria: 3, capped: false }); - expect(goalProgressFlag(b)).toBe("goal met 3/3"); + expect(initiativeProgress(b)).toEqual({ met: 3, criteria: 3, capped: false }); + expect(initiativeProgressFlag(b)).toBe("criteria 3/3"); }); it("shows unknown, never 0, when no Met: comment can be read", () => { const { s, bind } = world(); - const b = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: goal({ comments: [] }), pulls: [] } }); - expect(goalProgress(b)).toEqual({ met: null, criteria: 3, capped: false }); - expect(goalProgressFlag(b)).toBe("goal met unknown"); + const b = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: initiative({ comments: [] }), pulls: [] } }); + expect(initiativeProgress(b)).toEqual({ met: null, criteria: 3, capped: false }); + expect(initiativeProgressFlag(b)).toBe("criteria unknown"); }); it("shows a lower bound when the snapshot held a full page of comments", () => { const { s, bind } = world(); const comments = Array.from({ length: 50 }, (_, i) => (i < 2 ? comment({ id: `c${i}`, body: `**Met:** ${i === 0 ? "Scope memo approved" : "Expenses gathered"}` }) : comment({ id: `c${i}`, body: `**Note:** noise ${i}` }))); - const b = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: goal({ comments }), pulls: [] } }); - expect(goalProgress(b)).toEqual({ met: 2, criteria: 3, capped: true }); - expect(goalProgressFlag(b)).toBe("goal met ≥2/3"); + const b = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: initiative({ comments }), pulls: [] } }); + expect(initiativeProgress(b)).toEqual({ met: 2, criteria: 3, capped: true }); + expect(initiativeProgressFlag(b)).toBe("criteria ≥2/3"); }); it("shows met without a criteria count when the description has no criteria section", () => { const { s, bind } = world(); - const b = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: goal({ description: "## Outcome\n\nJust an outcome.", comments: [met("Something")] }), pulls: [] } }); - expect(goalProgress(b)).toEqual({ met: 1, criteria: null, capped: false }); - expect(goalProgressFlag(b)).toBe("goal met 1"); + const b = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: initiative({ description: "## Outcome\n\nJust an outcome.", comments: [met("Something")] }), pulls: [] } }); + expect(initiativeProgress(b)).toEqual({ met: 1, criteria: null, capped: false }); + expect(initiativeProgressFlag(b)).toBe("criteria 1"); }); - it("knows a goal by its playbook before the first snapshot, and shows unknown", () => { + it("knows an initiative by its playbook before the first snapshot, and shows unknown", () => { const { s, bind } = world(); - const b = s.patch(bind("ENG-12").id, { playbook: "goal" }); - expect(goalProgress(b)).toEqual({ met: null, criteria: null, capped: false }); - expect(goalProgressFlag(b)).toBe("goal met unknown"); + const b = s.patch(bind("ENG-12").id, { playbook: "initiative" }); + expect(initiativeProgress(b)).toEqual({ met: null, criteria: null, capped: false }); + expect(initiativeProgressFlag(b)).toBe("criteria unknown"); }); - it("is null for a ticket without the goal label, and for a non-ticket", () => { + it("is null for a ticket without the initiative label, and for a non-ticket", () => { const { s, bind } = world(); const plain = s.patch(bind("ENG-12").id, { lastSnapshot: { entity: issue({ comments: [met("Something")] }), pulls: [] } }); - expect(goalProgress(plain)).toBeNull(); - expect(goalProgressFlag(plain)).toBeNull(); - expect(goalProgress({ ...plain, kind: "pr" })).toBeNull(); + expect(initiativeProgress(plain)).toBeNull(); + expect(initiativeProgressFlag(plain)).toBeNull(); + expect(initiativeProgress({ ...plain, kind: "pr" })).toBeNull(); }); it("rides on the project steward's binding list and digest lines", () => { const { s, bind } = world(); - const b = s.patch(bind("ENG-12").id, { status: status("Driving the goal."), advancedAt: T - 3_600_000, lastSnapshot: { entity: goal({ comments: [met("Scope memo approved (owner)"), met("Claim filed (owner)")] }), pulls: [] } }); + const b = s.patch(bind("ENG-12").id, { status: status("Driving the initiative."), advancedAt: T - 3_600_000, lastSnapshot: { entity: initiative({ comments: [met("Scope memo approved (owner)"), met("Claim filed (owner)")] }), pulls: [] } }); const records: DigestRecords = { previous: null, since: T - DAY, moved: [b], ended: [], answered: [], withUser: [], stuck: [], noWakeSource: [b], stall: [], held: [b] }; const wake = formatProjectWake({ reason: "nightly", bindings: [{ binding: b, openEscalations: [] }], routed: [], problems: [], digestDue: true, notes: [], bigDecisions: [], questions: [], records }); - expect(wake).toContain("- ENG-12 (ticket, In Progress): Driving the goal. Next: Open the PR (steward) [goal met 2/3]"); - expect(wake).toMatch(/- ENG-12 \(ticket, In Progress\), moved .*\[goal met 2\/3\]/u); - expect(wake).toMatch(/- ENG-12: on hold: .*\[goal met 2\/3\]/u); - expect(wake).toMatch(/- ENG-12 \(ticket, In Progress\): waiting with no wake source.*\[goal met 2\/3\]/u); + expect(wake).toContain("- ENG-12 (ticket, In Progress): Driving the initiative. Next: Open the PR (steward) [criteria 2/3]"); + expect(wake).toMatch(/- ENG-12 \(ticket, In Progress\), moved .*\[criteria 2\/3\]/u); + expect(wake).toMatch(/- ENG-12: on hold: .*\[criteria 2\/3\]/u); + expect(wake).toMatch(/- ENG-12 \(ticket, In Progress\): waiting with no wake source.*\[criteria 2\/3\]/u); }); }); diff --git a/plugins/stewards/wake.ts b/plugins/stewards/wake.ts index cd1c5fc4..59427203 100644 --- a/plugins/stewards/wake.ts +++ b/plugins/stewards/wake.ts @@ -5,7 +5,7 @@ // Each wake is self-contained. A steward that has compacted away everything // it ever saw can act correctly from one wake alone, which is what lets its // transcript stop being the source of truth. -import { formatDuration, GITHUB_TODO_LABEL, GOAL_LABEL, GOAL_PLAYBOOK, phaseInstructions, type FilingTarget, type LessonRules, type Playbook } from "./config.js"; +import { formatDuration, GITHUB_TODO_LABEL, INITIATIVE_LABEL, INITIATIVE_PLAYBOOK, phaseInstructions, type FilingTarget, type LessonRules, type Playbook } from "./config.js"; import type { BigDecision } from "./decisions.js"; import { anyPending, type Deployments, type DeploymentWatch } from "./deploy.js"; import { localParts } from "./nightly.js"; @@ -44,6 +44,7 @@ export const STANDING_RULES = [ "- **A credential is a decision escalation the project steward forwards as a secret.** Raise it with `steward_report { escalate }`, naming the variable and purpose in `context`. Forward it with `resolution: \"secret\"` and either `writeEnv`/`worker` (the dotenv a worker reads) or `setting` (a plugin secret setting); the plugin spawns a requester thread that opens bb's secure form. `secret` is the only resolution even when the ticket or spec says the owner produces or seals it by hand, corrected at spec approval. Never paste a secret or route the user to a script.", "- **A finding that would stop the feature working once it ships**, or that changes what the ticket needs (a credential, an access, a contract), is escalated as a `decision` in the same turn, quoting the worker's words — never relayed as a follow-up. An escalation that asks the user to pick between fixed options carries `choices` (2-6 short labels) so the page shows one button each.", '- **A spec that says "do not merge before X is Done" is a merge hold.** Report it with `steward_report { mergeBehind: ["X"] }`, never as a `merge` need or as free text alone: while it stands the plugin files no Merge item (so the effort shows as held, not "needs you"), it is a live wake source, and it lifts itself, waking you, once every named binding has merged its pull requests or ended. Each report replaces the set, and `mergeBehind: []` clears it.', + "- **The plugin merges once the lane gate is met, when the pull request targets the default branch.** When a pull request's gate is met, no worker is in flight, and its base is the repository's default branch, the plugin squash-merges it if the binding's playbook permits `merge` — a ticket binding always does, a `pr` binding when its `may` includes `merge` — and wakes you with the merge so you proceed to the deployment watch. Do not file a Merge item for such a pull request: the item on the page is for a playbook that does not permit `merge`, for a stacked pull request whose base is another pull request's branch (the worker or a person merges it into its parent's branch while that pull request is open), or for a merge the plugin attempted and GitHub refused (a conflict or branch protection), which is also raised to the project steward.", ]; /** * The fixed first line of every brief, and of the per-turn system context the @@ -87,10 +88,21 @@ const DESCRIPTION_CHARS = 4000; const WORKER_SKILLS = "Write the worker's task so it follows the `build-tickets` skill, which tells the worker to spawn its reviewer with the `pr-reviewer` skill; a `.bb/skills/` copy overrides either."; +/** + * Whether the plugin itself merges this binding's gate-met pull request + * (BB-257): a ticket binding always runs the full loop and so always merges; + * a `pr` binding only when its playbook's `may` includes `merge`; a `review` + * binding (a teammate's pull request) never does, because its author merges + * (BB-170). One function decides it, so the worker skill line and the + * gate-met branch of `syncNeeds` cannot disagree. + */ +export function bindingMayMerge(binding: Pick, playbook: Pick): boolean { + return binding.kind === "ticket" || (binding.kind === "pr" && playbook.may.includes("merge")); +} + /** The skill line for a binding, or empty when its playbook's worker does not merge. */ function workerSkillsLine(binding: Binding, playbook: Playbook): string[] { - const runsTheLoop = binding.kind === "ticket" || (binding.kind === "pr" && playbook.may.includes("merge")); - return runsTheLoop ? ["", WORKER_SKILLS] : []; + return bindingMayMerge(binding, playbook) ? ["", WORKER_SKILLS] : []; } const COMMENT_CHARS = 1500; const RESULT_CHARS = 1500; @@ -1264,10 +1276,11 @@ function criteriaKeys(description: string): string[] { } /** - * A goal's progress (BB-243): `met` is the number of the description's + * An initiative's progress (BB-243): `met` is the number of the description's * criteria a `**Met:**` comment names, `criteria` the number of checklist - * lines under its `Criteria` heading. Null when the ticket is not a goal — it - * carries neither the `goal` label nor the `goal` playbook. + * lines under its `Criteria` heading. Null when the ticket is not an + * initiative — it carries neither the `initiative` label nor the `initiative` + * playbook. * * A criterion is named when a `**Met:**` comment's first line, normalised, * equals it or either is a prefix of the other. Evidence and the signature on @@ -1277,16 +1290,17 @@ function criteriaKeys(description: string): string[] { * null. * * `met` is null rather than 0 when no `**Met:**` comment can be read (or the - * snapshot has not been read yet), so a goal that has not been driven reads - * `unknown`, never `0`: an empty count cannot be told from an unread history, - * and only one of them means no criterion is met. `capped` is true when the - * snapshot held a full page of comments, so the count is a lower bound. + * snapshot has not been read yet), so an initiative that has not been driven + * reads `unknown`, never `0`: an empty count cannot be told from an unread + * history, and only one of them means no criterion is met. `capped` is true + * when the snapshot held a full page of comments, so the count is a lower + * bound. */ -export function goalProgress(binding: Pick): { met: number | null; criteria: number | null; capped: boolean } | null { +export function initiativeProgress(binding: Pick): { met: number | null; criteria: number | null; capped: boolean } | null { if (binding.kind !== "ticket") return null; const entity = binding.lastSnapshot?.entity; - const byLabel = entity !== undefined && entity.labels.some((l) => l.toLowerCase() === GOAL_LABEL); - if (!byLabel && binding.playbook !== GOAL_PLAYBOOK) return null; + const byLabel = entity !== undefined && entity.labels.some((l) => l.toLowerCase() === INITIATIVE_LABEL); + if (!byLabel && binding.playbook !== INITIATIVE_PLAYBOOK) return null; if (entity === undefined) return { met: null, criteria: null, capped: false }; const criteria = criteriaKeys(entity.description ?? ""); const names = new Set(); @@ -1305,18 +1319,18 @@ export function goalProgress(binding: Pick): string | null { - const p = goalProgress(binding); +export function initiativeProgressFlag(binding: Pick): string | null { + const p = initiativeProgress(binding); if (p === null) return null; - if (p.met === null) return "goal met unknown"; + if (p.met === null) return "criteria unknown"; const met = `${p.capped ? "≥" : ""}${p.met}`; - return p.criteria === null ? `goal met ${met}` : `goal met ${met}/${p.criteria}`; + return p.criteria === null ? `criteria ${met}` : `criteria ${met}/${p.criteria}`; } /** @@ -1463,7 +1477,7 @@ export function formatProjectWake(input: { for (const { binding: b, openEscalations } of input.bindings.slice(0, 200)) { const s = b.status; const conflicts = conflictsOf(b, allOpen); - const flags = [goalProgressFlag(b), b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}${b.holdStack.length === 0 ? "" : ` (stacked on ${b.holdStack.join(", ")})`}`, b.touches.length === 0 ? null : `touches ${b.touches.join(", ")}`, conflicts.length === 0 ? null : `file-level overlap: ${conflicts.map((c) => { const open = c.with.lastSnapshot === null ? null : openPull(c.with, c.with.lastSnapshot); return `${c.with.entityKey} on ${c.on.join(", ")}${open === null || open.head === null || open.head === "" ? "" : ` (its pull request ${open.key} is open on ${open.head})`}`; }).join("; ")}`, openEscalations.length > 0 ? `${openEscalations.length} escalation(s): ${openEscalations.map((x) => `${x.kind}→${x.route}`).join(", ")}` : null, unheardWait(s, openEscalations)].filter((f): f is string => f !== null); + const flags = [initiativeProgressFlag(b), b.priority === null ? null : `priority ${b.priority}`, b.hold === null ? null : `HOLD: ${b.hold}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}${b.holdStack.length === 0 ? "" : ` (stacked on ${b.holdStack.join(", ")})`}`, b.touches.length === 0 ? null : `touches ${b.touches.join(", ")}`, conflicts.length === 0 ? null : `file-level overlap: ${conflicts.map((c) => { const open = c.with.lastSnapshot === null ? null : openPull(c.with, c.with.lastSnapshot); return `${c.with.entityKey} on ${c.on.join(", ")}${open === null || open.head === null || open.head === "" ? "" : ` (its pull request ${open.key} is open on ${open.head})`}`; }).join("; ")}`, openEscalations.length > 0 ? `${openEscalations.length} escalation(s): ${openEscalations.map((x) => `${x.kind}→${x.route}`).join(", ")}` : null, unheardWait(s, openEscalations)].filter((f): f is string => f !== null); out.push(`- ${b.entityKey} (${b.kind}, ${b.phase ?? "?"}): ${s === null ? "no report yet" : `${s.summary} Next: ${s.nextAction} (${s.actor})${s.waitingOn === null ? "" : `; waiting on ${s.waitingOn}${b.requeueUntil === null ? "" : ` until ${day(b.requeueUntil)}`}`}`}${flags.length > 0 ? ` [${flags.join("; ")}]` : ""}`); } const bindings = out.splice(0); @@ -1624,15 +1638,15 @@ export function formatRecords(r: DigestRecords, questions: Array<{ question: Que if (r.previous === null) out.push("### Your previous digest", "", "None yet.", ""); else out.push(`### Your previous digest (${iso(r.previous.at)})`, "", quote(clip(r.previous.text, PREVIOUS_DIGEST_CHARS)), ""); - // A goal's progress rides on its line, wherever the digest lists it (BB-243). - const goalFlag = (b: Binding): string => { - const flag = goalProgressFlag(b); + // An initiative's progress rides on its line, wherever the digest lists it (BB-243). + const initiativeFlag = (b: Binding): string => { + const flag = initiativeProgressFlag(b); return flag === null ? "" : ` [${flag}]`; }; const moved = [ ...r.moved.map((b) => { const s = b.status; - return `- ${b.entityKey} (${b.kind}, ${b.phase ?? "?"}), moved ${b.advancedAt === null ? "?" : iso(b.advancedAt)}: ${s === null ? "no report yet" : `${oneLine(s.summary)} Next: ${oneLine(s.nextAction)} (${s.actor})`}${goalFlag(b)}`; + return `- ${b.entityKey} (${b.kind}, ${b.phase ?? "?"}), moved ${b.advancedAt === null ? "?" : iso(b.advancedAt)}: ${s === null ? "no report yet" : `${oneLine(s.summary)} Next: ${oneLine(s.nextAction)} (${s.actor})`}${initiativeFlag(b)}`; }), ...r.ended.map((b) => `- Ended: ${b.entityKey} (${b.kind}${b.title === null ? "" : `, ${oneLine(b.title, 120)}`}), ${b.endReason ?? "ended"} at ${b.endedAt === null ? "?" : iso(b.endedAt)}`), ...r.answered.map((q) => `- Answered: ${q.id} "${oneLine(q.question, 200)}" → ${oneLine(q.answer ?? "", 300)} (${q.answeredBy === "user" ? "by the user, on the stewards page" : "recorded by you"})`), @@ -1666,14 +1680,14 @@ export function formatRecords(r: DigestRecords, questions: Array<{ question: Que const stuck = [ ...r.stuck.map(({ escalation: x, from }) => `- ${from.entityKey}: stuck escalation ${x.id} with ${x.route}, since ${day(x.createdAt)}: ${oneLine(x.question)}${choicesNote(x.choices)}`), - ...r.held.map((b) => `- ${b.entityKey}: on hold: ${oneLine(b.hold ?? "")}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}${b.holdStack.length === 0 ? "" : ` (stacked on ${b.holdStack.join(", ")})`}${goalFlag(b)}`), + ...r.held.map((b) => `- ${b.entityKey}: on hold: ${oneLine(b.hold ?? "")}${b.holdBehind.length === 0 ? "" : ` (behind ${b.holdBehind.join(", ")})`}${b.holdStack.length === 0 ? "" : ` (stacked on ${b.holdStack.join(", ")})`}${initiativeFlag(b)}`), ]; out.push("### Stuck or held", "", ...capped(stuck, "Nothing."), ""); // BB-247: a dated wait is not a quiet stall: the plugin will wake the steward // at the date, so it is listed in its own section rather than under "waiting // with no wake source". - const dated = (r.datedWaits ?? []).map((b) => `- ${b.entityKey} (${b.kind}, ${b.phase ?? "?"}): waiting on ${oneLine(b.status?.waitingOn ?? "")} until ${day(b.requeueUntil!)}${goalFlag(b)}`); + const dated = (r.datedWaits ?? []).map((b) => `- ${b.entityKey} (${b.kind}, ${b.phase ?? "?"}): waiting on ${oneLine(b.status?.waitingOn ?? "")} until ${day(b.requeueUntil!)}${initiativeFlag(b)}`); out.push("### Dated waits", "", ...capped(dated, "Nothing."), ""); // BB-154: the quiet stall, visible once a day even before the requeue @@ -1681,7 +1695,7 @@ export function formatRecords(r: DigestRecords, questions: Array<{ question: Que // a stall can be open with the mark already cleared (the stall is itself a // live source), so the two lists are separate. const noWake = [ - ...r.noWakeSource.map((b) => `- ${b.entityKey} (${b.kind}, ${b.phase ?? "?"}): waiting with no wake source${b.status?.waitingOn === null || b.status?.waitingOn === undefined ? "" : `: ${oneLine(b.status.waitingOn)}`}${b.requeueWakeCount > 0 ? ` (${b.requeueWakeCount} requeue-only wake${b.requeueWakeCount === 1 ? "" : "s"})` : ""}${goalFlag(b)}`), + ...r.noWakeSource.map((b) => `- ${b.entityKey} (${b.kind}, ${b.phase ?? "?"}): waiting with no wake source${b.status?.waitingOn === null || b.status?.waitingOn === undefined ? "" : `: ${oneLine(b.status.waitingOn)}`}${b.requeueWakeCount > 0 ? ` (${b.requeueWakeCount} requeue-only wake${b.requeueWakeCount === 1 ? "" : "s"})` : ""}${initiativeFlag(b)}`), ...r.stall.map(({ escalation: x, from }) => `- ${from.entityKey}: stall escalation ${x.id} with the project steward, since ${day(x.createdAt)}: ${oneLine(x.question)}`), ]; out.push("### Waiting with no wake source", "", ...capped(noWake, "Nothing."), ""); @@ -1696,7 +1710,7 @@ export const PROJECT_STEWARD_INTRO = `You are this project's steward. Every Line - Before you ask the user something in a reply, record it with steward_update { ask: { question, context } } (with binding when it concerns one); close it with steward_update { resolve: "", answer } when they answer. Every wake lists the questions still open, so list them from there, not from memory. - You are woken by escalations, at the end of each nightly pass to write the morning digest, and by the user. When the user says something like "hold everything touching billing", turn it into steward_update calls on the bindings it concerns, and say what you changed. - You schedule the work so that two tickets do not change the same files at once. Every binding reports what it touches; when a ready ticket overlaps work in flight at file level, the plugin asks you with a schedule escalation. Hold it behind that work (steward_update { binding, hold, behind: [keys] }: the hold lifts itself when the work lands), stack it on a pull request still being built (steward_update { binding, hold, stack: [keys] }: the hold lifts itself, with the branch, when that pull request opens), or let it start (guidance + resolve). Use the same holds to sequence any two tickets whose overlap you can see in the bindings list. -- A goal's binding line carries \`goal met /\`, counted from its \`**Met:**\` comments against the criteria in its description (BB-243). \`unknown\` means no \`**Met:**\` comment could be read — never that none is met — so a goal that has not been driven yet is not mistaken for one with nothing met. +- An initiative's binding line carries \`criteria /\`, counted from its \`**Met:**\` comments against the criteria in its description (BB-243). \`unknown\` means no \`**Met:**\` comment could be read — never that none is met — so an initiative that has not been driven yet is not mistaken for one with nothing met. - Budget is advisory: keep the total work sensible through priority and holds. Wait for the user or a wake; there is nothing to do right now.`;