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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
63 changes: 57 additions & 6 deletions plugins/stewards/DESIGN.md
Original file line number Diff line number Diff line change
Expand Up @@ -661,13 +661,13 @@ follow-through: 6h # how long a terminal binding may be kept open
- **Threads:** spawning stewards, recognizing workers, building wake messages,
the project's sidebar section.
- **Agent tools:** `steward_report` and `steward_update`.
- **CLI:** `bb stewards init | check | list | show | detach | pass | digest`.
- **CLI:** `bb stewards init | check | list | show | needs | done | detach | pass | digest`.
- **UI:** the Stewards page, a nav panel with one tab per stewarded project:
waiting on you (open questions, which you can close there, forwarded
escalations and approval requests), in flight by stage (summary, next
action and actor, running workers), stuck or held, ended in the last two
weeks, and the latest digest with its date. Settings → Plugins →
Stewards keeps each project's configuration and health.
waiting on you (needs items with links and buttons, open questions, which you
can close there, forwarded escalations and approval requests), in flight by
stage (summary, next action and actor, running workers), stuck or held, ended
in the last two weeks, and the latest digest with its date. Settings →
Plugins → Stewards keeps each project's configuration and health.

### Changes to linear and github

Expand Down Expand Up @@ -715,6 +715,57 @@ plugins' contract before stewards uses them, bb-plugins before bb-gate.
5. **Board.** Built: the Stewards page, the question record (§12), and the
digest assembled from records.

## 18. Needs you items and one-click actions

Everything a person had to do on a ticket used to exist only as prose,
repeated across Linear comments, the project steward's digest and the stewards'
replies. A **needs** record makes it structured: one row per thing the user
must do, with a link, one line of what, steps, and a close rule. It is filed by
the plugin from the snapshot or by a steward through `steward_report { needs }`,
listed under "Waiting on you" on the Stewards page, in the digest, and by
`bb stewards needs` and `bb stewards show`.

| kind | filed by | link | done when | one-click action |
| -- | -- | -- | -- | -- |
| `approve-spec` | plugin, when the ready gate waits and the playbook's approver is `me` | the ticket | gate approval recorded | **Approve** / **Decline** (with an optional note); Approve records the approval on the gate, as BB-13 does from any surface |
| `approve-pr` | plugin, when a linked pull request is in the owner-reviewed lane, the reviewer's marker on the head is `approved`, checks are green, and no owner approval exists | the pull request | owner approval seen in the snapshot | **Approve**: posts the unsigned comment "Approved <sha> from the Stewards page" as the connected user |
| `merge` | plugin, when the lane gate is met and no worker is running, or by a steward whose worker reported a refused merge | the pull request | the pull request merged | **Merge**: the server re-checks the gate itself, squash-merges through the server's `gh` login, posts the "Merged: …" comment, and wakes the steward |
| `decide` | project steward (today's forwarded question) | the entity | answered | **Answer** (the question record's text box) |
| `provide-secret` | steward, with the variable name and purpose | the worker thread | the worker's `bb secret request` completes | **Provide**: opens the worker thread named in the item, or wakes the steward to start the worker that will request it |
| `configure` | steward, for a step outside the repos (install an app, grant a permission, enable an event, set a setting) | the external page where it happens | the user presses Done, or the steward observes it done | **Done** (with an optional note, saved as guidance) |

The rules that hold:

- **One gate function.** `prGate` in `reconcile.ts` is the build-tickets lane
gate: the reviewer's latest marker names the current head with `approved`,
every check has passed, and, in the owner-reviewed lane, the owner has
approved — an unsigned approving comment or an APPROVED review by the
connected user; a signed comment is a thread's, never the owner's. The merge
button, the item the plugin files and the wake's "Lane gate" line all read
it, so a steward is told whether a pull request's gate is met in the same
words the button acts on.
- **The buttons run on the server as the connected user, unsigned**, so they
count as human actions. Approve-PR is a comment, not a review, so GitHub is
the only thing that can refuse it (approving your own pull request); Merge
uses the server's `gh` token through the GitHub API. The server never signs
one with a thread id.
- **A button is offered only while the server can verify its preconditions.**
`syncNeeds` recomputes the plugin's items on every look and closes the ones
whose condition no longer holds; the page marks one whose condition has moved
since as not actionable and says why ("reviewer round 3 pending", "a worker
is still running"). The merge action re-checks `prGate` against a fresh
snapshot before it merges.
- **Every action wakes the steward with the item's closure** under "What
changed", and the wake lists the binding's open items and says not to ask the
user about them in prose. Closing an item from the page or with
`bb stewards done <id>` does the same.
- **Dedupe.** A need is keyed by (binding, kind, url) while open: a steward
that re-reports updates the wording rather than adding a row. The store
enforces it with a partial unique index.
- **`blockedOn` stays for third parties.** A `steward_report` whose `blockedOn`
names the user, the owner or a human with no open needs item is refused and
told to file one, so the ask reaches the page instead of only the prose.

## Known limits

- **Multi-repo projects only.** A bb project whose source is a single
Expand Down
34 changes: 25 additions & 9 deletions plugins/stewards/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -87,9 +87,10 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run.
unless a playbook says `approval: me`. The plugin asks for that approval
itself: whenever a ready gate's checklist is met, the ticket is
substantial and the current spec has no approval, it files an `approval`
escalation with the approver (the project steward, or the user in the
steward's thread), whatever the steward's report says, and closes it once
approved or no longer needed. An approval is recorded from the approver's
escalation with the project steward, or an `approve-spec` item on the
Stewards page when the approver is the user (`approval: me`), whatever
the steward's report says, and closes it once approved or no longer
needed. An approval is recorded from the approver's
words wherever they are: the project steward's guidance that resolves the
request, the user's answer on the Stewards page, their message in the
steward's thread, or their unsigned approving comment on the entity. A
Expand All @@ -104,17 +105,32 @@ bb. [DESIGN.md](DESIGN.md) is the design; this is how it is built and run.
escalations is with you, the project steward is woken with the change too,
since you may have answered on the ticket rather than in its thread. A
status blocked on the project steward or the user with no open
escalation is flagged in `bb stewards list` and the digest.
escalation or needs item is flagged in `bb stewards list` and the digest.
- **"Needs you" items** are the structured things only the user can do: an
`approve-spec`, an `approve-pr` or a `merge` the plugin files from the
snapshot, and a `configure`, `provide-secret` or `decide` a steward files
through `steward_report { needs }`. They are deduplicated by (binding,
kind, url) while open, listed under "Waiting on you" on the Stewards page
with a link and a button each, in the digest, and by `bb stewards needs`.
The buttons run on the server as the connected user, unsigned: Approve
posts the "Approved <sha> from the Stewards page" comment, Merge re-checks
the lane gate and squash-merges through the server's `gh` login, and every
action wakes the binding's steward with the closure under "What changed".
A button is shown only while the server can verify its preconditions;
otherwise the item says why not. `bb stewards done <id>` closes one from a
thread. A `blockedOn` naming the user, the owner or a human is refused
unless an open needs item says so.
- **The nightly pass** (01:00 in the project's time zone by default, done by
02:45 so bb-gate's 03:00 restarts do not cut a turn) gives every open
binding a turn, then wakes the project steward for the morning digest.
A half-hourly mechanical sweep is the adoption and stuck backstop.
- **The Stewards page** (a nav panel, [app.tsx](app.tsx)) has a tab per
stewarded project: what waits on you (questions the project steward put
to you, which you can answer and close there, forwarded escalations and
approval requests), what is in flight by stage with each status record
and running workers, what is stuck or held, what ended in the last two
weeks, and the latest digest with its date.
stewarded project: what waits on you (needs items with their links and
buttons, questions the project steward put to you, which you can answer
and close there, forwarded escalations and approval requests), what is in
flight by stage with each status record and running workers, what is stuck
or held, what ended in the last two weeks, and the latest digest with its
date.
- **Questions to you** are kept in the store from the moment the project
steward asks (`steward_update { ask }`, or forwarding an escalation)
until it records your answer (`steward_update { resolve: "<question id>",
Expand Down
83 changes: 82 additions & 1 deletion plugins/stewards/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -386,7 +386,7 @@ function BoardPage({ subPath }: { subPath: string }) {

function ProjectBoard({ board: b, refetch }: { board: Board; refetch: () => void }) {
const now = Date.now();
const waiting = b.questions.length + b.withUser.length;
const waiting = b.questions.length + b.withUser.length + b.needs.length;
return (
<>
<div className="flex flex-wrap items-baseline justify-between gap-2">
Expand Down Expand Up @@ -438,6 +438,9 @@ function ProjectBoard({ board: b, refetch }: { board: Board; refetch: () => void
</p>
</li>
))}
{b.needs.map((n) => (
<NeedRow key={n.id} need={n} now={now} onDone={refetch} />
))}
</List>
)}
</Section>
Expand Down Expand Up @@ -522,6 +525,84 @@ function ProjectBoard({ board: b, refetch }: { board: Board; refetch: () => void
);
}

/**
* One "needs you" item with its buttons. A button is offered only when the
* server can verify the item's preconditions now; otherwise the item says why
* it is not actionable yet. Every action runs on the server, as the user.
*/
function NeedRow({ need: n, now, onDone }: { need: Board["needs"][number]; now: number; onDone: () => void }) {
const rpc = useRpc<typeof rpcContract>();
const navigate = useBbNavigate();
const [note, setNote] = useState("");
const [state, setState] = useState<"idle" | "running" | { error: string }>("idle");
const act = (action: "approve" | "decline" | "done" | "merge" | "provide") => {
setState("running");
rpc.call("stewardsNeedAction", { needId: n.id, action, note: note.trim() === "" ? null : note.trim() }).then(
(r) => {
if (!r.ok) return setState({ error: r.message });
onDone();
if (r.threadId !== null && r.threadId !== undefined) navigate.toThread(r.threadId);
},
(e: unknown) => setState({ error: message(e) }),
);
};
const primary = "rounded-md border border-input bg-state-hover px-3 py-1 text-xs hover:bg-state-hover disabled:opacity-50";
const secondary = "rounded-md border border-input px-3 py-1 text-xs hover:bg-state-hover disabled:opacity-50";
const takesNote = n.kind === "approve-spec" || n.kind === "configure" || n.kind === "decide";
return (
<li className="flex flex-col gap-2 p-3">
<p className="flex flex-wrap items-center gap-2">
<EntityLink entityKey={n.key} url={n.url} />
<Badge tone="bad">{n.kind}</Badge>
<span className="text-xs text-muted-foreground">asked {ago(n.createdAt, now)}</span>
</p>
<p>{n.what}</p>
{n.how !== null ? <div className="text-muted-foreground"><Markdown content={n.how} /></div> : null}
{!n.actionable ? <p className="text-xs text-amber-600 dark:text-amber-500">Not actionable yet: {n.why ?? "the server cannot verify it now"}.</p> : null}
{takesNote ? (
<textarea
value={note}
onChange={(e) => setNote(e.target.value)}
rows={1}
placeholder={n.kind === "approve-spec" ? "Note (optional)" : n.kind === "decide" ? "Your answer (optional, saved as guidance)" : "Note (optional, saved as guidance)"}
aria-label={`Note for: ${n.what}`}
className="min-w-0 flex-1 rounded-md border border-input bg-transparent px-2 py-1"
/>
) : null}
<div className="flex flex-wrap items-center gap-2">
{n.kind === "approve-spec" ? (
<>
<button type="button" disabled={!n.actionable || state === "running"} className={primary} onClick={() => act("approve")}>
Approve
</button>
<button type="button" disabled={!n.actionable || state === "running"} className={secondary} onClick={() => act("decline")}>
Decline
</button>
</>
) : n.kind === "approve-pr" ? (
<button type="button" disabled={!n.actionable || state === "running"} className={primary} onClick={() => act("approve")}>
Approve
</button>
) : n.kind === "merge" ? (
<button type="button" disabled={!n.actionable || state === "running"} className={primary} onClick={() => act("merge")}>
Merge
</button>
) : n.kind === "provide-secret" ? (
<button type="button" disabled={!n.actionable || state === "running"} className={primary} onClick={() => act("provide")}>
Provide
</button>
) : (
<button type="button" disabled={!n.actionable || state === "running"} className={primary} onClick={() => act("done")}>
Done
</button>
)}
{n.threadId !== null ? <ThreadLink threadId={n.threadId}>Open the worker</ThreadLink> : null}
{typeof state === "object" ? <span className="text-destructive">{state.error}</span> : null}
</div>
</li>
);
}

function QuestionRow({ question: q, now, onClosed }: { question: Board["questions"][number]; now: number; onClosed: () => void }) {
const rpc = useRpc<typeof rpcContract>();
const [answer, setAnswer] = useState("");
Expand Down
91 changes: 91 additions & 0 deletions plugins/stewards/github.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
// GitHub writes the Stewards page makes as the connected user: an unsigned
// approval comment, and a squash merge. The credential is the gh login on this
// server host (read the way github-watcher/gh.ts reads it), and nothing here
// signs what it writes, so a page action counts as the user's, not a thread's.
//
// Everything goes through the GitHub API rather than the `gh` subcommands, so
// the request is exactly what the button says: POST a comment, PUT a merge.
import { execFile } from "node:child_process";

const API = "https://api.github.com";
const TOKEN_TIMEOUT_MS = 15_000;
const REQUEST_TIMEOUT_MS = 30_000;

export class NotSignedInError extends Error {
constructor(detail: string) {
super(`GitHub is not signed in on this bb server${detail === "" ? "" : ` (${detail})`}. Sign in from the GitHub row of the Team setup checklist on the home page.`);
this.name = "NotSignedInError";
}
}

export class GithubApiError extends Error {
constructor(message: string) {
super(message);
this.name = "GithubApiError";
}
}

export type TokenReader = (signal?: AbortSignal) => Promise<string>;

/** Reads the token gh holds for github.com. Throws NotSignedInError when there is none. */
export function createGhTokenReader(): TokenReader {
return (signal) =>
new Promise((resolve, reject) => {
const env: NodeJS.ProcessEnv = { ...process.env, GH_PROMPT_DISABLED: "1", GH_NO_UPDATE_NOTIFIER: "1", NO_COLOR: "1" };
execFile("gh", ["auth", "token", "--hostname", "github.com"], { env, timeout: TOKEN_TIMEOUT_MS, maxBuffer: 64 * 1024, ...(signal === undefined ? {} : { signal }) }, (error, stdout, stderr) => {
if (error !== null) {
const code = (error as NodeJS.ErrnoException).code;
if (code === "ENOENT") return reject(new NotSignedInError("gh is not installed"));
const line = String(stderr).split("\n").map((l) => l.trim()).find((l) => l !== "") ?? error.message;
return reject(new NotSignedInError(line));
}
const token = String(stdout).trim();
if (token === "") return reject(new NotSignedInError("gh printed no token"));
resolve(token);
});
});
}

export interface GithubWriter {
/** Post an unsigned comment as the connected user. */
comment(repo: string, number: number, body: string): Promise<void>;
/** Squash-merge the pull request, with the given commit title and message. */
squashMerge(repo: string, number: number, title: string, body: string): Promise<void>;
}

/** "owner/repo#12" or "https://github.com/owner/repo/pull/12" → { repo, number }. */
export function parsePullRef(ref: string): { repo: string; number: number } | null {
const m = /^(?:https?:\/\/github\.com\/)?([A-Za-z0-9_.-]+)\/([A-Za-z0-9_.-]+?)(?:\.git)?(?:#|\/pull\/)(\d+)\/?$/u.exec(ref.trim());
return m === null ? null : { repo: `${m[1]}/${m[2]}`, number: Number(m[3]) };
}

/** The default writer: the server's gh token against the GitHub REST API. */
export function createGhWriter(token: TokenReader = createGhTokenReader(), doFetch: typeof fetch = fetch): GithubWriter {
const request = async (method: string, path: string, body: unknown): Promise<void> => {
const value = await token();
const response = await doFetch(`${API}${path}`, {
method,
headers: {
Authorization: `Bearer ${value}`,
Accept: "application/vnd.github+json",
"X-GitHub-Api-Version": "2022-11-28",
"Content-Type": "application/json",
"User-Agent": "bb-stewards",
},
...(body === undefined ? {} : { body: JSON.stringify(body) }),
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
});
if (!response.ok) {
const detail = await response.text().catch(() => "");
throw new GithubApiError(`${method} ${path} failed: ${response.status} ${detail.replace(/\s+/gu, " ").trim().slice(0, 500)}`);
}
};
return {
async comment(repo, number, body) {
await request("POST", `/repos/${repo}/issues/${number}/comments`, { body });
},
async squashMerge(repo, number, title, body) {
await request("PUT", `/repos/${repo}/pulls/${number}/merge`, { merge_method: "squash", commit_title: title, commit_message: body });
},
};
}
Loading
Loading