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

A bet's card shows its estimate and the wallet balance side by side before it starts #13422

Merged opened this

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

Merged

scout/forge:scout/13404-a-bet-s-card-shows-its-estimate-and-the → main 7 commits fork 4 threads · 4 unresolved

  • Merged. scout/13404-a-bet-s-card-shows-its-estimate-and-the was merged into main as 08e2894.

Review

Sign in to review this change.
8 files changed +240 −14
docs/features/bets.md +1
@@ -7,6 +7,7 @@ A bet is a name, an appetite (a share of the week), what done looks like in a fe
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%.
99 - **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.
10 - **Before you press.** A proposed bet's card (and its row in the terminal) prints `Estimate $X of $Y left`, the estimate beside the wallet the refusal would judge by. When the estimate passes the wallet the line adds `short by $Z`, the *Back it* button is disabled, and the reason sits beside it. With no grant or no history there is no line. The line is on proposed cards only: a stopped bet re-backed from its page shows no estimate first, though the refusal still judges it.
1011 - **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.
1112 - **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).
1213 - **Scopes** read *figuring out* (no run yet), *executing*, or *raised hand* (nothing moved for two days), or *done*.
src/actions/bets.ts +12 −4
@@ -18,7 +18,7 @@ import { isStructural, LATER, pillarsOf, servedBy } from "../core/pillars.ts";
1818 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";
21 import { AUTO_SHARE, autoStarts, budgetSeconds, mayBack, spentSeconds, spentUp, walletRefusal } from "../crew/bets.ts";
21 import { AUTO_SHARE, autoStarts, budgetSeconds, mayBack, spentSeconds, spentUp, shortSentence, walletEstimate, type WalletEstimate } from "../crew/bets.ts";
2222 import { err, ok, type Result } from "../kernel/result.ts";
2323
2424 export type BetError = "forbidden" | "not_found" | "refused" | "wallet";
@@ -153,9 +153,10 @@ export function proposeBets(app: App, repo: Repo, now = new Date()): Bet[] {
153153 }
154154
155155 /**
156 * The wallet's sentence for a bet at `share` beside the `running` ones, or null when it is covered.
156 * The estimate for a bet at `share` beside the wallet left after the `running` ones; null without a
157 * grant or history.
157158 */
158 function tooPoor(app: App, repo: Repo, share: number, running: readonly Bet[], now: Date): string | null {
159 export function betEstimate(app: App, repo: Repo, share: number, running: readonly Bet[], now: Date): WalletEstimate | null {
159160 const wallet = grantLeft(app.db, repo.ownerId, now);
160161 const rate = costRate(app.db, repo.id, now);
161162 const seconds = budgetSeconds(share, repo.autonomySlots);

The committed-spend reduce is duplicated here and in tooPoor. Have tooPoor build on betEstimate (or extract one helper) so there is one calculation.

@@ -163,7 +164,14 @@ function tooPoor(app: App, repo: Repo, share: number, running: readonly Bet[], n
163164 const spent = spentSeconds(betRuns(app.db, b.id, b.backedAt ?? b.proposedAt), now);
164165 return sum + Math.max(0, budgetSeconds(b.appetite, repo.autonomySlots) - spent);
165166 }, 0);
166 return walletRefusal(wallet, rate, seconds, committed);
167 return walletEstimate(wallet, rate, seconds, committed);
168 }
169
170 /**
171 * The wallet's sentence for a bet at `share` beside the `running` ones, or null when it is covered.
172 */
173 function tooPoor(app: App, repo: Repo, share: number, running: readonly Bet[], now: Date): string | null {
174 return shortSentence(betEstimate(app, repo, share, running, now));
167175 }
168176
169177 /** The owner backs a proposed or stopped bet with a share of the week. */
src/crew/bets.ts +34 −2
@@ -63,11 +63,43 @@ const usd = (n: number): string => `$${n.toFixed(2)}`;
6363 * for them). With no grant or no history there is no estimate to hold the bet to.
6464 */
6565 export function walletRefusal(wallet: number | undefined, rate: number | undefined, seconds: number, committed = 0): string | null {
66 return shortSentence(walletEstimate(wallet, rate, seconds, committed));
67 }
68
69 /** The way out of a short wallet, said once by the refusal and the card's note. */
70 export const WALLET_WAY_OUT = "lower the share, or ask a site admin to raise your grant";
71
72 /**
73 * The refusal for an estimate the wallet cannot cover, or null: the one sentence the card and the
74 * refusal share.
75 */
76 export function shortSentence(e: WalletEstimate | null): string | null {
77 if (e === null || e.short === 0) return null;
78 return `This bet is estimated at ${usd(e.estimate)} but the wallet has ${usd(e.free)} free after the bets already running: ${WALLET_WAY_OUT}.`;
79 }
80
81 export interface WalletEstimate {
82 readonly estimate: number;
83 readonly free: number;
84 /** Dollars the estimate passes the wallet by; 0 when covered. */
85 readonly short: number;
86 }
87
88 /**
89 * The estimate beside the wallet (null with no grant or no history), the numbers `walletRefusal`
90 * judges by.
91 */
92 export function walletEstimate(wallet: number | undefined, rate: number | undefined, seconds: number, committed = 0): WalletEstimate | null {
6693 if (wallet === undefined || rate === undefined || !(rate > 0)) return null;
6794 const estimate = rate * seconds;
6895 const free = Math.max(0, wallet - rate * committed);
69 if (estimate <= free) return null;
70 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.`;
96 return { estimate, free, short: Math.max(0, estimate - free) };
97 }
98
99 /** The card's line: `Estimate $X of $Y left`, and when short, by how much. */
100 export function estimateLine(e: WalletEstimate): string {
101 const base = `Estimate ${usd(e.estimate)} of ${usd(e.free)} left`;
102 return e.short > 0 ? `${base}: short by ${usd(e.short)}` : base;
71103 }
72104
73105 export interface Proposed {
src/tui/screens/bets.ts +12 −2
@@ -8,7 +8,8 @@
88 * agent, a guest or a reader without admin sees nothing and does nothing.
99 */
1010
11 import { backBet, endBet, giveVerdict, proposeBets, stopBet, writeLeft, type BetError } from "../../actions/bets.ts";
11 import { backBet, betEstimate, endBet, giveVerdict, proposeBets, stopBet, writeLeft, type BetError } from "../../actions/bets.ts";
12 import { estimateLine } from "../../crew/bets.ts";
1213 import { type Bet, listBets } from "../../core/bets.ts";
1314 import { canAdmin, getRepoById, type Repo } from "../../core/repos.ts";
1415 import type { Result } from "../../kernel/result.ts";
@@ -43,6 +44,15 @@ export function betsScreen(f: Session, ctx: Ctx): Screen {
4344 const state = new ListState();
4445 let note = "";
4546 const lines = (): Line[] => administered(f).flatMap((repo) => listBets(f.app.db, repo.id).map((bet) => ({ repo, bet })));
47 /**
48 * The card's estimate line for a proposed bet, beside the bets already running; empty without a
49 * grant or history.
50 */
51 const estimateOf = (repo: Repo, bet: Bet): string => {
52 const running = listBets(f.app.db, repo.id).filter((b) => b.state === "backed");
53 const e = betEstimate(f.app, repo, bet.appetite, running, new Date());

No test reaches this branch. Add a terminal-screen test: covered shows 'Estimate $X of $Y left', short adds 'short by $Z', and no grant gives ''.

54 return e === null ? "" : estimateLine(e);
55 };
4656 const say = (text: string): void => {
4757 note = text;
4858 ctx.invalidate();
@@ -79,7 +89,7 @@ export function betsScreen(f: Session, ctx: Ctx): Screen {
7989 title: bet.name,
8090 ...(bet.state === "stopped" ? { tone: "danger" as const } : {}),
8191 secondary: `${repo.name} · ${bet.state} · ${bet.appetite}% of the week${bet.backedBy === "planner" ? " · not backed by the owner" : ""}`,
82 meta: bet.state === "done" && bet.verdict === "" ? "try it, then d or n" : "",
92 meta: bet.state === "done" && bet.verdict === "" ? "try it, then d or n" : bet.state === "proposed" ? estimateOf(repo, bet) : "",
8393 }));
8494 drawList(s, list!, c, state, rows);
8595 },
src/web/pages/bets.ts +8 −5
@@ -8,12 +8,12 @@
88 */
99
1010 import {
11 backBet, endBet, giveVerdict, oneLine, proposeBets, stopBet, writeLeft,
11 backBet, betEstimate, 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";
16 import { budgetSeconds, MAX_BACKED, mayBack, scopeState, spentSeconds } from "../../crew/bets.ts";
16 import { budgetSeconds, estimateLine, MAX_BACKED, mayBack, scopeState, spentSeconds, WALLET_WAY_OUT } from "../../crew/bets.ts";
1717 import type { Ctx } from "../../http/context.ts";
1818 import { json } from "../../http/respond.ts";
1919 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
@@ -85,10 +85,12 @@ export const SHOWN_JOURNEYS = 3;
8585 * the cap or the week forbids it the button is disabled and the reason sits
8686 * beside it. Changing the share is one disclosure away.
8787 */
88 function proposedRow(ctx: Ctx, repo: Repo, b: Bet, backed: readonly Bet[]): Html {
88 function proposedRow(ctx: Ctx, repo: Repo, b: Bet, backed: readonly Bet[], now: Date): Html {
8989 const scopes = betScopes(ctx.app.db, b.id);
9090 const journeys = b.journeys.split("\n").filter((j) => j !== "");
91 const why = mayBack(backed, b.appetite);
91 const estimate = betEstimate(ctx.app, repo, b.appetite, backed, now);
92 const why = mayBack(backed, b.appetite)
outdated

Principle 1: this note repeats the shortfall that the estimate line below already states ("short by $Z"). Keep one: make the disabled-button reason only the way out (lower the share, or ask a site admin to raise your grant), and use the shared dollar formatter rather than a hand-written toFixed.

93 ?? (estimate === null || estimate.short === 0 ? null : WALLET_WAY_OUT);
9294 const issues = scopes.length === 0
9395 ? html`<p class="muted">No issues yet.</p>`
9496 : html`<details><summary>${scopes.length} ${scopes.length === 1 ? "issue" : "issues"}</summary>
@@ -112,6 +114,7 @@ function proposedRow(ctx: Ctx, repo: Repo, b: Bet, backed: readonly Bet[]): Html
112114 </form>
113115 <details><summary>Change the share</summary>${backForm(repo, b, "Back it")}</details>
114116 ${oneButton(repo, b, "cut", "Cut it", "danger")}</div>
outdated

Principle 1: this line and the note under it both say the wallet is short by the same amount. Drop one.

117 ${estimate === null ? null : html`<p class="muted" data-bet-estimate>${estimateLine(estimate)}</p>`}
115118 ${why === null ? null : html`<p class="muted" role="note">${why[0]!.toUpperCase() + why.slice(1)}.</p>`}`,
116119 });
117120 }
@@ -146,7 +149,7 @@ export function betsPage(ctx: Ctx): Response {
146149 ${pageHead("Bets", { sub: `A few named wholes, each with a share of the week. ${running} of ${MAX_BACKED} running. Builders pick only from running bets, the owner's own asks and small fixes.` })}
147150 ${bets.length === 0
148151 ? html`<p class="muted">No bets yet. The planner proposes them from the open work.</p>`
149 : html`${rows([...(owner ? proposed.map((b) => proposedRow(ctx, repo, b, backed)) : []), ...rest.map((b) => betRow(ctx, repo, b, now, owner))])}`}
152 : html`${rows([...(owner ? proposed.map((b) => proposedRow(ctx, repo, b, backed, now)) : []), ...rest.map((b) => betRow(ctx, repo, b, now, owner))])}`}
150153 ${owner
151154 ? html`<form method="post" action="${repoBase(repo)}/bets/propose" class="mt">${btn("Ask the planner to propose bets", { variant: "secondary" })}</form>`
152155 : null}
test/bet-estimate-line.test.ts added +88
@@ -0,0 +1,88 @@
1 /**
2 * A proposed bet's card says what the bet is estimated to cost beside what the wallet has left
3 * (#13404): covered, it is one line; short, the line says by how much and the button is disabled
4 * with that reason. The same numbers decide the refusal.
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 { 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 { estimateLine, walletEstimate } from "../src/crew/bets.ts";
20 import { serve, type Servers } from "../src/http/server.ts";
21
22 let dir: string;
23 let app: App;
24 let servers: Servers;
25 let alice: User;
26 let repo: Repo;
27
28 beforeAll(async () => {
29 dir = await mkdtemp(join(tmpdir(), "forge-bet-estimate-"));
30 app = createApp({ dataDir: dir, port: 0 });
31 const a = await createUser(app.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
32 if (!a.ok) throw new Error(a.error);
33 alice = a.value;
34 const made = await createRepo(app, alice, { name: "notes", visibility: "public" });
35 if (!made.ok) throw new Error(String(made.error));
36 repo = made.value;
37 // $1 of builder time an hour.
38 recordUsage(app.db, {
39 runId: createRun(app.db, { repoId: repo.id, kind: "agent" }).id, repoId: repo.id, issueId: null, agentId: null, subscriptionId: null,
40 tokensIn: 0, tokensOut: 0, costUsd: 1, wallMs: 3600_000, outcome: "ok", at: new Date().toISOString(),
41 });
42 servers = await serve(app);
43 });
44
45 afterAll(async () => {
46 servers.stop();
47 app.close();
48 await rm(dir, { recursive: true, force: true });
49 });
50
51 async function card(): Promise<string> {
52 const login = await fetch(`${servers.url}/signin`, {
53 method: "POST", redirect: "manual",
54 headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url },
55 body: new URLSearchParams({ username: "alice", password: "a-good-passphrase" }),
56 });
57 const cookie = (login.headers.get("set-cookie") ?? "").split(";")[0] ?? "";
58 return (await fetch(`${servers.url}/alice/notes/bets`, { headers: { cookie } })).text();
59 }
60
61 describe("the estimate line", () => {
62 test("the words: covered says the two amounts, short says by how much, no grant or history says nothing", () => {
63 expect(estimateLine(walletEstimate(10, 0.01, 1000)!)).toBe("Estimate $10.00 of $10.00 left");
64 expect(estimateLine(walletEstimate(10, 0.01, 2000)!)).toBe("Estimate $20.00 of $10.00 left: short by $10.00");
65 expect(walletEstimate(undefined, 0.01, 1000)).toBeNull();
66 expect(walletEstimate(10, undefined, 1000)).toBeNull();
67 });
68
69 test("covered: the card prints the line and the button is live; short: it says by how much, and the button is disabled with the reason", async () => {
70 const bet = insertBet(app.db, { repoId: repo.id, name: "Costly", journeys: "", appetite: 20, leadId: null, issueIds: [] }, new Date());
71 const slots = getRepoById(app.db, repo.id)!.autonomySlots;
72 const estimate = (0.2 * slots * 7 * 24).toFixed(2);
73
74 setModelGrant(app.db, alice.id, 500, alice.id, new Date());
75 const covered = await card();
76 expect(covered).toContain(`Estimate $${estimate} of $500.00 left`);
77 expect(covered).not.toContain("short by");
78 expect(covered).not.toMatch(/<button[^>]*disabled[^>]*>\s*Back it at 20%/);
79
80 setModelGrant(app.db, alice.id, 5, alice.id, new Date());
81 const short = await card();
82 expect(short).toContain(`Estimate $${estimate} of $5.00 left: short by $${(Number(estimate) - 5).toFixed(2)}`);
83 expect(short).toMatch(/<button[^>]*disabled[^>]*>\s*Back it at 20%/);
84 expect(short).toContain("Lower the share, or ask a site admin to raise your grant.");
85 expect(short.match(/short by/g)).toHaveLength(1);
86 expect(backBet(app, alice, getRepoById(app.db, repo.id)!, bet.id, 20).ok).toBe(false);
87 });
88 });
test/refusals-lead-somewhere.test.ts +1 −1
@@ -42,7 +42,7 @@ const TERMINAL: Readonly<Record<string, string>> = {
4242 "src/http/respond.ts\tYour token's scope or your role on this resource": "The same hint, by code.",
4343 "src/actions/migrate.ts\tThat address is inside the network, not a public": "It gives the reader's own way through in the same sentence: connect the host as an origin.",
4444 "src/actions/contribute_token.ts\tthis repository does not take outside contributions": "A door its owner chose to keep shut, said as a fact to a stranger with no account here.",
45 "src/crew/bets.ts\tThis bet is estimated at ${usd(estimate)} but the wallet": "It gives the reader's own way through in the same sentence (lower the share); the grant is the owner's to raise, and the sentence is shared by the page, the planner and the tool.",
45 "src/crew/bets.ts\tlower the share, or ask a site admin to raise your grant": "The way out itself, shared by the refusal and the card's note beside the share control; the grant is the owner's to raise.",
4646 "src/actions/spawn.ts\t${name} is already claimed; ask its owner to": "The owner is of another forge (the hosted one), which this forge cannot ask on anyone's behalf.",
4747 };
4848
test/tui-bets-estimate.test.ts added +84
@@ -0,0 +1,84 @@
1 /**
2 * A proposed bet's row in the terminal carries the card's estimate line (#13404): covered, the two
3 * amounts; short, by how much; no grant, nothing.
4 */
5 import { afterAll, beforeAll, expect, test } from "bun:test";
6 import { mkdtemp, rm } from "node:fs/promises";
7 import { tmpdir } from "node:os";
8 import { join } from "node:path";
9 import { createRepo } from "../src/actions/repos.ts";
10 import { createApp, type App } from "../src/app.ts";
11 import { insertBet } from "../src/core/bets.ts";
12 import { setModelGrant } from "../src/core/model_grant.ts";
13 import { getRepoById } from "../src/core/repos.ts";
14 import { createRun } from "../src/core/runs.ts";
15 import { recordUsage } from "../src/core/usage.ts";
16 import { createUser, type User } from "../src/core/users.ts";
17 import { createForgeApp } from "../src/tui/forge.ts";
18 import { headlessTerminal } from "../src/tui/term/terminal.ts";
19 import { quietLogs } from "./helpers/globals.ts";
20 import { settleApp } from "./helpers/tui.ts";
21
22 quietLogs();
23
24 let dir: string;
25 let forge: App;
26 let alice: User;
27 let estimate: number;
28
29 beforeAll(async () => {
30 dir = await mkdtemp(join(tmpdir(), "forge-tui-betestimate-"));
31 forge = createApp({ dataDir: dir, port: 0 });
32 const made = await createUser(forge.db, { origin: "seed", trusted: true, username: "alice", email: "[email protected]", password: "a-good-passphrase", adminIfFirst: true });
33 if (!made.ok) throw new Error(made.error);
34 alice = made.value;
35 const repo = await createRepo(forge, alice, { name: "wallet", visibility: "public" });
36 if (!repo.ok) throw new Error("repo");
37 insertBet(forge.db, { repoId: repo.value.id, name: "Wide", journeys: "one", appetite: 20, leadId: null, issueIds: [] }, new Date());
38 // $1 of builder time an hour.
39 recordUsage(forge.db, {
40 runId: createRun(forge.db, { repoId: repo.value.id, kind: "agent" }).id, repoId: repo.value.id, issueId: null, agentId: null, subscriptionId: null,
41 tokensIn: 0, tokensOut: 0, costUsd: 1, wallMs: 3600_000, outcome: "ok", at: new Date().toISOString(),
42 });
43 estimate = 0.2 * getRepoById(forge.db, repo.value.id)!.autonomySlots * 7 * 24;
44 });
45
46 afterAll(async () => {
47 forge?.close();
48 await rm(dir, { recursive: true, force: true });
49 });
50
51 /** The Bets screen's text, opened from the palette. */
52 async function betsText(): Promise<string> {
53 const terminal = headlessTerminal(200, 24);
54 const { app } = createForgeApp(forge, { sshUsername: "t", remoteAddress: "127.0.0.1", user: alice }, { terminal, exitHooks: false });
55 app.start();
56 const key = (k: string) => app.dispatch({ type: "key", key: k, ctrl: false, alt: false, shift: false });
57 await settleApp(app);
58 app.dispatch({ type: "key", key: "k", ctrl: true, alt: false, shift: false });
59 for (const ch of "Bets") key(ch);
60 key("enter");
61 await settleApp(app);
62 const text = app.screen.toText().replace(/\s+/g, " ");
63 app.stop();
64 return text;
65 }
66
67 test("no grant: the row has no estimate line", async () => {
68 const text = await betsText();
69 expect(text).toContain("Wide");
70 expect(text).not.toContain("Estimate $");
71 });
72
73 test("covered: the row says the estimate of what is left", async () => {
74 setModelGrant(forge.db, alice.id, 500, alice.id, new Date());
75 const text = await betsText();
76 expect(text).toContain(`Estimate $${estimate.toFixed(2)} of $500.00 left`);
77 expect(text).not.toContain("short by");
78 });
79
80 test("short: the row adds by how much", async () => {
81 setModelGrant(forge.db, alice.id, 5, alice.id, new Date());
82 const text = await betsText();
83 expect(text).toContain(`Estimate $${estimate.toFixed(2)} of $5.00 left: short by $${(estimate - 5).toFixed(2)}`);
84 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs