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

Bets: the owner backs a few named wholes with a share of the week, and the crew finishes them #8723

Closed opened this
Closed without merging

mason/forge:mason/8713-bets-the-owner-backs-a-few-named-wholes → main 2 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
18 files changed +1460 −3
docs/features/bets.md added +30
@@ -0,0 +1,30 @@
1 # Bets
2
3 A bet is a name, an appetite (a percent of the crew's week), what done looks
4 like in a few plain journeys, and scopes (open issues that each finish on
5 their own), with one crew member as its lead. It is a thin record over the
6 issues: tables `bet` and `bet_scope`. Rules in `src/core/bets.ts`, actions in
7 `src/actions/bets.ts`, page in `src/web/pages/bets.ts`, MCP tool `bets`.
8
9 - **Backing.** `/<owner>/<name>/bets` shows the planner's proposals (open
10 issues in no bet, grouped by pillar, else first label, else `Other`; at most
11 5, each with up to 8 scopes). The owner backs one with a tap and a share
12 (10–50%). At most 5 bets run, and their shares total at most 100%.
13 - **Picking.** Once a repository has had a bet, builders pick only from a
14 backed bet's scopes, besides what the owner raised again and the
15 small-fixes lane (#8709, capped by `slots.smallShare`). A repository that
16 never had a bet plans as before. Order: bigger appetite first, then the
17 older bet; the same state gives the same picks.
18 - **Appetite.** A bet's spend is the run time on its scopes since it was
19 backed (or last re-backed) against its share of every slot's week. At the
20 appetite it stops; nothing extends it. The lead writes what is left in one
21 line; the owner re-backs (new share), cuts (what is open leaves the bet) or
22 ends it.
23 - **Scopes.** Each reads as figuring out or just executing (the lead sets it);
24 an open scope with no movement for 2 days reads as a raised hand.
25 - **Finishing.** When every scope is closed the bet shipped: a page with a link
26 to try, then one tap for "Feels done" or "Not yet, because…" (which stops it
27 with that line, to re-back). The changelog groups landings by bet.
28 - **A silent owner.** With bets but none backed and none changed for a day, the
29 planner's top two proposals start at 10% each, marked "not backed by the
30 owner"; the owner stops one or backs it with a tap.
src/actions/bets.ts added +334
@@ -0,0 +1,334 @@
1 /**
2 * Bets (#8713): what the owner and the lead do with them. The owner (a
3 * person who administers the repository) backs a bet with a share of the
4 * week and, when it stops at its appetite, re-backs, cuts or ends it, and
5 * says whether a finished one feels done. The lead (or any writer) records
6 * what is left, how each scope stands, and where to try the result.
7 * `settleBets` is the clock-driven part: it stops a bet at its appetite —
8 * no extension — and calls one shipped when its scopes are all closed.
9 * Reads and rules are in `core/bets.ts`.
10 */
11
12 import type { App } from "../app.ts";
13 import {
14 BET_MAX,
15 BET_NAME_MAX,
16 BET_TEXT_MAX,
17 LINE_MAX,
18 AUTO_MAX,
19 AUTO_PCT,
20 SILENT_HOURS,
21 proposals,
22 backedShare,
23 getBet,
24 listBets,
25 overAppetite,
26 runningBets,
27 scopesOf,
28 spentSeconds,
29 type Bet,
30 type ScopeMode,
31 } from "../core/bets.ts";
32 import { listCrewRoles } from "../core/agents.ts";
33 import { getIssue, type Issue } from "../core/issues.ts";
34 import { canAdmin, type Repo } from "../core/repos.ts";
35 import { getUserByName, type User } from "../core/users.ts";
36 import { id } from "../kernel/id.ts";
37 import { err, ok, type Result } from "../kernel/result.ts";
38 import { requireWriter } from "./access.ts";
39
40 export type BetError =
41 | "unauthorized"
42 | "forbidden"
43 | "not_found"
44 | "bad_name"
45 | "bad_share"
46 | "too_many"
47 | "over_week"
48 | "bad_done_when"
49 | "bad_scopes"
50 | "no_lead"
51 | "bad_line"
52 | "bad_url"
53 | "not_stopped"
54 | "no_line_yet"
55 | "not_shipped"
56 | "bad_mode"
57 | "bad_decision"
58 | "not_running";
59
60 /** What each refusal says, for every door. */
61 export const BET_WORDS: Record<BetError, string> = {
62 unauthorized: "sign in first",
63 forbidden: "that is for the repository's owner or the bet's lead",
64 not_found: "no such bet here",
65 bad_name: `a bet's name is 1 to ${BET_NAME_MAX} characters on one line`,
66 bad_share: "a share of the week is a whole number from 5 to 100",
67 too_many: `at most ${BET_MAX} bets run at once`,
68 over_week: "the running bets already hold more of the week than this leaves",
69 bad_done_when: `say what done looks like in a few plain journeys (at most ${BET_TEXT_MAX} characters)`,
70 bad_scopes: "pick 1 to 12 open issues of this repository that are in no running bet",
71 no_lead: "the crew has no member to lead it; name one",
72 bad_line: `say it in one line, at most ${LINE_MAX} characters`,
73 bad_url: "a link to try is a path on this forge or an https address",
74 not_stopped: "that bet has not stopped",
75 no_line_yet: "the lead has not written what is left yet",
76 not_shipped: "that bet is not waiting for a verdict",
77 bad_mode: "a scope is figuring out or executing",
78 bad_decision: "re-back, cut or end",
79 not_running: "that bet is not running",
80 };
81
82 const now = () => new Date();
83 const oneLine = (s: string, max: number) => s.trim().length >= 1 && s.trim().length <= max && !/[\r\n\u0000-\u001f]/.test(s.trim());
84
85 function owner(actor: User | undefined, app: App, repo: Repo): Result<User, "unauthorized" | "forbidden"> {
86 if (!actor) return err("unauthorized");
87 return actor.kind === "user" && canAdmin(app.db, repo, actor) ? ok(actor) : err("forbidden");
88 }
89
90 /** The lead, or whoever administers: those who may write a bet's lines. */
91 function leadOrOwner(app: App, actor: User | undefined, repo: Repo, bet: Bet): Result<User, BetError> {
92 const writer = requireWriter(app, actor, repo);
93 if (!writer.ok) return err(writer.error);
94 if (writer.value.id === bet.leadId || canAdmin(app.db, repo, writer.value)) return ok(writer.value);
95 return err("forbidden");
96 }
97
98 function touch(app: App, betId: string, set: string, ...values: (string | number)[]): void {
99 app.db.query(`UPDATE bet SET ${set}, updated_at = ?${values.length + 2} WHERE id = ?1`).run(betId, ...values, now().toISOString());
100 }
101
102 function eventOf(repo: Repo, actor: User | undefined, bet: Bet, extra: Record<string, unknown> = {}) {
103 return { repoId: repo.id, ...(actor === undefined ? {} : { actorId: actor.id }), payload: { bet: bet.id, name: bet.name, ...extra } };
104 }
105
106 /** The crew builder leading the fewest running bets (then by name): the same crew leads the same. */
107 function pickLead(app: App, repo: Repo): User | undefined {
108 const load = new Map<string, number>();
109 for (const b of runningBets(listBets(app.db, repo.id))) if (b.leadId !== null) load.set(b.leadId, (load.get(b.leadId) ?? 0) + 1);
110 const crew = listCrewRoles(app.db, repo.id)
111 .filter((c) => c.role === "builder")
112 .map((c) => c.agent.user)
113 .sort((a, b) => (load.get(a.id) ?? 0) - (load.get(b.id) ?? 0) || a.username.localeCompare(b.username));
114 return crew[0];
115 }
116
117 export interface BackInput {
118 readonly name: string;
119 readonly pct: number;
120 readonly doneWhen: string;
121 readonly numbers: readonly number[];
122 readonly lead?: string;
123 }
124
125 /** The owner backs a bet: a name, a share of the week, journeys, and scopes. */
126 export function backBet(app: App, actor: User | undefined, repo: Repo, input: BackInput): Result<Bet, BetError> {
127 const who = owner(actor, app, repo);
128 if (!who.ok) return err(who.error);
129 if (!oneLine(input.name, BET_NAME_MAX)) return err("bad_name");
130 if (!Number.isInteger(input.pct) || input.pct < 5 || input.pct > 100) return err("bad_share");
131 const doneWhen = input.doneWhen.trim();
132 if (doneWhen.length < 1 || doneWhen.length > BET_TEXT_MAX) return err("bad_done_when");
133 const bets = listBets(app.db, repo.id);
134 if (runningBets(bets).length >= BET_MAX) return err("too_many");
135 if (backedShare(bets) + input.pct > 100) return err("over_week");
136 const numbers = [...new Set(input.numbers)];
137 if (numbers.length < 1 || numbers.length > 12) return err("bad_scopes");
138 const taken = new Set(
139 app.db
140 .query<{ issue_id: string }, [string]>(
141 `SELECT s.issue_id FROM bet_scope s JOIN bet b ON b.id = s.bet_id WHERE b.repo_id = ?1 AND b.state IN ('backed', 'stopped', 'shipped')`,
142 )
143 .all(repo.id)
144 .map((r) => r.issue_id),
145 );
146 const issues = numbers.map((n) => (Number.isInteger(n) && n > 0 ? getIssue(app.db, repo.id, n) : undefined));
147 if (issues.some((i) => i === undefined || i.kind !== "issue" || i.state !== "open" || i.sealed || taken.has(i.id))) return err("bad_scopes");
148 const named = input.lead === undefined ? undefined : getUserByName(app.db, input.lead);
149 const lead =
150 input.lead === undefined
151 ? pickLead(app, repo)
152 : named !== undefined && named.kind === "agent" && listCrewRoles(app.db, repo.id).some((c) => c.agent.user.id === named.id)
153 ? named
154 : undefined;
155 if (lead === undefined) return err("no_lead");
156 const bet = insertBet(app, repo, { name: input.name.trim(), pct: input.pct, doneWhen, lead, issueIds: issues.map((i) => i!.id), auto: false });
157 app.bus.append({ kind: "bet.backed", ...eventOf(repo, who.value, bet, { pct: bet.appetitePct, lead: lead.username }) });
158 return ok(bet);
159 }
160
161 function insertBet(
162 app: App,
163 repo: Repo,
164 o: { name: string; pct: number; doneWhen: string; lead: User; issueIds: readonly string[]; auto: boolean },
165 ): Bet {
166 const at = now().toISOString();
167 const betId = id();
168 app.db.transaction(() => {
169 app.db
170 .query(
171 `INSERT INTO bet (id, repo_id, name, appetite_pct, done_when, lead_id, state, period_start, auto, created_at, updated_at)
172 VALUES (?1, ?2, ?3, ?4, ?5, ?6, 'backed', ?7, ?8, ?7, ?7)`,
173 )
174 .run(betId, repo.id, o.name, o.pct, o.doneWhen, o.lead.id, at, o.auto ? 1 : 0);
175 for (const issueId of o.issueIds) app.db.query("INSERT INTO bet_scope (bet_id, issue_id) VALUES (?1, ?2)").run(betId, issueId);
176 })();
177 return getBet(app.db, repo.id, betId)!;
178 }
179
180 /**
181 * The crew never sits idle waiting for a tap: when a repository has had bets
182 * but none is backed and none has changed for a day, the planner's top
183 * proposals start at a modest share, each marked as not backed by the owner.
184 * The owner stops one with a tap (`stopAuto`) or adopts it (`adoptAuto`).
185 */
186 export function startUnbacked(app: App, repo: Repo, open: () => readonly Issue[], at: Date = now()): Bet[] {
187 const bets = listBets(app.db, repo.id);
188 if (bets.length === 0 || bets.some((b) => b.state === "backed")) return [];
189 const newest = bets.reduce((m, b) => (b.updatedAt > m ? b.updatedAt : m), "");
190 if (at.getTime() - Date.parse(newest) < SILENT_HOURS * 3_600_000) return [];
191 const made: Bet[] = [];
192 for (const p of proposals(app.db, repo, open()).slice(0, AUTO_MAX)) {
193 const lead = pickLead(app, repo);
194 if (lead === undefined || runningBets(listBets(app.db, repo.id)).length >= BET_MAX || backedShare(listBets(app.db, repo.id)) + AUTO_PCT > 100) break;
195 const issueIds = p.issues.slice(0, 12).flatMap((i) => {
196 const issue = getIssue(app.db, repo.id, i.number);
197 return issue === undefined ? [] : [issue.id];
198 });
199 const doneWhen = p.issues.slice(0, 3).map((i) => `A person can: ${i.title}`).join("\n").slice(0, BET_TEXT_MAX);
200 const bet = insertBet(app, repo, { name: p.name.slice(0, BET_NAME_MAX), pct: AUTO_PCT, doneWhen, lead, issueIds, auto: true });
201 app.bus.append({ kind: "bet.backed", ...eventOf(repo, undefined, bet, { pct: AUTO_PCT, lead: lead.username, auto: true }) });
202 made.push(bet);
203 }
204 return made;
205 }
206
207 /** One tap from the owner stops a bet the planner started on its own. */
208 export function stopAuto(app: App, actor: User | undefined, repo: Repo, betId: string): Result<Bet, BetError> {
209 const who = owner(actor, app, repo);
210 if (!who.ok) return err(who.error);
211 const bet = getBet(app.db, repo.id, betId);
212 if (bet === undefined) return err("not_found");
213 if (!bet.auto || bet.state !== "backed") return err("not_running");
214 touch(app, bet.id, "state = 'ended'");
215 app.bus.append({ kind: "bet.ended", ...eventOf(repo, who.value, bet, { auto: true }) });
216 return ok(getBet(app.db, repo.id, betId)!);
217 }
218
219 /** The owner backs what the planner started: it stops being marked unbacked. */
220 export function adoptAuto(app: App, actor: User | undefined, repo: Repo, betId: string): Result<Bet, BetError> {
221 const who = owner(actor, app, repo);
222 if (!who.ok) return err(who.error);
223 const bet = getBet(app.db, repo.id, betId);
224 if (bet === undefined) return err("not_found");
225 if (!bet.auto || bet.state !== "backed") return err("not_running");
226 touch(app, bet.id, "auto = 0");
227 app.bus.append({ kind: "bet.backed", ...eventOf(repo, who.value, bet, { adopted: true }) });
228 return ok(getBet(app.db, repo.id, betId)!);
229 }
230
231 /**
232 * One turn of the clock for a repository's bets: a backed bet whose scopes
233 * are all closed has shipped; one that has used its appetite stops, and
234 * waits for its lead's line and the owner. Returns the bets that changed.
235 */
236 export function settleBets(app: App, repo: Repo, slots: number, at: Date = now()): Bet[] {
237 const changed: Bet[] = [];
238 for (const bet of listBets(app.db, repo.id)) {
239 if (bet.state !== "backed") continue;
240 const scopes = scopesOf(app.db, bet.id, at);
241 if (scopes.length > 0 && scopes.every((s) => !s.open)) {
242 touch(app, bet.id, "state = 'shipped', try_url = CASE WHEN try_url = '' THEN ?2 ELSE try_url END", `/${repo.ownerName}/${repo.name}`);
243 app.bus.append({ kind: "bet.shipped", ...eventOf(repo, undefined, bet) });
244 } else if (overAppetite(spentSeconds(app.db, bet, at), bet.appetitePct, slots)) {
245 touch(app, bet.id, "state = 'stopped'");
246 app.bus.append({ kind: "bet.stopped", ...eventOf(repo, undefined, bet, { pct: bet.appetitePct }) });
247 } else continue;
248 changed.push(getBet(app.db, repo.id, bet.id)!);
249 }
250 return changed;
251 }
252
253 /** The lead writes what is left, in one line, on a bet that stopped. */
254 export function writeLeft(app: App, actor: User | undefined, repo: Repo, betId: string, line: string): Result<Bet, BetError> {
255 const bet = getBet(app.db, repo.id, betId);
256 if (bet === undefined) return err("not_found");
257 const who = leadOrOwner(app, actor, repo, bet);
258 if (!who.ok) return err(who.error);
259 if (bet.state !== "stopped") return err("not_stopped");
260 if (!oneLine(line, LINE_MAX)) return err("bad_line");
261 touch(app, bet.id, "left_line = ?2", line.trim());
262 app.bus.append({ kind: "bet.left", ...eventOf(repo, who.value, bet, { left: line.trim() }) });
263 return ok(getBet(app.db, repo.id, betId)!);
264 }
265
266 /** A scope is figuring out or just executing: the lead says which. */
267 export function setScopeMode(app: App, actor: User | undefined, repo: Repo, betId: string, number: number, mode: string): Result<ScopeMode, BetError> {
268 const bet = getBet(app.db, repo.id, betId);
269 if (bet === undefined) return err("not_found");
270 const who = leadOrOwner(app, actor, repo, bet);
271 if (!who.ok) return err(who.error);
272 if (mode !== "figuring" && mode !== "executing") return err("bad_mode");
273 const issue = getIssue(app.db, repo.id, number);
274 const changed =
275 issue === undefined ? 0 : app.db.query("UPDATE bet_scope SET mode = ?3 WHERE bet_id = ?1 AND issue_id = ?2").run(bet.id, issue.id, mode).changes;
276 return changed === 1 ? ok(mode) : err("not_found");
277 }
278
279 /** Where to try what the bet made: a path on this forge or an https address. */
280 export function setTryLink(app: App, actor: User | undefined, repo: Repo, betId: string, url: string): Result<Bet, BetError> {
281 const bet = getBet(app.db, repo.id, betId);
282 if (bet === undefined) return err("not_found");
283 const who = leadOrOwner(app, actor, repo, bet);
284 if (!who.ok) return err(who.error);
285 const value = url.trim();
286 if (!/^(\/(?![\/\\])[^\s<>"]*|https:\/\/[^\s<>"]+)$/.test(value) || value.length > 300) return err("bad_url");
287 touch(app, bet.id, "try_url = ?2", value);
288 return ok(getBet(app.db, repo.id, betId)!);
289 }
290
291 /** The owner's word on a stopped bet: back it again with a fresh share, cut what is left, or end it. */
292 export function decideStopped(app: App, actor: User | undefined, repo: Repo, betId: string, decision: string, pct?: number): Result<Bet, BetError> {
293 const who = owner(actor, app, repo);
294 if (!who.ok) return err(who.error);
295 const bet = getBet(app.db, repo.id, betId);
296 if (bet === undefined) return err("not_found");
297 if (bet.state !== "stopped") return err("not_stopped");
298 if (bet.leftLine === "") return err("no_line_yet");
299 if (decision === "reback") {
300 const share = pct ?? bet.appetitePct;
301 if (!Number.isInteger(share) || share < 5 || share > 100) return err("bad_share");
302 if (backedShare(listBets(app.db, repo.id)) - bet.appetitePct + share > 100) return err("over_week");
303 touch(app, bet.id, "state = 'backed', appetite_pct = ?2, period_start = ?3, left_line = '', not_yet = ''", share, now().toISOString());
304 app.bus.append({ kind: "bet.reopened", ...eventOf(repo, who.value, bet, { pct: share }) });
305 } else if (decision === "cut") {
306 app.db
307 .query(`DELETE FROM bet_scope WHERE bet_id = ?1 AND issue_id IN (SELECT id FROM issue WHERE state = 'open')`)
308 .run(bet.id);
309 const rest = scopesOf(app.db, bet.id, now());
310 if (rest.length === 0) touch(app, bet.id, "state = 'ended'");
311 else touch(app, bet.id, "state = 'shipped', try_url = CASE WHEN try_url = '' THEN ?2 ELSE try_url END", `/${repo.ownerName}/${repo.name}`);
312 app.bus.append({ kind: rest.length === 0 ? "bet.ended" : "bet.shipped", ...eventOf(repo, who.value, bet, { cut: true }) });
313 } else if (decision === "end") {
314 touch(app, bet.id, "state = 'ended'");
315 app.bus.append({ kind: "bet.ended", ...eventOf(repo, who.value, bet) });
316 } else return err("bad_decision");
317 return ok(getBet(app.db, repo.id, betId)!);
318 }
319
320 /** The owner's tap on a finished bet: it feels done, or not yet and why (which goes back to stopped, to re-back). */
321 export function giveVerdict(app: App, actor: User | undefined, repo: Repo, betId: string, feelsDone: boolean, because = ""): Result<Bet, BetError> {
322 const who = owner(actor, app, repo);
323 if (!who.ok) return err(who.error);
324 const bet = getBet(app.db, repo.id, betId);
325 if (bet === undefined) return err("not_found");
326 if (bet.state !== "shipped") return err("not_shipped");
327 if (feelsDone) touch(app, bet.id, "state = 'done'");
328 else {
329 if (!oneLine(because, LINE_MAX)) return err("bad_line");
330 touch(app, bet.id, "state = 'stopped', not_yet = ?2, left_line = ?2", because.trim());
331 }
332 app.bus.append({ kind: "bet.verdict", ...eventOf(repo, who.value, bet, { feelsDone, ...(feelsDone ? {} : { because: because.trim() }) }) });
333 return ok(getBet(app.db, repo.id, betId)!);
334 }
src/core/bets.ts added +274
@@ -0,0 +1,274 @@
1 /**
2 * Bets (#8713): a few named wholes the owner backs with a share of the
3 * week. A bet is a name, an appetite (a percent of the crew's week), what
4 * done looks like in a few plain journeys, and scopes — open issues that
5 * each finish on their own — with one crew member as its lead. Only the
6 * tables `bet` and `bet_scope` are stored; the issues stay what they were.
7 *
8 * This module is the one reader and holds the rules as plain functions:
9 * what a bet has spent, whether a scope is a raised hand, which issues may
10 * start (`pickRanks`), and what the planner proposes (`proposals`). The same
11 * state gives the same answers: nothing here reads a clock but the `now` it
12 * is handed.
13 *
14 * A repository that never had a bet plans as it always did; once it has one,
15 * an issue in no running bet does not start by itself.
16 */
17
18 import type { Database } from "bun:sqlite";
19 import { labelsForIssues, type Issue } from "./issues.ts";
20 import { isStructural, pillarsOf, servedBy } from "./pillars.ts";
21 import type { Repo } from "./repos.ts";
22
23 /** Bets running at once. */
24 export const BET_MAX = 5;
25 export const BET_NAME_MAX = 80;
26 export const BET_TEXT_MAX = 1000;
27 export const LINE_MAX = 200;
28 /** Without a bet backed or changed for this long, the planner's top proposals start on their own. */
29 export const SILENT_HOURS = 24;
30 /** The modest share an unbacked bet starts at, and how many start at once. */
31 export const AUTO_PCT = 10;
32 export const AUTO_MAX = 2;
33 /** A scope that has not moved in this many days is a raised hand. */
34 export const HAND_DAYS = 2;
35 const DAY_MS = 86_400_000;
36
37 export type BetState = "backed" | "stopped" | "shipped" | "done" | "ended";
38 export type ScopeMode = "figuring" | "executing";
39
40 export interface Bet {
41 readonly id: string;
42 readonly repoId: string;
43 readonly name: string;
44 readonly appetitePct: number;
45 readonly doneWhen: string;
46 readonly leadId: string | null;
47 readonly state: BetState;
48 readonly periodStart: string;
49 readonly leftLine: string;
50 readonly tryUrl: string;
51 readonly notYet: string;
52 /** Started by the planner after a silent day, not backed by the owner. */
53 readonly auto: boolean;
54 readonly createdAt: string;
55 readonly updatedAt: string;
56 }
57
58 export interface Scope {
59 readonly issueId: string;
60 readonly number: number;
61 readonly title: string;
62 readonly open: boolean;
63 readonly mode: ScopeMode;
64 readonly updatedAt: string;
65 /** Open and not moved for {@link HAND_DAYS}: it says so without a log. */
66 readonly hand: boolean;
67 }
68
69 interface BetRow {
70 id: string;
71 repo_id: string;
72 name: string;
73 appetite_pct: number;
74 done_when: string;
75 lead_id: string | null;
76 state: BetState;
77 period_start: string;
78 left_line: string;
79 try_url: string;
80 not_yet: string;
81 auto: number;
82 created_at: string;
83 updated_at: string;
84 }
85
86 const betOf = (r: BetRow): Bet => ({
87 id: r.id,
88 repoId: r.repo_id,
89 name: r.name,
90 appetitePct: r.appetite_pct,
91 doneWhen: r.done_when,
92 leadId: r.lead_id,
93 state: r.state,
94 periodStart: r.period_start,
95 leftLine: r.left_line,
96 tryUrl: r.try_url,
97 notYet: r.not_yet,
98 auto: r.auto === 1,
99 createdAt: r.created_at,
100 updatedAt: r.updated_at,
101 });
102
103 /** The crew's week in seconds: every slot, seven days. */
104 export function weekSeconds(slots: number): number {
105 return Math.max(0, slots) * 7 * 86_400;
106 }
107
108 /** What `pct` of the week allows, in seconds of run time. */
109 export function allowanceSeconds(pct: number, slots: number): number {
110 return Math.round((weekSeconds(slots) * pct) / 100);
111 }
112
113 /** Whether the appetite is used up: no automatic extension, ever. */
114 export function overAppetite(spentSeconds: number, pct: number, slots: number): boolean {
115 return spentSeconds >= allowanceSeconds(pct, slots);
116 }
117
118 /** An open scope that has not moved for {@link HAND_DAYS}. */
119 export function isRaisedHand(open: boolean, updatedAt: string, now: Date): boolean {
120 return open && now.getTime() - Date.parse(updatedAt) >= HAND_DAYS * DAY_MS;
121 }
122
123 /** `3 of 5 scopes done`, the one line a bet reads as. */
124 export function progressWords(scopes: readonly Pick<Scope, "open">[]): string {
125 const done = scopes.filter((s) => !s.open).length;
126 return `${done} of ${scopes.length} ${scopes.length === 1 ? "scope" : "scopes"} done`;
127 }
128
129 /** The bets of a repository, oldest first. */
130 export function listBets(db: Database, repoId: string): Bet[] {
131 return db
132 .query<BetRow, [string]>("SELECT * FROM bet WHERE repo_id = ?1 ORDER BY created_at, id")
133 .all(repoId)
134 .map(betOf);
135 }
136
137 export function getBet(db: Database, repoId: string, id: string): Bet | undefined {
138 const row = db.query<BetRow, [string, string]>("SELECT * FROM bet WHERE repo_id = ?1 AND id = ?2").get(repoId, id);
139 return row === null ? undefined : betOf(row);
140 }
141
142 /** Bets that hold a place among the five: backed, and stopped ones waiting for the owner. */
143 export function runningBets(bets: readonly Bet[]): Bet[] {
144 return bets.filter((b) => b.state === "backed" || b.state === "stopped" || b.state === "shipped");
145 }
146
147 /** The share of the week already promised to running bets. */
148 export function backedShare(bets: readonly Bet[]): number {
149 return runningBets(bets).reduce((sum, b) => sum + b.appetitePct, 0);
150 }
151
152 export function scopesOf(db: Database, betId: string, now: Date): Scope[] {
153 return db
154 .query<
155 { issue_id: string; number: number; title: string; state: string; updated_at: string; mode: ScopeMode },
156 [string]
157 >(
158 `SELECT s.issue_id, i.number, i.title, i.state, i.updated_at, s.mode
159 FROM bet_scope s JOIN issue i ON i.id = s.issue_id
160 WHERE s.bet_id = ?1 ORDER BY i.number`,
161 )
162 .all(betId)
163 .map((r) => ({
164 issueId: r.issue_id,
165 number: r.number,
166 title: r.title,
167 open: r.state === "open",
168 mode: r.mode,
169 updatedAt: r.updated_at,
170 hand: isRaisedHand(r.state === "open", r.updated_at, now),
171 }));
172 }
173
174 /** Seconds of agent run time spent on a bet's scopes since its period began. */
175 export function spentSeconds(db: Database, bet: Bet, now: Date): number {
176 const row = db
177 .query<{ s: number | null }, [string, string, string]>(
178 `SELECT SUM(MAX(0, (julianday(COALESCE(r.finished_at, ?3)) - julianday(r.started_at)) * 86400)) AS s
179 FROM run r JOIN bet_scope s ON s.issue_id = r.issue_id
180 WHERE s.bet_id = ?1 AND r.kind = 'agent' AND r.started_at IS NOT NULL
181 AND COALESCE(r.finished_at, ?3) > ?2`,
182 )
183 .get(bet.id, bet.periodStart, now.toISOString());
184 return Math.round(row?.s ?? 0);
185 }
186
187 /** Whether this repository ever had a bet: the switch that keeps issues in no bet from starting. */
188 export function hasBets(db: Database, repoId: string): boolean {
189 return db.query("SELECT 1 FROM bet WHERE repo_id = ?1 LIMIT 1").get(repoId) !== null;
190 }
191
192 /**
193 * The issues that may start, each with its place in the pick order: those
194 * in a backed bet, bigger appetite first, then the older bet. Stopped,
195 * shipped, done and ended bets start nothing.
196 */
197 export function pickRanks(db: Database, repoId: string): Map<string, number> {
198 const rows = db
199 .query<{ issue_id: string }, [string]>(
200 `SELECT s.issue_id FROM bet b JOIN bet_scope s ON s.bet_id = b.id
201 WHERE b.repo_id = ?1 AND b.state = 'backed'
202 ORDER BY b.appetite_pct DESC, b.created_at, b.id, s.issue_id`,
203 )
204 .all(repoId);
205 const out = new Map<string, number>();
206 for (const r of rows) if (!out.has(r.issue_id)) out.set(r.issue_id, out.size);
207 return out;
208 }
209
210 /**
211 * The ready list after bets: kept as it is where the repository has no bets;
212 * else only what is in a backed bet (or exempt — the small-fixes lane and
213 * what the owner raised), the bets' work first in bet order, the rest after,
214 * each keeping its place.
215 */
216 export function betOrder<T>(
217 ready: readonly T[],
218 idOf: (t: T) => string,
219 ranks: ReadonlyMap<string, number>,
220 active: boolean,
221 exempt: (t: T) => boolean,
222 ): T[] {
223 if (!active) return [...ready];
224 const kept = ready.map((t, at) => ({ t, at, rank: ranks.get(idOf(t)) })).filter((x) => x.rank !== undefined || exempt(x.t));
225 return kept.sort((a, b) => (a.rank ?? Infinity) - (b.rank ?? Infinity) || a.at - b.at).map((x) => x.t);
226 }
227
228 export interface Proposal {
229 readonly theme: string;
230 readonly name: string;
231 readonly issues: readonly { readonly number: number; readonly title: string }[];
232 }
233
234 /** Proposals offered at once, and scopes listed in each: one screen. */
235 export const PROPOSALS_MAX = 5;
236 export const PROPOSAL_SCOPES = 8;
237
238 /**
239 * Themes from open work: open issues in no live bet, grouped by the pillar
240 * they serve, else their first label, else `Other`; the biggest groups first
241 * (ties by name), at most {@link PROPOSALS_MAX}.
242 */
243 export function proposals(db: Database, repo: Repo, open: readonly Issue[]): Proposal[] {
244 const taken = new Set(
245 db
246 .query<{ issue_id: string }, [string]>(
247 `SELECT s.issue_id FROM bet_scope s JOIN bet b ON b.id = s.bet_id
248 WHERE b.repo_id = ?1 AND b.state IN ('backed', 'stopped', 'shipped')`,
249 )
250 .all(repo.id)
251 .map((r) => r.issue_id),
252 );
253 const set = pillarsOf(db, repo);
254 const free = open.filter((i) => i.kind === "issue" && i.state === "open" && !taken.has(i.id) && !isStructural(set, i.id));
255 if (free.length === 0) return [];
256 const served = servedBy(db, set);
257 const labels = labelsForIssues(db, free.map((i) => i.id));
258 const groups = new Map<string, Issue[]>();
259 for (const issue of free) {
260 const theme = served.get(issue.id) ?? labels.get(issue.id)?.map((l) => l.name).sort()[0] ?? "Other";
261 groups.set(theme, [...(groups.get(theme) ?? []), issue]);
262 }
263 return [...groups]
264 .sort((a, b) => b[1].length - a[1].length || a[0].localeCompare(b[0]))
265 .slice(0, PROPOSALS_MAX)
266 .map(([theme, issues]) => ({
267 theme,
268 name: theme,
269 issues: issues
270 .sort((a, b) => a.number - b.number)
271 .slice(0, PROPOSAL_SCOPES)
272 .map((i) => ({ number: i.number, title: i.title })),
273 }));
274 }
src/core/event_audience.ts +7
@@ -36,6 +36,13 @@ const READER_KINDS: ReadonlySet<string> = new Set([
3636 // the admins' (`repo.upstream_follow`).
3737 "repo.following",
3838 "issue.labeled",
39 "bet.backed",
40 "bet.stopped",
41 "bet.left",
42 "bet.shipped",
43 "bet.verdict",
44 "bet.reopened",
45 "bet.ended",
3946 "issue.first",
4047 "issue.closed",
4148 "issue.commented",
src/core/migration-pins/20261102200000-bets.pin added +1
@@ -0,0 +1,1 @@
1 d733e196a5543403e2f19348aeb7c2d23e39efe8c967a29bb44df8cee670699c
src/core/migrations/20261102200000-bets.ts added +30
@@ -0,0 +1,30 @@
1 // Bets (#8713): the owner backs a few named wholes with a share of the week.
2 // A thin record over the existing issues: one row a bet, one row a scope
3 // (an issue the bet is made of); `auto` marks a bet the planner started
4 // because the owner stayed silent, not one they backed. Two new tables.
5 export default `
6 CREATE TABLE IF NOT EXISTS bet (
7 id TEXT PRIMARY KEY,
8 repo_id TEXT NOT NULL REFERENCES repo(id) ON DELETE CASCADE,
9 name TEXT NOT NULL,
10 appetite_pct INTEGER NOT NULL,
11 done_when TEXT NOT NULL DEFAULT '',
12 lead_id TEXT REFERENCES user(id) ON DELETE SET NULL,
13 state TEXT NOT NULL CHECK (state IN ('backed', 'stopped', 'shipped', 'done', 'ended')),
14 period_start TEXT NOT NULL,
15 left_line TEXT NOT NULL DEFAULT '',
16 try_url TEXT NOT NULL DEFAULT '',
17 not_yet TEXT NOT NULL DEFAULT '',
18 auto INTEGER NOT NULL DEFAULT 0,
19 created_at TEXT NOT NULL,
20 updated_at TEXT NOT NULL
21 );
22 CREATE INDEX IF NOT EXISTS bet_repo ON bet (repo_id, state);
23 CREATE TABLE IF NOT EXISTS bet_scope (
24 bet_id TEXT NOT NULL REFERENCES bet(id) ON DELETE CASCADE,
25 issue_id TEXT NOT NULL REFERENCES issue(id) ON DELETE CASCADE,
26 mode TEXT NOT NULL DEFAULT 'figuring' CHECK (mode IN ('figuring', 'executing')),
27 PRIMARY KEY (bet_id, issue_id)
28 );
29 CREATE INDEX IF NOT EXISTS bet_scope_issue ON bet_scope (issue_id);
30 `;
src/crew/autonomy.ts +13 −1
@@ -30,6 +30,9 @@ import { addLearned } from "../checks/learned.ts";
3030 import { batchWords, dropFromLine, enqueue, type GateCandidate, type Queued, type QueueOptions, queueClashes, queueWords, waitingPulls } from "../checks/queue.ts";
3131 import { checksFor } from "../checks/service.ts";
3232 import { queueBatch, queueDepth, smallShare } from "../core/capacity.ts";
33 import { listIssues } from "../core/issues.ts";
34 import { betOrder, hasBets, pickRanks } from "../core/bets.ts";
35 import { settleBets, startUnbacked } from "../actions/bets.ts";
3336 import { roadmapIssues, shareWords, slotOrder, smallCap, smallIssues, smallOfIds } from "./small_share.ts";
3437 import { raisedAt } from "../core/thought_links.ts";
3538 import { readConflictLane, readConflictRoom } from "./conflict_room.ts";
@@ -379,7 +382,7 @@ function inSlotOrder(app: App, repo: Repo, ready: readonly Ranked[], slotted: re
379382 const first = firstAt(app.db, issues.map((i) => i.id));
380383 const raised = raisedAt(app.db, issues.map((i) => i.id));
381384 const running = smallOfIds(app.db, slotted.flatMap((r) => (r.issueId === null ? [] : [r.issueId])));
382 return slotOrder(
385 const ordered = slotOrder(
383386 ready,
384387 (r) => ({
385388 raised: raised.has(r.issue.id) || first.has(r.issue.id),
@@ -389,6 +392,11 @@ function inSlotOrder(app: App, repo: Repo, ready: readonly Ranked[], slotted: re
389392 running,
390393 smallCap(slots, smallShare(app.db)),
391394 );
395 // Bets (#8713): once a repository has one, only a backed bet's scopes start —
396 // besides what the owner raised and the small-fixes lane, already capped above.
397 const ranks = new Map(pickRanks(app.db, repo.id));
398 for (const r of ordered) if (raised.has(r.issue.id) || first.has(r.issue.id)) ranks.set(r.issue.id, -1);
399 return betOrder(ordered, (r) => r.issue.id, ranks, hasBets(app.db, repo.id), (r) => small.has(r.issue.id));
392400 }
393401
394402 /** Slotted runs on small issues, and the slots they may hold (#7571). */
@@ -421,6 +429,10 @@ export async function driveRepo(
421429 if (status.paused !== null) return "paused";
422430 const by = getUserById(app.db, repo.autonomyBy!);
423431 if (!by) return "paused";
432 // A bet that used its appetite stops here and starts nothing more (#8713).
433 settleBets(app, repo, repo.autonomySlots, now);
434 // Silent owner for a day with nothing backed: the planner's top proposals start, marked unbacked.
435 startUnbacked(app, repo, () => listIssues(app.db, repo.id, { state: "open" }), now);
424436 const crew = listCrewRoles(app.db, repo.id);
425437 const active = activeRuns(app, repo.id);
426438 const slotted = slottedRuns(active, crew);
src/http/mcp/tools/bets.ts added +79
@@ -0,0 +1,79 @@
1 import {
2 adoptAuto,
3 BET_WORDS,
4 backBet,
5 decideStopped,
6 giveVerdict,
7 setScopeMode,
8 setTryLink,
9 stopAuto,
10 writeLeft,
11 } from "../../../actions/bets.ts";
12 import { betsData } from "../../../web/pages/bets.ts";
13 import { good, bad, type Answer, type Tool, APP_ARG, planRepo, isAnswer } from "../shared.ts";
14
15 const text = (v: unknown): string => (typeof v === "string" ? v : "");
16
17 export const tool: Tool = {
18 name: "bets",
19 doc: "`{ app, do?, … }`: bets, the named wholes the owner backs with a share of the week (at most 5 run; builders pick only from them). No `do`: the bets with each scope figuring out or executing, raised hands, the planner's proposals. `do`: back (owner: name, share, doneWhen, issues), left (lead: bet, line), mode (bet, issue, mode), try (bet, url), decide (owner: bet, decision reback|cut|end, share), verdict (owner: bet, feelsDone, because), stop or adopt (owner: a bet the planner started unbacked)",
20 description:
21 "Bets: list, or act with `do`: back|left|mode|try|decide|verdict|stop|adopt.",
22 inputSchema: {
23 type: "object",
24 properties: {
25 app: APP_ARG,
26 do: { type: "string", enum: ["back", "left", "mode", "try", "decide", "verdict", "stop", "adopt"] },
27 bet: { type: "string" },
28 name: { type: "string", maxLength: 80 },
29 share: { type: "integer", minimum: 5, maximum: 100, description: "Percent of the week." },
30 doneWhen: { type: "string", maxLength: 1000 },
31 issues: { type: "array", items: { type: "integer" }, maxItems: 12 },
32 lead: { type: "string" },
33 line: { type: "string", maxLength: 200 },
34 issue: { type: "integer" },
35 mode: { type: "string", enum: ["figuring", "executing"] },
36 url: { type: "string" },
37 decision: { type: "string", enum: ["reback", "cut", "end"] },
38 feelsDone: { type: "boolean" },
39 because: { type: "string", maxLength: 200 },
40 },
41 required: ["app"],
42 },
43 writes: true,
44 run(ctx, user, args) {
45 const repo = planRepo(ctx, user, args);
46 if (isAnswer(repo)) return repo;
47 const action = args["do"];
48 if (action === undefined) return good(betsData(ctx, repo));
49 const bet = text(args["bet"]);
50 const share = typeof args["share"] === "number" ? args["share"] : undefined;
51 const result =
52 action === "back"
53 ? backBet(ctx.app, user, repo, {
54 name: text(args["name"]),
55 pct: share ?? Number.NaN,
56 doneWhen: text(args["doneWhen"]),
57 numbers: Array.isArray(args["issues"]) ? args["issues"].map(Number) : [],
58 ...(typeof args["lead"] === "string" ? { lead: args["lead"] } : {}),
59 })
60 : action === "left"
61 ? writeLeft(ctx.app, user, repo, bet, text(args["line"]))
62 : action === "mode"
63 ? setScopeMode(ctx.app, user, repo, bet, Number(args["issue"]), text(args["mode"]))
64 : action === "try"
65 ? setTryLink(ctx.app, user, repo, bet, text(args["url"]))
66 : action === "decide"
67 ? decideStopped(ctx.app, user, repo, bet, text(args["decision"]), share)
68 : action === "verdict"
69 ? giveVerdict(ctx.app, user, repo, bet, args["feelsDone"] === true, text(args["because"]))
70 : action === "stop"
71 ? stopAuto(ctx.app, user, repo, bet)
72 : action === "adopt"
73 ? adoptAuto(ctx.app, user, repo, bet)
74 : undefined;
75 if (result === undefined) return bad("bad_action", "do is back, left, mode, try, decide, verdict, stop or adopt");
76 const answer: Answer = result.ok ? good(typeof result.value === "string" ? { mode: result.value } : { bet: result.value.id, state: result.value.state }) : bad(result.error, BET_WORDS[result.error]);
77 return answer;
78 },
79 };
src/http/mcp/tools/index.ts +1
@@ -27,6 +27,7 @@ export { tool as audit } from "./audit.ts";
2727 export { tool as backups } from "./backups.ts";
2828 export { tool as backups_destination } from "./backups_destination.ts";
2929 export { tool as backups_test } from "./backups_test.ts";
30 export { tool as bets } from "./bets.ts";
3031 export { tool as board_delete } from "./board_delete.ts";
3132 export { tool as board_pins } from "./board_pins.ts";
3233 export { tool as board_write } from "./board_write.ts";
src/http/server.ts +5
@@ -199,6 +199,7 @@ import { tellHerePage } from "../web/studio/tell_here.ts";
199199 import { globalMapPage } from "../web/pages/global-map.ts";
200200 import { mapPage } from "../web/pages/map.ts";
201201 import { firstSubmit } from "../web/pages/first.ts";
202 import { betBack, betOp, betPage, betsPage } from "../web/pages/bets.ts";
202203 import {
203204 milestonePage,
204205 milestonesPage,
@@ -1017,6 +1018,10 @@ export function buildRouter(): Router<Handler> {
10171018 );
10181019 router.add("GET", "/:owner/:name/map", mapPage);
10191020 router.add("POST", "/:owner/:name/issues/:number/first", firstSubmit);
1021 router.add("GET", "/:owner/:name/bets", betsPage);
1022 router.add("POST", "/:owner/:name/bets", betBack);
1023 router.add("GET", "/:owner/:name/bets/:id", betPage);
1024 router.add("POST", "/:owner/:name/bets/:id/:op", betOp);
10201025 router.add("GET", "/:owner/:name/milestones", milestonesPage);
10211026 router.add("GET", "/:owner/:name/milestones/:number", milestonePage);
10221027 router.add("POST", "/:owner/:name/milestones/:number/watch", milestoneWatch);
src/release/by_bet.ts added +43
@@ -0,0 +1,43 @@
1 /**
2 * The changelog by bet (#8713): the live landings whose pull closed a scope
3 * of a bet, grouped under the bet's name. A landing that closed no scope of
4 * any bet is left out; the day-by-day list still carries every one. Only
5 * repositories the viewer may read are looked into.
6 */
7
8 import type { Database } from "bun:sqlite";
9 import { getIssue } from "../core/issues.ts";
10 import { closesFromBody, getPull } from "../core/pulls.ts";
11 import { canRead, getRepo } from "../core/repos.ts";
12 import type { User } from "../core/users.ts";
13 import type { Landing } from "./landings.ts";
14
15 export interface BetLandings {
16 readonly bet: string;
17 readonly repo: string;
18 readonly landings: readonly Landing[];
19 }
20
21 export function landingsByBet(db: Database, landings: readonly Landing[], viewer: User | undefined): BetLandings[] {
22 const groups = new Map<string, { bet: string; repo: string; landings: Landing[] }>();
23 const find = db.query<{ id: string; name: string }, [string]>(
24 `SELECT b.id, b.name FROM bet_scope s JOIN bet b ON b.id = s.bet_id WHERE s.issue_id = ?1 ORDER BY b.created_at LIMIT 1`,
25 );
26 for (const l of landings) {
27 const [owner, name] = l.repo.split("/");
28 const repo = owner === undefined || name === undefined ? undefined : getRepo(db, owner, name);
29 if (repo === undefined || !canRead(db, repo, viewer)) continue;
30 const pull = getPull(db, repo.id, l.number);
31 if (pull === undefined) continue;
32 for (const n of closesFromBody(pull.body)) {
33 const issue = getIssue(db, repo.id, n);
34 const bet = issue === undefined ? null : find.get(issue.id);
35 if (bet === null || bet === undefined) continue;
36 const group = groups.get(bet.id) ?? { bet: bet.name, repo: l.repo, landings: [] };
37 if (!group.landings.includes(l)) group.landings.push(l);
38 groups.set(bet.id, group);
39 break;
40 }
41 }
42 return [...groups.values()];
43 }
src/web/chrome.ts +7
@@ -182,6 +182,7 @@ export type RepoTab =
182182 | "pulls"
183183 | "forks"
184184 | "map"
185 | "bets"
185186 | "commits"
186187 | "branches"
187188 | "app"
@@ -305,6 +306,12 @@ export function scopeHeader(
305306 current: active === "map",
306307 shortcut: "g a",
307308 },
309 {
310 label: "Bets",
311 href: `${base}/bets`,
312 icon: "rocket",
313 current: active === "bets",
314 },
308315 ...(studio
309316 ? []
310317 : [
src/web/pages/bets.ts added +310
@@ -0,0 +1,310 @@
1 /**
2 * Bets (#8713), the page and its forms. `/:owner/:name/bets` is one screen:
3 * the bets that run (each a line: share, lead, how far), what the planner
4 * proposes from open work for the owner to back with a tap, and the ones
5 * that stopped or shipped, which wait for the owner. `/bets/:id` is one bet:
6 * what done looks like, each scope as figuring out or executing — a scope
7 * that has not moved reads as a raised hand — and, once shipped, the moment:
8 * try it, then "feels done" or "not yet, because…".
9 *
10 * The rules are `core/bets.ts`; each button is one action in
11 * `actions/bets.ts`. Server-rendered, no script.
12 */
13
14 import {
15 BET_MAX,
16 allowanceSeconds,
17 backedShare,
18 getBet,
19 listBets,
20 progressWords,
21 proposals,
22 runningBets,
23 scopesOf,
24 spentSeconds,
25 type Bet,
26 type Proposal,
27 } from "../../core/bets.ts";
28 import {
29 BET_WORDS,
30 backBet,
31 decideStopped,
32 giveVerdict,
33 adoptAuto,
34 setScopeMode,
35 stopAuto,
36 setTryLink,
37 writeLeft,
38 type BetError,
39 } from "../../actions/bets.ts";
40 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
41 import { listIssues } from "../../core/issues.ts";
42 import { canAdmin, canWrite, type Repo } from "../../core/repos.ts";
43 import { getUserById } from "../../core/users.ts";
44 import type { Ctx } from "../../http/context.ts";
45 import { crumbsFor, forbiddenPage, loadRepo, notFoundPage, pageHead, repoBase, repoHeader, repoPalette, signInFirst } from "../chrome.ts";
46 import { field as formField, readForm } from "../form.ts";
47 import { html, type Html } from "../html.ts";
48 import { page, redirect } from "../layout.ts";
49 import { badge, btn, card, empty, field, listCard, row, time } from "../ui.ts";
50
51 const SHARES = [10, 20, 30, 50];
52
53 /** What a bet in each state is called. */
54 const STATE_WORDS: Record<Bet["state"], string> = {
55 backed: "running",
56 stopped: "stopped at its appetite",
57 shipped: "finished: try it",
58 done: "done",
59 ended: "ended",
60 };
61
62 const betHref = (repo: Repo, id: string) => `${repoBase(repo)}/bets/${id}`;
63
64 function hours(seconds: number): string {
65 return `${Math.round(seconds / 360) / 10} h`;
66 }
67
68 /** The bets as data: the page, the MCP tool and the API say the same. */
69 export function betsData(ctx: Ctx, repo: Repo, now: Date = new Date()) {
70 const db = ctx.app.db;
71 const bets = listBets(db, repo.id);
72 return {
73 max: BET_MAX,
74 backedShare: backedShare(bets),
75 bets: bets.map((b) => {
76 const scopes = scopesOf(db, b.id, now);
77 return {
78 id: b.id,
79 name: b.name,
80 state: b.state,
81 appetitePct: b.appetitePct,
82 backedByOwner: !b.auto,
83 spentSeconds: spentSeconds(db, b, now),
84 allowanceSeconds: allowanceSeconds(b.appetitePct, repo.autonomySlots),
85 lead: b.leadId === null ? null : (getUserById(db, b.leadId)?.username ?? null),
86 doneWhen: b.doneWhen,
87 left: b.leftLine,
88 tryUrl: b.state === "shipped" || b.state === "done" ? b.tryUrl : "",
89 progress: progressWords(scopes),
90 scopes: scopes.map((s) => ({ number: s.number, title: s.title, open: s.open, mode: s.mode, raisedHand: s.hand })),
91 };
92 }),
93 proposals: canAdmin(db, repo, ctx.auth.user) ? proposals(db, repo, listIssues(db, repo.id, { state: "open" })) : [],
94 };
95 }
96
97 function lineOf(repo: Repo, ctx: Ctx, b: Bet, now: Date): Html {
98 const scopes = scopesOf(ctx.app.db, b.id, now);
99 const hands = scopes.filter((s) => s.hand).length;
100 const lead = b.leadId === null ? null : getUserById(ctx.app.db, b.leadId)?.username;
101 return row({
102 href: betHref(repo, b.id),
103 title: b.name,
104 meta: html`${b.appetitePct}% of the week · ${lead ? `led by @${lead} · ` : ""}${progressWords(scopes)} · ${STATE_WORDS[b.state]}${b.auto ? " · not backed by the owner" : ""}${
105 hands > 0 ? html` · <strong>${hands} raised ${hands === 1 ? "hand" : "hands"}</strong>` : null
106 }`,
107 trail: time(b.updatedAt),
108 });
109 }
110
111 function proposalCard(repo: Repo, p: Proposal): Html {
112 const action = `${repoBase(repo)}/bets`;
113 const journeys = p.issues.slice(0, 3).map((i) => `A person can: ${i.title}`).join("\n");
114 return card(
115 html`<form method="post" action="${action}">
116 <ul class="list">${p.issues.map((i) => html`<li class="row"><label class="check"><input type="checkbox" name="scope" value="${i.number}" checked /> #${i.number} ${i.title}</label></li>`)}</ul>
117 <input type="hidden" name="name" value="${p.name}" />
118 ${field({ name: "done_when", label: "Done looks like", type: "textarea", rows: 3, value: journeys })}
119 ${field({
120 name: "share",
121 label: "Share of the week",
122 type: "select",
123 options: SHARES.map((s) => ({ value: String(s), label: `${s}%`, selected: s === 20 })),
124 })}
125 ${btn("Back this", { variant: "primary" })}
126 </form>`,
127 { head: html`<h3>${p.name}</h3>${badge(`${p.issues.length} open`)}` },
128 );
129 }
130
131 /** GET /:owner/:name/bets */
132 export function betsPage(ctx: Ctx, now: Date = new Date()): Response {
133 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
134 const started = performance.now();
135 const repo = loadRepo(ctx);
136 if (!repo) return notFoundPage(ctx);
137 const data = betsData(ctx, repo, now);
138 const bets = listBets(ctx.app.db, repo.id);
139 const live = bets.filter((b) => b.state === "backed");
140 const waiting = bets.filter((b) => b.state === "stopped" || b.state === "shipped");
141 const over = bets.filter((b) => b.state === "done" || b.state === "ended");
142 const admin = canAdmin(ctx.app.db, repo, ctx.auth.user);
143 const response = page({
144 ctx,
145 title: `Bets · ${repo.name}`,
146 crumbs: crumbsFor(repo),
147 palette: repoPalette(ctx, repo),
148 body: html`${repoHeader(ctx, repo, "bets")}
149 ${pageHead("Bets", {
150 sub: `${runningBets(bets).length} of ${BET_MAX} running · ${data.backedShare}% of the week backed. Builders pick only from a running bet, and from the small-fixes lane.`,
151 })}
152 ${waiting.length > 0 ? listCard(waiting.map((b) => lineOf(repo, ctx, b, now)), { head: html`<h2>Waiting for the owner</h2>` }) : null}
153 ${live.length > 0
154 ? listCard(live.map((b) => lineOf(repo, ctx, b, now)), { head: html`<h2>Running</h2>` })
155 : empty({ title: "No bet is running", note: admin ? "Back one below: a name, a share of the week, and what done looks like." : "The owner backs a few named wholes; they appear here." })}
156 ${admin && data.proposals.length > 0 ? html`<h2>Proposed from open work</h2>${data.proposals.map((p) => proposalCard(repo, p))}` : null}
157 ${over.length > 0 ? listCard(over.map((b) => lineOf(repo, ctx, b, now)), { head: html`<h2>Over</h2>` }) : null}`,
158 });
159 notePhase(ctx.request, "render", performance.now() - started);
160 return response;
161 }
162
163 function flashBack(ctx: Ctx, to: string, error: BetError): Response {
164 return redirect(to, { flash: { message: BET_WORDS[error], tone: "danger" }, url: ctx.url, forgeUrl: ctx.app.config.url });
165 }
166
167 /** GET /:owner/:name/bets/:id */
168 export function betPage(ctx: Ctx, now: Date = new Date()): Response {
169 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
170 const started = performance.now();
171 const repo = loadRepo(ctx);
172 if (!repo) return notFoundPage(ctx);
173 const bet = getBet(ctx.app.db, repo.id, ctx.params.id ?? "");
174 if (!bet) return notFoundPage(ctx);
175 const viewer = ctx.auth.user;
176 const admin = canAdmin(ctx.app.db, repo, viewer);
177 const writer = viewer !== undefined && canWrite(ctx.app.db, repo, viewer);
178 const scopes = scopesOf(ctx.app.db, bet.id, now);
179 const base = betHref(repo, bet.id);
180 const spent = spentSeconds(ctx.app.db, bet, now);
181 const post = (op: string, body: Html) => html`<form method="post" action="${base}/${op}" class="bar mt">${body}</form>`;
182 const scopeRows = scopes.map((s) =>
183 row({
184 href: `${repoBase(repo)}/issues/${s.number}`,
185 title: `#${s.number} ${s.title}`,
186 meta: html`${!s.open ? "done" : s.mode === "executing" ? "just executing" : "figuring out"}${
187 s.hand ? html` · <strong>raised hand: no movement in 2 days</strong>` : null
188 }`,
189 ...(writer && s.open
190 ? {
191 trail: html`<form method="post" action="${base}/mode">
192 <input type="hidden" name="number" value="${s.number}" />
193 <input type="hidden" name="mode" value="${s.mode === "executing" ? "figuring" : "executing"}" />
194 ${btn(s.mode === "executing" ? "Figuring out" : "Executing", { size: "sm" })}
195 </form>`,
196 }
197 : {}),
198 }),
199 );
200 const moment =
201 bet.state === "shipped"
202 ? card(
203 html`<p>This is done. Try it:</p>
204 <p>${btn("Try it", { href: bet.tryUrl, variant: "primary" })}</p>
205 <p>${bet.doneWhen.split("\n").map((l) => html`${l}<br />`)}</p>
206 ${admin
207 ? html`${post("verdict", html`<input type="hidden" name="verdict" value="done" />${btn("Feels done", { variant: "primary" })}`)}
208 ${post(
209 "verdict",
210 html`<input type="hidden" name="verdict" value="not_yet" />
211 ${field({ name: "because", label: "Not yet, because…", maxlength: 200, required: true })}
212 ${btn("Not yet")}`,
213 )}`
214 : null}`,
215 { head: html`<h2>Finished: does it feel done?</h2>` },
216 )
217 : null;
218 const unbacked =
219 bet.auto && bet.state === "backed"
220 ? card(
221 html`<p>The planner started this because nothing was backed for a day. It is not backed by the owner.</p>
222 ${admin
223 ? html`${post("adopt", btn("Back it", { variant: "primary" }))}${post("stop", btn("Stop it"))}`
224 : null}`,
225 { head: html`<h2>Not backed by the owner</h2>` },
226 )
227 : null;
228 const stopped =
229 bet.state === "stopped"
230 ? card(
231 html`<p>Used its ${bet.appetitePct}% of the week (${hours(spent)} of ${hours(allowanceSeconds(bet.appetitePct, repo.autonomySlots))}). It does not extend by itself.</p>
232 ${bet.leftLine === "" ? html`<p>Waiting for the lead to write what is left, in one line.</p>` : html`<p><strong>Left:</strong> ${bet.leftLine}</p>`}
233 ${writer ? post("left", html`${field({ name: "line", label: "What is left (one line)", maxlength: 200, value: bet.leftLine, required: true })}${btn("Write it")}`) : null}
234 ${admin && bet.leftLine !== ""
235 ? post(
236 "decide",
237 html`${field({ name: "share", label: "Share if re-backed", type: "select", options: SHARES.map((s) => ({ value: String(s), label: `${s}%`, selected: s === bet.appetitePct })) })}
238 <button name="decision" value="reback" class="btn" data-variant="primary">Re-back</button>
239 <button name="decision" value="cut" class="btn">Cut what is left</button>
240 <button name="decision" value="end" class="btn">End</button>`,
241 )
242 : null}`,
243 { head: html`<h2>Stopped</h2>` },
244 )
245 : null;
246 const response = page({
247 ctx,
248 title: `${bet.name} · Bets · ${repo.name}`,
249 crumbs: crumbsFor(repo),
250 palette: repoPalette(ctx, repo),
251 body: html`${repoHeader(ctx, repo, "bets")}
252 ${pageHead(bet.name, {
253 sub: `${bet.appetitePct}% of the week · ${STATE_WORDS[bet.state]} · ${progressWords(scopes)}${bet.leadId === null ? "" : ` · lead @${getUserById(ctx.app.db, bet.leadId)?.username ?? ""}`}`,
254 })}
255 ${unbacked}${moment}${stopped}
256 ${card(html`<p>${bet.doneWhen.split("\n").map((l) => html`${l}<br />`)}</p>`, { head: html`<h2>Done looks like</h2>` })}
257 ${listCard(scopeRows, { head: html`<h2>Scopes</h2>` })}
258 <p><a href="${repoBase(repo)}/bets">All bets</a></p>`,
259 });
260 notePhase(ctx.request, "render", performance.now() - started);
261 return response;
262 }
263
264 /** POST /:owner/:name/bets — the owner backs a proposal with a share. */
265 export async function betBack(ctx: Ctx): Promise<Response> {
266 const repo = loadRepo(ctx);
267 if (!repo) return notFoundPage(ctx);
268 if (!ctx.auth.user) return signInFirst(ctx);
269 const form = await readForm(ctx, "rw");
270 if (form instanceof Response) return form;
271 const here = `${repoBase(repo)}/bets`;
272 const made = backBet(ctx.app, ctx.auth.user, repo, {
273 name: formField(form, "name"),
274 pct: Number(formField(form, "share")),
275 doneWhen: formField(form, "done_when"),
276 numbers: form.getAll("scope").map((v) => Number(v)),
277 });
278 if (!made.ok) return made.error === "forbidden" ? forbiddenPage(ctx, BET_WORDS.forbidden) : flashBack(ctx, here, made.error);
279 return redirect(betHref(repo, made.value.id));
280 }
281
282 /** POST /:owner/:name/bets/:id/:op — left, mode, try, decide, verdict. */
283 export async function betOp(ctx: Ctx): Promise<Response> {
284 const repo = loadRepo(ctx);
285 if (!repo) return notFoundPage(ctx);
286 if (!ctx.auth.user) return signInFirst(ctx);
287 const form = await readForm(ctx, "rw");
288 if (form instanceof Response) return form;
289 const id = ctx.params.id ?? "";
290 const user = ctx.auth.user;
291 const result =
292 ctx.params.op === "left"
293 ? writeLeft(ctx.app, user, repo, id, formField(form, "line"))
294 : ctx.params.op === "mode"
295 ? setScopeMode(ctx.app, user, repo, id, Number(formField(form, "number")), formField(form, "mode"))
296 : ctx.params.op === "try"
297 ? setTryLink(ctx.app, user, repo, id, formField(form, "url"))
298 : ctx.params.op === "decide"
299 ? decideStopped(ctx.app, user, repo, id, formField(form, "decision"), Number(formField(form, "share")) || undefined)
300 : ctx.params.op === "stop"
301 ? stopAuto(ctx.app, user, repo, id)
302 : ctx.params.op === "adopt"
303 ? adoptAuto(ctx.app, user, repo, id)
304 : ctx.params.op === "verdict"
305 ? giveVerdict(ctx.app, user, repo, id, formField(form, "verdict") === "done", formField(form, "because"))
306 : undefined;
307 if (result === undefined) return notFoundPage(ctx);
308 if (!result.ok) return result.error === "not_found" ? notFoundPage(ctx) : flashBack(ctx, betHref(repo, id), result.error);
309 return redirect(betHref(repo, id));
310 }
src/web/pages/changelog.ts +7 −1
@@ -15,6 +15,7 @@ import { chosenRepo, readLandings, type Landing, type Landings } from "../../rel
1515 import { liveRegionsJs } from "../client.ts";
1616 import { pageHead } from "../chrome.ts";
1717 import { json } from "../../http/respond.ts";
18 import { landingsByBet } from "../../release/by_bet.ts";
1819 import { shippedAnswer } from "../../release/answer.ts";
1920 import { html, type Html } from "../html.ts";
2021 import { page } from "../layout.ts";
@@ -156,7 +157,12 @@ export async function changelogPage(ctx: Ctx): Promise<Response> {
156157 ]);
157158 const ownRepo = read.own === undefined ? undefined : getRepo(ctx.app.db, ...(read.own.split("/") as [string, string]));
158159 const readable = ownRepo !== undefined && canRead(ctx.app.db, ownRepo, ctx.auth.user);
159 const body = html`${pageHead("Changelog", { sub: "What went live, as it happens." })}${filters}
160 const bets = landingsByBet(ctx.app.db, read.live.filter((l) => choice === "all" || l.repo === choice), ctx.auth.user);
161 const byBet =
162 bets.length === 0
163 ? null
164 : html`<h2>By bet</h2>${bets.map((g) => listCard(g.landings.map((l) => landingRow(l, read.own, choice === "all")), { head: html`<h3>${g.bet}</h3>${badge(String(g.landings.length))}` }))}`;
165 const body = html`${pageHead("Changelog", { sub: "What went live, as it happens." })}${filters}${byBet}
160166 <div id="shipped" data-live="${LIVE}" aria-live="polite">${shippedRegion(read, choice, new Date(), "UTC", newestLive(ctx.app.db), readable)}</div>`;
161167 const response = page({ ctx, title: "Changelog", body, feed: { href: "/changelog.atom", title: "Changelog" }, json: { href: `/api/v1/changelog${choice === read.own ? "" : `?repo=${encodeURIComponent(choice)}`}`, title: "Changelog (JSON)" }, scriptJs: `${liveRegionsJs}\n${localDaysJs}` });
162168 notePhase(ctx.request, "render", performance.now() - rendering);
test/bets.test.ts added +315
@@ -0,0 +1,315 @@
1 /**
2 * Bets (#8713): the owner backs a few named wholes with a share of the week;
3 * builders pick only from them, a bet stops at its appetite, a finished one
4 * waits for the owner's word, and the same state gives the same picks.
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 { addToCrew, createAgent } from "../src/actions/crew.ts";
12 import { adoptAuto, backBet, decideStopped, giveVerdict, setScopeMode, settleBets, startUnbacked, stopAuto, writeLeft } from "../src/actions/bets.ts";
13 import { openIssue } from "../src/actions/issues.ts";
14 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
15 import { allowanceSeconds, betOrder, getBet, isRaisedHand, listBets, overAppetite, pickRanks, progressWords, proposals, spentSeconds } from "../src/core/bets.ts";
16 import { getIssueById, listIssues, type Issue } from "../src/core/issues.ts";
17 import { getRepoById, type Repo } from "../src/core/repos.ts";
18 import { createRun } from "../src/core/runs.ts";
19 import { createUser, type User } from "../src/core/users.ts";
20 import { driveRepo } from "../src/crew/autonomy.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22
23 describe("the rules", () => {
24 test("an appetite is a share of the crew's week, and used up means stop", () => {
25 expect(allowanceSeconds(10, 5)).toBe(5 * 7 * 86_400 * 0.1);
26 expect(overAppetite(allowanceSeconds(10, 5) - 1, 10, 5)).toBe(false);
27 expect(overAppetite(allowanceSeconds(10, 5), 10, 5)).toBe(true);
28 });
29
30 test("a scope that has not moved for two days is a raised hand; a closed one never is", () => {
31 const now = new Date("2026-11-04T12:00:00Z");
32 expect(isRaisedHand(true, "2026-11-02T12:00:00Z", now)).toBe(true);
33 expect(isRaisedHand(true, "2026-11-03T12:00:00Z", now)).toBe(false);
34 expect(isRaisedHand(false, "2026-10-01T12:00:00Z", now)).toBe(false);
35 expect(progressWords([{ open: false }, { open: true }])).toBe("1 of 2 scopes done");
36 });
37
38 test("without bets the list is kept; with bets only a bet's work, the lane and the raised stay, in bet order, and the same input gives the same list", () => {
39 const ready = ["x", "a", "small", "b", "raised"];
40 const ranks = new Map([["a", 1], ["b", 0], ["raised", -1]]);
41 const exempt = (t: string) => t === "small";
42 expect(betOrder(ready, (t) => t, ranks, false, exempt)).toEqual(ready);
43 const once = betOrder(ready, (t) => t, ranks, true, exempt);
44 expect(once).toEqual(["raised", "b", "a", "small"]);
45 expect(betOrder(ready, (t) => t, ranks, true, exempt)).toEqual(once);
46 });
47 });
48
49 let dataDir: string;
50 let app: App;
51 let alice: User;
52 let bob: User;
53 let repo: Repo;
54 let servers: Servers;
55 let cookie: string;
56
57 const fresh = () => getRepoById(app.db, repo.id)!;
58 const open = (title: string): Issue => {
59 const made = openIssue(app, alice, fresh(), { title });
60 if (!made.ok) throw new Error(String(made.error));
61 return made.value;
62 };
63 const back = (name: string, issues: Issue[], pct = 10) =>
64 backBet(app, alice, fresh(), { name, pct, doneWhen: "A person can use it.", numbers: issues.map((i) => i.number) });
65 const must = <T>(r: { ok: true; value: T } | { ok: false; error: unknown }): T => {
66 if (!r.ok) throw new Error(String(r.error));
67 return r.value;
68 };
69 const clear = () => app.db.exec("DELETE FROM bet; UPDATE issue SET state = 'closed' WHERE state = 'open'");
70
71 /** One drive; a pick gets the run its assignment would start, as the autonomy tests do. */
72 async function drive(issues: readonly Issue[]): Promise<Issue | undefined> {
73 const before = new Set(issues.filter((i) => getIssueById(app.db, i.id)!.assigneeId !== null).map((i) => i.id));
74 if ((await driveRepo(app, fresh())) !== "picked") return undefined;
75 const picked = issues.map((i) => getIssueById(app.db, i.id)!).find((i) => i.assigneeId !== null && !before.has(i.id));
76 if (picked === undefined) return undefined;
77 createRun(app.db, { repoId: repo.id, kind: "agent", issueId: picked.id, actorId: picked.assigneeId ?? undefined, reason: "assigned" });
78 return picked;
79 }
80
81 beforeAll(async () => {
82 dataDir = await mkdtemp(join(tmpdir(), "forge-bets-"));
83 app = createApp({ dataDir, port: 0 });
84 alice = must(await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true }));
85 bob = must(await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" }));
86 repo = must(await createRepo(app, alice, { name: "notes", visibility: "public" }));
87 must(await commitToBranch(app, alice, repo, { message: "Start", files: [{ path: "README.md", content: "notes\n" }] }));
88 for (const name of ["b1", "b2"]) {
89 must(await createAgent(app, alice, { username: name }));
90 expect(addToCrew(app, alice, repo, name).ok).toBe(true);
91 }
92 must(await updateRepoSettings(app, alice, repo, { autonomy: "autonomous", autonomyDirection: "Keep the notes tidy.", autonomyCeilingUsd: 10, autonomySlots: 5, autonomyBy: alice.id }));
93 servers = await serve(app);
94 const signin = await fetch(`${servers.url}/signin`, {
95 method: "POST",
96 redirect: "manual",
97 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
98 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
99 });
100 cookie = (signin.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
101 });
102
103 afterAll(async () => {
104 servers.stop();
105 app.close();
106 await rm(dataDir, { recursive: true, force: true });
107 });
108
109 test("backing is the owner's: a stranger is refused, and the name, share, journeys and scopes are checked", () => {
110 const a = open("Search by word");
111 expect(backBet(app, bob, fresh(), { name: "Search", pct: 10, doneWhen: "x", numbers: [a.number] })).toEqual({ ok: false, error: "forbidden" });
112 const rules = (o: Partial<Parameters<typeof backBet>[3]>) => backBet(app, alice, fresh(), { name: "Search", pct: 10, doneWhen: "A person can search.", numbers: [a.number], ...o });
113 expect(rules({ name: " " })).toEqual({ ok: false, error: "bad_name" });
114 expect(rules({ pct: 3 })).toEqual({ ok: false, error: "bad_share" });
115 expect(rules({ pct: 20.5 })).toEqual({ ok: false, error: "bad_share" });
116 expect(rules({ doneWhen: "" })).toEqual({ ok: false, error: "bad_done_when" });
117 expect(rules({ numbers: [] })).toEqual({ ok: false, error: "bad_scopes" });
118 expect(rules({ numbers: [9999] })).toEqual({ ok: false, error: "bad_scopes" });
119 expect(rules({ lead: "alice" })).toEqual({ ok: false, error: "no_lead" });
120 expect(listBets(app.db, repo.id)).toHaveLength(0);
121 });
122
123 test("at most five run, the shares cannot pass the whole week, and an issue is in one bet", () => {
124 clear();
125 const issues = [1, 2, 3, 4, 5, 6].map((n) => open(`Whole ${n}`));
126 for (const i of issues.slice(0, 5)) expect(back(`Whole ${i.number}`, [i], 10).ok).toBe(true);
127 expect(back("Sixth", [issues[5]!])).toEqual({ ok: false, error: "too_many" });
128 expect(back("Again", [issues[0]!])).toEqual({ ok: false, error: "too_many" });
129 clear();
130 const a = open("Big");
131 const b = open("Bigger");
132 expect(back("Big", [a], 70).ok).toBe(true);
133 expect(back("Bigger", [b], 40)).toEqual({ ok: false, error: "over_week" });
134 expect(back("Dup", [a], 10)).toEqual({ ok: false, error: "bad_scopes" });
135 });
136
137 test("builders pick only from a backed bet; an issue in no bet does not start, and the same state gives the same picks", async () => {
138 clear();
139 const inBet = open("Search by word");
140 const outside = open("Rename a note");
141 const small = open("A test pins the title");
142 // No bet yet: the repository plans as it always did, and the plain issue starts.
143 const bet = must(back("Search", [inBet]));
144 expect(bet.leadId).not.toBeNull();
145 expect([...pickRanks(app.db, repo.id).keys()]).toEqual([inBet.id]);
146 expect(pickRanks(app.db, repo.id)).toEqual(pickRanks(app.db, repo.id));
147 const started: Issue[] = [];
148 for (let n = 0; n < 4; n++) {
149 const picked = await drive([inBet, outside, small]);
150 if (picked !== undefined) started.push(picked);
151 }
152 expect(started.map((i) => i.id).sort()).toEqual([inBet.id, small.id].sort());
153 expect(getIssueById(app.db, outside.id)!.assigneeId).toBeNull();
154 });
155
156 test("a bet that hits its appetite stops, starts nothing, and waits for its lead's line and the owner", async () => {
157 clear();
158 const a = open("Export notes");
159 const b = open("Export as text");
160 let bet = must(back("Export", [a, b]));
161 const day = 86_400_000;
162 const run = createRun(app.db, { repoId: repo.id, kind: "agent", issueId: a.id, actorId: bet.leadId!, reason: "assigned" });
163 const started = new Date(Date.now() - 4 * day);
164 app.db.query("UPDATE bet SET period_start = ?2 WHERE id = ?1").run(bet.id, new Date(started.getTime() - day).toISOString());
165 bet = getBet(app.db, repo.id, bet.id)!;
166 app.db.query("UPDATE run SET state = 'ok', started_at = ?2, finished_at = ?3 WHERE id = ?1").run(typeof run === "string" ? run : (run as { id: string }).id, started.toISOString(), new Date(started.getTime() + 3 * day).toISOString());
167 expect(spentSeconds(app.db, bet, new Date())).toBe(3 * 86_400);
168 // 10% of five slots' week is 3.5 days: not yet used up.
169 expect(settleBets(app, fresh(), 5)).toHaveLength(0);
170 app.db.query("UPDATE run SET finished_at = ?2 WHERE issue_id = ?1").run(a.id, new Date(started.getTime() + 3.6 * day).toISOString());
171 expect(settleBets(app, fresh(), 5).map((x) => x.state)).toEqual(["stopped"]);
172 expect(pickRanks(app.db, repo.id).size).toBe(0);
173 expect(await drive([a, b])).toBeUndefined();
174 // No automatic extension: settling again changes nothing.
175 expect(settleBets(app, fresh(), 5)).toHaveLength(0);
176
177 // The owner cannot choose before the lead has written what is left.
178 expect(decideStopped(app, alice, fresh(), bet.id, "end")).toEqual({ ok: false, error: "no_line_yet" });
179 expect(writeLeft(app, bob, fresh(), bet.id, "x")).toEqual({ ok: false, error: "forbidden" });
180 expect(writeLeft(app, alice, fresh(), bet.id, "two\nlines")).toEqual({ ok: false, error: "bad_line" });
181 bet = must(writeLeft(app, alice, fresh(), bet.id, "The text export is still missing."));
182 expect(bet.leftLine).toBe("The text export is still missing.");
183 expect(decideStopped(app, alice, fresh(), bet.id, "later")).toEqual({ ok: false, error: "bad_decision" });
184 bet = must(decideStopped(app, alice, fresh(), bet.id, "reback", 20));
185 expect([bet.state, bet.appetitePct, bet.leftLine]).toEqual(["backed", 20, ""]);
186 expect(spentSeconds(app.db, bet, new Date())).toBe(0);
187 expect(pickRanks(app.db, repo.id).size).toBe(2);
188 });
189
190 test("cutting a stopped bet keeps what is closed and ends the rest; ending it ends it", () => {
191 clear();
192 const a = open("Part one");
193 const b = open("Part two");
194 const bet = must(back("Parts", [a, b]));
195 app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(a.id);
196 app.db.query("UPDATE bet SET state = 'stopped', left_line = 'part two' WHERE id = ?1").run(bet.id);
197 const cut = must(decideStopped(app, alice, fresh(), bet.id, "cut"));
198 expect(cut.state).toBe("shipped");
199 expect(cut.tryUrl).toBe("/alice/notes");
200 const c = open("Other");
201 const other = must(back("Other", [c]));
202 app.db.query("UPDATE bet SET state = 'stopped', left_line = 'all' WHERE id = ?1").run(other.id);
203 expect(must(decideStopped(app, alice, fresh(), other.id, "end")).state).toBe("ended");
204 });
205
206 test("a bet whose scopes are all closed has shipped: try it, then feels done, or not yet and why", () => {
207 clear();
208 const a = open("Tags");
209 const bet = must(back("Tags", [a]));
210 app.db.query("UPDATE issue SET state = 'closed' WHERE id = ?1").run(a.id);
211 expect(settleBets(app, fresh(), 5).map((x) => x.state)).toEqual(["shipped"]);
212 const shipped = getBet(app.db, repo.id, bet.id)!;
213 expect(shipped.tryUrl).toBe("/alice/notes");
214 expect(giveVerdict(app, bob, fresh(), bet.id, true)).toEqual({ ok: false, error: "forbidden" });
215 expect(giveVerdict(app, alice, fresh(), bet.id, false, "")).toEqual({ ok: false, error: "bad_line" });
216 const notYet = must(giveVerdict(app, alice, fresh(), bet.id, false, "Tags vanish on reload."));
217 expect([notYet.state, notYet.leftLine]).toEqual(["stopped", "Tags vanish on reload."]);
218 expect(giveVerdict(app, alice, fresh(), bet.id, true)).toEqual({ ok: false, error: "not_shipped" });
219 const again = must(decideStopped(app, alice, fresh(), bet.id, "cut"));
220 expect(again.state).toBe("shipped");
221 expect(must(giveVerdict(app, alice, fresh(), bet.id, true)).state).toBe("done");
222 });
223
224 test("the lead says how each scope stands, and a scope that has not moved reads as a raised hand on the page", async () => {
225 clear();
226 const a = open("Sync notes");
227 const bet = must(back("Sync", [a]));
228 expect(must(setScopeMode(app, alice, fresh(), bet.id, a.number, "executing"))).toBe("executing");
229 expect(setScopeMode(app, alice, fresh(), bet.id, a.number, "dreaming")).toEqual({ ok: false, error: "bad_mode" });
230 app.db.query("UPDATE issue SET updated_at = ?2 WHERE id = ?1").run(a.id, new Date(Date.now() - 3 * 86_400_000).toISOString());
231 const text = await (await fetch(`${servers.url}/alice/notes/bets/${bet.id}`, { headers: { cookie } })).text();
232 expect(text).toContain("just executing");
233 expect(text).toContain("raised hand");
234 const list = await (await fetch(`${servers.url}/alice/notes/bets`, { headers: { cookie } })).text();
235 expect(list).toContain("Sync");
236 expect(list).toContain("1 raised hand");
237 });
238
239 test("the owner taps Back on a proposal from the page; a cross-origin post is refused", async () => {
240 clear();
241 const a = open("Pin a note");
242 const b = open("Unpin a note");
243 app.db.query("INSERT OR IGNORE INTO label (id, repo_id, name, color) VALUES ('l1', ?1, 'pinning', 'aaaaaa')").run(repo.id);
244 for (const i of [a, b]) app.db.query("INSERT INTO issue_label (issue_id, label_id) VALUES (?1, 'l1')").run(i.id);
245 const open_ = listIssues(app.db, repo.id, { state: "open" });
246 expect(proposals(app.db, fresh(), open_)).toEqual(proposals(app.db, fresh(), open_));
247 const proposed = proposals(app.db, fresh(), open_).find((p) => p.theme === "pinning");
248 expect(proposed?.issues.map((i) => i.number)).toEqual([a.number, b.number]);
249 const page = await (await fetch(`${servers.url}/alice/notes/bets`, { headers: { cookie } })).text();
250 expect(page).toContain("Proposed from open work");
251 expect(page).toContain("Back this");
252 const post = (origin: string) =>
253 fetch(`${servers.url}/alice/notes/bets`, {
254 method: "POST",
255 redirect: "manual",
256 headers: { cookie, origin, "content-type": "application/x-www-form-urlencoded" },
257 body: new URLSearchParams([["name", "pinning"], ["share", "20"], ["done_when", "A person can pin."], ["scope", String(a.number)], ["scope", String(b.number)]]),
258 });
259 expect((await post("https://evil.example")).status).toBe(403);
260 expect(listBets(app.db, repo.id)).toHaveLength(0);
261 const ok = await post(servers.url);
262 expect(ok.status).toBe(303);
263 expect(ok.headers.get("location")).toMatch(/\/alice\/notes\/bets\/\w+/);
264 expect(listBets(app.db, repo.id).map((x) => [x.name, x.appetitePct, x.auto])).toEqual([["pinning", 20, false]]);
265 expect(proposals(app.db, fresh(), listIssues(app.db, repo.id, { state: "open" }))).toEqual([]);
266 });
267
268 test("nothing backed for a day: the top proposals start at a modest share, marked unbacked, and one tap stops one", async () => {
269 clear();
270 const old = open("Old work");
271 const done = must(back("Old", [old]));
272 app.db.query("UPDATE bet SET state = 'ended', updated_at = ?2 WHERE id = ?1").run(done.id, new Date(Date.now() - 3_600_000).toISOString());
273 const x = open("Alpha work");
274 const y = open("Beta work");
275 const openNow = () => listIssues(app.db, repo.id, { state: "open" });
276 // Silent for an hour only: the crew waits.
277 expect(startUnbacked(app, fresh(), openNow)).toHaveLength(0);
278 app.db.query("UPDATE bet SET updated_at = ?2 WHERE id = ?1").run(done.id, new Date(Date.now() - 25 * 3_600_000).toISOString());
279 const made = startUnbacked(app, fresh(), openNow);
280 expect(made.map((b) => [b.auto, b.appetitePct, b.state])).toEqual([[true, 10, "backed"]]);
281 expect(made[0]!.name).toBe("Other");
282 expect(pickRanks(app.db, repo.id).size).toBe(3);
283 expect(await drive([old, x, y])).toBeDefined();
284 // Already running: nothing more is started.
285 expect(startUnbacked(app, fresh(), openNow)).toHaveLength(0);
286 expect(stopAuto(app, bob, fresh(), made[0]!.id)).toEqual({ ok: false, error: "forbidden" });
287 expect(must(adoptAuto(app, alice, fresh(), made[0]!.id)).auto).toBe(false);
288 expect(stopAuto(app, alice, fresh(), made[0]!.id)).toEqual({ ok: false, error: "not_running" });
289 expect(backBet(app, alice, fresh(), { name: "n", pct: 10, doneWhen: "d", numbers: [x.number] }).ok).toBe(false);
290 });
291
292 test("an unbacked bet shows as such on its page, and Stop it ends it", async () => {
293 clear();
294 const old = open("Old work");
295 const done = must(back("Old", [old]));
296 app.db.query("UPDATE bet SET state = 'ended', updated_at = ?2 WHERE id = ?1").run(done.id, new Date(Date.now() - 25 * 3_600_000).toISOString());
297 open("Fresh work");
298 const [auto] = startUnbacked(app, fresh(), () => listIssues(app.db, repo.id, { state: "open" }));
299 const text = await (await fetch(`${servers.url}/alice/notes/bets/${auto!.id}`, { headers: { cookie } })).text();
300 expect(text).toContain("not backed by the owner");
301 const stop = await fetch(`${servers.url}/alice/notes/bets/${auto!.id}/stop`, { method: "POST", redirect: "manual", headers: { cookie, origin: servers.url } });
302 expect(stop.status).toBe(303);
303 expect(getBet(app.db, repo.id, auto!.id)!.state).toBe("ended");
304 });
305
306 test("the MCP tool lists the bets and backs one", async () => {
307 clear();
308 const a = open("Share a note");
309 const tool = (await import("../src/http/mcp/tools/bets.ts")).tool;
310 const ctx = { app, auth: { user: alice } } as never;
311 const backed = await tool.run(ctx, alice, { app: "alice/notes", do: "back", name: "Share", share: 20, doneWhen: "A person can share.", issues: [a.number] });
312 expect(backed.ok).toBe(true);
313 const listed = await tool.run(ctx, alice, { app: "alice/notes" });
314 expect(JSON.stringify(listed)).toContain('"name":"Share"');
315 });
test/conversation-confirm.test.ts +1 −1
@@ -121,7 +121,7 @@ describe("the one list of what asks first", () => {
121121 // settings and can be put back. A new `writes: true` tool is on neither list until someone decides.
122122 const NOT_ASKED = new Set([
123123 "access", "account_verify", "app_members", "app_notes", "asks_act", "asks_decide", "asks_proposal", "asks_undecide",
124 "assign", "attach_look", "board_pins", "board_write", "branches", "capacity", "cloud_accounts", "close", "confirm_wait",
124 "assign", "attach_look", "bets", "board_pins", "board_write", "branches", "capacity", "cloud_accounts", "close", "confirm_wait",
125125 "crew", "decisions_by", "detach", "edit", "email_verify", "feed_chips", "feed_dismiss", "flag_set", "flag_winner",
126126 "follow_mode", "front_page", "hold", "issue_teams", "labels", "limb", "make_it_yours", "map", "merge", "new_app",
127127 "notify", "org_create", "origin_apps", "pins", "plan", "profile", "propose_to_parent_forge", "repo_labels", "reports",
test/mcp.test.ts +1
@@ -339,6 +339,7 @@ describe("the forge over MCP", () => {
339339 "flow",
340340 "system",
341341 "backups",
342 "bets",
342343 "telemetry_history",
343344 "contribute",
344345 "limits",
test/security-floor-routes.test.ts +2
@@ -43,11 +43,13 @@ const SECRET = "needs a secret scope an operator has set";
4343 const GO = "needs a short code minted by a share; the seed shares nothing";
4444 const ARCH = "needs an archived-home operation id; the seed archives nothing";
4545 const GATE = "needs a kept gate log, written only when a full gate runs on land";
46 const BET = "needs a backed bet; the seed backs none";
4647 const HOOK = "needs a webhook, which the seed does not register";
4748
4849 /** GET patterns the seed cannot fill → why. Requested with a placeholder all the same. */
4950 const UNSEEDED: Record<string, string> = {
5051 "/:owner/-/teams/:team": ORG,
52 "/:owner/:name/bets/:id": BET,
5153 "/:owner/:name/looks/:env/:commit/:kind.png": LOOK,
5254 "/:owner/:name/milestones/:number/limb/:op": LIMB,
5355 "/:owner/:name/variants/:group": VARIANT,

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs