diff --git a/plugins/stewards/DESIGN.md b/plugins/stewards/DESIGN.md index f4ac7a3b..9ec7edfa 100644 --- a/plugins/stewards/DESIGN.md +++ b/plugins/stewards/DESIGN.md @@ -1623,8 +1623,8 @@ for the length of the crossfade. **Grouping is the steward relationship, then the thread tree.** A worker belongs to its binding through the plugin's `workers` table and a reviewer -through the worker the RPC names, so the grouping survives a worker spawned -without a parent. The thread tree (`parentThreadId ?? lifecycleOwnerThreadId`) +through the live thread whose parent is a claimed worker, so the grouping +survives a worker spawned without a parent. The thread tree (`parentThreadId ?? lifecycleOwnerThreadId`) places what the records do not cover: a worker an older steward parented under it, and a one-off thread's children. BB-72 restored the parent link — stewards under the project steward, workers under their steward, reviewers under their @@ -1648,9 +1648,10 @@ lane gate re-checked server-side). There is no **Details** button: the row itself opens the effort's detail view (BB-85), where the free-text answer and the secret form live. The inline block adds no write path the page does not already make. The -project dropdown carries each project's count in its option label, and that -count is the number of yellow effort rows, so the picker and the sections -cannot disagree. `stewardsSidebar` carries, per project, +project dropdown carries each project's count in its option label, and the +server counts the needs-you bindings (`needsCount`, the open bindings with +`needsUser`), so the picker and the sections cannot disagree. `stewardsSidebar` +carries, per project, `needs: { count, items }` with the board's row shapes, each tagged `question`/`withUser`/`need` and carrying the binding's entity key as `bindingKey` so a row owns its item; the effort row filters the items by that @@ -1685,7 +1686,7 @@ to the user or resolved (`reroute`, `resolve`, `approve`, `decline`), and a need filed, updated or closed (`fileNeed`, `closeNeed`, `closeNeeds`, `closeNeedByKey`). A synchronous coalescing guard makes one question filed or answered publish exactly one event even when the operation nests (`answer` -resolves its escalation). Every open sidebar refetches when the event names a +resolves its escalation). Every open sidebar refetches when the event names the project it shows, the board page refetches when it names its project, and the overview (which covers every project) refetches on any event; the half-minute poll remains the fallback. diff --git a/plugins/stewards/app.test.tsx b/plugins/stewards/app.test.tsx index a081dc73..8b48871e 100644 --- a/plugins/stewards/app.test.tsx +++ b/plugins/stewards/app.test.tsx @@ -442,12 +442,20 @@ const sidebarBinding = (over: Record) => ({ ...over, }); -const sidebarData = (over: { p1?: Record; p2?: Record } = {}) => ({ - projects: [ - { projectId: "p1", name: "Acme", projectStewardThreadId: null, needs: { count: 0, items: [] }, bindings: [], ended: [], ...over.p1 }, - { projectId: "p2", name: "Beta", projectStewardThreadId: null, needs: { count: 0, items: [] }, bindings: [], ended: [], ...over.p2 }, - ], -}); +const sidebarData = (over: { p1?: Record; p2?: Record; needsCounts?: Record } = {}) => { + const p1 = over.p1 ?? {}; + return { + projects: [ + { projectId: "p1", name: "Acme", needsCount: over.needsCounts?.p1 ?? 0 }, + { projectId: "p2", name: "Beta", needsCount: over.needsCounts?.p2 ?? 0 }, + ], + projectId: "p1", + projectStewardThreadId: (p1.projectStewardThreadId as string | null) ?? null, + needs: p1.needs ?? { count: 0, items: [] }, + bindings: p1.bindings ?? [], + ended: p1.ended ?? [], + }; +}; describe("the stewards sidebar's picker counts and refresh (BB-46)", () => { const renderSidebar = async (rpc: Record, props: Record = {}, threads: unknown[] = []): Promise => { @@ -464,8 +472,8 @@ describe("the stewards sidebar's picker counts and refresh (BB-46)", () => { { stewardsSidebar: () => sidebarData({ + needsCounts: { p1: 2, p2: 1 }, p1: { bindings: [sidebarBinding({ key: "ENG-1", threadId: "thr_a", needsUser: true }), sidebarBinding({ key: "ENG-2", threadId: "thr_b", needsUser: true })], needs: { count: 9, items: [] } }, - p2: { bindings: [sidebarBinding({ key: "ENG-3", threadId: "thr_c", needsUser: true })] }, }), }, {}, @@ -542,7 +550,7 @@ describe("the stewards overview's refresh (BB-90)", () => { rpc: { stewardsOverview: () => { calls += 1; - return { paused: false, projects: [], lastSweepAt: 0 }; + return { paused: false, projects: [], lastSweepAt: 0, stats: { rpc: {}, cli: {}, signals: {} } }; }, }, } as never); diff --git a/plugins/stewards/app.tsx b/plugins/stewards/app.tsx index 4200e560..537c625d 100644 --- a/plugins/stewards/app.tsx +++ b/plugins/stewards/app.tsx @@ -42,8 +42,8 @@ type Project = Overview["projects"][number]; type Steward = Project["stewards"][number]; type BoardResult = Awaited> extends infer R ? Extract : never; type Board = NonNullable; -type SidebarResult = Awaited> extends infer R ? Extract }> : never; -type SidebarNeeds = SidebarResult["projects"][number]["needs"]; +type SidebarResult = Awaited> extends infer R ? Extract : never; +type SidebarNeeds = SidebarResult["needs"]; type SidebarNeedItem = SidebarNeeds["items"][number]; type CheckResult = { ok: boolean; lines: string[] }; @@ -202,6 +202,28 @@ function Row({ label, children }: { label: string; children: ReactNode }) { // ---- Status --------------------------------------------------------------------------------------- +/** The plugin's in-memory per-method stat (BB-100), shown in the Status section. */ +function MethodStats({ title, rows }: { title: string; rows: Record }) { + const entries = Object.entries(rows).sort((a, b) => a[0].localeCompare(b[0])); + return ( +
+

{title}

+ {entries.length === 0 ? ( +

none

+ ) : ( +
    + {entries.map(([name, s]) => ( +
  • + {name}: {s.count} call{s.count === 1 ? "" : "s"}, total {s.totalMs}ms, max {s.maxMs}ms, last {s.lastMs}ms + {s.lastAt === null ? "" : ` (${ago(s.lastAt, Date.now())})`} +
  • + ))} +
+ )} +
+ ); +} + function StatusSection() { const { overview, error } = useOverview(); if (overview === null) return ; @@ -222,6 +244,29 @@ function StatusSection() { overview.projects.map((p) => ) )}

Last sweep {ago(overview.lastSweepAt, now)}; the sweep runs every half hour. Configuration is reread from committed HEAD every few minutes.

+
+ Handler stats (this process) +
+ + +
+

Signals published in the last hour

+ {Object.keys(overview.stats.signals).length === 0 ? ( +

none

+ ) : ( +
    + {Object.entries(overview.stats.signals) + .sort((a, b) => a[0].localeCompare(b[0])) + .map(([projectId, count]) => ( +
  • + {projectId}: {count} +
  • + ))} +
+ )} +
+
+
{error !== null ?

Refresh failed: {error}

: null} ); @@ -1830,44 +1875,63 @@ function StewardsSidebarCore({ }) { const rpc = useRpc(); const { status, threads, projects } = experimental_useSidebarThreads(); - const { data, error, loaded, refetch } = usePolled(useCallback(() => rpc.call("stewardsSidebar", null), [rpc])); + // The Stewards page's route, when that panel is mounted (BB-94). It is null + // on a thread route, where the props above are the source. + const boardRoute = useBoardRoute(); + const navigate = useBbNavigate(); + const [picked, setPicked] = useState(null); + // The active tab follows the panel route, then the thread route; a pick only + // lasts until one of them moves. + useEffect(() => setPicked(null), [activeProjectId, boardRoute.projectId]); + // The one project the RPC is asked for; null lets the server pick the first + // by name. `load` depends on it, so a pick refetches like the board's `wanted`. + const wanted = picked ?? boardRoute.projectId ?? activeProjectId; + const { data, error, loaded, refetch } = usePolled(useCallback(() => rpc.call("stewardsSidebar", { projectId: wanted }), [rpc, wanted])); // The previous tabs, so `buildSidebar` can hand back the same effort and // thread objects for unchanged rows and the memoised rows skip a render // (BB-95). The ref is written during render; the call is idempotent. const previousTabs = useRef([]); const tabs = useMemo(() => { - const next = buildSidebar({ projects, threads, data: data?.projects ?? [], now: Date.now() }, previousTabs.current); + // The RPC carries one project's data; that tab is the only one whose rows + // render, so the others are built from the live threads alone (BB-100). + const projectData = + data === null || data.projectId === null + ? [] + : [ + { + projectId: data.projectId, + name: data.projects.find((p) => p.projectId === data.projectId)?.name ?? data.projectId, + projectStewardThreadId: data.projectStewardThreadId, + bindings: data.bindings, + ended: data.ended, + }, + ]; + const next = buildSidebar({ projects, threads, data: projectData, now: Date.now() }, previousTabs.current); previousTabs.current = next; return next; }, [projects, threads, data]); - const needsByProject = useMemo(() => new Map((data?.projects ?? []).map((p) => [p.projectId, p.needs] as const)), [data]); - // The picker counts the yellow rows, so the pill and the sections cannot disagree (BB-76). - const counts = useMemo(() => new Map(tabs.map((t) => [t.projectId, t.blocked.filter((e) => e.state === "you").length] as const)), [tabs]); - // A steward's visible change updates the badge and block within seconds; - // the half-minute poll stays the fallback. Only a project this sidebar shows - // triggers a refetch. + // The picker's count is the server's needs-you binding count, so the pill and + // the yellow rows cannot disagree (BB-100). + const counts = useMemo(() => new Map((data?.projects ?? []).map((p) => [p.projectId, p.needsCount] as const)), [data]); + const active = tabs.find((t) => t.projectId === wanted) ?? tabs.find((t) => t.projectId === data?.projectId) ?? tabs[0] ?? null; + // A steward's visible change updates the badge and block within seconds; the + // half-minute poll stays the fallback. Only a signal that names the shown + // project triggers a refetch, not one for another listed project (BB-100). + const shownProjectId = active?.projectId ?? data?.projectId ?? wanted; useRealtime( PROJECT_CHANGED, useCallback( (payload) => { const projectId = payload === null || typeof payload !== "object" ? null : (payload as { projectId?: unknown }).projectId; - if (typeof projectId === "string" && projects.some((p) => p.id === projectId)) refetch(); + if (typeof projectId === "string" && projectId === shownProjectId) refetch(); }, - [projects, refetch], + [shownProjectId, refetch], ), ); const byId = useMemo(() => new Map(threads.map((t) => [t.id, t] as const)), [threads]); - // The Stewards page's route, when that panel is mounted (BB-94). It is null - // on a thread route, where the props above are the source. - const boardRoute = useBoardRoute(); - const navigate = useBbNavigate(); - const [picked, setPicked] = useState(null); - // The active tab follows the panel route, then the thread route; a pick only - // lasts until one of them moves. - useEffect(() => setPicked(null), [activeProjectId, boardRoute.projectId]); - const wanted = picked ?? boardRoute.projectId ?? activeProjectId; - const active = tabs.find((t) => t.projectId === wanted) ?? tabs[0] ?? null; - const activeNeeds = active === null ? undefined : needsByProject.get(active.projectId); + // The requested project's needs items, only while the data matches the tab on + // screen; a stale answer for a previous project shows nothing (BB-100). + const needItems = active !== null && data?.projectId === active.projectId ? data.needs.items : EMPTY_NEEDS; const now = Date.now(); const activeKey = boardRoute.key; const openThreads = useMemo(() => revealThreads(tabs, activeThreadId), [tabs, activeThreadId]); @@ -1885,7 +1949,6 @@ function StewardsSidebarCore({ const newThread = useCallback(() => { if (active !== null) onNewThread(active.projectId); }, [active, onNewThread]); - const needItems = activeNeeds?.items ?? EMPTY_NEEDS; const rows = (list: readonly SidebarEffort[]) => list.map((e) => ( makeThreadResponse({ id, status: t.status as never, archivedAt: t.archivedAt, parentThreadId: t.parentThreadId ?? null, sectionId: t.sectionId ?? null })), + experimental_listDescendants: async ({ threadIds, includeArchived, includeHidden }: { threadIds: string[]; includeArchived?: boolean; includeHidden?: boolean }) => { + const descendants = (id: string): string[] => { + const out: string[] = []; + for (const [childId, child] of threads) { + if ((child.parentThreadId ?? null) !== id) continue; + if (includeArchived !== true && child.archivedAt !== null) continue; + if (includeHidden !== true && child.visibility === "hidden") continue; + out.push(childId, ...descendants(childId)); + } + return out; + }; + return { threads: threadIds.map((threadId) => ({ threadId, descendantIds: descendants(threadId) })) }; + }, archive: async ({ threadId }: { threadId: string }) => { threads.get(threadId)!.archivedAt = 1; return {}; @@ -1048,11 +1061,11 @@ describe("a Linear ticket steward", () => { // The reviewer is a child of the worker, filed under it, not a worker. await t.created("thr_r1", "thr_w1", "Review acme/web#7"); expect(t.hooks.store.worker("thr_r1")).toBeNull(); - const result = (await t.harness.callRpc("stewardsSidebar", null)) as { projects: Array<{ bindings: Array<{ workers: Array<{ threadId: string }>; reviewers: Array<{ threadId: string; workerThreadId: string }> }> }> }; - expect(result.projects[0]!.bindings[0]).toMatchObject({ - workers: [{ threadId: "thr_w1" }], - reviewers: [{ threadId: "thr_r1", workerThreadId: "thr_w1" }], - }); + // The sidebar RPC no longer names reviewers; the client derives them from + // the live thread tree, so the field is absent (BB-100). + const result = (await t.harness.callRpc("stewardsSidebar", { projectId: "p1" })) as { bindings: Array<{ workers: Array<{ threadId: string }>; reviewers?: unknown }> }; + expect(result.bindings[0]).toMatchObject({ workers: [{ threadId: "thr_w1" }] }); + expect(result.bindings[0]!.reviewers).toBeUndefined(); }); it("keeps a running worker's own pull request activity for the next turn instead of waking for it", async () => { @@ -2580,8 +2593,8 @@ describe("the status report actor (BB-97)", () => { } const status = (t: Awaited>) => t.hooks.store.find("ENG-12")!.status; const needsUser = async (t: Awaited>) => { - const sidebar = (await t.harness.callRpc("stewardsSidebar", null)) as { projects: Array<{ bindings: Array<{ key: string; needsUser: boolean }> }> }; - return sidebar.projects[0]!.bindings.find((b) => b.key === "ENG-12")!.needsUser; + const sidebar = (await t.harness.callRpc("stewardsSidebar", { projectId: "p1" })) as { bindings: Array<{ key: string; needsUser: boolean }> }; + return sidebar.bindings.find((b) => b.key === "ENG-12")!.needsUser; }; it("records `user` as the server's owner, so the row needs you; `steward` and `other` do not", async () => { @@ -2772,7 +2785,7 @@ describe("archiving finished workers and reviewers (BB-47)", () => { const steward = t.spawns[1]!.id; await t.created("thr_w1", steward); // "Unknown" is not "no reviewers": the worker waits for a listing that works. - t.harness.sdk.stub("threads.list", async () => { + t.harness.sdk.stub("threads.experimental_listDescendants", async () => { throw new Error("listing is down"); }); await t.idle("thr_w1", "Implemented the fix."); @@ -3425,53 +3438,82 @@ describe("questions to the user", () => { describe("the stewards sidebar call", () => { type Sidebar = { - projects: Array<{ - projectId: string; - name: string; - projectStewardThreadId: string | null; - bindings: Array<{ - key: string; - kind: string; - stage: string | null; - phase: string | null; - threadId: string | null; - hold: string | null; - holdBehind: string[]; - blockedOn: string | null; - needsUser: boolean; - stuck: boolean; - status: { actor: string; nextAction: string; at: number } | null; - deployment: string | null; - advancedAt: number | null; - workers: Array<{ threadId: string; title: string; status: string }>; - reviewers: Array<{ threadId: string; workerThreadId: string }>; - }>; - needs: { count: number; items: Array<{ type: string; id: string; bindingKey: string | null }> }; - ended: Array<{ key: string; kind: string; threadId: string | null; title: string | null; endedAt: number }>; + projects: Array<{ projectId: string; name: string; needsCount: number }>; + projectId: string | null; + projectStewardThreadId: string | null; + needs: { count: number; items: Array<{ type: string; id: string; bindingKey: string | null }> }; + bindings: Array<{ + key: string; + kind: string; + stage: string | null; + phase: string | null; + threadId: string | null; + hold: string | null; + holdBehind: string[]; + blockedOn: string | null; + needsUser: boolean; + stuck: boolean; + status: { actor: string; nextAction: string; at: number } | null; + deployment: string | null; + advancedAt: number | null; + workers: Array<{ threadId: string; title: string; status: string }>; + reviewers?: unknown; }>; + ended: Array<{ key: string; kind: string; threadId: string | null; title: string | null; endedAt: number }>; }; - it("returns every stewarded project's bindings, workers and reviewers, the project steward and what ended", async () => { + it("returns the requested project's bindings and a needsCount for every project (BB-100)", async () => { const t = await setup(); + const originalProjects = t.sdk.projects.list; + t.harness.sdk.stub("projects.list", async () => [...(await originalProjects()), { id: "p2", name: "Beta" }]); t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); await t.ring("linear", "uuid-12"); const [project, steward] = t.spawns.map((x) => x.id) as [string, string]; + const b = t.hooks.store.find("ENG-12", "p1")!; + // One open need makes p1's needs count 1; p2 has none. + t.hooks.store.fileNeed({ bindingId: b.id, kind: "configure", url: "", what: "Enable the flag", how: null }); + + const result = (await t.harness.callRpc("stewardsSidebar", { projectId: "p1" })) as Sidebar; + expect(result.projects).toEqual( + expect.arrayContaining([ + expect.objectContaining({ projectId: "p1", name: "Acme", needsCount: 1 }), + expect.objectContaining({ projectId: "p2", name: "Beta", needsCount: 0 }), + ]), + ); + expect(result.projectId).toBe("p1"); + expect(result.projectStewardThreadId).toBe(project); + expect(result.bindings).toMatchObject([{ key: "ENG-12", kind: "ticket", threadId: steward, needsUser: true }]); + expect(result.ended).toEqual([]); + }); + + it("null picks the first project by name, as the board does (BB-100)", async () => { + const t = await setup(); + const originalProjects = t.sdk.projects.list; + // "Aardvark" sorts before "Acme". + t.harness.sdk.stub("projects.list", async () => [...(await originalProjects()), { id: "p2", name: "Aardvark" }]); + t.entities.set("uuid-12", issue()); + await t.ring("linear", "uuid-12"); + + const result = (await t.harness.callRpc("stewardsSidebar", { projectId: null })) as Sidebar; + expect(result.projectId).toBe("p2"); + }); + + it("makes no per-worker threads.list call (BB-100)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const steward = t.spawns[1]!.id; await t.created("thr_w1", steward, "Implement retry"); await t.created("thr_r1", "thr_w1", "Review the pull request"); - const result = (await t.harness.callRpc("stewardsSidebar", null)) as Sidebar; - expect(result.projects).toMatchObject([{ projectId: "p1", name: "Acme", projectStewardThreadId: project }]); - expect(result.projects[0]!.bindings).toMatchObject([ - { - key: "ENG-12", - kind: "ticket", - threadId: steward, - needsUser: false, - workers: [{ threadId: "thr_w1", title: "Implement retry" }], - reviewers: [{ threadId: "thr_r1", workerThreadId: "thr_w1" }], - }, - ]); - expect(result.projects[0]!.ended).toEqual([]); + let listCalls = 0; + const originalList = t.sdk.threads.list; + t.harness.sdk.stub("threads.list", async (args: { parentThreadId?: string }) => { + listCalls += 1; + return originalList(args); + }); + await t.harness.callRpc("stewardsSidebar", { projectId: "p1" }); + expect(listCalls).toBe(0); }); it("carries phase, status, holdBehind, stuck, deployment, worker status and a needs item's bindingKey (BB-76)", async () => { @@ -3496,8 +3538,8 @@ describe("the stewards sidebar call", () => { t.hooks.store.escalate({ bindingId: b.id, kind: "stuck", question: "Stuck", meanwhile: "Waiting", route: "project", recommendation: null, projectId: "p1" }); const q = t.hooks.store.ask({ projectId: "p1", bindingId: b.id, escalationId: null, question: "Which option?", context: null }); - const result = (await t.harness.callRpc("stewardsSidebar", null)) as Sidebar; - const binding = result.projects[0]!.bindings.find((x) => x.key === "ENG-12")!; + const result = (await t.harness.callRpc("stewardsSidebar", { projectId: "p1" })) as Sidebar; + const binding = result.bindings.find((x) => x.key === "ENG-12")!; expect(binding).toMatchObject({ phase: "In Review", hold: "a freeze", @@ -3507,7 +3549,7 @@ describe("the stewards sidebar call", () => { deployment: "deployed", workers: [{ threadId: "thr_w1", title: "Implement retry", status: "running" }], }); - expect(result.projects[0]!.needs.items).toContainEqual(expect.objectContaining({ type: "question", id: q.id, bindingKey: "ENG-12" })); + expect(result.needs.items).toContainEqual(expect.objectContaining({ type: "question", id: q.id, bindingKey: "ENG-12" })); }); it("lists an ended binding in `ended` and drops it from the bindings", async () => { @@ -3517,49 +3559,44 @@ describe("the stewards sidebar call", () => { const binding = t.hooks.store.find("ENG-12")!; t.hooks.store.patch(binding.id, { endedAt: t.now(), endReason: "merged" }); - const result = (await t.harness.callRpc("stewardsSidebar", null)) as Sidebar; - expect(result.projects[0]!.bindings).toEqual([]); - expect(result.projects[0]!.ended).toMatchObject([{ key: "ENG-12", kind: "ticket" }]); - expect(result.projects[0]!.ended[0]!.endedAt).toBe(t.now()); + const result = (await t.harness.callRpc("stewardsSidebar", { projectId: "p1" })) as Sidebar; + expect(result.bindings).toEqual([]); + expect(result.ended).toMatchObject([{ key: "ENG-12", kind: "ticket" }]); + expect(result.ended[0]!.endedAt).toBe(t.now()); }); - it("caches the per-worker reviewer lookup and lists projects once per call (BB-95)", async () => { + it("sends running and finished workers, and any other that ended within the last hour (BB-100)", async () => { const t = await setup(); t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); await t.ring("linear", "uuid-12"); const steward = t.spawns[1]!.id; - await t.created("thr_w1", steward, "Implement retry"); - await t.created("thr_r1", "thr_w1", "Review the pull request"); - - let listCalls = 0; - let projectListCalls = 0; - const originalList = t.sdk.threads.list; - t.harness.sdk.stub("threads.list", async (args: { parentThreadId?: string }) => { - listCalls += 1; - return originalList(args); - }); - const originalProjects = t.sdk.projects.list; - t.harness.sdk.stub("projects.list", async () => { - projectListCalls += 1; - return originalProjects(); - }); - - const first = (await t.harness.callRpc("stewardsSidebar", null)) as Sidebar; - expect(first.projects[0]!.bindings[0]!.reviewers).toEqual([{ threadId: "thr_r1", workerThreadId: "thr_w1" }]); - expect(listCalls).toBe(1); - expect(projectListCalls).toBe(1); + for (const [id, title] of [["thr_run", "Run"], ["thr_fin", "Finish"], ["thr_stop_old", "Old stop"], ["thr_stop_new", "New stop"]] as const) await t.created(id, steward, title); + // The old stop and the finish end now; two hours pass; the new stop ends + // then, and the running worker stays running. + t.hooks.store.setWorker("thr_stop_old", "stopped", null); + t.hooks.store.setWorker("thr_fin", "finished", "done"); + t.advance(2 * 3_600_000); + t.hooks.store.setWorker("thr_stop_new", "stopped", null); + t.hooks.store.setWorker("thr_run", "running", null); - // A second call inside the cache window shares the lookup and lists - // projects once more. - const second = (await t.harness.callRpc("stewardsSidebar", null)) as Sidebar; - expect(second.projects[0]!.bindings[0]!.reviewers).toEqual([{ threadId: "thr_r1", workerThreadId: "thr_w1" }]); - expect(listCalls).toBe(1); - expect(projectListCalls).toBe(2); + const result = (await t.harness.callRpc("stewardsSidebar", { projectId: "p1" })) as Sidebar; + const workers = result.bindings.find((x) => x.key === "ENG-12")!.workers.map((w) => w.threadId).sort(); + // The old stop is absent; the finished one rides regardless of age. + expect(workers).toEqual(["thr_fin", "thr_run", "thr_stop_new"]); + }); - // Past the window the lookup runs again. - t.advance(6_000); - await t.harness.callRpc("stewardsSidebar", null); - expect(listCalls).toBe(2); + it("reports a call and a signal in bb stewards stats (BB-100)", async () => { + const t = await setup(); + t.entities.set("uuid-12", issue({ state: "In Progress", stateType: "started" })); + await t.ring("linear", "uuid-12"); + const b = t.hooks.store.find("ENG-12", "p1")!; + const before = JSON.parse((await t.harness.behavior.runCli(["stats", "--json"])).stdout) as { rpc: Record; signals: Record }; + await t.harness.callRpc("stewardsSidebar", { projectId: "p1" }); + // One visible patch publishes one signal. + t.hooks.store.patch(b.id, { phase: "In Review" }); + const after = JSON.parse((await t.harness.behavior.runCli(["stats", "--json"])).stdout) as { rpc: Record; signals: Record }; + expect(after.rpc.stewardsSidebar!.count).toBe((before.rpc.stewardsSidebar?.count ?? 0) + 1); + expect(after.signals.p1).toBe((before.signals.p1 ?? 0) + 1); }); }); @@ -3571,9 +3608,9 @@ describe("the sidebar's needs you block (BB-46)", () => { withUser: Array<{ id: string }>; needs: Array<{ id: string; kind: string; actionable: boolean }>; }; - type SidebarView = { projects: Array<{ projectId: string; needs: { count: number; items: Array<{ type: string; id: string }> } }> }; + type SidebarView = { projectId: string | null; needs: { count: number; items: Array<{ type: string; id: string }> } }; const boardView = async (t: Awaited>): Promise => ((await t.harness.callRpc("stewardsBoard", { projectId: "p1" })) as { board: BoardView }).board; - const sidebarView = async (t: Awaited>) => ((await t.harness.callRpc("stewardsSidebar", null)) as SidebarView).projects.find((p) => p.projectId === "p1")!; + const sidebarView = async (t: Awaited>) => (await t.harness.callRpc("stewardsSidebar", { projectId: "p1" })) as SidebarView; it("agrees with the board, excluding a non-actionable need and a with-user escalation a question covers", async () => { const t = await setup(); diff --git a/plugins/stewards/server.ts b/plugins/stewards/server.ts index 43d8ddf8..66d9eef2 100644 --- a/plugins/stewards/server.ts +++ b/plugins/stewards/server.ts @@ -13,7 +13,7 @@ // Configuration lives in the project's `.bb`, read through multi-repo's RPC // from the canonical checkout's committed HEAD. Nothing here reads a file. import { randomBytes } from "node:crypto"; -import { PluginCliError, cliCommand, defineCli, defineRpcContract, type BbPluginApi } from "@get-bb/plugin-sdk"; +import { PluginCliError, cliCommand, defineCli, defineRpcContract, type BbPluginApi, type ExperimentalPluginRpcHandlersWithContext, type PluginCliCommand } from "@get-bb/plugin-sdk"; import { z } from "zod"; import { DEFAULT_FOLLOW_THROUGH_MS, @@ -279,6 +279,23 @@ const sidebarNeedsItemSchema = z.discriminatedUnion("type", [ needViewSchema.extend({ type: z.literal("need"), bindingKey: z.string() }), ]); +/** One RPC method's or CLI command's in-memory stat (BB-100). */ +const methodStatSchema = z.object({ + count: z.number(), + totalMs: z.number(), + maxMs: z.number(), + lastMs: z.number(), + lastAt: z.number().nullable(), +}); +/** The plugin's in-memory handler table, read by `bb stewards stats` and the Status section (BB-100). */ +const statsSchema = z.object({ + rpc: z.record(z.string(), methodStatSchema), + cli: z.record(z.string(), methodStatSchema), + /** Signals published per project in the last hour. */ + signals: z.record(z.string(), z.number()), +}); +export type StewardStats = z.infer; + /** The steward's own surface for the app and the CLI. Cross-plugin methods are in source-contract.ts. */ export const rpcContract = defineRpcContract({ ...stewardsContract, @@ -309,6 +326,8 @@ export const rpcContract = defineRpcContract({ output: z.object({ paused: z.boolean(), lastSweepAt: z.number().nullable(), + /** The plugin's in-memory per-method stat, for the Status section (BB-100). */ + stats: statsSchema, projects: z.array( z.object({ projectId: z.string(), @@ -460,58 +479,62 @@ export const rpcContract = defineRpcContract({ .nullable(), }), }, - // The sidebar thread list's one call: every stewarded project's bindings, - // their workers and known reviewers, the project steward, what ended, and - // the project's "needs you" count and items. One call for all projects, so a - // replaced sidebar does not refetch per tab. + // The sidebar thread list's one call: one project's bindings, workers and + // "needs you" items, plus the picker's per-project needs count. The requested + // project is the input, or the first by name when null; a client built from + // the previous image still validates because `reviewers` stays optional for + // one release (BB-100). stewardsSidebar: { - input: z.null(), + input: z.object({ projectId: z.string().min(1).max(100).nullable() }), output: z.object({ - projects: z.array( + /** Every stewarded project, for the picker, with its needs-you binding count. */ + projects: z.array(z.object({ projectId: z.string(), name: z.string(), needsCount: z.number() })), + /** The project the rest of the payload is for; null when nothing is stewarded. */ + projectId: z.string().nullable(), + projectStewardThreadId: z.string().nullable(), + /** + * The board's "waiting on you" items, in the sidebar's own shape: the + * same questions, with-user escalations and actionable needs, tagged + * so the app knows which write a choice makes. `count` is their sum; + * a non-actionable need is in neither the items nor the count. + */ + needs: z.object({ count: z.number(), items: z.array(sidebarNeedsItemSchema) }), + bindings: z.array( z.object({ - projectId: z.string(), - name: z.string(), - projectStewardThreadId: z.string().nullable(), + key: z.string(), + kind: z.string(), + stage: z.string().nullable(), + /** The entity's own phase, for line two; null when the binding has none (ops). */ + phase: z.string().nullable(), + threadId: z.string().nullable(), + hold: z.string().nullable(), + /** Entity keys this hold waits behind, for `held behind `. */ + holdBehind: z.array(z.string()), + blockedOn: z.string().nullable(), + needsUser: z.boolean(), + /** An open `stuck` escalation: the row is blocked (BB-76). */ + stuck: z.boolean(), + /** The status report's actor, next action and timestamp; null with no report. */ + status: z.object({ actor: z.string(), nextAction: z.string(), at: z.number() }).nullable(), + /** The newest deployment watch's state, or null with none (BB-76). */ + deployment: z.enum(DEPLOY_STATES).nullable(), + /** Notes queued for the next turn, so a quiet worker finish can be shown (BB-83). */ + pending: z.array(z.object({ text: z.string(), quiet: z.boolean().optional() })), + /** When the binding is next due a look, for `next look