Public: anyone can read this; the crew can change it.

A crew with builders and no reviewer says so loudly: settings, the tick line and the crew page #3521

Parked opened this in answer to
Closed without merging

mason/forge:mason/3512-a-crew-with-builders-and-no-reviewer-say → main 7 commits fork 3 threads · 3 unresolved

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
16 files changed +628 −27
README.md +16
@@ -1064,6 +1064,22 @@ row is not cut by model, and is under the agents on the page and in the
10641064 terminal's "Crew scorecard per agent" (see above). Runs from before this was recorded show as *default* /
10651065 *not recorded*; they are not backfilled.
10661066
1067 **A crew nobody reviews.** An agent's green pull lands only once a crew
1068 reviewer approves it, so a crew of builders with no reviewer lands nothing
1069 on its own: each pull waits for a person. An agent added to a crew starts
1070 as a builder, unless it is the reviewer on most of the other crews it is on:
1071 then it is added as the reviewer, and the flash, the `crew.added` event and
1072 the feed say so ("put @juniper on the crew as its reviewer"). When a crew
1073 has builders and no reviewer, the repository's settings page (Crew card)
1074 says "No reviewer: agent pulls wait for you." in one line, with a **Make
1075 <name> the reviewer** button for a repository admin: it offers a member who
1076 reviews elsewhere, else the first builder. In the terminal the palette's
1077 **Crew of a repository** command (`owner/name`, for people who can write
1078 it) lists the crew and their roles, says the same line, and `r` does what
1079 the button does, for a repository admin. The autonomy tick line says
1080 `review="no reviewer: 3 wait for a reviewer"`, counting the green agent
1081 pulls held for it.
1082
10671083 **Tell the crew from any page.** In a repository you may direct, the web palette
10681084 (`:` in the browser) has a *Tell the crew* row. With the script it opens the thread's own
10691085 comment box over the page you are on, without leaving it: `enter` sends (shift+
docs/PLANNING.md +6 −1
@@ -399,7 +399,12 @@ asked, under **Settings → Autonomy**:
399399 the same limit a failing check has; then the green head goes to the
400400 crew's _reviewer_ (`review` run: the diff, the preview, the pictures the
401401 forge took), whose approval lands it and whose change request goes back
402 to the builder as feedback; a crew with no reviewer lands it. With two
402 to the builder as feedback. A crew with builders and no reviewer lands
403 none of its agents' pulls — each waits for a person — and says so: the
404 settings page's crew card and the terminal's crew screen say so in one
405 line with one click (`r` in the terminal) to make a member the reviewer, the tick line says `review="no reviewer: N wait for a
406 reviewer"` (`crew/no_reviewer.ts`), and an agent that reviews on most of
407 its other crews is added as a reviewer, not a builder. With two
403408 reviewers, a change to sign-in, tokens, secrets, the sandbox or the HTTP
404409 edge goes to the one whose brief says it reads for security, and every
405410 other change to the other (`crew/review.ts`). Every green pull an agent
src/actions/crew.ts +49 −4
@@ -15,10 +15,13 @@ import {
1515 getAgent,
1616 getAgentByName,
1717 isCrew,
18 isCrewRole,
1819 listAgents,
1920 listCrew as queryCrew,
2021 listCrewRoles,
2122 removeCrew as deleteCrew,
23 setCrewRole,
24 usualRole,
2225 updateAgent as patchAgent,
2326 type Agent,
2427 type AgentPatch,
@@ -236,13 +239,23 @@ export function crewAsSeen(
236239 );
237240 }
238241
239 /** Put an agent on the crew: it may now read and write this repository. */
242 /**
243 * Put an agent on the crew: it may now read and write this repository. It
244 * builds, unless it is a reviewer on most of the crews it is already on:
245 * then it reviews here too (#3512), so a reviewer added without a second
246 * thought does not leave the crew with nobody to review its pulls. Only
247 * the reviewer is carried over; a second planner is a person's choice.
248 * `joinedAs` is the role this call gave it; absent when it was already on.
249 */
240250 export function addToCrew(
241251 app: App,
242252 actor: User | undefined,
243253 repo: Repo,
244254 username: string,
245 ): Result<Agent, "not_found" | "no_such_agent" | "not_an_agent" | "unverified"> {
255 ): Result<
256 { agent: Agent; joinedAs?: CrewRole },
257 "not_found" | "no_such_agent" | "not_an_agent" | "unverified"
258 > {
246259 const admin = requireRepoAdmin(app, actor, repo);
247260 if (!admin.ok) return admin;
248261 const proven = requireVerified(app, admin.value);
@@ -252,14 +265,46 @@ export function addToCrew(
252265 if (!agent)
253266 return err(getUserByName(app.db, username) ? "not_an_agent" : "no_such_agent");
254267 if (insertCrew(app.db, repo.id, agent.user.id, admin.value.id)) {
268 const role: CrewRole =
269 usualRole(app.db, agent.user.id, repo.id) === "reviewer" ? "reviewer" : "builder";
270 if (role !== "builder") setCrewRole(app.db, repo.id, agent.user.id, role);
271 // The role rides on the event, so a reviewer added as one is never a surprise.
255272 app.bus.append({
256273 kind: "crew.added",
257274 repoId: repo.id,
258275 actorId: admin.value.id,
259 payload: { agent: agent.user.username },
276 payload: { agent: agent.user.username, role },
260277 });
278 return ok({ agent, joinedAs: role });
261279 }
262 return ok(agent);
280 return ok({ agent });
281 }
282
283 /**
284 * Give a crew member a role here: the settings page's role select, its
285 * one click that makes a member the reviewer, and the terminal's crew
286 * screen all come through this one door. A repository admin's.
287 */
288 export function setCrewMemberRole(
289 app: App,
290 actor: User | undefined,
291 repo: Repo,
292 username: string,
293 role: unknown,
294 ): Result<CrewRole, "not_found" | "no_such_agent" | "invalid_role"> {
295 const admin = requireRepoAdmin(app, actor, repo);
296 if (!admin.ok) return admin;
297 if (!isCrewRole(role)) return err("invalid_role");
298 const agent = getAgentByName(app.db, username);
299 if (!agent || !setCrewRole(app.db, repo.id, agent.user.id, role))
300 return err("no_such_agent");
301 app.bus.append({
302 kind: "crew.role",
303 repoId: repo.id,
304 actorId: admin.value.id,
305 payload: { agent: agent.user.username, role },
306 });
307 return ok(role);
263308 }
264309
265310 export function removeFromCrew(
src/core/agents.ts +25
@@ -317,6 +317,31 @@ export function setCrewRole(
317317 );
318318 }
319319
320 /**
321 * The role an agent holds most often on the other crews it is on, ties
322 * going to `builder`; undefined when it is on no other crew. What a new
323 * place is given by default (#3512): a reviewer elsewhere reviews here.
324 */
325 export function usualRole(
326 db: Database,
327 userId: string,
328 exceptRepoId: string,
329 ): CrewRole | undefined {
330 const counts = db
331 .query<{ role: string; n: number }, [string, string]>(
332 `SELECT role, COUNT(*) AS n FROM repo_crew
333 WHERE user_id = ?1 AND repo_id != ?2 GROUP BY role`,
334 )
335 .all(userId, exceptRepoId);
336 let best: { role: CrewRole; n: number } | undefined;
337 for (const { role, n } of counts) {
338 const r = isCrewRole(role) ? role : "builder";
339 if (best === undefined || n > best.n || (n === best.n && r === "builder"))
340 best = { role: r, n };
341 }
342 return best?.role;
343 }
344
320345 /** The crew with each member's role, by name. */
321346 export function listCrewRoles(
322347 db: Database,
src/core/event_audience.ts +1
@@ -85,6 +85,7 @@ const READER_KINDS: ReadonlySet<string> = new Set([
8585 "agent.deleted",
8686 "crew.added",
8787 "crew.removed",
88 "crew.role",
8889 "account.model_granted",
8990 "account.model_added",
9091 "account.ceiling_set",
src/crew/autonomy.ts +6 −7
@@ -118,6 +118,7 @@ import { crewOffInPreview } from "./preview.ts";
118118 import { approvedOnHead, finishApproved, finishFields } from "./finishing.ts";
119119 import { moveRequested, tallyRequested, tallyWords } from "./requested.ts";
120120 import { reviewersOf, sendToReview, sweepReviews } from "./review.ts";
121 import { noReviewerWords } from "./no_reviewer.ts";
121122 import { lastWaits, noteWaits, tallyWaits, type Wait, waitWords } from "./waits.ts";
122123 import { bootCounts } from "../kernel/boots.ts";
123124
@@ -1170,13 +1171,10 @@ export async function autonomyTick(
11701171 const status = autonomyStatus(app, current, now);
11711172 const approved = waitWords(lastWaits(current.id));
11721173 const ready = readyNow(repoGraph(app.db, current.id, { sealed: true }));
1173 const held = heldBy(
1174 app,
1175 current,
1176 ready,
1177 listCrewRoles(app.db, current.id),
1178 activeRuns(app, current.id),
1179 );
1174 const crew = listCrewRoles(app.db, current.id);
1175 const held = heldBy(app, current, ready, crew, activeRuns(app, current.id));
1176 // Builders and no reviewer: their pulls never land on their own (#3512).
1177 const review = noReviewerWords(app, current, crew);
11801178 const boots = bootCounts(app.config.dataDir);
11811179 log.info("tick", {
11821180 repo: `${repo.ownerName}/${repo.name}`,
@@ -1198,6 +1196,7 @@ export async function autonomyTick(
11981196 : {
11991197 requested: tallyWords(tallyRequested(requested)),
12001198 }),
1199 ...(review === undefined ? {} : { review }),
12011200 // The approved pulls the last green sweep saw, and why each waits (#3055).
12021201 ...(approved === undefined ? {} : { approved }),
12031202 // What the merge queue is doing now, not what the sweep admitted (#3430).
src/crew/no_reviewer.ts added +56
@@ -0,0 +1,56 @@
1 /**
2 * A crew with builders and no reviewer (#3512). Its agents' green pulls
3 * wait for a review nobody on the crew will give (`reviewWaitsFor`, why
4 * `no reviewer`), so none of them lands on its own. That is never a quiet
5 * hold: the settings page's crew card warns and offers one click to make
6 * a member the reviewer (`studio/crew.ts`), and the tick line says
7 * `review="no reviewer: 12 wait for a reviewer"` (`autonomy.ts`).
8 */
9
10 import type { Database } from "bun:sqlite";
11 import type { App } from "../app.ts";
12 import { type Agent, type CrewRole, usualRole } from "../core/agents.ts";
13 import type { Repo } from "../core/repos.ts";
14 import { openPullsOldestFirst, reviewWaitsFor } from "./review.ts";
15
16 type Member = { readonly agent: Agent; readonly role: CrewRole };
17
18 /** Whether the crew builds and nobody on it reviews what it builds. */
19 export const lacksReviewer = (crew: readonly Member[]): boolean =>
20 crew.some((c) => c.role === "builder") && !crew.some((c) => c.role === "reviewer");
21
22 /**
23 * Who to make the reviewer: a member that reviews on most of its other
24 * crews, else the first builder. Undefined when the crew does not lack one.
25 */
26 export function reviewerCandidate(
27 db: Database,
28 repoId: string,
29 crew: readonly Member[],
30 ): Agent | undefined {
31 if (!lacksReviewer(crew)) return undefined;
32 const reviews = crew.find(
33 (c) => usualRole(db, c.agent.user.id, repoId) === "reviewer",
34 );
35 return (reviews ?? crew.find((c) => c.role === "builder"))?.agent;
36 }
37
38 /** The agent pulls open here that wait on a review because nobody on the crew reviews. */
39 export function waitingForReviewer(app: App, repo: Repo): number {
40 const pulls = openPullsOldestFirst(app.db, repo.id).map((pull) => ({ repo, pull }));
41 let n = 0;
42 for (const w of reviewWaitsFor(app.db, pulls).values())
43 if (w.person?.why === "no reviewer") n++;
44 return n;
45 }
46
47 /** The tick line's words for it: `no reviewer: 12 wait for a reviewer`; undefined when the crew has one. */

This is the tick-line source, but src/tty.ts has no equivalent. Expose lacksReviewer/reviewerCandidate there so the terminal can warn and make the reviewer.

48 export function noReviewerWords(
49 app: App,
50 repo: Repo,
51 crew: readonly Member[],
52 ): string | undefined {
53 if (!lacksReviewer(crew)) return undefined;
54 const n = waitingForReviewer(app, repo);
55 return `no reviewer: ${n} ${n === 1 ? "waits" : "wait"} for a reviewer`;
56 }
src/crew/review.ts +1 −1
@@ -510,7 +510,7 @@ export const SWEEP_SENDS = 10;
510510 const said = new Map<string, string>();
511511
512512 /** Every open pull of a repository, oldest first, paged past the list cap. */
513 function openPullsOldestFirst(db: Database, repoId: string): Pull[] {
513 export function openPullsOldestFirst(db: Database, repoId: string): Pull[] {
514514 const all: Pull[] = [];
515515 let cursor: number | undefined;
516516 for (;;) {
src/design/activity.ts +7 −1
@@ -44,10 +44,16 @@ export function eventVerb(event: ForgeEvent): string {
4444 if (kind === "crew.added" || kind === "crew.removed") {
4545 const agent = payload["agent"];
4646 const who = typeof agent === "string" ? `@${agent}` : "an agent";
47 const role = payload["role"];
4748 return kind === "crew.added"
48 ? `put ${who} on the crew`
49 ? `put ${who} on the crew${role === "reviewer" || role === "planner" ? ` as its ${role}` : ""}`
4950 : `took ${who} off the crew`;
5051 }
52 if (kind === "crew.role") {
53 const agent = payload["agent"];
54 const role = payload["role"];
55 return `made ${typeof agent === "string" ? `@${agent}` : "an agent"} a ${typeof role === "string" ? role : "member"} on the crew`;
56 }
5157 if (kind === "app.serving")
5258 return `started serving ${environment(payload["env"])}`;
5359 if (kind === "app.stopped") return `stopped ${environment(payload["env"])}`;
src/http/api.ts +1 −1
@@ -6017,7 +6017,7 @@ export function apiRoutes(router: Router<Handler>): void {
60176017 ctx.params.username ?? "",
60186018 );
60196019 if (!added.ok) return respondAccess(added.error, 422);
6020 return json(agentJson(added.value));
6020 return json(agentJson(added.value.agent));
60216021 });
60226022
60236023 router.add("DELETE", "/api/v1/repos/:owner/:name/crew/:username", (ctx) => {
src/tui/forge.ts +9
@@ -51,6 +51,7 @@ import { trustedHostsPrompt } from "./screens/trustedhosts.ts";
5151 import { flagsScreen } from "./screens/flags.ts";
5252 import { scorecardScreen } from "./screens/scorecard.ts";
5353 import { cloudScreen } from "./screens/cloud.ts";
54 import { crewPrompt } from "./screens/crew.ts";
5455 import { crewSplitsScreen } from "./screens/crewsplits.ts";
5556 import { usageScreen } from "./screens/usage.ts";
5657 import { canScreen } from "./screens/can.ts";
@@ -405,6 +406,14 @@ export function forgeCommands(session: Session): (ctx: Ctx) => Command[] {
405406 hint: "each agent's pulls landed, review rounds, red checks, reverts, time to land",
406407 run: () => ctx.push(scorecardScreen(session, ctx)),
407408 });
409 // A repository's crew and its roles, as its settings page's crew card has them (#3512).
410 if (session.user !== undefined)
411 commands.push({
412 id: "repo-crew",
413 title: "Crew of a repository",
414 hint: "who builds and who reviews; r makes a reviewer when nobody does",
415 run: () => ctx.push(crewPrompt(session, ctx, blank("Crew"))),
416 });
408417 // Proposal tokens for a repository you write, as the API and MCP have them (#2148).
409418 if (session.user !== undefined)
410419 commands.push({
src/tui/screens/crew.ts added +83
@@ -0,0 +1,83 @@
1 /**
2 * A repository's crew in the terminal, as its settings page's crew card has
3 * it: each member and its role, and — when the crew builds and nobody
4 * reviews (#3512) — the same one line, "No reviewer: agent pulls wait for
5 * you.", with `r` making the likeliest member the reviewer. The gates are
6 * the page's: the roster for who can write here (`canSeeOwnerFacts`), the
7 * key for a repository admin, and the change goes through the very action
8 * the page posts to (`setCrewMemberRole`).
9 */
10
11 import { setCrewMemberRole } from "../../actions/crew.ts";
12 import { repoByName } from "../../actions/proposal_tokens.ts";
13 import { listCrewRoles } from "../../core/agents.ts";
14 import { canAdmin, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
15 import { lacksReviewer, reviewerCandidate } from "../../crew/no_reviewer.ts";
16 import type { Ctx, Screen } from "../app/app.ts";
17 import { binding } from "../app/keys.ts";
18 import { style } from "../term/style.ts";
19 import { truncate } from "../term/width.ts";
20 import type { Session } from "../session.ts";
21 import { fill, len, split } from "../ui/layout.ts";
22 import { ListState, drawList, later, promptScreen, type ListRow } from "./common.ts";
23
24 const ROLE_WORD = { builder: "builds", reviewer: "reviews", planner: "plans" } as const;
25
26 /** Ask for `owner/name`, then show its crew; a repository you cannot write is not visible. */
27 export function crewPrompt(f: Session, ctx: Ctx, parent: Screen): Screen {
28 return promptScreen(ctx, parent, {
29 title: "Crew",
30 label: "repository, as owner/name",
31 onSubmit: (raw) => {
32 const repo = repoByName(f.app, raw.trim());
33 if (repo === undefined || !canSeeOwnerFacts(f.db, repo, f.user))
34 return "not visible to you";
35 return later(ctx, () => crewScreen(f, ctx, repo));
36 },
37 });
38 }
39
40 export function crewScreen(f: Session, ctx: Ctx, repo: Repo): Screen {
41 const state = new ListState();
42 const admin = canAdmin(f.db, repo, f.user);
43 let note = "";
44 const crew = () => listCrewRoles(f.db, repo.id);
45 const candidate = () => (admin ? reviewerCandidate(f.db, repo.id, crew()) : undefined);
46 const rows = (): ListRow[] =>
47 crew().map((c) => ({
48 title: c.agent.user.username,
49 secondary: ROLE_WORD[c.role],
50 meta: c.agent.model,
51 }));
52 const headLine = (): string => {
53 if (note !== "") return note;
54 const members = crew();
55 if (members.length === 0) return "Nobody on the crew yet.";
56 if (!lacksReviewer(members)) return "Each member and what it does here.";
57 const offered = candidate();
58 return offered === undefined
59 ? "No reviewer: agent pulls wait for you."
60 : `No reviewer: agent pulls wait for you. r makes ${offered.user.username} the reviewer.`;
61 };
62 return {
63 title: `Crew: ${repo.ownerName}/${repo.name}`,
64 keys: [binding(["j", "k"], "move cursor"), ...(admin ? [binding(["r"], "make the reviewer")] : [])],
65 render(area, s) {
66 const c = ctx.theme.c;
67 const [head, list] = split(area, "v", [len(1), fill(1)]);
68 const warn = note === "" && lacksReviewer(crew());
69 s.text(head!.x, head!.y, truncate(headLine(), head!.w), style(warn ? c.attn : c.mutedFg, c.bg), head!.x + head!.w);
70 drawList(s, list!, c, state, rows());
71 },
72 key(e) {
73 if (state.key(e, crew().length)) return true;
74 if (e.ctrl || e.alt || e.key !== "r") return false;
75 const offered = candidate();
76 if (offered === undefined) return false;
77 const set = setCrewMemberRole(f.app, f.user, repo, offered.user.username, "reviewer");
78 note = set.ok ? `${offered.user.username} is the reviewer here.` : "That role could not be set.";
79 ctx.invalidate();
80 return true;
81 },
82 };
83 }
src/web/live.ts +1 −1
@@ -302,7 +302,7 @@ export const liveClientJs = /* js */ `
302302 'label.created', 'label.updated', 'label.deleted',
303303 'run.queued', 'run.started', 'run.finished', 'app.serving',
304304 'app.created', 'app.updated', 'app.deleted', 'app.stopped',
305 'limb.moved', 'limb.replan', 'limb.replan_taken_back', 'issue.assigned', 'pull.assigned', 'crew.added', 'crew.removed',
305 'limb.moved', 'limb.replan', 'limb.replan_taken_back', 'issue.assigned', 'pull.assigned', 'crew.added', 'crew.removed', 'crew.role',
306306 ];
307307 var extra = (cfg.getAttribute('data-repos') || '').split(' ').filter(Boolean);
308308 var watching = [repo].concat(extra).filter(function (r, i, all) {
src/web/pages/settings.ts +11 −8
@@ -44,8 +44,7 @@ import {
4444 type AppEnvName,
4545 type AppEnvScope,
4646 } from "../../core/app_env.ts";
47 import { addToCrew, listCrew, removeFromCrew } from "../../actions/crew.ts";
48 import { getAgentByName, isCrewRole, setCrewRole } from "../../core/agents.ts";
47 import { addToCrew, listCrew, removeFromCrew, setCrewMemberRole } from "../../actions/crew.ts";
4948 import { isAutonomy, isDecisionsBy } from "../../core/repos.ts";
5049 import {
5150 createLabel,
@@ -1596,7 +1595,12 @@ export async function crewAdd(ctx: Ctx): Promise<Response> {
15961595 `${repoBase(repo)}/settings#crew`,
15971596 added.ok
15981597 ? {
1599 message: `${added.value.user.username} is on the crew. Assign it an issue and it starts.`,
1598 // A reviewer elsewhere is added as one (`addToCrew`): said when
1599 // this add made it so, never repeated for a member already on.
1600 message:
1601 added.value.joinedAs === "reviewer"
1602 ? `${added.value.agent.user.username} is on the crew as its reviewer, as on its other crews. Change it under Crew.`
outdated

This reads the stored role, not whether this call made the insert, so re-adding an existing reviewer repeats the "on the crew as its reviewer" flash. Fix: have addToCrew say whether it inserted.

1603 : `${added.value.agent.user.username} is on the crew. Assign it an issue and it starts.`,
16001604 }
16011605 : {
16021606 tone: "danger",
@@ -2019,16 +2023,15 @@ export async function crewRoleUpdate(ctx: Ctx): Promise<Response> {
20192023 if (gate instanceof Response) return gate;
20202024 const { repo, form } = gate;
20212025 const base = repoBase(repo);
2022 const agent = getAgentByName(ctx.app.db, ctx.params.username ?? "");
2023 const role = field(form, "role");
2024 if (!agent || !isCrewRole(role))
2026 const username = ctx.params.username ?? "";
2027 const set = setCrewMemberRole(ctx.app, ctx.auth.user, repo, username, field(form, "role"));
2028 if (!set.ok)
20252029 return flashTo(ctx, `${base}/settings#crew`, {
20262030 tone: "danger",
20272031 message: "That role could not be set.",
20282032 });
2029 setCrewRole(ctx.app.db, repo.id, agent.user.id, role);
20302033 return flashTo(ctx, `${base}/settings#crew`, {
2031 message: `${agent.user.username} is a ${role} here.`,
2034 message: `${username} is a ${set.value} here.`,
20322035 });
20332036 }
20342037
src/web/studio/crew.ts +39 −3
@@ -26,11 +26,12 @@
2626 */
2727
2828 import { listAllAgents, listCrew } from "../../actions/crew.ts";
29 import { CREW_ROLES, listCrewRoles, type CrewRole } from "../../core/agents.ts";
29 import { CREW_ROLES, listCrewRoles, type Agent, type CrewRole } from "../../core/agents.ts";
3030 import { getAppByRepo } from "../../core/apps.ts";
3131 import { canAdmin, canSeeOwnerFacts, type Repo } from "../../core/repos.ts";
3232 import { crewHasCredential } from "../../core/subscriptions.ts";
3333 import { autonomyStatus } from "../../crew/autonomy.ts";
34 import { lacksReviewer, reviewerCandidate } from "../../crew/no_reviewer.ts";
3435 import { crewOffInPreview } from "../../crew/preview.ts";
3536 import type { Ctx } from "../../http/context.ts";
3637 import { repoBase } from "../chrome.ts";
@@ -237,17 +238,49 @@ function crewCard(ctx: Ctx, repo: Repo, base: string, admin: boolean): Html {
237238 });
238239 })()
239240 : null;
241 const foot = noReviewerFoot(ctx, repo, base, admin, crew);
240242 return html`<div id="crew">
241243 ${admin ? crewReadiness(ctx) : null}
242244 ${card(html`${rows}`, {
243245 head: html`${icon("bot")}
244246 <h2>Crew</h2>`,
245247 pad: false,
248 ...(foot === null ? {} : { tone: "attn" as const, foot }),
246249 })}
247250 ${add} ${grants}
248251 </div>`;
249252 }
250253
254 /**
255 * A crew with builders and no reviewer lands none of its pulls (#3512):
256 * one line in the crew card's foot, the card in `attn`, and beside it for
257 * an admin the one click that makes the likeliest member the reviewer —
258 * posted to `crewRoleUpdate`, the route the role select uses.
259 */
260 function noReviewerFoot(
261 ctx: Ctx,
262 repo: Repo,
263 base: string,
264 admin: boolean,
265 crew: readonly { agent: Agent; role: CrewRole }[],
outdated

Hand-rolled markup. Use card() with data-tone=attn (head + body + foot) per DESIGN.md. role="alert" on a static page announces on every load, so drop it. Shorten to one line, e.g. 'No reviewer: pulls wait for you.', with the button beside it. Pillar 0 rules out a banner over the board.

266 ): Html | null {
267 if (!lacksReviewer(crew)) return null;
268 const candidate = admin ? reviewerCandidate(ctx.app.db, repo.id, crew) : undefined;
269 const line = html`<span>No reviewer: agent pulls wait for you.</span>`;
270 if (candidate === undefined)
271 return html`<p class="small" id="crew-no-reviewer">${line}</p>`;
272 return html`<form
273 class="row-fields"
274 id="crew-no-reviewer"
275 method="post"
276 action="${base}/settings/crew/${encodeURIComponent(candidate.user.username)}/role"
277 >
278 ${line}
279 <input type="hidden" name="role" value="reviewer" />
280 ${btn(`Make ${candidate.user.username} the reviewer`, { size: "sm" })}
281 </form>`;
282 }
283
251284 function autonomyCard(ctx: Ctx, repo: Repo, base: string, admin: boolean): Html {
252285 const planner = listCrewRoles(ctx.app.db, repo.id).find(
253286 (c) => c.role === "planner",
@@ -361,10 +394,13 @@ ${repo.autonomyDirection}</textarea
361394 <div class="form-actions">${btn("Save", { variant: "primary" })}</div>
362395 </form>`;
363396 // An autonomous repository with no reviewer lands nothing an agent wrote
364 // on its own: each such pull waits for a person's review (#597).
397 // on its own: each such pull waits for a person's review (#597). Said
398 // here only when the crew card has not said it already (#3512).
399 const crew = listCrewRoles(ctx.app.db, repo.id);
365400 const noReviewer =
366401 repo.autonomy === "autonomous" &&
367 !listCrewRoles(ctx.app.db, repo.id).some((c) => c.role === "reviewer")
402 !crew.some((c) => c.role === "reviewer") &&
403 !lacksReviewer(crew)
368404 ? html`<p class="small" id="no-reviewer">
369405 <b>No reviewer: agent pulls wait for you.</b> Put a reviewer on the
370406 crew under Crew to have them reviewed and land on their own.
test/crew-no-reviewer.test.ts added +317
@@ -0,0 +1,317 @@
1 /**
2 * A crew with builders and no reviewer says so (#3512): an agent that
3 * reviews elsewhere is added as a reviewer, and its event says so; the
4 * settings page's crew card says "No reviewer: agent pulls wait for you."
5 * in its foot with one click to make a member the reviewer; the terminal's
6 * crew screen says the same line with `r` for the click; and the tick line
7 * says `review="no reviewer: N wait for a reviewer"`, counting the green
8 * agent pulls held for it.
9 */
10
11 import { afterAll, afterEach, beforeAll, describe, expect, spyOn, test } from "bun:test";
12 import { mkdtemp, rm } from "node:fs/promises";
13 import { tmpdir } from "node:os";
14 import { join } from "node:path";
15 import { createApp, type App } from "../src/app.ts";
16 import { addToCrew, createAgent, setCrewMemberRole } from "../src/actions/crew.ts";
17 import { openPull } from "../src/actions/pulls.ts";
18 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
19 import { crewRole, listCrewRoles, setCrewRole, usualRole } from "../src/core/agents.ts";
20 import { getPull } from "../src/core/pulls.ts";
21 import { getRepoById, type Repo } from "../src/core/repos.ts";
22 import { claimRun, createRun, finishRun } from "../src/core/runs.ts";
23 import { createUser, getUserByName, type User } from "../src/core/users.ts";
24 import { autonomyTick } from "../src/crew/autonomy.ts";
25 import { lacksReviewer, noReviewerWords, reviewerCandidate } from "../src/crew/no_reviewer.ts";
26 import { serve, type Servers } from "../src/http/server.ts";
27 import { logLevel, setLogLevel } from "../src/kernel/log.ts";
28 import { createForgeApp } from "../src/tui/forge.ts";
29 import { headlessTerminal } from "../src/tui/term/terminal.ts";
30 import { eventVerb } from "../src/design/activity.ts";
31 import { listEvents } from "../src/core/events.ts";
32 import { settleApp } from "./helpers/tui.ts";
33
34 const PASSWORD = "a-long-reviewer-passphrase";
35
36 describe("a crew with builders and no reviewer", () => {
37 let dataDir = "";
38 let app: App;
39 let servers: Servers;
40 let alice: User;
41 let arm: Repo;
42 let elsewhere: Repo;
43 let cookie = "";
44 const level = logLevel();
45 let lines: string[] = [];
46 let spy: ReturnType<typeof spyOn> | undefined;
47 const crew = () => listCrewRoles(app.db, arm.id);
48 const settings = async () =>
49 (
50 await (await fetch(`${servers.url}/alice/arm/settings`, { headers: { cookie } })).text()
51 ).replace(/\s+/g, " ");
52
53 const greenAgentPull = async (name: string) => {
54 await commitToBranch(app, alice, arm, {
55 branch: `feature/${name}`,
56 base: "main",
57 message: name,
58 files: [{ path: `${name}.ts`, content: `export const n = "${name}";\n` }],
59 });
60 const opened = await openPull(app, alice, arm, {
61 title: name,
62 baseBranch: "main",
63 headBranch: `feature/${name}`,
64 });
65 if (!opened.ok) throw new Error(String(opened.error));
66 app.db
67 .query("UPDATE issue SET author_id = ?2 WHERE id = ?1")
68 .run(opened.value.id, getUserByName(app.db, "smith")!.id);
69 const pull = getPull(app.db, arm.id, opened.value.number)!;
70 const check = createRun(app.db, {
71 repoId: arm.id,
72 kind: "check",
73 issueId: pull.id,
74 env: `pull-${pull.number}`,
75 commitOid: pull.headOid,
76 reason: "pull",
77 });
78 claimRun(app.db, check.id);
79 finishRun(app.db, check.id, { state: "ok", summary: "check passed" });
80 };
81
82 beforeAll(async () => {
83 setLogLevel("info");
84 dataDir = await mkdtemp(join(tmpdir(), "forge-no-reviewer-"));
85 app = createApp({ dataDir, port: 0 });
86 servers = await serve(app);
87 const a = await createUser(app.db, {
88 origin: "seed",
89 username: "alice",
90 email: "[email protected]",
91 password: PASSWORD,
92 adminIfFirst: true,
93 trusted: true,
94 });
95 if (!a.ok) throw new Error("user");
96 alice = a.value;
97 // bob reads nothing of arm: the terminal's crew screen is not his.
98 await createUser(app.db, {
99 origin: "seed",
100 username: "bob",
101 email: "[email protected]",
102 password: PASSWORD,
103 trusted: true,
104 });
105 for (const name of ["arm", "elsewhere"]) {
106 const made = await createRepo(app, alice, { name, visibility: "private" });
107 if (!made.ok) throw new Error(String(made.error));
108 await commitToBranch(app, alice, made.value, {
109 message: "seed",
110 files: [{ path: "README.md", content: `# ${name}\n` }],
111 });
112 if (name === "arm") arm = made.value;
113 else elsewhere = made.value;
114 }
115 for (const name of ["smith", "juniper", "quill"])
116 await createAgent(app, alice, { username: name });
117 // juniper reviews elsewhere; quill builds there.
118 addToCrew(app, alice, elsewhere, "juniper");
119 addToCrew(app, alice, elsewhere, "quill");
120 setCrewRole(app.db, elsewhere.id, getUserByName(app.db, "juniper")!.id, "reviewer");
121 app.db
122 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2 WHERE id = ?1")
123 .run(arm.id, alice.id);
124 arm = getRepoById(app.db, arm.id)!;
125 const res = await fetch(`${servers.url}/signin`, {
126 method: "POST",
127 body: new URLSearchParams({ username: "alice", password: PASSWORD }),
128 redirect: "manual",
129 });
130 cookie = `${(res.headers.get("set-cookie") ?? "").split(";")[0]!}; forge_mode=studio`;
131 }, 30_000);
132
133 afterEach(() => {
134 spy?.mockRestore();
135 spy = undefined;
136 });
137
138 afterAll(async () => {
139 setLogLevel(level);
140 await servers.stop();
141 app.close();
142 await rm(dataDir, { recursive: true, force: true });
143 });
144
145 test("a new member builds unless it reviews elsewhere", () => {
146 expect(addToCrew(app, alice, arm, "smith").ok).toBe(true);
147 expect(addToCrew(app, alice, arm, "quill").ok).toBe(true);
148 expect(crewRole(app.db, arm.id, getUserByName(app.db, "smith")!.id)).toBe("builder");
149 expect(crewRole(app.db, arm.id, getUserByName(app.db, "quill")!.id)).toBe("builder");
150 expect(lacksReviewer(crew())).toBe(true);
151 });
152
153 test("the crew card says it in one line in its foot, and offers a builder when nobody reviews elsewhere", async () => {
154 const page = await settings();
155 expect(page).toContain('data-tone="attn"');
156 expect(page).toMatch(/<div class="card-foot"> ?<form class="row-fields" id="crew-no-reviewer"/);
157 expect(page).toContain("No reviewer: agent pulls wait for you.");
158 expect(page).toContain("Make quill the reviewer");
159 // Said once: the autonomy card does not say it again.
160 expect(page).not.toContain('id="no-reviewer"');
161 expect(page).not.toContain('role="alert"');
162 });
163
164 test("the tick line says no reviewer and counts the pulls that wait for one", async () => {
165 await greenAgentPull("one");
166 await greenAgentPull("two");
167 expect(noReviewerWords(app, arm, crew())).toBe("no reviewer: 2 wait for a reviewer");
168 lines = [];
169 spy = spyOn(console, "info").mockImplementation((line: unknown) => {
170 lines.push(String(line));
171 });
172 await autonomyTick(app);
173 const tick = lines.find(
174 (l) => l.includes("[autonomy] tick") && l.includes("repo=alice/arm"),
175 );
176 expect(tick).toContain("no reviewer: 2 wait for a reviewer");
177 });
178
179 test("a member that reviews elsewhere is added as the reviewer, and the warning goes", async () => {
180 expect(addToCrew(app, alice, arm, "juniper").ok).toBe(true);
181 expect(crewRole(app.db, arm.id, getUserByName(app.db, "juniper")!.id)).toBe("reviewer");
182 // The event says the role it was given, so the feed says it too.
183 const added = listEvents(app.db, { repoId: arm.id }).find(
184 (e) => e.kind === "crew.added" && e.payload["agent"] === "juniper",
185 )!;
186 expect(added.payload["role"]).toBe("reviewer");
187 expect(eventVerb(added)).toBe("put @juniper on the crew as its reviewer");
188 expect(lacksReviewer(crew())).toBe(false);
189 expect(noReviewerWords(app, arm, crew())).toBeUndefined();
190 expect(await settings()).not.toContain('id="crew-no-reviewer"');
191 });
192
193 test("re-adding a member already on says nothing of a role it was not just given", async () => {
194 const again = addToCrew(app, alice, arm, "juniper");
195 expect(again.ok && again.value.joinedAs).toBeUndefined();
196 const res = await fetch(`${servers.url}/alice/arm/settings/crew`, {
197 method: "POST",
198 headers: { cookie },
199 body: new URLSearchParams({ agent: "juniper" }),
200 redirect: "manual",
201 });
202 expect(res.status).toBe(303);
203 const flash = decodeURIComponent(res.headers.get("set-cookie") ?? "");
204 expect(flash).toContain("juniper is on the crew.");
205 expect(flash).not.toContain("as its reviewer");
206 });
207
208 test("a tie between the roles held elsewhere goes to builder", async () => {
209 const made = await createRepo(app, alice, { name: "third", visibility: "private" });
210 if (!made.ok) throw new Error(String(made.error));
211 // quill builds on elsewhere and reviews on third: one each.
212 const quill = getUserByName(app.db, "quill")!;
213 const joined = addToCrew(app, alice, made.value, "quill");
214 expect(joined.ok && joined.value.joinedAs).toBe("builder");
215 setCrewRole(app.db, made.value.id, quill.id, "reviewer");
216 expect(usualRole(app.db, quill.id, arm.id)).toBe("builder");
217 });
218
219 test("the one click makes the offered member the reviewer", async () => {
220 const juniper = getUserByName(app.db, "juniper")!;
221 setCrewRole(app.db, arm.id, juniper.id, "builder");
222 // juniper still reviews elsewhere: it is the one offered.
223 expect(reviewerCandidate(app.db, arm.id, crew())?.user.username).toBe("juniper");
224 expect(await settings()).toContain("Make juniper the reviewer");
225 const res = await fetch(`${servers.url}/alice/arm/settings/crew/juniper/role`, {
226 method: "POST",
227 headers: { cookie },
228 body: new URLSearchParams({ role: "reviewer" }),
229 redirect: "manual",
230 });
231 expect(res.status).toBe(303);
232 expect(crewRole(app.db, arm.id, juniper.id)).toBe("reviewer");
233 expect(await settings()).not.toContain('id="crew-no-reviewer"');
234 });
235
236 const boot = (username: string) => {
237 const { app: tui } = createForgeApp(
238 app,
239 { sshUsername: "t", remoteAddress: "127.0.0.1", user: getUserByName(app.db, username)! },
240 { terminal: headlessTerminal(140, 32), exitHooks: false },
241 );
242 tui.start();
243 const key = (k: string, ctrl = false) =>
244 tui.dispatch({ type: "key", key: k, ctrl, alt: false, shift: false });
245 return {
246 text: () => tui.screen.toText(),
247 open: async (repoName: string) => {
248 key("k", true);
249 await settleApp(tui);
250 for (const ch of "Crew of a repository") key(ch);
251 await settleApp(tui);
252 key("enter");
253 await settleApp(tui);
254 for (const ch of repoName) key(ch);
255 await settleApp(tui);
256 key("enter");
257 await settleApp(tui);
258 },
259 press: async (k: string) => {
260 key(k);
261 await settleApp(tui);
262 },
263 stop: () => tui.stop(),
264 };
265 };
266
267 test("the terminal's crew screen says it, and r makes the offered member the reviewer", async () => {
268 const juniper = getUserByName(app.db, "juniper")!;
269 setCrewRole(app.db, arm.id, juniper.id, "builder");
270 const h = boot("alice");
271 await h.open("alice/arm");
272 expect(h.text()).toContain("No reviewer: agent pulls wait for you. r makes juniper the reviewer.");
273 expect(h.text()).toContain("smith");
274 await h.press("r");
275 expect(crewRole(app.db, arm.id, juniper.id)).toBe("reviewer");
276 expect(h.text()).toContain("juniper is the reviewer here.");
277 const set = listEvents(app.db, { repoId: arm.id }).find((e) => e.kind === "crew.role")!;
278 expect(eventVerb(set)).toBe("made @juniper a reviewer on the crew");
279 h.stop();
280 });
281
282 test("the terminal's crew screen is not shown to who cannot write the repository", async () => {
283 setCrewRole(app.db, arm.id, getUserByName(app.db, "juniper")!.id, "builder");
284 const h = boot("bob");
285 await h.open("alice/arm");
286 expect(h.text()).toContain("not visible to you");
287 expect(h.text()).not.toContain("No reviewer");
288 await h.press("r");
289 expect(crewRole(app.db, arm.id, getUserByName(app.db, "juniper")!.id)).toBe("builder");
290 h.stop();
291 });
292
293 test("who is not an admin of the repository cannot set a role, by the action or the route", async () => {
294 const bob = getUserByName(app.db, "bob")!;
295 const smith = getUserByName(app.db, "smith")!;
296 const refused = setCrewMemberRole(app, bob, arm, "smith", "reviewer");
297 expect(refused.ok).toBe(false);
298 expect(!refused.ok && refused.error).toBe("not_found");
299 expect(setCrewMemberRole(app, undefined, arm, "smith", "reviewer").ok).toBe(false);
300 const signin = await fetch(`${servers.url}/signin`, {
301 method: "POST",
302 body: new URLSearchParams({ username: "bob", password: PASSWORD }),
303 redirect: "manual",
304 });
305 const bobCookie = `${(signin.headers.get("set-cookie") ?? "").split(";")[0]!}; forge_mode=studio`;
306 const before = listEvents(app.db, { repoId: arm.id }).filter((e) => e.kind === "crew.role").length;
307 const res = await fetch(`${servers.url}/alice/arm/settings/crew/smith/role`, {
308 method: "POST",
309 headers: { cookie: bobCookie },
310 body: new URLSearchParams({ role: "reviewer" }),
311 redirect: "manual",
312 });
313 expect(res.status).toBe(404);
314 expect(crewRole(app.db, arm.id, smith.id)).toBe("builder");
315 expect(listEvents(app.db, { repoId: arm.id }).filter((e) => e.kind === "crew.role").length).toBe(before);
316 });
317 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs