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

Variants of one intent: sibling pulls grouped under one tell, and a swipe deck that records likes and dislikes in the decision ledger #998

Closed opened this in answer to
Closed without merging

scout/forge:scout/387-variants-of-one-intent-sibling-pulls-gro → main 1 commit fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
15 files changed +731 −25
src/actions/issues.ts +9 −1
@@ -83,7 +83,12 @@ export function openIssue(
8383 app: App,
8484 actor: User | undefined,
8585 repo: Repo,
86 input: { title: string; body?: string; sealed?: boolean },
86 input: {
87 title: string;
88 body?: string;
89 sealed?: boolean;
90 variantGroup?: string;
91 },
8792 ): Result<
8893 Issue,
8994 "not_found" | "unauthorized" | TitleError | "body_too_long" | MirrorError
@@ -100,6 +105,9 @@ export function openIssue(
100105 title: input.title,
101106 body: input.body ?? "",
102107 sealed: input.sealed === true,
108 ...(input.variantGroup === undefined
109 ? {}
110 : { variantGroup: input.variantGroup }),
103111 });
104112 if (!created.ok) return created;
105113 app.bus.append({
src/actions/tell.ts +54 −15
@@ -14,6 +14,7 @@ import { listRuns } 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 as newId } 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,6 +26,20 @@ 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 id when it asked for several variants; their issues, first one included. */
30 readonly group?: string;
31 readonly siblings?: readonly Issue[];
32 }
33
34 /** The most candidates one tell may ask for. */
35 export const MAX_VARIANTS = 4;
36
37 /** `variants` as a door gives it: a whole number from 1 to MAX_VARIANTS, else undefined. */
38 export function parseVariants(raw: unknown): number | undefined {
39 const n = typeof raw === "string" && raw.trim() !== "" ? Number(raw) : raw;
40 return typeof n === "number" && Number.isInteger(n) && n >= 1 && n <= MAX_VARIANTS
41 ? n
42 : undefined;
2843 }
2944
3045 export type TellError =
@@ -37,6 +52,7 @@ export type TellError =
3752 | "unverified"
3853 | TitleError
3954 | "body_too_long"
55 | "bad_variants"
4056 | MirrorError;
4157
4258 export async function tell(
@@ -44,6 +60,7 @@ export async function tell(
4460 actor: User | undefined,
4561 repo: Repo,
4662 said: string,
63 variants = 1,
4764 ): Promise<Result<Told, TellError>> {
4865 // A tell is a run: only someone who may direct the crew here says one,
4966 // and a refused tell opens nothing (`crew/direct.ts`).
@@ -55,30 +72,52 @@ export async function tell(
5572 if (!requireVerified(app, participant.value).ok) return err("unverified");
5673 const text = said.trim();
5774 if (text === "") return err("empty");
75 if (!Number.isInteger(variants) || variants < 1 || variants > MAX_VARIANTS)
76 return err("bad_variants");
77 const group = variants > 1 ? newId() : undefined;
5878 const firstLine = text.split(/\n/)[0]!.trim();
5979 const title =
6080 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;
6681 const crew = listCrewRoles(app.db, repo.id);
6782 const inFlight = new Map<string, number>();
6883 for (const r of listRuns(app.db, repo.id, { kind: "agent", limit: 50 }))
6984 if ((r.state === "running" || r.state === "queued") && r.actorId !== null)
7085 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,
86 // One issue per candidate, each handed to a builder of its own while the
87 // crew has any (the load of the ones already handed out counts), all in
88 // the one group that ties their pulls back to this tell.
89 const siblings: Issue[] = [];
90 let first: Told | undefined;
91 for (let n = 1; n <= variants; n++) {
92 const opened = openIssue(app, actor, repo, {
93 title,
94 body:
95 group === undefined
96 ? text === firstLine
97 ? ""
98 : text
99 : `${text === firstLine ? "" : `${text}\n\n`}Variant ${n} of ${variants}: one of ${variants} candidates for this tell; a person chooses among them.`,
100 ...(group === undefined ? {} : { variantGroup: group }),
101 });
102 if (!opened.ok) {
103 if (first === undefined) return opened;
104 break;
105 }
106 siblings.push(opened.value);
107 const routed = await routeIssue(app, repo, opened.value, crew, inFlight);
108 let assigned = false;
109 if (routed !== undefined) {
110 assigned = assignIssue(app, actor, repo, opened.value, routed.builder.user).ok;
111 inFlight.set(
112 routed.builder.user.id,
113 (inFlight.get(routed.builder.user.id) ?? 0) + 1,
114 );
115 }
116 first ??= { issue: opened.value, routed, assigned };
117 }
118 return ok(
119 group === undefined ? first! : { ...first!, group, siblings },
80120 );
81 return ok({ issue: opened.value, routed, assigned: assigned.ok });
82121 }
83122
84123 /** What every door says when a tell is refused for an unverified address. */
src/core/issues.ts +36 −2
@@ -62,6 +62,8 @@ export interface Issue {
6262 * (`core/sealed.ts`).
6363 */
6464 readonly sealed: boolean;
65 /** The group of sibling variants of one tell, when it asked for several (`crew/variants.ts`). */
66 readonly variantGroup: string | null;
6567 }
6668
6769 interface IssueRow {
@@ -85,6 +87,7 @@ interface IssueRow {
8587 assignee_is_agent: number | null;
8688 author_is_agent: number;
8789 sealed: number;
90 variant_group: string | null;
8891 }
8992
9093 const SELECT = `
@@ -115,6 +118,7 @@ function toIssue(row: IssueRow): Issue {
115118 assigneeIsAgent: row.assignee_is_agent === 1,
116119 authorIsAgent: row.author_is_agent === 1,
117120 sealed: row.sealed === 1,
121 variantGroup: row.variant_group,
118122 };
119123 }
120124
@@ -248,6 +252,8 @@ export interface CreateIssueInput {
248252 kind?: IssueKind;
249253 /** A security report, seen only by writers and the crew (`sealed.ts`). @default false */
250254 sealed?: boolean;
255 /** Siblings of one tell share a group id. @default none */
256 variantGroup?: string | undefined;
251257 }
252258
253259 /** Caps on free text. Generous for humans, bounded for the index and the wire. */
@@ -275,8 +281,8 @@ export function createIssue(
275281 const number = nextNumber(db, input.repoId);
276282 const newId = id();
277283 db.query(
278 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, sealed)
279 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8)`,
284 `INSERT INTO issue (id, repo_id, number, kind, title, body, author_id, sealed, variant_group)
285 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9)`,
280286 ).run(
281287 newId,
282288 input.repoId,
@@ -286,6 +292,7 @@ export function createIssue(
286292 input.body ?? "",
287293 input.authorId,
288294 input.sealed === true ? 1 : 0,
295 input.variantGroup ?? null,
289296 );
290297 return newId;
291298 });
@@ -1007,3 +1014,30 @@ export function searchIssuesVisibleTo(
10071014 repoName: row.repo_name,
10081015 }));
10091016 }
1017
1018 /** Put an issue (or the pull that is its own issue) in a variant group. */
1019 export function setVariantGroup(
1020 db: Database,
1021 issueId: string,
1022 group: string,
1023 ): void {
1024 db.query("UPDATE issue SET variant_group = ?2 WHERE id = ?1").run(
1025 issueId,
1026 group,
1027 );
1028 }
1029
1030 /** Every issue and pull of a group in this repository, oldest first. */
1031 export function listVariantGroup(
1032 db: Database,
1033 repoId: string,
1034 group: string,
1035 ): Issue[] {
1036 return db
1037 .query<
1038 IssueRow,
1039 [string, string]
1040 >(`${SELECT} WHERE issue.repo_id = ?1 AND issue.variant_group = ?2 ORDER BY issue.number`)
1041 .all(repoId, group)
1042 .map(toIssue);
1043 }
src/core/runs.ts +7 −2
@@ -60,6 +60,8 @@ export interface Run {
6060 readonly actorId: string | null;
6161 /** Why this run exists: `assigned`, `feedback`, `check_failed`, `push`, `boot`, … */
6262 readonly reason: string;
63 /** The variant group of the issue this run works, when it has one. */
64 readonly variantGroup: string | null;
6365 /** The agent session to resume for a follow-up, when there is one. */
6466 readonly sessionId: string;
6567 readonly costUsd: number;
@@ -100,6 +102,7 @@ interface RunRow {
100102 cost_usd: number;
101103 not_before: string | null;
102104 attempt: number;
105 variant_group: string | null;
103106 heartbeat_at: string | null;
104107 turns: number;
105108 sandbox_enforced: number | null;
@@ -123,6 +126,7 @@ const toRun = (r: RunRow): Run => ({
123126 summary: r.summary,
124127 actorId: r.actor_id,
125128 reason: r.reason,
129 variantGroup: r.variant_group,
126130 sessionId: r.session_id,
127131 costUsd: r.cost_usd,
128132 notBefore: r.not_before,
@@ -159,8 +163,9 @@ export function createRun(db: Database, input: CreateRunInput): Run {
159163 const runId = id();
160164 db.query(
161165 `INSERT INTO run (id, repo_id, kind, issue_id, env, commit_oid, branch, actor_id, reason,
162 not_before, attempt, summary)
163 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12)`,
166 not_before, attempt, summary, variant_group)
167 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12,
168 (SELECT variant_group FROM issue WHERE id = ?4))`,
164169 ).run(
165170 runId,
166171 input.repoId,
src/core/schema.ts +8
@@ -1540,4 +1540,12 @@ export const migrations: readonly string[] = [
15401540 SELECT RAISE(ABORT, 'a sealed repository is never public');
15411541 END;
15421542 `,
1543 // 71 — variants of one intent (#387): a tell that asked for several
1544 // candidates gives its issues, the pulls they open and their runs one
1545 // group id, so the siblings can be laid side by side and chosen among.
1546 `
1547 ALTER TABLE issue ADD COLUMN variant_group TEXT;
1548 ALTER TABLE run ADD COLUMN variant_group TEXT;
1549 CREATE INDEX issue_variant_group ON issue(variant_group) WHERE variant_group IS NOT NULL;
1550 `,
15431551 ];
src/crew/runner.ts +4
@@ -28,6 +28,7 @@ import {
2828 getIssueById,
2929 labelsForIssues,
3030 listComments,
31 setVariantGroup,
3132 type Issue,
3233 } from "../core/issues.ts";
3334 import { getPull, listPulls, type Pull } from "../core/pulls.ts";
@@ -1494,6 +1495,9 @@ async function landWork(
14941495 summary: `pushed ${branch} but could not open a pull (${String(opened.error)})`,
14951496 };
14961497 }
1498 // The pull belongs to the tell's variants when its issue does.
1499 if (issue.variantGroup !== null)
1500 setVariantGroup(app.db, opened.value.id, issue.variantGroup);
14971501 write(`opened pull #${opened.value.number}`);
14981502 return {
14991503 pushed: true,
src/crew/variants.ts added +166
@@ -0,0 +1,166 @@
1 /**
2 * Variants of one intent. A tell that asked for several candidates gave its
3 * issues and their pulls one group id; the deck lays the siblings side by
4 * side and a person answers each with a like or a dislike. Both are rows in
5 * the decision ledger (kind `lean`, answer `like` or `dislike`, about the
6 * pull). A dislike closes the pull with a one-line reason the builder reads
7 * on the thread; the last pull liked, once every sibling is answered, is the
8 * one the deck offers to ship.
9 */
10
11 import type { Database } from "bun:sqlite";
12 import type { App } from "../app.ts";
13 import { addComment, setIssueState } from "../actions/issues.ts";
14 import { latestDecision, recordDecision, resolveOpen } from "../core/decisions.ts";
15 import { getIssue, listVariantGroup, type Issue } from "../core/issues.ts";
16 import { getPull, type Pull } from "../core/pulls.ts";
17 import { canWrite, type Repo } from "../core/repos.ts";
18 import type { User } from "../core/users.ts";
19 import { err, ok, type Result } from "../kernel/result.ts";
20
21 export type Verdict = "like" | "dislike";
22
23 export const MAX_REASON = 200;
24
25 /** What the builder reads when no reason was given. */
26 export const DEFAULT_REASON = "another variant of this tell suited better";
27
28 export interface Variant {
29 readonly pull: Pull;
30 /** The newest answer given to this sibling, if any. */
31 readonly answer: Verdict | undefined;
32 /** When it was given. */
33 readonly answeredAt: string | undefined;
34 }
35
36 export interface Deck {
37 readonly group: string;
38 /** Siblings that have not opened a pull yet: the builder is still at it. */
39 readonly working: readonly Issue[];
40 readonly variants: readonly Variant[];
41 /** The first open sibling nobody has answered. */
42 readonly current: Variant | undefined;
43 /** The last one liked once every open sibling is answered. */
44 readonly ship: Variant | undefined;
45 }
46
47 /** One line of free text: no control characters, no breaks, bounded. */
48 export function oneLine(raw: string): string {
49 // eslint-disable-next-line no-control-regex
50 const line = raw.replace(/[\u0000-\u001f\u007f\s]+/g, " ").trim();
51 return line.length <= MAX_REASON ? line : `${line.slice(0, MAX_REASON - 1)}…`;
52 }
53
54 export function deckOf(db: Database, repo: Repo, group: string): Deck | undefined {
55 const members = listVariantGroup(db, repo.id, group);
56 const variants: Variant[] = [];
57 for (const m of members) {
58 if (m.kind !== "pull") continue;
59 const pull = getPull(db, repo.id, m.number);
60 if (pull === undefined) continue;
61 const d = latestDecision(db, pull.id, "lean");
62 const answer =
63 d?.answer === "like" || d?.answer === "dislike" ? d.answer : undefined;
64 variants.push({ pull, answer, answeredAt: d?.createdAt });
65 }
66 if (variants.length === 0 && members.length === 0) return undefined;
67 const working = members.filter(
68 (m) => m.kind === "issue" && m.state === "open" && !variants.some((v) => v.pull.body.includes(`Closes #${m.number}`)),
69 );
70 const live = variants.filter(
71 (v) => v.pull.state === "open" && v.pull.mergedAt === null,
72 );
73 const current = live.find((v) => v.answer === undefined);
74 const liked = live
75 .filter((v) => v.answer === "like")
76 .sort((a, b) => (a.answeredAt ?? "").localeCompare(b.answeredAt ?? ""));
77 const ship =
78 current === undefined && working.length === 0 ? liked.at(-1) : undefined;
79 return { group, working, variants, current, ship };
80 }
81
82 export type ChooseError =
83 | "not_found"
84 | "unauthorized"
85 | "forbidden"
86 | "not_variant"
87 | "not_open";
88
89 /**
90 * Answer one sibling. A like is a row in the ledger and nothing more; a
91 * dislike also closes the pull — and the tell's own issue for that
92 * candidate — and leaves the reason on both threads for the builder.
93 */
94 export function chooseVariant(
95 app: App,
96 actor: User | undefined,
97 repo: Repo,
98 pull: Pull,
99 answer: Verdict,
100 reason = "",
101 ): Result<Variant, ChooseError> {
102 if (actor === undefined) return err("unauthorized");
103 if (!canWrite(app.db, repo, actor)) return err("forbidden");
104 if (pull.variantGroup === null || pull.repoId !== repo.id)
105 return err("not_variant");
106 if (pull.state !== "open" || pull.mergedAt !== null) return err("not_open");
107 recordDecision(app.db, {
108 kind: "lean",
109 repoId: repo.id,
110 issueId: pull.id,
111 state: { group: pull.variantGroup, pull: pull.number, title: pull.title },
112 answer,
113 p: 1,
114 by: actor.username,
115 ms: 0,
116 });
117 if (answer === "dislike") {
118 const why = oneLine(reason) || DEFAULT_REASON;
119 const told = /Closes #(\d+)/.exec(pull.body);
120 const tellIssue =
121 told === null ? undefined : getIssue(app.db, repo.id, Number(told[1]));
122 // Closed first: a word on an open pull would wake its builder for a
123 // run that has no work left.
124 setIssueState(app, actor, repo, pull, "closed");
125 if (tellIssue !== undefined && tellIssue.variantGroup === pull.variantGroup) {
126 setIssueState(app, actor, repo, tellIssue, "closed", { reason: "dropped" });
127 addComment(app, actor, repo, tellIssue, `Not chosen: ${why}`);
128 }
129 addComment(app, actor, repo, pull, `Not chosen: ${why}`);
130 resolveOpen(app.db, pull.id, "lean", "closed");
131 }
132 const fresh = getPull(app.db, repo.id, pull.number) ?? pull;
133 return ok({ pull: fresh, answer, answeredAt: undefined });
134 }
135
136 /** Open decks with something still to answer, across these repositories. */
137 export function openDecks(
138 db: Database,
139 repoIds: readonly string[],
140 ): { repoId: string; group: string; number: number; title: string; at: string }[] {
141 if (repoIds.length === 0) return [];
142 return db
143 .query<
144 { repo_id: string; variant_group: string; number: number; title: string; at: string },
145 string[]
146 >(
147 `SELECT issue.repo_id, issue.variant_group, MIN(issue.number) AS number,
148 MIN(issue.title) AS title, MAX(issue.created_at) AS at
149 FROM issue JOIN pull ON pull.issue_id = issue.id
150 WHERE issue.kind = 'pull' AND issue.state = 'open' AND pull.merged_at IS NULL
151 AND issue.sealed = 0 AND issue.variant_group IS NOT NULL
152 AND issue.repo_id IN (${repoIds.map((_, n) => `?${n + 1}`).join(",")})
153 AND NOT EXISTS (SELECT 1 FROM decision d
154 WHERE d.issue_id = issue.id AND d.kind = 'lean')
155 GROUP BY issue.repo_id, issue.variant_group
156 LIMIT 50`,
157 )
158 .all(...repoIds)
159 .map((r) => ({
160 repoId: r.repo_id,
161 group: r.variant_group,
162 number: r.number,
163 title: r.title,
164 at: r.at,
165 }));
166 }
src/feed/items.ts +21
@@ -20,6 +20,7 @@ import {
2020 } from "../core/repos.ts";
2121 import { getUserById, type User } from "../core/users.ts";
2222 import { watchedBy } from "../core/watches.ts";
23 import { openDecks } from "../crew/variants.ts";
2324 import { askLinesFor } from "../web/studio/asks.ts";
2425
2526 export type FeedKind =
@@ -27,6 +28,8 @@ export type FeedKind =
2728 | "ask"
2829 | "pull"
2930 | "decision"
31 // A deck of sibling variants of one tell, waiting to be chosen among (#387).
32 | "choose"
3033 | "map"
3134 | "cost"
3235 // A post: something a person or the crew said — a tell opened, a reply
@@ -80,6 +83,8 @@ const ASK_URGENCY_FLOOR = 5;
8083 /** What a person asked to watch sits above plain news, and its landing with a failure. */
8184 const WATCH_URGENCY = 2;
8285 const LANDED_URGENCY = 4;
86 /** A deck waiting on a person: above news, below a decision that blocks. */
87 const CHOOSE_URGENCY = 3;
8388
8489 /**
8590 * What the viewer watches (`core/watches.ts`), one item for each milestone:
@@ -182,6 +187,22 @@ export function candidatesFor(
182187 });
183188 }
184189 out.push(...watchedCandidates(db, viewer, now));
190 for (const d of openDecks(db, writable.map((r) => r.id))) {
191 const repo = repos.get(d.repoId);
192 if (!repo) continue;
193 out.push({
194 id: `choose:${d.group}`,
195 kind: "choose",
196 repoId: repo.id,
197 app: slug(repo),
198 actorId: null,
199 actor: null,
200 at: d.at,
201 link: `${base(repo)}/variants/${d.group}`,
202 what: `${clip(d.title, 80)} came back in several variants: swipe to choose`,
203 urgency: CHOOSE_URGENCY,
204 });
205 }
185206 for (const d of decided) {
186207 const repo = repos.get(d.repoId);
187208 if (!repo) continue;
src/http/mcp.ts +23 −3
@@ -37,7 +37,7 @@ import { openPlan, parsePlan, PLAN_MAX } from "../actions/plan.ts";
3737 import { cancelRepoRun } from "../actions/runs.ts";
3838 import { clientRows } from "../spawn/clients.ts";
3939 import { reissueDoor, spawnDoor } from "../spawn/door.ts";
40 import { tell, toldWords, UNVERIFIED_WORDS } from "../actions/tell.ts";
40 import { parseVariants, tell, toldWords, UNVERIFIED_WORDS } from "../actions/tell.ts";
4141 import { readReturns, reportSpend } from "../actions/returns.ts";
4242 import {
4343 readUsage,
@@ -272,14 +272,28 @@ const TOOLS: readonly Tool[] = [
272272 "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.",
273273 inputSchema: {
274274 type: "object",
275 properties: { repo: REPO_ARG, text: { type: "string", maxLength: 8000 } },
275 properties: {
276 repo: REPO_ARG,
277 text: { type: "string", maxLength: 8000 },
278 variants: {
279 type: "integer",
280 minimum: 1,
281 maximum: 4,
282 description:
283 "Ask for this many candidate changes of the one tell (default 1); a person then chooses among them in a deck.",
284 },
285 },
276286 required: ["repo", "text"],
277287 },
278288 writes: true,
279289 async run(ctx, user, args) {
280290 const repo = repoArg(ctx, user, args);
281291 if (isAnswer(repo)) return repo;
282 const told = await tell(ctx.app, user, repo, str(args["text"]));
292 const variants =
293 args["variants"] === undefined ? 1 : parseVariants(args["variants"]);
294 if (variants === undefined)
295 return bad("bad_variants", "variants is a whole number from 1 to 4");
296 const told = await tell(ctx.app, user, repo, str(args["text"]), variants);
283297 if (!told.ok)
284298 return bad(
285299 told.error,
@@ -295,6 +309,12 @@ const TOOLS: readonly Tool[] = [
295309 says: toldWords(told.value),
296310 issue: told.value.issue.number,
297311 page: `${ctx.url.origin}/${repo.ownerName}/${repo.name}/issues/${told.value.issue.number}`,
312 ...(told.value.group === undefined
313 ? {}
314 : {
315 variants: told.value.siblings?.map((i) => i.number) ?? [],
316 deck: `${ctx.url.origin}/${repo.ownerName}/${repo.name}/variants/${told.value.group}`,
317 }),
298318 });
299319 },
300320 },
src/http/server.ts +3
@@ -244,6 +244,7 @@ import {
244244 crewPage,
245245 } from "../web/pages/crew.ts";
246246 import { newPullPage, newPullSubmit } from "../web/pages/pulls.ts";
247 import { deckAnswer, deckPage } from "../web/studio/deck.ts";
247248 import { changePage, pullPage } from "../web/studio/change.ts";
248249 import {
249250 pullCommentSubmit,
@@ -870,6 +871,8 @@ export function buildRouter(): Router<Handler> {
870871 // The home's composer without a script: a tell to the app it names (#599).
871872 router.add("POST", "/tell", composerSubmit);
872873 router.add("POST", "/:owner/:name/pulls/:number/ship", shipSubmit);
874 router.add("GET", "/:owner/:name/variants/:group", deckPage);
875 router.add("POST", "/:owner/:name/variants/:group/:number", deckAnswer);
873876 router.add("POST", "/:owner/:name/pulls/:number/say", saySubmit);
874877 router.add("POST", "/:owner/:name/pulls/:number/take-back", takeBackSubmit);
875878 router.add("POST", "/:owner/:name/pulls/:number/hold", holdSubmit);
src/web/studio/actions.ts +13 −2
@@ -11,7 +11,7 @@
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 { parseVariants, tell } from "../../actions/tell.ts";
1515 import { DIRECTION_NOTE } from "../../crew/direct.ts";
1616 import { mergePull } from "../../actions/pulls.ts";
1717 import { revertPull, type RevertPullError } from "../../actions/revert.ts";
@@ -52,7 +52,14 @@ async function tellFrom(
5252 tone: "danger",
5353 message: "Say something first.",
5454 });
55 const told = await tell(ctx.app, ctx.auth.user, repo, text);
55 const asked = field(form, "variants");
56 const variants = asked === "" ? 1 : parseVariants(asked);
57 if (variants === undefined)
58 return flashTo(ctx, back, {
59 tone: "danger",
60 message: "Ask for one to four variants.",
61 });
62 const told = await tell(ctx.app, ctx.auth.user, repo, text, variants);
5663 if (!told.ok)
5764 return flashTo(ctx, back, {
5865 tone: "danger",
@@ -69,6 +76,10 @@ async function tellFrom(
6976 message: `Told. Nobody is on the crew to take it yet — add someone under Settings → Crew.`,
7077 });
7178 const builder = routed.builder;
79 if (told.value.group !== undefined)
80 return flashTo(ctx, `${repoBase(repo)}/variants/${told.value.group}`, {
81 message: `${builder.user.username} is on ${variants} variants. They gather here as they come back.`,
82 });
7283 return flashTo(ctx, back, {
7384 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.`,
7485 });
src/web/studio/app.ts +8
@@ -299,6 +299,14 @@ export async function studioApp(
299299 ${builders.length === 1 ? "takes it" : "share the work"}`}
300300 </span>
301301 <span class="spacer"></span>
302 <label class="muted small"
303 >Variants
304 <select name="variants" aria-label="How many variants">
305 <option value="1" selected>1</option>
306 <option value="2">2</option>
307 <option value="3">3</option>
308 </select></label
309 >
302310 ${btn("Tell the crew", { variant: "primary", type: "submit" })}
303311 </div>
304312 </form>`;
src/web/studio/deck.ts added +211
@@ -0,0 +1,211 @@
1 /**
2 * The deck: the sibling changes one tell produced, one card each, with the
3 * look (phone and desktop) and the preview of each. Swipe right to like,
4 * left to dislike — or the arrow keys, or the two buttons; every way posts
5 * the same form. The last one liked, once every card is answered, gets Ship.
6 * The answers are rows of the decision ledger (`crew/variants.ts`).
7 */
8
9 import { getAppByRepo } from "../../core/apps.ts";
10 import { mayView } from "../../core/sealed.ts";
11 import { canWrite, type Repo } from "../../core/repos.ts";
12 import { getPull } from "../../core/pulls.ts";
13 import {
14 chooseVariant,
15 deckOf,
16 MAX_REASON,
17 type ChooseError,
18 type Variant,
19 } from "../../crew/variants.ts";
20 import type { Ctx } from "../../http/context.ts";
21 import {
22 crumbsFor,
23 loadRepo,
24 notFoundPage,
25 repoBase,
26 signInFirst,
27 } from "../chrome.ts";
28 import { field, readForm } from "../form.ts";
29 import { html, when, type Html } from "../html.ts";
30 import { flashOrJson, flashTo, page } from "../layout.ts";
31 import { btn, card } from "../ui.ts";
32 import { previewCard } from "../pages/apps.ts";
33 import { lookCard } from "../pages/looks.ts";
34 import { changeHref } from "./nouns.ts";
35
36 const GROUP = /^[0-9a-z]{20,40}$/;
37
38 /** Arrow keys and swipes answer the current card by submitting its form. */
39 const DECK_JS = `(function(){
40 var cur = document.querySelector('[data-current] form');
41 if (!cur) return;
42 function answer(v){ var b = cur.querySelector('button[value="'+v+'"]'); if (b) cur.requestSubmit(b); }
43 document.addEventListener('keydown', function(e){
44 if (e.target && /input|textarea/i.test(e.target.tagName)) return;
45 if (e.key === 'ArrowRight') answer('like');
46 else if (e.key === 'ArrowLeft') answer('dislike');
47 });
48 var card = cur.closest('[data-current]'), x0 = null;
49 card.addEventListener('pointerdown', function(e){
50 if (e.target.closest('a,button,input,form')) return;
51 x0 = e.clientX;
52 });
53 card.addEventListener('pointerup', function(e){
54 if (x0 === null) return;
55 var dx = e.clientX - x0; x0 = null;
56 if (dx > 80) answer('like'); else if (dx < -80) answer('dislike');
57 });
58 })();`;
59
60 const WORDS: Record<ChooseError, string> = {
61 not_found: "That change was not found.",
62 unauthorized: "Sign in first.",
63 forbidden: "Only someone who can write here chooses among variants.",
64 not_variant: "That change is not one of a set of variants.",
65 not_open: "That change is no longer open.",
66 };
67
68 function cardOf(
69 ctx: Ctx,
70 repo: Repo,
71 v: Variant,
72 deckHref: string,
73 isCurrent: boolean,
74 isShip: boolean,
75 ): Html {
76 const record = getAppByRepo(ctx.app.db, repo.id);
77 const base = repoBase(repo);
78 const p = v.pull;
79 const status =
80 p.mergedAt !== null
81 ? "shipped"
82 : p.state === "closed"
83 ? "closed"
84 : v.answer === "like"
85 ? "liked"
86 : v.answer === "dislike"
87 ? "disliked"
88 : "waiting for you";
89 return html`<section
90 class="deck-card"
91 ${isCurrent ? html`data-current` : null}
92 aria-label="Variant #${p.number}"
93 >
94 ${card(
95 html`<p>
96 <a href="${changeHref(base, p.number)}">${p.title}
97 <span class="number">#${p.number}</span></a>
98 <span class="badge">${status}</span>
99 </p>
100 ${record ? lookCard(ctx, repo, record, p, p.headOid) : null}
101 ${record ? previewCard(ctx, repo, p) : null}
102 ${when(isCurrent, () =>
103 html`<form method="post" action="${deckHref}/${p.number}" class="bar mt">
104 <input
105 type="text"
106 name="reason"
107 maxlength="${MAX_REASON}"
108 placeholder="Why not, in a line (the builder reads it)"
109 aria-label="Why not"
110 />
111 ${btn("Dislike ←", { size: "sm", name: "answer", value: "dislike" })}
112 ${btn("Like →", { size: "sm", variant: "primary", name: "answer", value: "like" })}
113 </form>`,
114 )}
115 ${when(isShip, () =>
116 html`<form method="post" action="${base}/pulls/${p.number}/ship" class="bar mt">
117 ${btn("Ship this one", { variant: "primary" })}
118 </form>`,
119 )}`,
120 )}
121 </section>`;
122 }
123
124 /** GET /:owner/:name/variants/:group */
125 export function deckPage(ctx: Ctx): Response {
126 const repo = loadRepo(ctx);
127 const group = ctx.params.group ?? "";
128 if (!repo || !GROUP.test(group)) return notFoundPage(ctx);
129 const deck = deckOf(ctx.app.db, repo, group);
130 const cards = deck?.variants.filter((v) =>
131 mayView(ctx.app.db, repo, v.pull, ctx.auth.user),
132 );
133 if (!deck || !cards || (cards.length === 0 && deck.working.length === 0))
134 return notFoundPage(ctx);
135 const base = repoBase(repo);
136 const href = `${base}/variants/${group}`;
137 const writer = ctx.auth.user !== undefined && canWrite(ctx.app.db, repo, ctx.auth.user);
138 const title = cards[0]?.pull.title ?? deck.working[0]!.title;
139 const body = html`<div class="issue-head"><h1>${title}</h1>
140 <p class="muted">
141 ${cards.length} variant${cards.length === 1 ? "" : "s"} of one tell${deck.working.length > 0
142 ? `, ${deck.working.length} still being built`
143 : ""}. ${writer
144 ? "Swipe right to like, left to dislike (or → and ←); the last one you like gets Ship."
145 : "Someone who can write here chooses among them."}
146 </p></div>
147 <div class="deck">
148 ${cards.map((v) =>
149 cardOf(
150 ctx,
151 repo,
152 v,
153 href,
154 writer && deck.current?.pull.id === v.pull.id,
155 writer && deck.ship?.pull.id === v.pull.id,
156 ),
157 )}
158 </div>`;
159 return page({
160 ctx,
161 title: `Choose · ${title}`,
162 crumbs: crumbsFor(repo),
163 body,
164 scriptJs: DECK_JS,
165 });
166 }
167
168 /** POST /:owner/:name/variants/:group/:number { answer: like|dislike, reason? } */
169 export async function deckAnswer(ctx: Ctx): Promise<Response> {
170 const repo = loadRepo(ctx);
171 if (!repo) return notFoundPage(ctx);
172 if (!ctx.auth.user) return signInFirst(ctx);
173 const form = await readForm(ctx, "rw");
174 if (form instanceof Response) return form;
175 const group = ctx.params.group ?? "";
176 const number = Number(ctx.params.number);
177 const pull = Number.isInteger(number)
178 ? getPull(ctx.app.db, repo.id, number)
179 : undefined;
180 if (
181 !GROUP.test(group) ||
182 !pull ||
183 pull.variantGroup !== group ||
184 !mayView(ctx.app.db, repo, pull, ctx.auth.user)
185 )
186 return notFoundPage(ctx);
187 const back = `${repoBase(repo)}/variants/${group}`;
188 const answer = field(form, "answer");
189 if (answer !== "like" && answer !== "dislike")
190 return flashTo(ctx, back, { tone: "danger", message: "Like or dislike it." });
191 const chosen = chooseVariant(
192 ctx.app,
193 ctx.auth.user,
194 repo,
195 pull,
196 answer,
197 field(form, "reason"),
198 );
199 return flashOrJson(
200 ctx,
201 back,
202 chosen.ok
203 ? {
204 message:
205 answer === "like"
206 ? `Liked #${pull.number}.`
207 : `Closed #${pull.number}; the builder has your reason.`,
208 }
209 : { tone: "danger" as const, message: WORDS[chosen.error] },
210 );
211 }
src/web/studio/feed.ts +1
@@ -32,6 +32,7 @@ const KIND_LABEL: Record<FeedItem["kind"], string> = {
3232 ask: "Needs you",
3333 pull: "Change",
3434 decision: "Decision",
35 choose: "Choose",
3536 map: "Map",
3637 cost: "Cost",
3738 milestone: "Watching",
test/variants.test.ts added +167
@@ -0,0 +1,167 @@
1 /**
2 * Variants of one intent (#387): a tell asking for several makes sibling
3 * issues in one group, their pulls inherit it, and the deck records likes and
4 * dislikes in the decision ledger; a dislike closes with a reason.
5 */
6 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
7 import { mkdtemp, rm } from "node:fs/promises";
8 import { tmpdir } from "node:os";
9 import { join } from "node:path";
10 import { createApp, type App } from "../src/app.ts";
11 import { enableApp } from "../src/actions/apps.ts";
12 import { addToCrew, createAgent } from "../src/actions/crew.ts";
13 import { getIssue, listComments, listVariantGroup, setVariantGroup } from "../src/core/issues.ts";
14 import { openPull } from "../src/actions/pulls.ts";
15 import { commitToBranch, createRepo } from "../src/actions/repos.ts";
16 import { parseVariants, tell } from "../src/actions/tell.ts";
17 import { latestDecision } from "../src/core/decisions.ts";
18 import { getPull } from "../src/core/pulls.ts";
19 import type { Repo } from "../src/core/repos.ts";
20 import { createUser, type User } from "../src/core/users.ts";
21 import { chooseVariant, deckOf, oneLine } from "../src/crew/variants.ts";
22 import { candidatesFor } from "../src/feed/items.ts";
23 import { serve, type Servers } from "../src/http/server.ts";
24
25 describe("variants of one tell", () => {
26 let dir: string;
27 let app: App;
28 let servers: Servers;
29 let alice: User;
30 let repo: Repo;
31 let cookie: string;
32 let group: string;
33 const pulls: number[] = [];
34
35 beforeAll(async () => {
36 dir = await mkdtemp(join(tmpdir(), "forge-variants-"));
37 app = createApp({ dataDir: dir, port: 0 });
38 servers = await serve(app);
39 const a = await createUser(app.db, {
40 trusted: true,
41 username: "alice",
42 email: "[email protected]",
43 password: "a-good-passphrase",
44 adminIfFirst: true,
45 });
46 if (!a.ok) throw new Error(a.error);
47 alice = a.value;
48 cookie = (
49 (
50 await fetch(`${servers.url}/signin`, {
51 method: "POST",
52 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
53 redirect: "manual",
54 })
55 ).headers.get("set-cookie") ?? ""
56 ).split(";")[0]!;
57 const made = await createRepo(app, alice, { name: "notes", visibility: "private", description: "" });
58 if (!made.ok) throw new Error(String(made.error));
59 repo = made.value;
60 const seeded = await commitToBranch(app, alice, repo, {
61 message: "Start",
62 files: [
63 { path: "package.json", content: '{"name":"notes","scripts":{"start":"bun run server.ts"}}\n' },
64 { path: "server.ts", content: "Bun.serve({ port: Number(process.env.PORT), fetch: () => new Response('ok') });\n" },
65 ],
66 });
67 if (!seeded.ok) throw new Error(JSON.stringify(seeded.error));
68 const enabled = await enableApp(app, alice, repo, { slug: "notes" });
69 if (!enabled.ok) throw new Error(String(enabled.error));
70 const scout = await createAgent(app, alice, { username: "scout" });
71 if (!scout.ok) throw new Error(String(scout.error));
72 addToCrew(app, alice, repo, "scout");
73 });
74
75 afterAll(async () => {
76 servers.stop();
77 app.close();
78 await rm(dir, { recursive: true, force: true });
79 });
80
81 test("parseVariants takes one to four and nothing else", () => {
82 expect(parseVariants("2")).toBe(2);
83 expect(parseVariants(4)).toBe(4);
84 for (const bad of ["0", "5", "1.5", "x", "", undefined, -1]) expect(parseVariants(bad)).toBeUndefined();
85 });
86
87 test("oneLine strips breaks and bounds the length", () => {
88 expect(oneLine("a\nb\u0000 c")).toBe("a b c");
89 expect(oneLine("x".repeat(500)).length).toBe(200);
90 });
91
92 test("a tell for three makes three siblings in one group; one stays alone", async () => {
93 const bad = await tell(app, alice, repo, "Tidy the page", 9);
94 expect(bad.ok).toBe(false);
95 const told = await tell(app, alice, repo, "Make the header calmer", 3);
96 if (!told.ok) throw new Error(told.error);
97 group = told.value.group!;
98 expect(told.value.siblings).toHaveLength(3);
99 expect(listVariantGroup(app.db, repo.id, group)).toHaveLength(3);
100 const single = await tell(app, alice, repo, "One only", 1);
101 if (!single.ok) throw new Error(single.error);
102 expect(single.value.group).toBeUndefined();
103 expect(getIssue(app.db, repo.id, single.value.issue.number)!.variantGroup).toBeNull();
104 for (const [i, s] of told.value.siblings!.entries()) {
105 const branch = await commitToBranch(app, alice, repo, {
106 branch: `variant-${i}`,
107 base: "main",
108 message: `Variant ${i}`,
109 files: [{ path: `V${i}.md`, content: "x\n" }],
110 });
111 if (!branch.ok) throw new Error(JSON.stringify(branch.error));
112 const p = await openPull(app, alice, repo, {
113 title: `Calmer header ${i}`,
114 body: `Closes #${s.number}`,
115 baseBranch: "main",
116 headBranch: `variant-${i}`,
117 });
118 if (!p.ok) throw new Error(String(p.error));
119 setVariantGroup(app.db, p.value.id, group);
120 pulls.push(p.value.number);
121 }
122 });
123
124 test("the deck is a feed item of type choose", () => {
125 const items = candidatesFor(app.db, alice, Date.now());
126 expect(items.some((i) => i.kind === "choose" && i.link.endsWith(`/variants/${group}`))).toBe(true);
127 });
128
129 test("the deck page shows a card per sibling and the form", async () => {
130 const res = await fetch(`${servers.url}/alice/notes/variants/${group}`, { headers: { cookie } });
131 expect(res.status).toBe(200);
132 const text = await res.text();
133 for (const n of pulls) expect(text).toContain(`Variant #${n}`);
134 expect(text).toContain('value="like"');
135 expect(text).not.toContain("Ship this one");
136 expect((await fetch(`${servers.url}/alice/notes/variants/nope`, { headers: { cookie } })).status).toBe(404);
137 });
138
139 test("likes and dislikes land in the ledger; a dislike closes with the reason; the last liked ships", async () => {
140 const [a, b, c] = pulls.map((n) => getPull(app.db, repo.id, n)!);
141 expect(chooseVariant(app, undefined, repo, a!, "like").ok).toBe(false);
142 expect(chooseVariant(app, alice, repo, a!, "like").ok).toBe(true);
143 expect(latestDecision(app.db, a!.id, "lean")?.answer).toBe("like");
144 expect(chooseVariant(app, alice, repo, b!, "dislike", "too\nbusy").ok).toBe(true);
145 expect(getPull(app.db, repo.id, b!.number)!.state).toBe("closed");
146 const said = listComments(app.db, b!.id).map((x) => x.body);
147 expect(said).toContain("Not chosen: too busy");
148 expect(deckOf(app.db, repo, group)!.ship).toBeUndefined();
149 expect(chooseVariant(app, alice, repo, c!, "like").ok).toBe(true);
150 const deck = deckOf(app.db, repo, group)!;
151 expect(deck.ship?.pull.number).toBe(c!.number);
152 expect(chooseVariant(app, alice, repo, getPull(app.db, repo.id, b!.number)!, "like").ok).toBe(false);
153 const page = await (await fetch(`${servers.url}/alice/notes/variants/${group}`, { headers: { cookie } })).text();
154 expect(page).toContain(`/pulls/${c!.number}/ship`);
155 });
156
157 test("the answer form is same-origin only", async () => {
158 const res = await fetch(`${servers.url}/alice/notes/variants/${group}/${pulls[0]}`, {
159 method: "POST",
160 headers: { cookie, origin: "http://evil.test" },
161 body: new URLSearchParams({ answer: "dislike" }),
162 redirect: "manual",
163 });
164 expect(res.status).toBeGreaterThanOrEqual(400);
165 expect(getPull(app.db, repo.id, pulls[0]!)!.state).toBe("open");
166 });
167 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs