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

A bet refuses to start when the wallet cannot cover its estimate, and says both numbers #13505

Merged opened this

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

Merged

scout/forge:scout/13490-a-bet-refuses-to-start-when-the-wallet-c → main 4 commits fork 2 threads · 2 unresolved

  • Merged. scout/13490-a-bet-refuses-to-start-when-the-wallet-c was merged into main as e31be76.

Review

Sign in to review this change.
7 files changed +218 −15
docs/features/bets.md +1 −1
@@ -6,7 +6,7 @@ A bet is a name, an appetite (a share of the week), what done looks like in a fe
66 - **Propose.** "Ask the planner to propose bets" groups open issues in no live bet: by first label; else by the pillar an unlabelled issue holds up (later and structural issues are skipped); else by the title word most unlabelled issues share. A group of two or more becomes a proposal at 20% of the week. At most five proposals a pass; no model, so the same state gives the same proposals.
77 - **Notes.** Only notes written by the repo's owner or an admin count (a visitor's never join or appear). Such a note joins a proposal when its issue is held there, it names one of the group's issues as `#N`, or it shares two words with the group's name and its issues' titles; it is quoted in the journeys as "The owner's note".
88 - **Back.** The owner (a person who administers the repo, never an agent) backs one with a share. At most 5 run, and their shares stay within 100%.
9 - **The wallet.** Backing is refused, with one sentence, when the bet's estimate passes what is left of the owner's model grant by more than a quarter. The estimate is the bet's budget (below) at the dollars a builder second has cost this repository's runs over 30 days, and the wallet is the grant's remainder less what the bets already running have yet to spend. With no grant or no history nothing is refused. The planner's own starts skip a bet the wallet cannot cover. The sentence ends with the way out: lower the share, or ask a site admin to raise the grant (Settings, Accounts). The web page, MCP `bet` and terminal show the same sentence.
9 - **The wallet.** Backing is refused, with one sentence naming both numbers, when the bet's estimate is above what is free of the owner's model grant; an estimate equal to it starts. A form shows the sentence as a flash on the bet; a JSON client gets 409. The estimate is the bet's budget (below) at the dollars a builder second has cost this repository's runs over 30 days, and the wallet is the grant's remainder less what the bets already running have yet to spend. With no grant or no history nothing is refused. The planner's own starts skip a bet the wallet cannot cover. The sentence ends with the way out: lower the share, or ask a site admin to raise the grant (Settings, Accounts). The web page, MCP `bet` and terminal show the same sentence.
1010 - **Picks.** Once a repository has ever had a bet backed, builders pick only scopes of a running bet, issues the owner asked for or raised, and small fixes, polish included (polish held to its share of the week, see polish-share.md). An issue in no bet does not start by itself. A repository with no bet picks as before.
1111 - **Appetite.** The budget is share × builder slots × one week of builder time, counted from the runs on the bet's scopes since it was backed. At the budget the bet stops: no extension. Its left line defaults to the open scopes; the lead rewrites it in one line; the owner re-backs, cuts or ends it (ending as done is for a stopped bet only; a running bet finishes when every scope closes).
1212 - **Scopes** read *figuring out* (no run yet), *executing*, or *raised hand* (nothing moved for two days), or *done*.
src/actions/bets.ts +2 −2
@@ -21,7 +21,7 @@ import { getUserById, type User } from "../core/users.ts";
2121 import { AUTO_SHARE, autoStarts, budgetSeconds, mayBack, spentSeconds, spentUp, walletRefusal } from "../crew/bets.ts";
2222 import { err, ok, type Result } from "../kernel/result.ts";
2323
24 export type BetError = "forbidden" | "not_found" | "refused";
24 export type BetError = "forbidden" | "not_found" | "refused" | "wallet";

Docs: docs/features/bets.md still describes the 25% margin; update it in this pull.

2525 type Answer = Result<Bet, { error: BetError; message: string }>;
2626
2727 const refuse = (error: BetError, message: string): Answer => err({ error, message });
@@ -176,7 +176,7 @@ export function backBet(app: App, user: User, repo: Repo, id: string, share: num
176176 const why = mayBack(others, share);
177177 if (why !== null) return refuse("refused", why);
178178 const poor = tooPoor(app, repo, share, others, now);
179 if (poor !== null) return refuse("refused", poor);
179 if (poor !== null) return refuse("wallet", poor);
180180 markBacked(app.db, id, share, "owner", now);
181181 app.bus.append({ kind: "bet.backed", repoId: repo.id, actorId: user.id, payload: { bet: id, share, by: "owner" } });
182182 return ok(getBet(app.db, id)!);
src/crew/bets.ts +1 −4
@@ -54,9 +54,6 @@ export function mayBack(backed: readonly { readonly appetite: number }[], share:
5454 return null;
5555 }
5656
57 /** An estimate counts as too much only when it passes the wallet by this much (it is rough). */
58 export const WALLET_MARGIN = 1.25;
59
6057 const usd = (n: number): string => `$${n.toFixed(2)}`;
6158
6259 /**
@@ -69,7 +66,7 @@ export function walletRefusal(wallet: number | undefined, rate: number | undefin
6966 if (wallet === undefined || rate === undefined || !(rate > 0)) return null;
7067 const estimate = rate * seconds;
7168 const free = Math.max(0, wallet - rate * committed);
72 if (estimate <= free * WALLET_MARGIN) return null;
69 if (estimate <= free) return null;
7370 return `This bet is estimated at ${usd(estimate)} but the wallet has ${usd(free)} free after the bets already running: lower the share, or ask a site admin to raise your grant.`;
7471 }
7572
src/web/pages/bets.ts +8 −4
@@ -8,16 +8,17 @@
88 */
99
1010 import {
11 backBet, endBet, giveVerdict, oneLine, proposeBets, stopBet, writeLeft, type BetError,
11 backBet, endBet, giveVerdict, oneLine, proposeBets, stopBet, writeLeft,
1212 } from "../../actions/bets.ts";
1313 import { type Bet, betRuns, betScopes, getBet, listBets } from "../../core/bets.ts";
1414 import { getUserById } from "../../core/users.ts";
1515 import { canAdmin, type Repo } from "../../core/repos.ts";
1616 import { budgetSeconds, MAX_BACKED, mayBack, scopeState, spentSeconds } from "../../crew/bets.ts";
1717 import type { Ctx } from "../../http/context.ts";
18 import { json } from "../../http/respond.ts";
1819 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
1920 import { crumbsFor, loadRepo, notFoundPage, pageHead, repoBase, repoHeader, repoPalette } from "../chrome.ts";
20 import { field, readForm } from "../form.ts";
21 import { field, prefersJson, readForm } from "../form.ts";
2122 import { html, type Html } from "../html.ts";
2223 import { flashTo, page } from "../layout.ts";
2324 import { liveClientJs, liveMount } from "../live.ts";
@@ -219,7 +220,7 @@ export function betPage(ctx: Ctx): Response {
219220 return response;
220221 }
221222
222 const WHY: Record<BetError, string> = { forbidden: "Only the owner can do that.", not_found: "No such bet.", refused: "" };
223 const WHY: Record<"forbidden" | "not_found", string> = { forbidden: "Only the owner can do that.", not_found: "No such bet." };
223224
224225 // POST /:owner/:name/bets/propose
225226 export async function betPropose(ctx: Ctx): Promise<Response> {
@@ -257,6 +258,9 @@ export async function betAct(ctx: Ctx): Promise<Response> {
257258 : verb === "verdict" && (verdict === "done" || verdict === "not_yet") ? giveVerdict(ctx.app, user, repo, id, verdict, field(form, "why"))
258259 : null;
259260 if (result === null) return notFoundPage(ctx);
260 if (!result.ok) return flashTo(ctx, result.error.error === "not_found" ? list : betHref(repo, id), { tone: "danger", message: result.error.message || WHY[result.error.error] });
261 // A wallet refusal is a 409 for a client that asked for JSON; a form gets the flash back on the
outdated

Principles 1 and 8: hand-rolled alert and a vague "Not started" heading. Use the flash/danger component and say plainly that the wallet cannot cover the bet. The comment above also wraps mid-sentence.

262 // bet.
263 if (!result.ok && result.error.error === "wallet" && prefersJson(ctx)) return json({ ok: false, error: result.error.message }, 409);
264 if (!result.ok) return flashTo(ctx, result.error.error === "not_found" ? list : betHref(repo, id), { tone: "danger", message: result.error.message || WHY[result.error.error === "not_found" ? "not_found" : "forbidden"] });
261265 return flashTo(ctx, betHref(repo, id), { message: oneLine(`${result.value.name}: ${STATE_WORDS[result.value.state]}.`) });
262266 }
test/bet-wallet-refusal.test.ts added +138
@@ -0,0 +1,138 @@
1 /**
2 * #13490: a bet whose estimate passes the wallet's balance is refused with 409 and one sentence
3 * naming both numbers; equal to the balance goes through; with no grant (no cap) nothing changes.
4 * The page, the API (JSON) and the MCP say the same words.
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 { backBet } from "../src/actions/bets.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { getBet, insertBet } from "../src/core/bets.ts";
14 import { setModelGrant } from "../src/core/model_grant.ts";
15 import { getRepoById, type Repo } from "../src/core/repos.ts";
16 import { createRun } 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 { walletRefusal } from "../src/crew/bets.ts";
20 import type { Ctx } from "../src/http/context.ts";
21 import { serve, type Servers } from "../src/http/server.ts";
22 import { tool as betTool } from "../src/http/mcp/tools/bet.ts";
23
24 const NOW = new Date("2026-11-03T12:00:00Z");
25 let dir: string;
26 let app: App;
27 let alice: User;
28 let repo: Repo;
29 let servers: Servers;
30
31 const fresh = () => getRepoById(app.db, repo.id)!;
32 const proposal = (appetite = 20) =>
33 insertBet(app.db, { repoId: repo.id, name: `Bet ${Math.random()}`, journeys: "", appetite, leadId: null, issueIds: [] }, NOW);
34 /** $1 per builder hour, so a whole slot-week (168 h) is $168 and a share is $1.68 a percent. */
35 const spend = (): void =>
36 recordUsage(app.db, {
37 runId: createRun(app.db, { repoId: repo.id, kind: "agent" }).id, repoId: repo.id, issueId: null, agentId: null, subscriptionId: null,
38 tokensIn: 0, tokensOut: 0, costUsd: 1, wallMs: 3600_000, outcome: "ok", at: "2026-11-02T10:00:00.000Z",
39 });
40 const cookieOf = async (): Promise<string> => {
41 const r = await fetch(`${servers.url}/signin`, {
42 method: "POST", redirect: "manual",
43 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
44 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
45 });
46 return (r.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
47 };
48 const mcpCtx = (): Ctx => {
49 const url = new URL("http://forge.test/mcp");
50 return { app, request: new Request(url.href), url, params: {}, auth: { user: alice, scope: "rw", via: "token" }, theme: undefined };
51 };
52
53 beforeAll(async () => {
54 dir = await mkdtemp(join(tmpdir(), "forge-betwallet-"));
55 app = createApp({ dataDir: dir, port: 0 });
56 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
57 if (!a.ok) throw new Error(a.error);
58 alice = a.value;
59 const made = await createRepo(app, alice, { name: "wallet", visibility: "public" });
60 if (!made.ok) throw new Error(String(made.error));
61 repo = made.value;
62 servers = await serve(app);
63 });
64
65 afterAll(async () => {
66 servers.stop();
67 app.close();
68 await rm(dir, { recursive: true, force: true });
69 });
70
71 describe("the sentence", () => {
72 test("below and equal to the balance pass; above refuses and names both numbers", () => {
73 expect(walletRefusal(10, 0.5, 19)).toBeNull();
74 expect(walletRefusal(10, 0.5, 20)).toBeNull();
75 expect(walletRefusal(10, 0.5, 21)).toBe(
76 "This bet is estimated at $10.50 but the wallet has $10.00 free after the bets already running: lower the share, or ask a site admin to raise your grant.",
77 );
78 });
79 });
80
81 describe("starting a bet", () => {
82 test("below the balance starts, above is refused as 'wallet' and stays proposed, no grant behaves as before", () => {
83 spend();
84 // 50% of a slot-week is $84.
85 setModelGrant(app.db, alice.id, 100, alice.id, NOW);
86 const ok = backBet(app, alice, fresh(), proposal().id, 50, NOW);
87 expect(ok.ok).toBe(true);
88 const over = proposal();
89 setModelGrant(app.db, alice.id, 50, alice.id, NOW);
90 const refused = backBet(app, alice, fresh(), over.id, 50, NOW);
91 expect(!refused.ok && refused.error.error).toBe("wallet");
92 expect(!refused.ok && refused.error.message).toContain("estimated at $84.00");
93 expect(!refused.ok && refused.error.message).toContain("the wallet has $");
94 expect(getBet(app.db, over.id)!.state).toBe("proposed");
95 setModelGrant(app.db, alice.id, null, alice.id, NOW);
96 expect(backBet(app, alice, fresh(), over.id, 50, NOW).ok).toBe(true);
97 });
98
99 test("equal to the balance starts", () => {
100 app.db.query("UPDATE bet SET state = 'stopped' WHERE repo_id = ?1").run(repo.id);
101 const b = proposal();
102 const slots = fresh().autonomySlots;
103 // The estimate of a 10% share, as the wallet reckons it, is exactly the grant.
104 const seconds = 0.1 * 7 * 24 * 3600 * slots;
105 const estimate = (1 / 3600) * seconds;
106 setModelGrant(app.db, alice.id, Math.ceil(estimate), alice.id, NOW);
107 expect(backBet(app, alice, fresh(), b.id, 10, NOW).ok).toBe(true);
108 setModelGrant(app.db, alice.id, null, alice.id, NOW);
109 });
110 });
111
112 describe("the doors", () => {
113 test("JSON answers 409, a form flashes the sentence on the bet, and the MCP says the same words", async () => {
114 app.db.query("UPDATE bet SET state = 'stopped' WHERE repo_id = ?1").run(repo.id);
115 const b = proposal();
116 setModelGrant(app.db, alice.id, 5, alice.id, NOW);
117 try {
118 const cookie = await cookieOf();
119 const headers = { cookie, "content-type": "application/x-www-form-urlencoded", origin: servers.url };
120 const path = `${servers.url}/alice/wallet/bets/${b.id}/back`;
121 const page = await fetch(path, { method: "POST", redirect: "manual", headers, body: "share=100" });
122 expect(page.status).toBe(303);
123 expect(page.headers.get("location")).toBe(`/alice/wallet/bets/${b.id}`);
124 const api = await fetch(path, { method: "POST", redirect: "manual", headers: { ...headers, accept: "application/json" }, body: "share=100" });
125 expect(api.status).toBe(409);
126 const sentence = ((await api.json()) as { error: string }).error;
127 expect(sentence).toMatch(/^This bet is estimated at \$[\d.]+ but the wallet has \$[\d.]+ free/);
128 const shown = await fetch(`${servers.url}/alice/wallet/bets/${b.id}`, { headers: { cookie: [cookie, ...page.headers.getSetCookie().map((c) => c.split(";")[0]!)].join("; ") } });
129 expect((await shown.text()).replace(/&amp;/g, "&")).toContain(sentence);
130 const mcp = await betTool.run(mcpCtx(), alice, { app: "alice/wallet", verb: "back", bet: b.id, share: 100 });
131 expect(!mcp.ok && mcp.error).toBe("wallet");
132 expect(!mcp.ok && mcp.message).toBe(sentence);
133 expect(getBet(app.db, b.id)!.state).toBe("proposed");
134 } finally {
135 setModelGrant(app.db, alice.id, null, alice.id, NOW);
136 }
137 });
138 });
test/bets.test.ts +4 −4
@@ -670,7 +670,7 @@ describe("the wallet", () => {
670670
671671 test("the sentence refuses only past the margin, counts what is running, and says nothing without a grant or history", () => {
672672 expect(walletRefusal(10, 0.01, 1000)).toBeNull();
673 expect(walletRefusal(10, 0.01, 1250)).toBeNull();
673 expect(walletRefusal(10, 0.01, 1250)).not.toBeNull();
674674 expect(walletRefusal(undefined, 0.01, 1e9)).toBeNull();
675675 expect(walletRefusal(10, undefined, 1e9)).toBeNull();
676676 expect(walletRefusal(10, 0.01, 2000)).toBe(
@@ -712,10 +712,10 @@ describe("the wallet", () => {
712712 setModelGrant(app.db, alice.id, 100, alice.id, NOW);
713713 spend(into, "2026-11-02T10:00:00.000Z");
714714 const slots = fresh(into).autonomySlots;
715 // One slot-week is $168 at $1 an hour: 60% is ~$100.8 and 40% ~$67.2, each inside the wallet's
716 // margin.
715 // One slot-week is $168 at $1 an hour: 50% is ~$84 and 40% ~$67.2, each inside the wallet,
716 // together past it.
717717 expect(slots).toBe(1);
718 expect(backBet(app, alice, fresh(into), first.id, 60, NOW).ok).toBe(true);
718 expect(backBet(app, alice, fresh(into), first.id, 50, NOW).ok).toBe(true);
719719 const refused = backBet(app, alice, fresh(into), second.id, 40, NOW);
720720 expect(refused.ok).toBe(false);
721721 expect(!refused.ok && refused.error.message).toContain("free after the bets already running");
test/tui-bets-wallet.test.ts added +64
@@ -0,0 +1,64 @@
1 /** #13490: backing a bet the wallet cannot cover, in the terminal, shows the page's sentence. */
2 import { afterAll, beforeAll, expect, test } from "bun:test";
3 import { mkdtemp, rm } from "node:fs/promises";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { createRepo } from "../src/actions/repos.ts";
7 import { createApp, type App } from "../src/app.ts";
8 import { insertBet } from "../src/core/bets.ts";
9 import { setModelGrant } from "../src/core/model_grant.ts";
10 import { createRun } from "../src/core/runs.ts";
11 import { recordUsage } from "../src/core/usage.ts";
12 import { createUser, type User } from "../src/core/users.ts";
13 import { createForgeApp } from "../src/tui/forge.ts";
14 import { headlessTerminal } from "../src/tui/term/terminal.ts";
15 import { quietLogs } from "./helpers/globals.ts";
16 import { settleApp } from "./helpers/tui.ts";
17
18 quietLogs();
19
20 let dir: string;
21 let forge: App;
22 let alice: User;
23
24 beforeAll(async () => {
25 dir = await mkdtemp(join(tmpdir(), "forge-tui-betwallet-"));
26 forge = createApp({ dataDir: dir, port: 0 });
27 const made = await createUser(forge.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
28 if (!made.ok) throw new Error(made.error);
29 alice = made.value;
30 const repo = await createRepo(forge, alice, { name: "wallet", visibility: "public" });
31 if (!repo.ok) throw new Error("repo");
32 insertBet(forge.db, { repoId: repo.value.id, name: "Wide", journeys: "one", appetite: 20, leadId: null, issueIds: [] }, new Date());
33 recordUsage(forge.db, {
34 runId: createRun(forge.db, { repoId: repo.value.id, kind: "agent" }).id, repoId: repo.value.id, issueId: null, agentId: null, subscriptionId: null,
35 tokensIn: 0, tokensOut: 0, costUsd: 1, wallMs: 3600_000, outcome: "ok", at: new Date().toISOString(),
36 });
37 setModelGrant(forge.db, alice.id, 5, alice.id, new Date());
38 });
39
40 afterAll(async () => {
41 forge?.close();
42 await rm(dir, { recursive: true, force: true });
43 });
44
45 test("backing over the wallet shows the same sentence and leaves the bet proposed", async () => {
46 const terminal = headlessTerminal(160, 32);
47 const { app } = createForgeApp(forge, { sshUsername: "t", remoteAddress: "127.0.0.1", user: alice }, { terminal, exitHooks: false });
48 app.start();
49 const key = (k: string) => app.dispatch({ type: "key", key: k, ctrl: k.startsWith("ctrl+"), alt: false, shift: false });
50 await settleApp(app);
51 app.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false });
52 for (const ch of "Bets") key(ch);
53 key("enter");
54 await settleApp(app);
55 key("b");
56 await settleApp(app);
57 key("enter");
58 await settleApp(app);
59 const text = app.screen.toText().replace(/\s+/g, " ");
60 expect(text).toContain("This bet is estimated at $");
61 expect(text).toContain("but the wallet has $");
62 expect(text).toContain("lower the share");
63 app.stop();
64 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs