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

Sibling pulls of one tell share a group: `variants: n` on tell and the MCP starts n builders, and each pull and run carries the group id #1416

Closed opened this
Closed without merging

scout/forge:scout/1409-sibling-pulls-of-one-tell-share-a-group → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
13 files changed +362 −29
scripts/gate.ts +1
@@ -132,6 +132,7 @@ export const GATE: readonly string[] = [
132132 "test/forge-cloudflare.test.ts",
133133 "test/forge-cloudflare-celld.test.ts",
134134 "test/branch_tell.test.ts",
135 "test/variants.test.ts",
135136 "test/usage.test.ts",
136137 "test/tokens.test.ts",
137138 "test/credentials.test.ts",
src/actions/pulls.ts +3
@@ -85,6 +85,8 @@ export interface OpenPullInput {
8585 /** The issue id of the pull this one reverts ("Take it back"). Native
8686 * repos only — a mirror's pull is the origin's, which has no such field. */
8787 revertsIssueId?: string;
88 /** The group of sibling variants this pull belongs to (`actions/tell.ts`). */
89 variantGroup?: string;
8890 /**
8991 * A person's deliberate yes to fixing a sealed report from a branch that
9092 * is already public (this repository, or a public fork). Without it such
@@ -217,6 +219,7 @@ export async function openPull(
217219 }
218220 : {}),
219221 ...(input.revertsIssueId ? { revertsIssueId: input.revertsIssueId } : {}),
222 ...(input.variantGroup ? { variantGroup: input.variantGroup } : {}),
220223 },
221224 );
222225 if (!created.ok) return created;
src/actions/tell.ts +73 −17
@@ -10,10 +10,11 @@ import type { App } from "../app.ts";
1010 import { listCrewRoles } from "../core/agents.ts";
1111 import type { Issue, TitleError } from "../core/issues.ts";
1212 import type { Repo } from "../core/repos.ts";
13 import { listRuns } from "../core/runs.ts";
13 import { activeRunFor, listRuns, setRunGroup } from "../core/runs.ts";
1414 import type { User } from "../core/users.ts";
1515 import { mayDirectCrew } from "../crew/direct.ts";
1616 import { routeIssue, type Routed } from "../crew/route.ts";
17 import { id } from "../kernel/id.ts";
1718 import { err, ok, type Result } from "../kernel/result.ts";
1819 import { requireParticipant } from "./access.ts";
1920 import { assignIssue, openIssue, type MirrorError } from "./issues.ts";
@@ -25,10 +26,36 @@ export interface Told {
2526 readonly routed: Routed | undefined;
2627 /** Whether the builder could be assigned (and so a run will start). */
2728 readonly assigned: boolean;
29 /** The group the sibling variants share; null for a plain tell. */
30 readonly variantGroup: string | null;
31 /** Every issue opened, the first being `issue`; one for a plain tell. */
32 readonly issues: readonly Issue[];
33 }
34
35 /** Most builders one tell may start. */
36 export const VARIANTS_MAX = 4;
37
38 /** What every door says when `variants` is refused. */
39 export const VARIANTS_WORDS = `variants is a whole number from 1 to ${VARIANTS_MAX}`;
40
41 /**
42 * `variants` as a door received it (a number, a form's string, or nothing):
43 * a whole number 1–4, else undefined. Nothing at all is one.
44 */
45 export function parseVariants(raw: unknown): number | undefined {
46 if (raw === undefined || raw === null || raw === "") return 1;
47 const n =
48 typeof raw === "number"
49 ? raw
50 : typeof raw === "string" && /^[0-9]{1,3}$/.test(raw.trim())
51 ? Number(raw.trim())
52 : NaN;
53 return Number.isInteger(n) && n >= 1 && n <= VARIANTS_MAX ? n : undefined;
2854 }
2955
3056 export type TellError =
3157 | "empty"
58 | "invalid_variants"
3259 | "not_found"
3360 | "unauthorized"
3461 /** Someone who may not direct the crew here (`crew/direct.ts`). */
@@ -44,7 +71,10 @@ export async function tell(
4471 actor: User | undefined,
4572 repo: Repo,
4673 said: string,
74 variants: number = 1,
4775 ): Promise<Result<Told, TellError>> {
76 if (!Number.isInteger(variants) || variants < 1 || variants > VARIANTS_MAX)
77 return err("invalid_variants");
4878 // A tell is a run: only someone who may direct the crew here says one,
4979 // and a refused tell opens nothing (`crew/direct.ts`).
5080 const participant = requireParticipant(app, actor, repo);
@@ -58,29 +88,53 @@ export async function tell(
5888 const firstLine = text.split(/\n/)[0]!.trim();
5989 const title =
6090 firstLine.length <= 80 ? firstLine : `${firstLine.slice(0, 77).trimEnd()}…`;
61 const opened = openIssue(app, actor, repo, {
62 title,
63 body: text === firstLine ? "" : text,
64 });
65 if (!opened.ok) return opened;
91 const group = variants > 1 ? id() : null;
6692 const crew = listCrewRoles(app.db, repo.id);
6793 const inFlight = new Map<string, number>();
6894 for (const r of listRuns(app.db, repo.id, { kind: "agent", limit: 50 }))
6995 if ((r.state === "running" || r.state === "queued") && r.actorId !== null)
7096 inFlight.set(r.actorId, (inFlight.get(r.actorId) ?? 0) + 1);
71 const routed = await routeIssue(app, repo, opened.value, crew, inFlight);
72 if (routed === undefined)
73 return ok({ issue: opened.value, routed: undefined, assigned: false });
74 const assigned = assignIssue(
75 app,
76 actor,
77 repo,
78 opened.value,
79 routed.builder.user,
80 );
81 return ok({ issue: opened.value, routed, assigned: assigned.ok });
97 const told: Told[] = [];
98 for (let i = 0; i < variants; i++) {
99 const opened = openIssue(app, actor, repo, {
100 title,
101 body: text === firstLine ? "" : text,
102 });
103 if (!opened.ok) return told.length === 0 ? opened : ok(whole(told, group));
104 const routed = await routeIssue(app, repo, opened.value, crew, inFlight);
105 if (routed === undefined) {
106 told.push({ ...bare(opened.value, group), routed: undefined });
107 break;
108 }
109 const builderId = routed.builder.user.id;
110 // The next variant sees this builder as busier, so the n spread.
111 inFlight.set(builderId, (inFlight.get(builderId) ?? 0) + 1);
112 const assigned = assignIssue(app, actor, repo, opened.value, routed.builder.user);
113 // Assigning queued the run; the group is stamped on it now.
114 if (group !== null && assigned.ok) {
115 const run = activeRunFor(app.db, "agent", opened.value.id, builderId);
116 if (run !== undefined) setRunGroup(app.db, run.id, group);
117 }
118 told.push({ ...bare(opened.value, group), routed, assigned: assigned.ok });
119 }
120 return ok(whole(told, group));
82121 }
83122
123 const bare = (issue: Issue, variantGroup: string | null): Told => ({
124 issue,
125 routed: undefined,
126 assigned: false,
127 variantGroup,
128 issues: [issue],
129 });
130
131 /** The first variant's answer, carrying every issue opened. */
132 const whole = (told: readonly Told[], group: string | null): Told => ({
133 ...told[0]!,
134 variantGroup: group,
135 issues: told.map((t) => t.issue),
136 });
137
84138 /** What every door says when a tell is refused for an unverified address. */
85139 export const UNVERIFIED_WORDS = "verify your email first";
86140
@@ -90,6 +144,8 @@ export function toldWords(told: Told): string {
90144 return `Told as #${told.issue.number}. Nobody is on the crew to take it yet — add someone under Settings → Crew.`;
91145 const r = told.routed;
92146 const who = r.builder.user.username;
147 if (told.issues.length > 1)
148 return `${told.issues.length} variants told (${told.issues.map((i) => `#${i.number}`).join(", ")}); each builder opens a pull of its own.`;
93149 return told.assigned
94150 ? `${who} is on it — ${r.size} ${r.kind}${r.by === "rule" ? "" : `, ${r.by} decided in ${r.ms} ms`}.`
95151 : `Told as #${told.issue.number}, but ${who} could not take it.`;
src/core/pulls.ts +26 −2
@@ -56,6 +56,8 @@ export interface Pull extends Issue {
5656 readonly originHeadRepo: string | null;
5757 /** The pull this one reverts, when it was opened by "Take it back". */
5858 readonly revertsPullId: string | null;
59 /** The group of sibling variants of one tell; null for an ordinary pull. */
60 readonly variantGroup: string | null;
5961 }
6062
6163 interface PullRow {
@@ -68,6 +70,7 @@ interface PullRow {
6870 head_repo_id: string | null;
6971 origin_head_repo: string | null;
7072 reverts_issue_id: string | null;
73 variant_group: string | null;
7174 }
7275
7376 function fromRow(issue: Issue, row: PullRow): Pull {
@@ -84,6 +87,7 @@ function fromRow(issue: Issue, row: PullRow): Pull {
8487 crossRepo: headRepoId !== issue.repoId,
8588 originHeadRepo: row.origin_head_repo,
8689 revertsPullId: row.reverts_issue_id,
90 variantGroup: row.variant_group,
8791 };
8892 }
8993
@@ -119,6 +123,8 @@ export interface CreatePullInput {
119123 headDir?: string;
120124 /** The issue id of the pull this one reverts ("Take it back"). */
121125 revertsIssueId?: string;
126 /** The group of sibling variants this pull belongs to (`actions/tell.ts`). */
127 variantGroup?: string;
122128 }
123129
124130 /**
@@ -233,8 +239,8 @@ export async function createPull(
233239
234240 const headRepoId = input.headRepoId ?? input.repoId;
235241 db.query(
236 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id, reverts_issue_id)
237 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7)`,
242 `INSERT INTO pull (issue_id, base_branch, head_branch, base_oid, head_oid, head_repo_id, reverts_issue_id, variant_group)
243 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`,
238244 ).run(
239245 issue.value.id,
240246 input.baseBranch,
@@ -243,6 +249,7 @@ export async function createPull(
243249 headOid,
244250 headRepoId,
245251 input.revertsIssueId ?? null,
252 input.variantGroup ?? null,
246253 );
247254
248255 // A durable, fetchable ref for the PR head — the way tooling addresses it,
@@ -252,6 +259,23 @@ export async function createPull(
252259 return ok(join(db, issue.value)!);
253260 }
254261
262 /** The numbers of the other pulls in a variant group, oldest first. */
263 export function siblingNumbers(
264 db: Database,
265 repoId: string,
266 pull: Pick<Pull, "id" | "variantGroup">,
267 ): number[] {
268 if (pull.variantGroup === null) return [];
269 return db
270 .query<{ number: number }, [string, string, string]>(
271 `SELECT i.number FROM pull p JOIN issue i ON i.id = p.issue_id
272 WHERE p.variant_group = ?1 AND i.repo_id = ?2 AND i.id != ?3
273 ORDER BY i.number`,
274 )
275 .all(pull.variantGroup, repoId, pull.id)
276 .map((r) => r.number);
277 }
278
255279 export function getPull(
256280 db: Database,
257281 repoId: string,
src/core/runs.ts +9
@@ -82,9 +82,12 @@ export interface Run {
8282 /** When this deploy's environment started serving — set once, at the swap-in. */
8383 readonly servingAt: string | null;
8484 readonly finishedAt: string | null;
85 /** The group of sibling variants this run belongs to; null for an ordinary run. */
86 readonly variantGroup: string | null;
8587 }
8688
8789 interface RunRow {
90 variant_group: string | null;
8891 id: string;
8992 repo_id: string;
9093 kind: RunKind;
@@ -137,6 +140,7 @@ const toRun = (r: RunRow): Run => ({
137140 startedAt: r.started_at,
138141 servingAt: r.serving_at,
139142 finishedAt: r.finished_at,
143 variantGroup: r.variant_group,
140144 });
141145
142146 export interface CreateRunInput {
@@ -178,6 +182,11 @@ export function createRun(db: Database, input: CreateRunInput): Run {
178182 return getRun(db, runId)!;
179183 }
180184
185 /** Put a run in a group of sibling variants (`actions/tell.ts`). */
186 export function setRunGroup(db: Database, runId: string, group: string): void {
187 db.query("UPDATE run SET variant_group = ?2 WHERE id = ?1").run(runId, group);
188 }
189
181190 export function getRun(db: Database, runId: string): Run | undefined {
182191 const row = db
183192 .query<RunRow, [string]>("SELECT * FROM run WHERE id = ?1")
src/core/schema.ts +8
@@ -1578,6 +1578,14 @@ export const migrations: readonly string[] = [
15781578 expires_at TEXT NOT NULL
15791579 );
15801580 `,
1581 // variant_group — the id the sibling pulls of one tell share (#1409). Null
1582 // for an ordinary run or pull.
1583 `
1584 ALTER TABLE run ADD COLUMN variant_group TEXT;
1585 ALTER TABLE pull ADD COLUMN variant_group TEXT;
1586 CREATE INDEX run_variant_group ON run(variant_group) WHERE variant_group IS NOT NULL;
1587 CREATE INDEX pull_variant_group ON pull(variant_group) WHERE variant_group IS NOT NULL;
1588 `,
15811589 ];
15821590
15831591 /**
src/crew/runner.ts +3
@@ -1178,6 +1178,7 @@ async function work(
11781178 : `Budget reached at $${stoppedAt.toFixed(2)}; this is where it stopped.`,
11791179 write,
11801180 Object.values(grant.env),
1181 run.variantGroup,
11811182 );
11821183 return {
11831184 state: result.ok || landed.pushed ? "ok" : "failed",
@@ -1411,6 +1412,7 @@ async function landWork(
14111412 note: string | undefined,
14121413 write: (line: string) => void,
14131414 granted: readonly string[] = [],
1415 variantGroup: string | null = null,
14141416 ): Promise<{ pushed: boolean; summary: string }> {
14151417 // A model may echo a granted value into a file; the tree is scrubbed
14161418 // before the forge commits it, and the agent's own commits are searched
@@ -1555,6 +1557,7 @@ async function landWork(
15551557 baseBranch: repo.defaultBranch,
15561558 headBranch: branch,
15571559 headRepo: fork,
1560 ...(variantGroup === null ? {} : { variantGroup }),
15581561 });
15591562 if (!opened.ok) {
15601563 write(`could not open the pull: ${JSON.stringify(opened.error)}`);
src/http/api.ts +3 −1
@@ -155,6 +155,7 @@ import {
155155 import {
156156 getPull,
157157 listPulls,
158 siblingNumbers,
158159 pullDiff,
159160 pullDir,
160161 type Pull,
@@ -2689,7 +2690,7 @@ export function apiRoutes(router: Router<Handler>): void {
26892690 ...query,
26902691 ...sealedScope(ctx.app.db, repo, ctx.auth.user),
26912692 }),
2692 );
2693 ).map((p) => ({ ...p, siblings: siblingNumbers(ctx.app.db, repo.id, p) }));
26932694 return json(paged(items, query.limit, (p) => p.number));
26942695 });
26952696
@@ -2751,6 +2752,7 @@ export function apiRoutes(router: Router<Handler>): void {
27512752 const hold = getHold(ctx.app.db, found.pull.id);
27522753 return json({
27532754 ...withLabels(ctx, found.pull),
2755 siblings: siblingNumbers(ctx.app.db, found.repo.id, found.pull),
27542756 status,
27552757 diff,
27562758 hold: hold === undefined ? null : holdJson(hold),
src/http/feed.ts +22 −3
@@ -3,7 +3,12 @@
33 * are the signed-in viewer's own — there is no way to ask for another's.
44 */
55
6 import { tell, UNVERIFIED_WORDS } from "../actions/tell.ts";
6 import {
7 parseVariants,
8 tell,
9 UNVERIFIED_WORDS,
10 VARIANTS_WORDS,
11 } from "../actions/tell.ts";
712 import { DIRECTION_NOTE } from "../crew/direct.ts";
813 import { audienceFilter } from "../core/event_audience.ts";
914 import { getEvent } from "../core/events.ts";
@@ -154,20 +159,34 @@ export function feedRoutes(router: Router<Handler>): void {
154159 const text = str(input.text).trim();
155160 if (text === "" || text.length > 2000)
156161 return apiError("invalid_text", 422, "text is 1 to 2000 characters");
162 const variants = parseVariants(input.variants);
163 if (variants === undefined)
164 return apiError("invalid_variants", 422, VARIANTS_WORDS);
157165 const [owner, name, extra] = str(input.app).split("/");
158166 const repo =
159167 owner && name && extra === undefined
160168 ? getRepo(ctx.app.db, owner, name)
161169 : undefined;
162170 if (!repo || !canRead(ctx.app.db, repo, viewer)) return notFound();
163 const told = await tell(ctx.app, viewer, repo, text);
171 const told = await tell(ctx.app, viewer, repo, text, variants);
164172 if (!told.ok)
165173 return told.error === "forbidden"
166174 ? apiError("forbidden", 403, DIRECTION_NOTE)
167175 : told.error === "unverified"
168176 ? apiError("unverified", 403, UNVERIFIED_WORDS)
169177 : apiError("refused", told.error === "unauthorized" ? 403 : 422, "that could not be told");
170 return json({ issue: told.value.issue.number }, 201);
178 return json(
179 {
180 issue: told.value.issue.number,
181 ...(told.value.variantGroup === null
182 ? {}
183 : {
184 variantGroup: told.value.variantGroup,
185 issues: told.value.issues.map((i) => i.number),
186 }),
187 },
188 201,
189 );
171190 });
172191
173192 router.add("POST", "/api/v1/share", async (ctx) => {
src/http/mcp.ts +44 −4
@@ -17,6 +17,7 @@
1717 * no page. `ro` tokens read; `rw` tokens act.
1818 */
1919
20 import type { Database } from "bun:sqlite";
2021 import { mayView, mayViewId, sealedScope } from "../core/sealed.ts";
2122 import { changeCapacity, listCapacity } from "../actions/capacity.ts";
2223 import { relationOf, takeUpdates } from "../actions/forks.ts";
@@ -37,7 +38,14 @@ import { openPlan, parsePlan, PLAN_MAX } from "../actions/plan.ts";
3738 import { cancelRepoRun } from "../actions/runs.ts";
3839 import { clientRows } from "../spawn/clients.ts";
3940 import { reissueDoor, spawnDoor } from "../spawn/door.ts";
40 import { tell, toldWords, UNVERIFIED_WORDS } from "../actions/tell.ts";
41 import {
42 parseVariants,
43 tell,
44 toldWords,
45 UNVERIFIED_WORDS,
46 VARIANTS_MAX,
47 VARIANTS_WORDS,
48 } from "../actions/tell.ts";
4149 import { readReturns, reportSpend } from "../actions/returns.ts";
4250 import {
4351 readUsage,
@@ -57,7 +65,7 @@ import { parseTargets } from "./feed.ts";
5765 import { appsRuntime, envsFor } from "../apps/runtime.ts";
5866 import { getIssue, getIssueById, listOpenAgentPullsVisibleTo } from "../core/issues.ts";
5967 import { waitsForPerson } from "../crew/review.ts";
60 import { getPull } from "../core/pulls.ts";
68 import { getPull, siblingNumbers } from "../core/pulls.ts";
6169 import { repoGraph } from "../core/dependencies.ts";
6270 import { pillarView } from "../core/pillars.ts";
6371 import { getAppByRepo } from "../core/apps.ts";
@@ -125,6 +133,18 @@ import { nextStepsFor } from "../core/next-steps.ts";
125133
126134 const PROTOCOLS = ["2025-06-18", "2025-03-26", "2024-11-05"] as const;
127135 /** Who answers: the forge, at the version its build stamped. */
136 /** A pull's variant group and the other pulls in it; nothing for an ordinary pull. */
137 const variantOf = (
138 ctx: { app: { db: Database } },
139 pull: Parameters<typeof siblingNumbers>[2] & { repoId: string },
140 ) =>
141 pull.variantGroup === null
142 ? {}
143 : {
144 variantGroup: pull.variantGroup,
145 siblings: siblingNumbers(ctx.app.db, pull.repoId, pull),
146 };
147
128148 const server = () => ({ name: "forge", version: running().version });
129149
130150 type Args = Record<string, unknown>;
@@ -272,14 +292,26 @@ const TOOLS: readonly Tool[] = [
272292 "Tell an app's crew what should change. One sentence or several; the first line becomes the title. A builder is picked and starts on the crew's next tick.",
273293 inputSchema: {
274294 type: "object",
275 properties: { repo: REPO_ARG, text: { type: "string", maxLength: 8000 } },
295 properties: {
296 repo: REPO_ARG,
297 text: { type: "string", maxLength: 8000 },
298 variants: {
299 type: "integer",
300 minimum: 1,
301 maximum: VARIANTS_MAX,
302 description:
303 "How many builders try it, each in a pull of its own; the pulls share a variantGroup. Default 1.",
304 },
305 },
276306 required: ["repo", "text"],
277307 },
278308 writes: true,
279309 async run(ctx, user, args) {
280310 const repo = repoArg(ctx, user, args);
281311 if (isAnswer(repo)) return repo;
282 const told = await tell(ctx.app, user, repo, str(args["text"]));
312 const variants = parseVariants(args["variants"]);
313 if (variants === undefined) return bad("invalid_variants", VARIANTS_WORDS);
314 const told = await tell(ctx.app, user, repo, str(args["text"]), variants);
283315 if (!told.ok)
284316 return bad(
285317 told.error,
@@ -294,6 +326,12 @@ const TOOLS: readonly Tool[] = [
294326 return good({
295327 says: toldWords(told.value),
296328 issue: told.value.issue.number,
329 ...(told.value.variantGroup === null
330 ? {}
331 : {
332 variantGroup: told.value.variantGroup,
333 issues: told.value.issues.map((i) => i.number),
334 }),
297335 page: `${ctx.url.origin}/${repo.ownerName}/${repo.name}/issues/${told.value.issue.number}`,
298336 });
299337 },
@@ -534,6 +572,7 @@ const TOOLS: readonly Tool[] = [
534572 says: wait.why === "lapsed" ? "the reviewer did not answer" : "no reviewer on the crew",
535573 since: wait.since,
536574 costUsd: 0,
575 ...(pull ? variantOf(ctx, pull) : {}),
537576 },
538577 ];
539578 });
@@ -556,6 +595,7 @@ const TOOLS: readonly Tool[] = [
556595 since: r.startedAt ?? r.createdAt,
557596 // What a run costs is the owner's fact (`canSeeOwnerFacts`).
558597 costUsd: owned.has(r.repoId) ? r.costUsd : 0,
598 ...(r.variantGroup === null ? {} : { variantGroup: r.variantGroup }),
559599 };
560600 }),
561601 ]);
src/web/studio/actions.ts +12 −2
@@ -11,7 +11,12 @@
1111 import { mayView } from "../../core/sealed.ts";
1212 import { holdPull, releasePull } from "../../actions/holds.ts";
1313 import { addComment } from "../../actions/issues.ts";
14 import { tell } from "../../actions/tell.ts";
14 import {
15 parseVariants,
16 tell,
17 toldWords,
18 VARIANTS_WORDS,
19 } from "../../actions/tell.ts";
1520 import { DIRECTION_NOTE } from "../../crew/direct.ts";
1621 import { mergePull } from "../../actions/pulls.ts";
1722 import { revertPull, type RevertPullError } from "../../actions/revert.ts";
@@ -52,7 +57,10 @@ async function tellFrom(
5257 tone: "danger",
5358 message: "Say something first.",
5459 });
55 const told = await tell(ctx.app, ctx.auth.user, repo, text);
60 const variants = parseVariants(field(form, "variants"));
61 if (variants === undefined)
62 return flashTo(ctx, back, { tone: "danger", message: VARIANTS_WORDS });
63 const told = await tell(ctx.app, ctx.auth.user, repo, text, variants);
5664 if (!told.ok)
5765 return flashTo(ctx, back, {
5866 tone: "danger",
@@ -68,6 +76,8 @@ async function tellFrom(
6876 return flashTo(ctx, back, {
6977 message: `Told. Nobody is on the crew to take it yet — add someone under Settings → Crew.`,
7078 });
79 if (told.value.issues.length > 1)
80 return flashTo(ctx, back, { message: toldWords(told.value) });
7181 const builder = routed.builder;
7282 return flashTo(ctx, back, {
7383 message: `${builder.user.username} is on it — ${routed.size} ${routed.kind}${routed.by === "rule" ? "" : `, ${routed.by} decided in ${routed.ms} ms`}. Watch it work below.`,
src/web/studio/app.ts +6
@@ -299,6 +299,12 @@ export async function studioApp(
299299 ${builders.length === 1 ? "takes it" : "share the work"}`}
300300 </span>
301301 <span class="spacer"></span>
302 <select class="input" name="variants" aria-label="How many builders try it">
303 <option value="1">1 try</option>
304 <option value="2">2 tries</option>
305 <option value="3">3 tries</option>
306 <option value="4">4 tries</option>
307 </select>
302308 ${btn("Tell the crew", { variant: "primary", type: "submit" })}
303309 </div>
304310 </form>`;
test/variants.test.ts added +152
@@ -0,0 +1,152 @@
1 /**
2 * Sibling pulls of one tell (#1409): `variants: n` starts n builders whose
3 * runs and pulls share one group id; a plain tell has none.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createApp, type App } from "../src/app.ts";
10 import { addToCrew, createAgent } from "../src/actions/crew.ts";
11 import { openPull } from "../src/actions/pulls.ts";
12 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
13 import { parseVariants, tell } from "../src/actions/tell.ts";
14 import { getPull, siblingNumbers } from "../src/core/pulls.ts";
15 import type { Repo } from "../src/core/repos.ts";
16 import { listRuns } from "../src/core/runs.ts";
17 import { createUser, type User } from "../src/core/users.ts";
18 import { startCrew, type CrewHandle } from "../src/crew/dispatch.ts";
19
20 let dataDir: string;
21 let app: App;
22 let crew: CrewHandle;
23 let alice: User;
24 let repo: Repo;
25
26 const runsOf = (numbers: readonly number[]) =>
27 listRuns(app.db, repo.id, { kind: "agent" }).filter((r) =>
28 numbers.some((n) => r.issueId !== null && issueNumber(r.issueId) === n),
29 );
30 const issueNumber = (issueId: string): number | undefined =>
31 app.db
32 .query<{ number: number }, [string]>("SELECT number FROM issue WHERE id = ?1")
33 .get(issueId)?.number;
34
35 beforeAll(async () => {
36 dataDir = await mkdtemp(join(tmpdir(), "forge-variants-"));
37 app = createApp({ dataDir, port: 0 });
38 // No usable agent binary: runs are queued (and fail) but nothing is spent.
39 crew = await startCrew(app, {
40 forgeUrl: "http://localhost:0",
41 localUrl: "http://localhost:0",
42 binary: join(dataDir, "no-such-claude"),
43 concurrency: 1,
44 budgetUsd: 1,
45 runTimeoutMs: 60_000,
46 });
47 const a = await createUser(app.db, {
48 trusted: true,
49 username: "alice",
50 email: "[email protected]",
51 password: "a-good-passphrase",
52 adminIfFirst: true,
53 });
54 if (!a.ok) throw new Error(a.error);
55 alice = a.value;
56 for (const username of ["bot", "bot2"]) {
57 const b = await createAgent(app, alice, { username, brief: "Be brief." });
58 if (!b.ok) throw new Error(String(b.error));
59 }
60 const created = await createRepo(app, alice, { name: "square", visibility: "public" });
61 if (!created.ok) throw new Error(String(created.error));
62 repo = created.value;
63 const seeded = await commitToBranch(app, alice, repo, {
64 message: "Start",
65 files: [{ path: "README.md", content: "# square\n" }],
66 });
67 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
68 expect(addToCrew(app, alice, repo, "bot").ok).toBe(true);
69 expect(addToCrew(app, alice, repo, "bot2").ok).toBe(true);
70 }, 30_000);
71
72 afterAll(async () => {
73 await crew?.stop();
74 app?.close();
75 await rm(dataDir, { recursive: true, force: true });
76 });
77
78 describe("variants on a tell", () => {
79 test("variants: 2 makes two runs in one group", async () => {
80 const told = await tell(app, alice, repo, "Make it purple", 2);
81 expect(told.ok).toBe(true);
82 if (!told.ok) return;
83 const group = told.value.variantGroup;
84 expect(group).not.toBeNull();
85 expect(told.value.issues).toHaveLength(2);
86 const runs = runsOf(told.value.issues.map((i) => i.number));
87 expect(runs).toHaveLength(2);
88 expect(new Set(runs.map((r) => r.variantGroup))).toEqual(new Set([group]));
89 expect(new Set(runs.map((r) => r.issueId)).size).toBe(2);
90 });
91
92 test("a plain tell has no group", async () => {
93 for (const told of [
94 await tell(app, alice, repo, "Make it green"),
95 await tell(app, alice, repo, "Make it blue", 1),
96 ]) {
97 expect(told.ok).toBe(true);
98 if (!told.ok) return;
99 expect(told.value.variantGroup).toBeNull();
100 expect(told.value.issues).toHaveLength(1);
101 const runs = runsOf([told.value.issue.number]);
102 expect(runs).toHaveLength(1);
103 expect(runs[0]!.variantGroup).toBeNull();
104 }
105 });
106
107 test("0 and 9 are refused, and open nothing", async () => {
108 const before = listRuns(app.db, repo.id, { kind: "agent" }).length;
109 for (const n of [0, 9, 1.5, -1]) {
110 const told = await tell(app, alice, repo, "Nope", n);
111 expect(told.ok).toBe(false);
112 if (!told.ok) expect(told.error).toBe("invalid_variants");
113 }
114 expect(listRuns(app.db, repo.id, { kind: "agent" }).length).toBe(before);
115 });
116
117 test("the boundary reads numbers and form strings, nothing else", () => {
118 expect(parseVariants(undefined)).toBe(1);
119 expect(parseVariants("")).toBe(1);
120 expect(parseVariants("3")).toBe(3);
121 expect(parseVariants(4)).toBe(4);
122 for (const bad of [0, 5, 9, "0", "9", "2.5", "abc", "1e1", true, [2], {}])
123 expect(parseVariants(bad)).toBeUndefined();
124 });
125
126 test("pulls opened with a group name their siblings", async () => {
127 const group = "grp-1";
128 const numbers: number[] = [];
129 for (const branch of ["bot/1-a", "bot2/2-a", "bot/3-other"]) {
130 const c = await commitToBranch(app, alice, repo, {
131 message: branch,
132 branch,
133 files: [{ path: `${branch.replace("/", "-")}.txt`, content: branch }],
134 });
135 expect(c.ok).toBe(true);
136 const pull = await openPull(app, alice, repo, {
137 title: branch,
138 baseBranch: repo.defaultBranch,
139 headBranch: branch,
140 ...(branch === "bot/3-other" ? {} : { variantGroup: group }),
141 });
142 expect(pull.ok).toBe(true);
143 if (pull.ok) numbers.push(pull.value.number);
144 }
145 const [a, b, other] = numbers.map((n) => getPull(app.db, repo.id, n)!);
146 expect(a!.variantGroup).toBe(group);
147 expect(siblingNumbers(app.db, repo.id, a!)).toEqual([b!.number]);
148 expect(siblingNumbers(app.db, repo.id, b!)).toEqual([a!.number]);
149 expect(other!.variantGroup).toBeNull();
150 expect(siblingNumbers(app.db, repo.id, other!)).toEqual([]);
151 });
152 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs