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

A bet can carry a daily spend cap, and the crew holds at it with a plain note #13996

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

scout/forge:scout/13979-a-bet-can-carry-a-daily-spend-cap-and-th → main 3 commits fork 2 threads · 2 unresolved

  • Merged. scout/13979-a-bet-can-carry-a-daily-spend-cap-and-th was merged into main as 339ebae.

Review

Sign in to review this change.
16 files changed +420 −19
docs/MCP.md +1 −1
@@ -80,7 +80,7 @@ bytes in `tools/list`. After changing a tool run `bun scripts/mcp-table.ts`;
8080 | `backups` | — | Admin: snapshot destination, recent, mirror | 163 |
8181 | `backups_destination` | `set`, `forget` | Admin: snapshot destination | 322 |
8282 | `backups_test` | — | Test the snapshot destination | 102 |
83 | `bet` | — | Propose, back, stop, cut or end a bet; write what is left; say whether it feels done | 480 |
83 | `bet` | — | Propose, back, stop, cut or end a bet; write what is left; say whether it feels done | 510 |
8484 | `bets` | — | A repository's bets and their scopes | 195 |
8585 | `board_delete` | — | Delete a board by slug (history keeps it) | 194 |
8686 | `board_pins` | — | The panels pinned to the caller's home (person admins) | 302 |
docs/features/bets.md +2
@@ -14,6 +14,8 @@ A bet is a name, an appetite (a share of the week), what done looks like in a fe
1414 - **Finishing.** When every scope is closed the bet is finished and its page says "This is done. Try it." with a link; the owner taps *Feels done* or *Not yet, because…* (the bet returns to stopped with that reason). `/changelog` marks each landing with its bet and filters by it (`?bet=`).
1515 - **Idle forge.** If nothing was ever backed and the oldest proposal is a day old, the top two start at 10%, marked "not backed by the owner". One tap on *Stop it* ends any of them, and the planner does not restart a stopped bet.
1616
17 - **Daily cap.** A bet can carry a cap in dollars a day (the bet page, MCP `bet` verb `cap`, `$` in the terminal; empty clears it; a positive amount of at most cents, else refused). Once the runs on its scopes have spent the cap since 00:00 UTC (`usage` rows), the crew holds the bet's *queued* runs, never a running one, with the log note `queued, not started: the bet "…" is at its daily cap of $X (UTC day); it resumes at 00:00 UTC`; vitals counts them as held by a bet's daily cap, not as failures. The next UTC day they start as usual. Setting emits `bet.capped`.
18
1719 Left out: a per-week reset of the appetite window.
1820
1921 A note of the owner's (or an admin's) whose issue no group holds seeds a bet of its own, named from the note and quoting it, even alone. A visitor's note never does.
src/actions/bets.ts +15 −1
@@ -9,7 +9,7 @@
99 import type { App } from "../app.ts";
1010 import { listCrewRoles } from "../core/agents.ts";
1111 import {
12 type Bet, betRuns, betScopes, costRate, getBet, insertBet, listBets, markBacked, markEnded, setLeftLine, setTryUrl, setVerdict,
12 type Bet, betRuns, betScopes, costRate, getBet, insertBet, listBets, markBacked, markEnded, setCap, setLeftLine, setTryUrl, setVerdict,
1313 } from "../core/bets.ts";
1414 import { notesOfRepo } from "../core/app_notes.ts";
1515 import { themeWords, groupByWords } from "../core/bet_themes.ts";
@@ -19,6 +19,7 @@ import { canAdmin, type Repo } from "../core/repos.ts";
1919 import { grantLeft } from "../core/model_grant.ts";
2020 import { getUserById, type User } from "../core/users.ts";
2121 import { AUTO_SHARE, autoStarts, budgetSeconds, mayBack, spentSeconds, spentUp, shortSentence, walletEstimate, type WalletEstimate } from "../crew/bets.ts";
22 import { parseCap } from "../crew/bet_cap.ts";
2223 import { err, ok, type Result } from "../kernel/result.ts";
2324
2425 export type BetError = "forbidden" | "not_found" | "refused" | "wallet";
@@ -190,6 +191,19 @@ export function backBet(app: App, user: User, repo: Repo, id: string, share: num
190191 return ok(getBet(app.db, id)!);
191192 }
192193
194 /** The owner sets (or clears, with an empty `raw`) a bet's daily spend cap in dollars (#13979). */
195 export function capBet(app: App, user: User, repo: Repo, id: string, raw: unknown): Answer {
196 if (!owns(app, repo, user)) return refuse("forbidden", "only the owner sets a bet's cap");
197 const bet = load(app, repo, id);
198 if (bet === undefined) return refuse("not_found", "no such bet");
199 if (bet.state === "done" || bet.state === "cut") return refuse("refused", "that bet has ended");
200 const cap = parseCap(raw);
201 if (!cap.ok) return refuse("refused", cap.why);
202 setCap(app.db, id, cap.cap);
203 app.bus.append({ kind: "bet.capped", repoId: repo.id, actorId: user.id, payload: { bet: id, cap: cap.cap } });
204 return ok(getBet(app.db, id)!);
205 }
206
193207 /** One tap stops a bet, whoever started it: it keeps its scopes and can be backed again. */
194208 export function stopBet(app: App, user: User, repo: Repo, id: string, now = new Date()): Answer {
195209 if (!owns(app, repo, user)) return refuse("forbidden", "only the owner stops a bet");
src/core/bets.ts +20 −2
@@ -17,6 +17,8 @@ export interface Bet {
1717 readonly name: string;
1818 readonly journeys: string;
1919 readonly appetite: number;
20 /** Dollars a day (UTC) its scopes' runs may spend; null is no cap (#13979). */
21 readonly capUsd: number | null;
2022 readonly leadId: string | null;
2123 readonly state: BetState;
2224 readonly backedBy: "" | "owner" | "planner";
@@ -30,13 +32,13 @@ export interface Bet {
3032 }
3133
3234 interface Row {
33 id: string; repo_id: string; name: string; journeys: string; appetite: number; lead_id: string | null;
35 id: string; repo_id: string; name: string; journeys: string; appetite: number; cap_usd: number | null; lead_id: string | null;
3436 state: BetState; backed_by: "" | "owner" | "planner"; left_line: string; try_url: string;
3537 verdict: "" | "done" | "not_yet"; verdict_why: string; proposed_at: string; backed_at: string | null; ended_at: string | null;
3638 }
3739
3840 const toBet = (r: Row): Bet => ({
39 id: r.id, repoId: r.repo_id, name: r.name, journeys: r.journeys, appetite: r.appetite, leadId: r.lead_id,
41 id: r.id, repoId: r.repo_id, name: r.name, journeys: r.journeys, appetite: r.appetite, capUsd: r.cap_usd, leadId: r.lead_id,
4042 state: r.state, backedBy: r.backed_by, leftLine: r.left_line, tryUrl: r.try_url, verdict: r.verdict,
4143 verdictWhy: r.verdict_why, proposedAt: r.proposed_at, backedAt: r.backed_at, endedAt: r.ended_at,
4244 });
@@ -91,6 +93,22 @@ export function setVerdict(db: Database, id: string, verdict: "done" | "not_yet"
9193 db.query("UPDATE bet SET verdict = ?2, verdict_why = ?3 WHERE id = ?1").run(id, verdict, why);
9294 }
9395
96 export function setCap(db: Database, id: string, cap: number | null): void {
97 db.query("UPDATE bet SET cap_usd = ?2 WHERE id = ?1").run(id, cap);
98 }
99
100 /** What the runs on a bet's scopes spent since `since` (the start of the UTC day), in dollars. */
101 export function betSpentSince(db: Database, betId: string, since: string): number {
102 return (
103 db
104 .query<{ s: number }, [string, string]>(
105 `SELECT COALESCE(SUM(cost_usd), 0) AS s FROM usage
106 WHERE at >= ?2 AND issue_id IN (SELECT issue_id FROM bet_issue WHERE bet_id = ?1)`,
107 )
108 .get(betId, since)?.s ?? 0
109 );
110 }
111
94112 export function setTryUrl(db: Database, id: string, url: string): void {
95113 db.query("UPDATE bet SET try_url = ?2 WHERE id = ?1").run(id, url);
96114 }
src/core/migration-pins/20261116110000-bet-cap.pin added +1
@@ -0,0 +1,1 @@
1 5393620cd9f1ab043bac66bdf91ff42f3284cd6e94a6648e41aa35e57a772db5
src/core/migrations/20261116110000-bet-cap.ts added +5
@@ -0,0 +1,5 @@
1 // A bet's daily spend cap (#13979): dollars a day (UTC) its scopes' runs may spend before the crew
2 // holds their queued runs until the next day. Null is no cap. One nullable column. Additive.
3 export default `
4 ALTER TABLE bet ADD COLUMN cap_usd REAL CHECK (cap_usd IS NULL OR cap_usd > 0);
5 `;
src/crew/bet_cap.ts added +48
@@ -0,0 +1,48 @@
1 /**
2 * A bet's daily spend cap (#13979): pure rules. The day is the UTC day; a cap is a positive amount
3 * in dollars; spend at the cap holds the bet's queued runs (never kills a running one) until the
4 * UTC day turns.
5 */
6
7 /** The most a cap may be: a typo's guard, not a policy. */
8 export const CAP_MAX = 100_000;
9
10 /** The start of `now`'s UTC day, ISO 8601. */
11 export function dayStart(now: Date): string {
12 return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate())).toISOString();
13 }
14
15 const BAD = "a cap is a positive amount in dollars, like 5 or 2.50";
16
17 /**
18 * A cap from a form or a tool: a positive amount, cents at most; empty or "none" clears it (null).
19 */
20 export function parseCap(raw: unknown): { ok: true; cap: number | null } | { ok: false; why: string } {
21 if (raw === null || raw === undefined) return { ok: true, cap: null };
22 if (typeof raw === "string" && /^\s*(|none|off)\s*$/i.test(raw)) return { ok: true, cap: null };
23 const text = typeof raw === "string" ? raw.trim().replace(/^\$/, "") : raw;
24 if (typeof text === "string" && !/^\d{1,9}(\.\d{1,2})?$/.test(text)) return { ok: false, why: BAD };
25 if (typeof text !== "string" && typeof text !== "number") return { ok: false, why: BAD };
26 const n = Number(text);
27 if (!Number.isFinite(n) || n <= 0) return { ok: false, why: BAD };
28 if (n > CAP_MAX) return { ok: false, why: `a cap is at most $${CAP_MAX} a day` };
29 return { ok: true, cap: Math.round(n * 100) / 100 };
30 }
31
32 /** A dollar amount, always two decimals: the one way a cap is written. */
33 export const money = (n: number): string => `$${(Math.round(n * 100) / 100).toFixed(2)}`;
34
35 /** Whether today's spend has reached the cap. */
36 export const capReachedToday = (cap: number | null, spent: number): boolean => cap !== null && spent >= cap;
37
38 /** The plain note on a held run: not a failure. */
39 export function capNote(name: string, cap: number): string {
40 return `queued, not started: the bet "${name}" is at its daily cap of ${money(cap)} (UTC day); it resumes at 00:00 UTC`;
41 }
42
43 /** Where a capped bet stands today, for the owner's eye: the spend against the cap, and a hold. */
44 export function capStanding(cap: number, spent: number): string {
45 return capReachedToday(cap, spent)
46 ? `held now: ${money(spent)} of ${money(cap)} spent today, resumes at 00:00 UTC`
47 : `${money(spent)} of ${money(cap)} spent today`;
48 }
src/crew/bet_cap_hold.ts added +27
@@ -0,0 +1,27 @@
1 /**
2 * The dispatcher's question for a bet's daily cap (#13979): is this issue a scope of a running bet
3 * that has spent its cap today (UTC)? The words of the hold, or null. One read per bet per pass
4 * (`memo`, the pass's own map: bet id → the words or null).
5 */
6
7 import type { App } from "../app.ts";
8 import { betSpentSince, getBet } from "../core/bets.ts";
9 import { capNote, capReachedToday, dayStart } from "./bet_cap.ts";
10
11 export function betCapHold(app: App, repoId: string, issueId: string, memo: Map<string, string | null>, now = new Date()): string | null {
12 const rows = app.db
13 .query<{ bet_id: string }, [string, string]>(
14 `SELECT bi.bet_id FROM bet_issue bi JOIN bet b ON b.id = bi.bet_id
15 WHERE bi.issue_id = ?2 AND b.repo_id = ?1 AND b.state = 'backed' AND b.cap_usd IS NOT NULL`,
16 )
17 .all(repoId, issueId);
18 for (const { bet_id } of rows) {
19 if (!memo.has(bet_id)) {
20 const bet = getBet(app.db, bet_id)!;
21 memo.set(bet_id, capReachedToday(bet.capUsd, betSpentSince(app.db, bet_id, dayStart(now))) ? capNote(bet.name, bet.capUsd!) : null);
22 }
23 const note = memo.get(bet_id)!;
24 if (note !== null) return note;
25 }
26 return null;
27 }
src/crew/dispatch.ts +12
@@ -13,6 +13,7 @@ import { chapterHold } from "../core/chapters.ts";
1313 import { crewFilters, isStrangerPull } from "./stranger.ts";
1414 import { TEMP_FULL } from "../checks/disk_full.ts";
1515 import { freshPullFor } from "./fresh_pull.ts";
16 import { betCapHold } from "./bet_cap_hold.ts";
1617 import { weekHold } from "./week_hold.ts";
1718 import { weekFor, weekSpent } from "./week_read.ts";
1819 import { twinNote, twinOf, type Twin } from "./twin.ts";
@@ -1682,6 +1683,7 @@ export function pump(
16821683 // One week read per repository per pass: past the slots the loop still
16831684 // reads every queued run, to say which the pace or a limit holds (#11518).
16841685 const weeks = new Map<string, ReturnType<typeof weekFor>>();
1686 const capDay = new Map<string, string | null>();
16851687 for (const queued of gated.order) {
16861688 // One run per issue at a time: this one waits for its sibling, not for a slot.
16871689 // A sibling that hangs is still caught: the running run goes stale on its
@@ -1718,6 +1720,16 @@ export function pump(
17181720 continue;
17191721 }
17201722 }
1723 // A bet at its daily cap holds its scopes' queued runs till the UTC day turns (#13979).
1724 const capped = fresh.issueId === null ? null : betCapHold(app, fresh.repoId, fresh.issueId, capDay);
1725 if (capped !== null) {
1726 held.set(fresh.id, "cap");
1727 if (!noted.has(fresh.id)) {
1728 noted.add(fresh.id);
1729 appendRunLog(app.config.dataDir, fresh.id, capped);
1730 }
1731 continue;
1732 }
17211733 // An account at its concurrent-runs limit keeps this run queued, with
17221734 // the count in its log once, until one of its runs ends.
17231735 const owner = getRepoById(app.db, fresh.repoId)?.ownerId;
src/http/mcp/tools/bet.ts +6 −4
@@ -1,18 +1,19 @@
1 import { backBet, endBet, giveVerdict, proposeBets, stopBet, writeLeft } from "../../../actions/bets.ts";
1 import { backBet, capBet, endBet, giveVerdict, proposeBets, stopBet, writeLeft } from "../../../actions/bets.ts";
22 import { canAdmin } from "../../../core/repos.ts";
33 import { scopeAllows } from "../../../core/tokens.ts";
44 import { good, bad, type Tool, str, APP_ARG, planRepo, isAnswer } from "../shared.ts";
55
66 export const tool: Tool = {
77 name: "bet",
8 doc: "`{ app, verb, bet?, share?, line?, verdict?, why? }`: `propose` has the planner propose bets from open work; the owner `back`s one with a `share` of the week (at most 5 run), `stop`s, `cut`s or `end`s it, and gives a `verdict` (done, or not_yet with `why`) on a finished one; the lead writes what is `left` in one `line`. Needs a write token",
8 doc: "`{ app, verb, bet?, share?, line?, verdict?, why? }`: `propose` has the planner propose bets from open work; the owner `back`s one with a `share` of the week (at most 5 run), `cap`s it at a daily spend in dollars (`cap`, empty clears; the crew holds its queued runs at the cap until the UTC day turns), `stop`s, `cut`s or `end`s it, and gives a `verdict` (done, or not_yet with `why`) on a finished one; the lead writes what is `left` in one `line`. Needs a write token",
99 description: "Propose, back, stop, cut or end a bet; write what is left; say whether it feels done.",
1010 inputSchema: {
1111 type: "object",
1212 properties: {
1313 app: APP_ARG,
14 verb: { type: "string", enum: ["propose", "back", "stop", "cut", "end", "left", "verdict"] },
14 verb: { type: "string", enum: ["propose", "back", "cap", "stop", "cut", "end", "left", "verdict"] },
1515 bet: { type: "string", maxLength: 64 },
16 cap: { type: "string", maxLength: 12 },
1617 share: { type: "integer", minimum: 1, maximum: 100 },
1718 line: { type: "string", maxLength: 240 },
1819 verdict: { type: "string", enum: ["done", "not_yet"] },
@@ -35,13 +36,14 @@ export const tool: Tool = {
3536 const verdict = str(args["verdict"]);
3637 const done =
3738 verb === "back" ? backBet(ctx.app, user, repo, id, Number(args["share"]))
39 : verb === "cap" ? capBet(ctx.app, user, repo, id, str(args["cap"]))
3840 : verb === "stop" ? stopBet(ctx.app, user, repo, id)
3941 : verb === "cut" ? endBet(ctx.app, user, repo, id, "cut")
4042 : verb === "end" ? endBet(ctx.app, user, repo, id, "done")
4143 : verb === "left" ? writeLeft(ctx.app, user, repo, id, str(args["line"]))
4244 : verb === "verdict" && (verdict === "done" || verdict === "not_yet") ? giveVerdict(ctx.app, user, repo, id, verdict, str(args["why"]))
4345 : undefined;
44 if (done === undefined) return bad("bad_verb", "verb is propose, back, stop, cut, end, left or verdict");
46 if (done === undefined) return bad("bad_verb", "verb is propose, back, cap, stop, cut, end, left or verdict");
4547 if (!done.ok) return bad(done.error.error, done.error.message);
4648 return good({ says: `${done.value.name}: ${done.value.state}.`, state: done.value.state });
4749 },
src/runs/held.ts +2 −1
@@ -17,7 +17,7 @@ import type { Database } from "bun:sqlite";
1717 export const HELD_FRESH_MS = 2 * 60_000;
1818
1919 /** Why the dispatcher held a run. */
20 export type HoldCause = "valve" | "pace" | "limit" | "maintenance" | "issue" | "memory";
20 export type HoldCause = "valve" | "pace" | "limit" | "maintenance" | "issue" | "memory" | "cap";
2121
2222 /** How vitals names each cause: "2 by a shut valve". */
2323 export const HOLD_WORDS: Readonly<Record<HoldCause, string>> = {
@@ -27,6 +27,7 @@ export const HOLD_WORDS: Readonly<Record<HoldCause, string>> = {
2727 maintenance: "planned maintenance",
2828 issue: "its own issue's run still going",
2929 memory: "the forge's memory near its limit",
30 cap: "a bet's daily cap",
3031 };
3132
3233 interface Pass {
src/tui/screens/bets.ts +13 −3
@@ -8,8 +8,9 @@
88 * agent, a guest or a reader without admin sees nothing and does nothing.
99 */
1010
11 import { backBet, betEstimate, endBet, giveVerdict, proposeBets, stopBet, writeLeft, type BetError } from "../../actions/bets.ts";
11 import { backBet, betEstimate, capBet, endBet, giveVerdict, proposeBets, stopBet, writeLeft, type BetError } from "../../actions/bets.ts";
1212 import { estimateLine } from "../../crew/bets.ts";
13 import { money } from "../../crew/bet_cap.ts";
1314 import { type Bet, listBets } from "../../core/bets.ts";
1415 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
1516 import type { Result } from "../../kernel/result.ts";
@@ -65,7 +66,7 @@ export function betsScreen(f: Session, ctx: Ctx): Screen {
6566 const screen: Screen = {
6667 title: "Bets",
6768 keys: [
68 binding(["j", "k"], "move cursor"), binding(["p"], "propose"), binding(["b"], "back"), binding(["s"], "stop"),
69 binding(["j", "k"], "move cursor"), binding(["p"], "propose"), binding(["b"], "back"), binding(["$"], "daily cap"), binding(["s"], "stop"),
6970 binding(["c"], "cut"), binding(["e"], "end"), binding(["l"], "what is left"), binding(["d"], "feels done"), binding(["n"], "not yet"),
7071 ],
7172 async load(signal) {
@@ -88,7 +89,7 @@ export function betsScreen(f: Session, ctx: Ctx): Screen {
8889 const rows: ListRow[] = all.map(({ repo, bet }) => ({
8990 title: bet.name,
9091 ...(bet.state === "stopped" ? { tone: "danger" as const } : {}),
91 secondary: `${repo.name} · ${bet.state} · ${bet.appetite}% of the week${bet.backedBy === "planner" ? " · not backed by the owner" : ""}`,
92 secondary: `${repo.name} · ${bet.state} · ${bet.appetite}% of the week${bet.capUsd === null ? "" : ` · cap ${money(bet.capUsd)}/day`}${bet.backedBy === "planner" ? " · not backed by the owner" : ""}`,
9293 meta: bet.state === "done" && bet.verdict === "" ? "try it, then d or n" : bet.state === "proposed" ? estimateOf(repo, bet) : "",
9394 }));
9495 drawList(s, list!, c, state, rows);
@@ -117,6 +118,15 @@ export function betsScreen(f: Session, ctx: Ctx): Screen {
117118 onSubmit: (raw) => settle(backBet(f.app, user, repo, bet.id, Number(raw.trim())), "backed"),
118119 }),
119120 );
121 else if (e.key === "$")
122 ctx.push(
123 promptScreen(ctx, screen, {
124 title: `Daily cap for ${bet.name}`,
125 label: "dollars a day (UTC), empty for none",
126 value: bet.capUsd === null ? "" : bet.capUsd.toFixed(2),
127 onSubmit: (raw) => settle(capBet(f.app, user, repo, bet.id, raw), "cap set"),
128 }),
129 );
120130 else if (e.key === "s") settle(stopBet(f.app, user, repo, bet.id), "stopped");
121131 else if (e.key === "e") settle(endBet(f.app, user, repo, bet.id, "done"), "ended as done");
122132 else if (e.key === "c")
src/web/pages/bets.ts +16 −6
@@ -8,11 +8,12 @@
88 */
99
1010 import {
11 backBet, betEstimate, endBet, giveVerdict, oneLine, proposeBets, stopBet, writeLeft,
11 backBet, betEstimate, capBet, endBet, giveVerdict, oneLine, proposeBets, stopBet, writeLeft,
1212 } from "../../actions/bets.ts";
13 import { type Bet, betRuns, betScopes, getBet, listBets } from "../../core/bets.ts";
13 import { type Bet, betRuns, betScopes, betSpentSince, getBet, listBets } from "../../core/bets.ts";
1414 import { getUserById } from "../../core/users.ts";
1515 import { canAdmin, type Repo } from "../../core/repos.ts";
16 import { capStanding, dayStart, money } from "../../crew/bet_cap.ts";
1617 import { budgetSeconds, estimateLine, MAX_BACKED, mayBack, scopeState, spentSeconds, WALLET_WAY_OUT } from "../../crew/bets.ts";
1718 import type { Ctx } from "../../http/context.ts";
1819 import { json } from "../../http/respond.ts";
@@ -70,6 +71,14 @@ function backForm(repo: Repo, b: Bet, label: string): Html {
7071 </form>`;
7172 }
7273
74 /** The daily cap in dollars (UTC day); empty clears it (#13979). */
75 function capForm(repo: Repo, b: Bet): Html {
76 return html`<form method="post" action="${post(repo, b, "cap")}" class="bar">
outdated

Phone/keyboard: add inputmode="decimal" (and autocomplete off) so a thumb gets the numeric pad; shorten the label to 'Daily cap in dollars' and keep 'UTC day, empty for none' as a hint (principle 1, 8).

77 ${fieldRow({ name: "cap", label: "Daily cap in dollars", hint: "UTC day, empty for none", type: "text", inputmode: "decimal", autocomplete: "off", maxlength: 12, value: b.capUsd === null ? "" : b.capUsd.toFixed(2), id: `cap-${b.id}` })}
78 ${btn("Set the cap")}
79 </form>`;
80 }
81
7382 function oneButton(repo: Repo, b: Bet, verb: string, label: string, variant: "danger" | "secondary" = "secondary"): Html {
7483 return html`<form method="post" action="${post(repo, b, verb)}">${btn(label, { variant })}</form>`;
7584 }
@@ -124,11 +133,11 @@ const rows = (items: readonly Html[]): Html => html`<ul class="list setting-list
124133
125134 /** What the owner can do with a bet, by where it is. */
126135 function ownerActions(repo: Repo, b: Bet): Html | null {
127 if (b.state === "proposed") return html`${backForm(repo, b, "Back it")}${oneButton(repo, b, "cut", "Cut it", "danger")}`;
136 if (b.state === "proposed") return html`${backForm(repo, b, "Back it")}${capForm(repo, b)}${oneButton(repo, b, "cut", "Cut it", "danger")}`;
128137 if (b.state === "backed")
129 return html`${backForm(repo, b, "Change the share")}${oneButton(repo, b, "stop", "Stop it")}`;
138 return html`${backForm(repo, b, "Change the share")}${capForm(repo, b)}${oneButton(repo, b, "stop", "Stop it")}`;
130139 if (b.state === "stopped")
131 return html`${backForm(repo, b, "Back it again")}${oneButton(repo, b, "cut", "Cut it", "danger")}${oneButton(repo, b, "end", "End it: it's done")}`;
140 return html`${backForm(repo, b, "Back it again")}${capForm(repo, b)}${oneButton(repo, b, "cut", "Cut it", "danger")}${oneButton(repo, b, "end", "End it: it's done")}`;
132141 return null;
133142 }
134143
@@ -209,7 +218,7 @@ export function betPage(ctx: Ctx): Response {
209218 : null}`
210219 : null;
211220 const body = html`${repoHeader(ctx, repo, "issues")}
212 ${pageHead(bet.name, { sub: owner ? `${STATE_WORDS[bet.state]} · ${bet.appetite}% of the week${bet.state === "backed" ? ` · ${useWords(ctx, repo, bet, now)}` : ""}${whoBacked(bet) === "" ? "" : ` · ${whoBacked(bet)}`}${lead === undefined ? "" : ` · lead: ${lead.username}`}` : STATE_WORDS[bet.state] })}
221 ${pageHead(bet.name, { sub: owner ? `${STATE_WORDS[bet.state]} · ${bet.appetite}% of the week${bet.capUsd === null ? "" : ` · ${bet.state === "backed" ? capStanding(bet.capUsd, betSpentSince(ctx.app.db, bet.id, dayStart(now))) : `capped at ${money(bet.capUsd)} a day`}`}${bet.state === "backed" ? ` · ${useWords(ctx, repo, bet, now)}` : ""}${whoBacked(bet) === "" ? "" : ` · ${whoBacked(bet)}`}${lead === undefined ? "" : ` · lead: ${lead.username}`}` : STATE_WORDS[bet.state] })}
213222 ${moment}
214223 ${owner ? html`<h2 class="mt">Done looks like</h2>
215224 <ul>${bet.journeys.split("\n").filter((j) => j !== "").map((j) => html`<li>${j}</li>`)}</ul>` : null}
@@ -254,6 +263,7 @@ export async function betAct(ctx: Ctx): Promise<Response> {
254263 const verdict = field(form, "verdict");
255264 const result =
256265 verb === "back" ? backBet(ctx.app, user, repo, id, share)
266 : verb === "cap" ? capBet(ctx.app, user, repo, id, field(form, "cap"))
257267 : verb === "stop" ? stopBet(ctx.app, user, repo, id)
258268 : verb === "cut" ? endBet(ctx.app, user, repo, id, "cut")
259269 : verb === "end" ? endBet(ctx.app, user, repo, id, "done")
src/web/ui.ts +3
@@ -1280,6 +1280,8 @@ export interface FieldOptions {
12801280 autofocus?: boolean;
12811281 readonly?: boolean;
12821282 autocomplete?: string;
1283 /** The keyboard a phone opens: `decimal` for an amount. */
1284 inputmode?: "decimal" | "numeric";
12831285 placeholder?: string;
12841286 pattern?: string;
12851287 minlength?: number;
@@ -1361,6 +1363,7 @@ ${o.value ?? ""}</textarea
13611363 value="${o.value ?? ""}"
13621364 ${o.checked ? raw("checked") : null}
13631365 ${o.autocomplete ? html`autocomplete="${o.autocomplete}"` : null}
1366 ${o.inputmode ? html`inputmode="${o.inputmode}"` : null}
13641367 ${o.pattern ? html`pattern="${o.pattern}"` : null}
13651368 ${o.minlength !== undefined ? html`minlength="${o.minlength}"` : null}
13661369 ${o.maxlength !== undefined ? html`maxlength="${o.maxlength}"` : null}
test/bet-cap.test.ts added +159
@@ -0,0 +1,159 @@
1 /**

Missing tests: the web cap form/verb, MCP bet verb cap, and the TUI $ key are untested. Each needs a test that fails without it (refuse non-owner, refuse bad amount, store a good one).

2 * A bet's daily spend cap (#13979): validated as a positive amount, held (not failed, not killed)
3 * at the cap on the UTC day, resumed the next day.
4 */
5 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
6 import { chmodSync, writeFileSync } from "node:fs";
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 { backBet, capBet } from "../src/actions/bets.ts";
12 import { openIssue } from "../src/actions/issues.ts";
13 import { createRepo } from "../src/actions/repos.ts";
14 import { getBet, insertBet, markBacked } from "../src/core/bets.ts";
15 import { getRepoById, type Repo } from "../src/core/repos.ts";
16 import { createRun, getRun } from "../src/core/runs.ts";
17 import { recordUsage } from "../src/core/usage.ts";
18 import { createUser, type User } from "../src/core/users.ts";
19 import { dayStart, parseCap } from "../src/crew/bet_cap.ts";
20 import { betCapHold } from "../src/crew/bet_cap_hold.ts";
21 import { startCrew } from "../src/crew/dispatch.ts";
22 import { serve } from "../src/http/server.ts";
23 import { readRunLog } from "../src/runs/log.ts";
24 import { heldRuns } from "../src/runs/held.ts";
25
26 describe("the cap is a positive amount", () => {
27 test("dollars and cents, or empty for none; nothing else", () => {
28 expect(parseCap("5")).toEqual({ ok: true, cap: 5 });
29 expect(parseCap("$2.50")).toEqual({ ok: true, cap: 2.5 });
30 expect(parseCap("")).toEqual({ ok: true, cap: null });
31 expect(parseCap("none")).toEqual({ ok: true, cap: null });
32 for (const bad of ["0", "-3", "1e3", "abc", "2.555", "NaN", "1,5", "999999999999", "100001"]) expect(parseCap(bad).ok).toBe(false);
33 expect(parseCap({}).ok).toBe(false);
34 });
35
36 test("the day is the UTC day", () => {
37 expect(dayStart(new Date("2026-11-03T23:59:59-05:00"))).toBe("2026-11-04T00:00:00.000Z");
38 expect(dayStart(new Date("2026-11-03T00:00:00Z"))).toBe("2026-11-03T00:00:00.000Z");
39 });
40 });
41
42 let dataDir: string;
43 let app: App;
44 let alice: User;
45 let bob: User;
46 let repo: Repo;
47
48 beforeAll(async () => {
49 dataDir = await mkdtemp(join(tmpdir(), "forge-betcap-"));
50 app = createApp({ dataDir, port: 0, disk: () => ({ freeBytes: 100, totalBytes: 100 }) });
51 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
52 if (!a.ok) throw new Error(a.error);
53 alice = a.value;
54 const b = await createUser(app.db, { origin: "seed", trusted: true, username: "bob", email: "[email protected]", password: "a-good-passphrase" });
55 if (!b.ok) throw new Error(b.error);
56 bob = b.value;
57 const made = await createRepo(app, alice, { name: "capped", visibility: "public" });
58 if (!made.ok) throw new Error(String(made.error));
59 repo = made.value;
60 });
61 afterAll(async () => {
62 app.close();
63 await rm(dataDir, { recursive: true, force: true });
64 });
65
66 function bet(): { id: string; issueId: string } {
67 const issue = openIssue(app, alice, getRepoById(app.db, repo.id)!, { title: `Scope ${crypto.randomUUID().slice(0, 6)}` });
68 if (!issue.ok) throw new Error(String(issue.error));
69 const made = insertBet(app.db, { repoId: repo.id, name: "Night work", journeys: "", appetite: 20, leadId: null, issueIds: [issue.value.id] }, new Date());
70 markBacked(app.db, made.id, 20, "owner", new Date());
71 return { id: made.id, issueId: issue.value.id };
72 }
73
74 /** A finished run's line in the ledger (its own finished run row, so nothing is queued by it). */
75 function spend(issueId: string, usd: number, at: Date): void {
76 const done = createRun(app.db, { repoId: repo.id, kind: "check" });
77 app.db.query("UPDATE run SET state = 'ok' WHERE id = ?1").run(done.id);
78 recordUsage(app.db, { runId: done.id, repoId: repo.id, issueId, agentId: null, subscriptionId: null, tokensIn: 1, tokensOut: 1, costUsd: usd, wallMs: 1, outcome: "ok", at: at.toISOString() });
79 }
80
81 describe("setting the cap", () => {
82 test("only the owner sets it; a bad amount is refused; empty clears it", () => {
83 const { id } = bet();
84 const r = getRepoById(app.db, repo.id)!;
85 expect(capBet(app, bob, r, id, "5")).toMatchObject({ ok: false, error: { error: "forbidden" } });
86 expect(capBet(app, alice, r, id, "-1")).toMatchObject({ ok: false, error: { error: "refused" } });
87 expect(getBet(app.db, id)!.capUsd).toBeNull();
88 expect(capBet(app, alice, r, id, "7.5").ok).toBe(true);
89 expect(getBet(app.db, id)!.capUsd).toBe(7.5);
90 expect(capBet(app, alice, r, id, "").ok).toBe(true);
91 expect(getBet(app.db, id)!.capUsd).toBeNull();
92 });
93
94 test("the database refuses a zero cap", () => {
95 const { id } = bet();
96 expect(() => app.db.query("UPDATE bet SET cap_usd = 0 WHERE id = ?1").run(id)).toThrow();
97 });
98 });
99
100 describe("the hold", () => {
101 test("spend to the cap holds with a note naming the cap; the next UTC day resumes", () => {
102 const { id, issueId } = bet();
103 const r = getRepoById(app.db, repo.id)!;
104 capBet(app, alice, r, id, "5");
105 const day = new Date("2026-11-03T10:00:00Z");
106 spend(issueId, 3, day);
107 expect(betCapHold(app, repo.id, issueId, new Map(), day)).toBeNull();
108 spend(issueId, 2, new Date("2026-11-03T11:00:00Z"));
109 const note = betCapHold(app, repo.id, issueId, new Map(), new Date("2026-11-03T23:59:00Z"));
110 expect(note).toContain("daily cap of $5.00");
111 expect(note).toContain("queued, not started");
112 expect(betCapHold(app, repo.id, issueId, new Map(), new Date("2026-11-04T00:00:00Z"))).toBeNull();
113 });
114
115 test("a bet with no cap, or one that is not running, holds nothing", () => {
116 const { id, issueId } = bet();
117 spend(issueId, 1000, new Date("2026-11-03T10:00:00Z"));
118 expect(betCapHold(app, repo.id, issueId, new Map(), new Date("2026-11-03T12:00:00Z"))).toBeNull();
119 capBet(app, alice, getRepoById(app.db, repo.id)!, id, "1");
120 app.db.query("UPDATE bet SET state = 'stopped' WHERE id = ?1").run(id);
121 expect(betCapHold(app, repo.id, issueId, new Map(), new Date("2026-11-03T12:00:00Z"))).toBeNull();
122 });
123
124 test("the dispatcher holds a queued run at the cap, as held and not failed, and starts it when the spend is yesterday's", async () => {
125 const { id, issueId } = bet();
126 capBet(app, alice, getRepoById(app.db, repo.id)!, id, "5");
127 const run = createRun(app.db, { repoId: repo.id, kind: "agent", issueId });
128 spend(issueId, 5, new Date());
129 const servers = await serve(app);
130 const fake = join(dataDir, "fake-claude");
131 writeFileSync(fake, `#!/bin/sh\nif [ "$1" = "--version" ]; then echo "2.1.0 (fake)"; exit 0; fi\nexit 1\n`);
132 chmodSync(fake, 0o755);
133 const crew = await startCrew(app, { forgeUrl: servers.url, localUrl: servers.url, binary: fake, concurrency: 2, budgetUsd: 1, runTimeoutMs: 60_000, tickMs: 20 });
134 try {
135 const deadline = Date.now() + 10_000;
136 while (heldRuns(app.db).get(run.id) !== "cap" && Date.now() < deadline) await Bun.sleep(20); // real-timer: polls a live dispatcher tick for the hold
137 expect(heldRuns(app.db).get(run.id)).toBe("cap");
138 expect(getRun(app.db, run.id)?.state).toBe("queued");
139 expect(readRunLog(dataDir, run.id).lines.join("\n")).toContain("daily cap of $5.00");
140 // The day turns: today's spend is now yesterday's, and the run is no longer held.
141 app.db.query("UPDATE usage SET at = ?2 WHERE issue_id = ?1").run(issueId, new Date(Date.now() - 2 * 86400_000).toISOString());
142 const until = Date.now() + 10_000;
143 while (getRun(app.db, run.id)?.state === "queued" && Date.now() < until) await Bun.sleep(20); // real-timer: polls a live dispatcher tick for the release
144 expect(getRun(app.db, run.id)?.state).not.toBe("queued");
145 expect(heldRuns(app.db).get(run.id)).toBeUndefined();
146 } finally {
147 await crew.stop();
148 servers.stop();
149 }
150 });
151 });
152
153 test("backing a bet leaves its cap alone", () => {
154 const { id } = bet();
155 const r = getRepoById(app.db, repo.id)!;
156 capBet(app, alice, r, id, "4");
157 backBet(app, alice, r, id, 10);
158 expect(getBet(app.db, id)!.capUsd).toBe(4);
159 });
test/bets.test.ts +90 −1
@@ -8,7 +8,7 @@ import { mkdtemp, rm } from "node:fs/promises";
88 import { tmpdir } from "node:os";
99 import { join } from "node:path";
1010 import { createApp, type App } from "../src/app.ts";
11 import { backBet, endBet, giveVerdict, proposeBets, stopBet, tickBets, writeLeft } from "../src/actions/bets.ts";
11 import { backBet, capBet, endBet, giveVerdict, proposeBets, stopBet, tickBets, writeLeft } from "../src/actions/bets.ts";
1212 import { addToCrew, createAgent } from "../src/actions/crew.ts";
1313 import { openIssue } from "../src/actions/issues.ts";
1414 import { commitToBranch, createRepo, updateRepoSettings } from "../src/actions/repos.ts";
@@ -787,3 +787,92 @@ describe("the wallet", () => {
787787 });
788788 });
789789 });
790
791 describe("the daily cap at its three doors (#13979)", () => {
792 const BAD = "a cap is a positive amount in dollars";
793 const capOf = (id: string) => getBet(app.db, id)!.capUsd;
794
795 test("the page: a non-owner is refused, a bad amount is refused plainly, a good one is stored and drawn with two decimals", async () => {
796 const b = fresh2("CapPage");
797 const bob = await signIn("bob");
798 await act(bob, `/alice/notes/bets/${b.id}/cap`, { cap: "5" });
799 expect(capOf(b.id)).toBeNull();
800 const alicec = await signIn("alice");
801 const bad = await act(alicec, `/alice/notes/bets/${b.id}/cap`, { cap: "lots" });
802 expect(bad.status).toBe(303);
803 expect(capOf(b.id)).toBeNull();
804 const flash = (bad.headers.getSetCookie?.() ?? []).map((c) => c.split(";")[0]).join("; ");
805 const after = await (await fetch(`${servers.url}${bad.headers.get("location")}`, { headers: { cookie: `${alicec}; ${flash}` } })).text();
806 expect(after).toContain(BAD);
807 expect((await act(alicec, `/alice/notes/bets/${b.id}/cap`, { cap: "2.5" })).status).toBe(303);
808 expect(capOf(b.id)).toBe(2.5);
809 const page = await (await fetch(`${servers.url}/alice/notes/bets/${b.id}`, { headers: { cookie: alicec } })).text();
810 expect(page).toContain("Daily cap in dollars");
811 expect(page).toContain('inputmode="decimal"');
812 expect(page).toContain('value="2.50"');
813 expect(page).toContain("$2.50");
814 expect(page).not.toContain("$2.5 ");
815 });
816
817 test("the page says where the owner set the cap that a backed bet is held now", async () => {
818 const b = fresh2("CapHeld");
819 markBacked(app.db, b.id, 10, "owner", NOW);
820 capBet(app, alice, fresh(), b.id, "3");
821 const alicec = await signIn("alice");
822 expect(await (await fetch(`${servers.url}/alice/notes/bets/${b.id}`, { headers: { cookie: alicec } })).text()).toContain("$0.00 of $3.00 spent today");
823 const issue = open("Capped scope");
824 app.db.query("INSERT INTO bet_issue (bet_id, issue_id) VALUES (?1, ?2)").run(b.id, issue.id);
825 recordUsage(app.db, {
826 runId: createRun(app.db, { repoId: repo.id, kind: "agent", issueId: issue.id }).id, repoId: repo.id, issueId: issue.id, agentId: null, subscriptionId: null,
827 tokensIn: 0, tokensOut: 0, costUsd: 3, wallMs: 1000, outcome: "ok", at: new Date().toISOString(),
828 });
829 expect(await (await fetch(`${servers.url}/alice/notes/bets/${b.id}`, { headers: { cookie: alicec } })).text()).toContain("held now: $3.00 of $3.00 spent today");
830 });
831
832 test("MCP: a non-owner is refused, a bad amount is refused plainly, a good one is stored", async () => {
833 const b = fresh2("CapMcp");
834 const bob = (await getUserByName(app.db, "bob"))!;
835 const refused = await betTool.run(mcpCtx(bob, "rw"), bob, { app: "alice/notes", verb: "cap", bet: b.id, cap: "5" });
836 expect(refused.ok).toBe(false);
837 expect(capOf(b.id)).toBeNull();
838 const bad = await betTool.run(mcpCtx(alice, "rw"), alice, { app: "alice/notes", verb: "cap", bet: b.id, cap: "-1" });
839 expect(bad.ok).toBe(false);
840 expect(JSON.stringify(bad)).toContain(BAD);
841 expect(capOf(b.id)).toBeNull();
842 const good = await betTool.run(mcpCtx(alice, "rw"), alice, { app: "alice/notes", verb: "cap", bet: b.id, cap: "4.25" });
843 expect(good.ok).toBe(true);
844 expect(capOf(b.id)).toBe(4.25);
845 });
846
847 async function typeInto(user: User, name: string, chars: string): Promise<string> {
848 const terminal = headlessTerminal(160, 32);
849 const { app: tui } = createForgeApp(app, { sshUsername: "t", remoteAddress: "127.0.0.1", user }, { terminal, exitHooks: false });
850 tui.start();
851 const key = async (k: string) => {
852 tui.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false });
853 await settleApp(tui);
854 };
855 tui.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false });
856 await settleApp(tui);
857 for (const ch of "Bets") await key(ch);
858 await key("enter");
859 await key("$");
860 for (const ch of chars) await key(ch);
861 await key("enter");
862 const text = tui.screen.toText().replace(/\s+/g, " ");
863 tui.stop();
864 return text;
865 }
866
867 test("the terminal: a non-owner cannot set it, a bad amount is refused plainly, a good one is stored", async () => {
868 app.db.query("DELETE FROM bet WHERE repo_id = ?1").run(repo.id);
869 const b = fresh2("CapTerm");
870 const bob = (await getUserByName(app.db, "bob"))!;
871 await typeInto(bob, "CapTerm", "5");
872 expect(capOf(b.id)).toBeNull();
873 expect(await typeInto(alice, "CapTerm", "lots")).toContain(BAD);
874 expect(capOf(b.id)).toBeNull();
875 await typeInto(alice, "CapTerm", "2.5");
876 expect(capOf(b.id)).toBe(2.5);
877 });
878 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs