Public: anyone can read this; the crew can change it.
A repository's wallet can hold a monthly cap, and spend past it pauses its crew with one line #13343
Check · Review · Land · Live done — Landed and live in production.
torque/forge:torque/13309-a-repository-s-wallet-can-hold-a-monthly → main 11 commits fork 2 threads · 2 unresolved
15 files
changed +507
−13
docs/features/cost-ledger.md +11
| @@ -74,3 +74,14 @@ To check a bill: | ||
| 74 | 74 | bun scripts/ledger-verify.ts --key "ssh-ed25519 AAAA…" <bill> |
| 75 | 75 | |
| 76 | 76 | It prints `ok N entries $X` (the sum of `usd_tokens`), or `broken at line N: <why>` and exits 1 when an entry changed, the own chain is cut, or the signature is not by that key. The first own entry's `prev` is not checked, because the bill holds one month. The address match trusts the email on both accounts. |
| 77 | ||
| 78 | ## A repository's monthly cap (#13309) | |
| 79 | ||
| 80 | An admin of a repository can hold a cap on what its crew spends in a month. Spend is this ledger's list-price dollars for the repository's runs since 00:00 UTC on the 1st (read from the `usage` table, `monthSpent` in `src/core/wallet.ts`). | |
| 81 | ||
| 82 | - **Set it, on the page.** `/<owner>/<name>/wallet` (admins only). Whole US dollars, 1 to 100000; empty removes the cap. | |
| 83 | - **Set it, in the terminal.** With the repository open, the palette's "Wallet" shows the month's spend and the cap; `c` sets it, empty removes it. Same gate (`saveCap`, `src/actions/wallet.ts`), same `wallet.cap` event. | |
| 84 | - **At the cap.** New runs are refused with one sentence: "This repository's monthly cap of $N is reached; its crew starts no new runs until YYYY-MM-01 (UTC) or the cap is raised." A run already under way is not cut off. The repository page shows the same sentence as one plain line (admins only), linking the wallet. | |
| 85 | - **Resume.** Raise or remove the cap, or wait for the new month. The check is in `executeAgentRun` (`src/crew/runner.ts`). | |
| 86 | ||
| 87 | Tests: `test/repo-wallet.test.ts`, `test/repo-wallet-routes.test.ts`. |
src/actions/wallet.ts +28 −2
| @@ -1,5 +1,6 @@ | ||
| 1 | 1 | /** |
| 2 | * The repository wallet: its last 20 spends, one row each, newest first — | |
| 2 | * The repository wallet: its last 20 spends (`readWallet`, #13324) and the monthly cap (`saveCap`, | |
| 3 | * #13309). Each spend is one row, newest first: | |
| 3 | 4 | * the date, the dollars, what the run paid for and the run itself. Read from |
| 4 | 5 | * the usage ledger (`core/usage.ts`) through `usage_repo (repo_id, at)`, so |
| 5 | 6 | * the cost is twenty index steps however long the ledger grows. Dollars are |
| @@ -12,9 +13,10 @@ | ||
| 12 | 13 | |
| 13 | 14 | import type { App } from "../app.ts"; |
| 14 | 15 | import { getIssuesByIds } from "../core/issues.ts"; |
| 15 | import { canSeeOwnerFacts, type Repo } from "../core/repos.ts"; | |
| 16 | import { canAdmin, canSeeOwnerFacts, type Repo } from "../core/repos.ts"; | |
| 16 | 17 | import type { UsageKind, UsageOutcome } from "../core/usage.ts"; |
| 17 | 18 | import type { User } from "../core/users.ts"; |
| 19 | import { monthCap, setMonthCap, validCap, WALLET_CAP_MAX_USD } from "../core/wallet.ts"; | |
| 18 | 20 | import { err, ok, type Result } from "../kernel/result.ts"; |
| 19 | 21 | |
| 20 | 22 | export const WALLET_ROWS = 20; |
| @@ -80,3 +82,27 @@ export function readWallet(app: App, actor: User | undefined, repo: Repo): Resul | ||
| 80 | 82 | }), |
| 81 | 83 | }); |
| 82 | 84 | } |
| 85 | ||
| 86 | ||
| 87 | export type WalletError = "not_found" | "invalid_amount"; | |
| 88 | ||
| 89 | /** `text` is what was typed: empty clears the cap, otherwise whole dollars. */ | |
| 90 | export function saveCap(app: App, actor: User | undefined, repo: Repo, text: string): Result<{ capUsd: number | undefined }, WalletError> { | |
| 91 | if (actor === undefined || actor.kind === "agent" || !canAdmin(app.db, repo, actor)) return err("not_found"); | |
| 92 | const typed = text.trim(); | |
| 93 | let usd: number | undefined; | |
| 94 | if (typed !== "") { | |
| 95 | if (!/^\d{1,7}$/.test(typed)) return err("invalid_amount"); | |
| 96 | usd = Number(typed); | |
| 97 | if (!validCap(usd)) return err("invalid_amount"); | |
| 98 | } | |
| 99 | const from = monthCap(app.db, repo.id); | |
| 100 | setMonthCap(app.db, repo.id, usd, actor.id, new Date()); | |
| 101 | app.bus.append({ kind: "wallet.cap", repoId: repo.id, actorId: actor.id, payload: { from: from ?? null, to: usd ?? null } }); | |
| 102 | return ok({ capUsd: usd }); | |
| 103 | } | |
| 104 | ||
| 105 | export const capInvalidWords = `A cap is a whole number of dollars from 1 to ${WALLET_CAP_MAX_USD}, or empty for none.`; | |
| 106 | ||
| 107 | export const capSavedWords = (usd: number | undefined): string => | |
| 108 | usd === undefined ? "The cap is removed." : `The monthly cap is $${usd}. Runs resume when spend is under it.`; |
src/core/event_audience.ts +2
| @@ -259,6 +259,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined { | ||
| 259 | 259 | kind.startsWith("keeper_") || |
| 260 | 260 | kind === "forge_down" || |
| 261 | 261 | kind === "forge_up" || |
| 262 | // A repository's monthly spend cap, set or cleared, is its admins' (`actions/wallet.ts`). | |
| 263 | kind === "wallet.cap" || | |
| 262 | 264 | // Who is trusted to fold in, and the switch that stops it, are the owner's |
| 263 | 265 | // (`actions/trusted_sources.ts`). |
| 264 | 266 | kind.startsWith("trust.") || |
src/core/migration-pins/20261115130000-repo-wallet.pin added +1
| @@ -0,0 +1,1 @@ | ||
| 1 | a401c01e916c1a6eb784f6a2898192e3059cc08c94037cf58f5150cd50c07370 |
src/core/migrations/20261115130000-repo-wallet.ts added +10
| @@ -0,0 +1,10 @@ | ||
| 1 | // A repository's wallet (#13309): an optional monthly cap in whole US dollars. One row per | |
| 2 | // repository that has set one; no row is no cap. Additive. | |
| 3 | export default ` | |
| 4 | CREATE TABLE IF NOT EXISTS repo_wallet ( | |
| 5 | repo_id TEXT PRIMARY KEY REFERENCES repo(id) ON DELETE CASCADE, | |
| 6 | month_cap_usd INTEGER NOT NULL, | |
| 7 | set_by TEXT NOT NULL, | |
| 8 | set_at TEXT NOT NULL | |
| 9 | ); | |
| 10 | `; |
src/core/wallet.ts added +53
| @@ -0,0 +1,53 @@ | ||
| 1 | /** | |
| 2 | * A repository's wallet (#13309): an optional monthly cap, in whole US dollars, on what its | |
| 3 | * crew's runs may spend. Spend is the usage ledger's `cost_usd` for the repository since the | |
| 4 | * start of the UTC month (`usage_repo` index); the month resets at 00:00 UTC on the 1st. | |
| 5 | * When spend has reached the cap, new runs are refused with one sentence. Plain data in and out. | |
| 6 | */ | |
| 7 | ||
| 8 | import type { Database } from "bun:sqlite"; | |
| 9 | import { monthStart } from "./model_grant.ts"; | |
| 10 | ||
| 11 | export const WALLET_CAP_MAX_USD = 100_000; | |
| 12 | ||
| 13 | /** Whole dollars, at least one, within the maximum. */ | |
| 14 | export const validCap = (usd: number): boolean => Number.isInteger(usd) && usd >= 1 && usd <= WALLET_CAP_MAX_USD; | |
| 15 | ||
| 16 | export function monthCap(db: Database, repoId: string): number | undefined { | |
| 17 | return db.query<{ n: number }, [string]>("SELECT month_cap_usd AS n FROM repo_wallet WHERE repo_id = ?1").get(repoId)?.n; | |
| 18 | } | |
| 19 | ||
| 20 | /** Set (`usd` a valid whole amount) or clear (`undefined`) the cap; false for an invalid amount. */ | |
| 21 | export function setMonthCap(db: Database, repoId: string, usd: number | undefined, actorId: string, now: Date): boolean { | |
| 22 | if (usd === undefined) { | |
| 23 | db.query("DELETE FROM repo_wallet WHERE repo_id = ?1").run(repoId); | |
| 24 | return true; | |
| 25 | } | |
| 26 | if (!validCap(usd)) return false; | |
| 27 | db.query( | |
| 28 | `INSERT INTO repo_wallet (repo_id, month_cap_usd, set_by, set_at) VALUES (?1, ?2, ?3, ?4) | |
| 29 | ON CONFLICT(repo_id) DO UPDATE SET month_cap_usd = ?2, set_by = ?3, set_at = ?4`, | |
| 30 | ).run(repoId, usd, actorId, now.toISOString()); | |
| 31 | return true; | |
| 32 | } | |
| 33 | ||
| 34 | /** Dollars the repository's runs have cost this UTC month, from the ledger. */ | |
| 35 | export function monthSpent(db: Database, repoId: string, now: Date): number { | |
| 36 | return ( | |
| 37 | db | |
| 38 | .query<{ n: number }, [string, string]>("SELECT COALESCE(SUM(cost_usd), 0) AS n FROM usage WHERE repo_id = ?1 AND at >= ?2") | |
| 39 | .get(repoId, monthStart(now))?.n ?? 0 | |
| 40 | ); | |
| 41 | } | |
| 42 | ||
| 43 | /** The first day of next UTC month, as `2026-12-01`. */ | |
| 44 | export const resetDate = (now: Date): string => new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 1)).toISOString().slice(0, 10); | |
| 45 | ||
| 46 | /** | |
| 47 | * The one sentence a refused run, and the repository page, say; undefined while spend is under the | |
| 48 | * cap or there is none. A caller that has read the cap passes it, so it is not read twice. | |
| 49 | */ | |
| 50 | export function capReached(db: Database, repoId: string, now: Date, cap: number | undefined = monthCap(db, repoId)): string | undefined { | |
| 51 | if (cap === undefined || monthSpent(db, repoId, now) < cap) return undefined; | |
| 52 | return `This repository's monthly cap of $${cap} is reached; its crew starts no new runs until ${resetDate(now)} (UTC) or the cap is raised.`; | |
| 53 | } |
src/crew/runner.ts +7
| @@ -168,6 +168,7 @@ import { owed } from "./team_share.ts"; | ||
| 168 | 168 | import { pauseReason } from "./pacing.ts"; |
| 169 | 169 | import { grantLeft } from "../core/model_grant.ts"; |
| 170 | 170 | import { modelAccess } from "./model_access.ts"; |
| 171 | import { capReached } from "../core/wallet.ts"; | |
| 171 | 172 | import { dailyLeft, reserveCeiling } from "../core/account_ceiling.ts"; |
| 172 | 173 | import { |
| 173 | 174 | credentialEnvOf, |
| @@ -1414,6 +1415,12 @@ async function work( | ||
| 1414 | 1415 | // way past it: the forge's token, up to what is left of the month. |
| 1415 | 1416 | // The host's included credit is a way past it too (#12105); a copy that says |
| 1416 | 1417 | // there is too little may be stale: ask the host before refusing (at most once in 15 s). |
| 1418 | // The repository's own monthly cap (`core/wallet.ts`): reached, no new run starts. | |
| 1419 | const walletSaid = capReached(app.db, repo.id, new Date()); | |
| 1420 | if (walletSaid !== undefined) { | |
| 1421 | write(walletSaid); | |
| 1422 | return { state: "failed", summary: walletSaid }; | |
| 1423 | } | |
| 1417 | 1424 | const heldLeft = lentCreditLeft(picked.kind === "none", app.config.dataDir); |
| 1418 | 1425 | if (picked.kind === "none" && (heldLeft === undefined || heldLeft < MIN_RUN_USD)) await refreshFundingOnce(app); |
| 1419 | 1426 | const access = modelAccess(app, picked, repo.ownerId, repo.ownerName); |
src/http/server.ts +3 −2
| @@ -488,6 +488,7 @@ import { | ||
| 488 | 488 | crewSettingsPage, |
| 489 | 489 | crewSubscriptionsSave, |
| 490 | 490 | } from "../web/pages/crew-settings.ts"; |
| 491 | import { walletPage, walletSave } from "../web/pages/wallet.ts"; | |
| 491 | 492 | import { |
| 492 | 493 | promptSourceAdd, |
| 493 | 494 | promptSourceDelete, |
| @@ -585,7 +586,6 @@ import { startPullSchedule } from "../apps/pull_schedule.ts"; | ||
| 585 | 586 | import { startGithubPull } from "../perf/github_traffic.ts"; |
| 586 | 587 | import { appSourcesPage } from "../web/pages/sources.ts"; |
| 587 | 588 | import { statementPage } from "../web/pages/statement.ts"; |
| 588 | import { walletPage } from "../web/pages/wallet.ts"; | |
| 589 | 589 | import { createViewWriter } from "../perf/views_store.ts"; |
| 590 | 590 | import { createReadWriter, readOf } from "../perf/reads.ts"; |
| 591 | 591 | import { parseServerTiming } from "../perf/record.ts"; |
| @@ -1718,7 +1718,6 @@ export function buildRouter(): Router<Handler> { | ||
| 1718 | 1718 | router.add("GET", "/:owner/:name/settings/app", appSettingsPage); |
| 1719 | 1719 | router.add("GET", "/:owner/:name/settings/app/traffic", appSourcesPage); |
| 1720 | 1720 | router.add("GET", "/:owner/:name/settings/app/statement", statementPage); |
| 1721 | router.add("GET", "/:owner/:name/wallet", walletPage); | |
| 1722 | 1721 | router.add("GET", "/:owner/:name/settings/machines", machinesSettingsPage); |
| 1723 | 1722 | // The shell page; an upgrade at the same path is the socket (`machines/shell.ts`). |
| 1724 | 1723 | router.add("GET", "/:owner/:name/machines/:machine/shell", machineShellPage); |
| @@ -1765,6 +1764,8 @@ export function buildRouter(): Router<Handler> { | ||
| 1765 | 1764 | "/:owner/:name/settings/prompts/:id/delete", |
| 1766 | 1765 | promptSourceDelete, |
| 1767 | 1766 | ); |
| 1767 | router.add("GET", "/:owner/:name/wallet", walletPage); | |
| 1768 | router.add("POST", "/:owner/:name/wallet", walletSave); | |
| 1768 | 1769 | router.add("GET", "/:owner/:name/settings/crew", crewSettingsPage); |
| 1769 | 1770 | router.add("POST", "/:owner/:name/settings/crew", crewAdd); |
| 1770 | 1771 | router.add( |
src/tui/screens/wallet.ts added +84
| @@ -0,0 +1,84 @@ | ||
| 1 | /** | |
| 2 | * A repository's wallet, in the terminal (#13309): the wallet page (`web/pages/wallet.ts`) from the | |
| 3 | * same action (`actions/wallet.ts`), gated the same way: a repository's admins. `c` sets the | |
| 4 | * monthly cap in whole dollars; an empty value removes it. Each write is a `wallet.cap` event. | |
| 5 | */ | |
| 6 | ||
| 7 | import { capInvalidWords, capSavedWords, saveCap } from "../../actions/wallet.ts"; | |
| 8 | import { canAdmin, type Repo } from "../../core/repos.ts"; | |
| 9 | import { capReached, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts"; | |
| 10 | import type { Ctx, Screen } from "../app/app.ts"; | |
| 11 | import { binding } from "../app/keys.ts"; | |
| 12 | import type { Command } from "../app/palette.ts"; | |
| 13 | import type { Session } from "../session.ts"; | |
| 14 | import { style } from "../term/style.ts"; | |
| 15 | import { truncate } from "../term/width.ts"; | |
| 16 | import { live, promptScreen } from "./common.ts"; | |
| 17 | ||
| 18 | /** The wallet's gate: an admin of the repository. */ | |
| 19 | export const mayManageWallet = (f: Session, repo: Repo): boolean => f.user !== undefined && canAdmin(f.db, repo, f.user); | |
| 20 | ||
| 21 | /** The lines the screen draws: what was spent, then the paused sentence when the cap is reached. */ | |
| 22 | export function walletLines(f: Session, repo: Repo, now: Date): string[] { | |
| 23 | if (!mayManageWallet(f, repo)) return ["An admin of this repository manages its wallet."]; | |
| 24 | const cap = monthCap(f.db, repo.id); | |
| 25 | const spent = monthSpent(f.db, repo.id, now).toFixed(2); | |
| 26 | const lines = [`Spent this month: $${spent}${cap === undefined ? ". No cap is set." : `, cap $${cap}.`}`]; | |
| 27 | const paused = capReached(f.db, repo.id, now, cap); | |
| 28 | if (paused !== undefined) lines.push(paused); | |
| 29 | lines.push(`c sets the cap in whole dollars, 1 to ${WALLET_CAP_MAX_USD}; empty removes it. A cap stops new runs, never one under way.`); | |
| 30 | return lines; | |
| 31 | } | |
| 32 | ||
| 33 | export function walletScreen(f: Session, ctx: Ctx, repo: Repo): Screen { | |
| 34 | const screen: Screen = { | |
| 35 | title: `${repo.ownerName}/${repo.name} — Wallet`, | |
| 36 | keys: [binding(["c"], "set the cap")], | |
| 37 | async load(signal) { | |
| 38 | live(f, signal, { repoId: repo.id, where: (e) => e.kind === "wallet.cap" }, () => ctx.invalidate()); | |
| 39 | }, | |
| 40 | render(area, s) { | |
| 41 | const c = ctx.theme.c; | |
| 42 | walletLines(f, repo, new Date()).forEach((line, i) => { | |
| 43 | if (i < area.h) s.text(area.x, area.y + i, truncate(line, area.w), style(i === 0 ? c.fg : c.mutedFg, c.bg), area.x + area.w); | |
| 44 | }); | |
| 45 | }, | |
| 46 | key(e) { | |
| 47 | if (e.ctrl || e.alt || e.key !== "c") return false; | |
| 48 | if (!mayManageWallet(f, repo)) { | |
| 49 | ctx.toast("An admin of this repository manages its wallet.", "danger"); | |
| 50 | return true; | |
| 51 | } | |
| 52 | const have = monthCap(f.db, repo.id); | |
| 53 | ctx.push( | |
| 54 | promptScreen(ctx, screen, { | |
| 55 | title: "Monthly cap", | |
| 56 | label: "US dollars", | |
| 57 | value: have === undefined ? "" : String(have), | |
| 58 | onSubmit: (typed) => { | |
| 59 | const saved = saveCap(f.app, f.user, repo, typed); | |
| 60 | if (!saved.ok) return saved.error === "not_found" ? "An admin of this repository manages its wallet." : capInvalidWords; | |
| 61 | ctx.toast(capSavedWords(saved.value.capUsd)); | |
| 62 | ctx.invalidate(); | |
| 63 | return undefined; | |
| 64 | }, | |
| 65 | }), | |
| 66 | ); | |
| 67 | return true; | |
| 68 | }, | |
| 69 | }; | |
| 70 | return screen; | |
| 71 | } | |
| 72 | ||
| 73 | /** The palette's command while a repository the viewer administers is open. */ | |
| 74 | export function walletCapCommands(f: Session, ctx: Ctx, repo: Repo | undefined): Command[] { | |
| 75 | if (repo === undefined || !mayManageWallet(f, repo)) return []; | |
| 76 | return [ | |
| 77 | { | |
| 78 | id: "wallet", | |
| 79 | title: `${repo.ownerName}/${repo.name} — Wallet cap`, | |
| 80 | hint: "see this month's spend, set a monthly cap on the crew", | |
| 81 | run: () => ctx.push(walletScreen(f, ctx, repo)), | |
| 82 | }, | |
| 83 | ]; | |
| 84 | } |
src/tui/screens/workspace.ts +2
| @@ -182,6 +182,7 @@ import { autonomyCommands } from "./autonomy.ts"; | ||
| 182 | 182 | import { trafficCommands } from "./trafficview.ts"; |
| 183 | 183 | import { chaptersCommands } from "./chapters.ts"; |
| 184 | 184 | import { outsideAgentsCommands } from "./outsideagents.ts"; |
| 185 | import { walletCapCommands } from "./wallet.ts"; | |
| 185 | 186 | import { settingHistoryCommands } from "./settinghistory.ts"; |
| 186 | 187 | import { templateCommands } from "./template.ts"; |
| 187 | 188 | import { buildCacheCommands } from "./buildcache.ts"; |
| @@ -2135,6 +2136,7 @@ export function workspaceScreen( | ||
| 2135 | 2136 | ...recheckWindowCommands(f, ctx, repo, () => screen), |
| 2136 | 2137 | ...deskCommands(f, ctx, repo), |
| 2137 | 2138 | ...outsideAgentsCommands(f, ctx, repo), |
| 2139 | ...walletCapCommands(f, ctx, repo), | |
| 2138 | 2140 | ...templateCommands(f, ctx, repo), |
| 2139 | 2141 | ...settingHistoryCommands(f, ctx, repo), |
| 2140 | 2142 | ...buildCacheCommands(f, ctx, repo), |
src/web/pages/repo.ts +15 −2
| @@ -25,6 +25,7 @@ import { lacks, NOT_A_MEMBER } from "../../core/roles.ts"; | ||
| 25 | 25 | import { storageLimitMessage } from "../../core/storage.ts"; |
| 26 | 26 | import { canRead, canWrite, listForks, type Repo } from "../../core/repos.ts"; |
| 27 | 27 | import { reportsClosed } from "../../core/reports.ts"; |
| 28 | import { capReached, monthCap } from "../../core/wallet.ts"; | |
| 28 | 29 | import { takesOutside } from "../../actions/contribute_token.ts"; |
| 29 | 30 | import { FORKS_PER_DAY, forkRepo, repositoryLimitMessage } from "../../actions/repos.ts"; |
| 30 | 31 | import { |
| @@ -1384,6 +1385,18 @@ function movedLine(ctx: Ctx, repo: Repo): Html | null { | ||
| 1384 | 1385 | return html`<p class="muted small moved-from">Moved from ${move.from} on ${time(move.at, { date: true })}</p>`; |
| 1385 | 1386 | } |
| 1386 | 1387 | |
| 1388 | /** | |
| 1389 | * One plain line, for an admin, when the repository's monthly cap is reached (#13309); no banner. | |
| 1390 | */ | |
| 1391 | function walletLine(ctx: Ctx, repo: Repo): Html | null { | |
| 1392 | // The cheap case first: a repository with no cap row costs one primary-key read, no access check. | |
| 1393 | const cap = monthCap(ctx.app.db, repo.id); | |
| 1394 | if (cap === undefined || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return null; | |
| 1395 | const said = capReached(ctx.app.db, repo.id, new Date(), cap); | |
| 1396 | if (said === undefined) return null; | |
| 1397 | return html`<p class="muted small mt" id="wallet-line">${said} <a href="${repoBase(repo)}/wallet">Wallet</a></p>`; | |
| 1398 | } | |
| 1399 | ||
| 1387 | 1400 | /** |
| 1388 | 1401 | * The one visible line on a public repository's front page that says how |
| 1389 | 1402 | * someone with no account reports a problem or offers a change, or that the |
| @@ -1434,7 +1447,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> { | ||
| 1434 | 1447 | |
| 1435 | 1448 | if (refs.branches.length === 0) { |
| 1436 | 1449 | const emptyRendering = performance.now(); |
| 1437 | const body = html`${scopeHeader(ctx, scope, "code")}${archivedLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp} | |
| 1450 | const body = html`${scopeHeader(ctx, scope, "code")}${archivedLine(ctx, repo)}${walletLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp} | |
| 1438 | 1451 | <div class="mt"> |
| 1439 | 1452 | ${empty({ |
| 1440 | 1453 | icon: "repo", |
| @@ -1511,7 +1524,7 @@ async function codeHome(ctx: Ctx, repo: Repo): Promise<Response> { | ||
| 1511 | 1524 | const rendering = performance.now(); |
| 1512 | 1525 | const body = html`${scopeHeader(ctx, scope, "code", { |
| 1513 | 1526 | branchCount: refs.branches.length, |
| 1514 | })}${credit}${standing}${archivedLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp} | |
| 1527 | })}${credit}${standing}${archivedLine(ctx, repo)}${walletLine(ctx, repo)}${reportLine(ctx, repo)}${movedLine(ctx, repo)}${noApp} | |
| 1515 | 1528 | ${offerUpstream(repo, parent, offer)} |
| 1516 | 1529 | ${latest === null |
| 1517 | 1530 | ? "" |
src/web/pages/wallet.ts +53 −6
| @@ -1,17 +1,25 @@ | ||
| 1 | 1 | /** |
| 2 | * GET /:owner/:name/wallet — the repository's last 20 spends from the usage | |
| 3 | * ledger, one row each: date, dollars, what it paid for, and a link to the | |
| 4 | * run (`actions/wallet.ts`). Server-rendered, no script. For whoever may | |
| 5 | * read the app's spend (a writer); anyone else gets the not-found page. | |
| 2 | * /:owner/:name/wallet: the repository's wallet. A writer reads the last 20 spends from the usage | |
| 3 | * ledger (#13324, `actions/wallet.ts`): date, dollars, what it paid for, a link to the run. An | |
| 4 | * admin also sets an optional monthly cap in whole US dollars (#13309); spend at the cap pauses | |
| 5 | * new runs (`core/wallet.ts`), and the page says so once, in the sentence the refused run reads. | |
| 6 | * Server-rendered, no script; anyone else gets the not-found page. | |
| 6 | 7 | */ |
| 7 | 8 | |
| 8 | import { readWallet } from "../../actions/wallet.ts"; | |
| 9 | import { capInvalidWords, capSavedWords, readWallet, saveCap } from "../../actions/wallet.ts"; | |
| 9 | 10 | import { notePhase, takeSessionTime, timePhase } from "../../core/route_timing.ts"; |
| 11 | import { canAdmin } from "../../core/repos.ts"; | |
| 12 | import { capReached, monthCap, monthSpent, WALLET_CAP_MAX_USD } from "../../core/wallet.ts"; | |
| 10 | 13 | import type { Ctx } from "../../http/context.ts"; |
| 11 | import { loadRepo, repoNotFound } from "../chrome.ts"; | |
| 14 | import { adminForm } from "../admin_form.ts"; | |
| 15 | import { loadRepo, repoBase, repoNotFound } from "../chrome.ts"; | |
| 16 | import { field } from "../form.ts"; | |
| 12 | 17 | import { html } from "../html.ts"; |
| 18 | import { flashTo } from "../layout.ts"; | |
| 19 | import { btn, field as formField } from "../ui.ts"; | |
| 13 | 20 | import { settingsPageResponse } from "./settings.ts"; |
| 14 | 21 | |
| 22 | // GET /:owner/:name/wallet | |
| 15 | 23 | export function walletPage(ctx: Ctx): Response { |
| 16 | 24 | notePhase(ctx.request, "session", takeSessionTime(ctx.request)); |
| 17 | 25 | const repo = timePhase(ctx.request, "repo", () => loadRepo(ctx)); |
| @@ -20,8 +28,33 @@ export function walletPage(ctx: Ctx): Response { | ||
| 20 | 28 | if (!read.ok) return repoNotFound(ctx); |
| 21 | 29 | const rendering = performance.now(); |
| 22 | 30 | const w = read.value; |
| 31 | const base = repoBase(repo); | |
| 32 | let capBlock = null; | |
| 33 | if (canAdmin(ctx.app.db, repo, ctx.auth.user)) { | |
| 34 | const now = new Date(); | |
| 35 | const cap = monthCap(ctx.app.db, repo.id); | |
| 36 | const spent = monthSpent(ctx.app.db, repo.id, now); | |
| 37 | const paused = capReached(ctx.app.db, repo.id, now, cap); | |
| 38 | capBlock = html`<p id="wallet-spend">Spent this month: <strong class="num">$${spent.toFixed(2)}</strong>.</p> | |
| 39 | ${paused === undefined ? null : html`<p id="wallet-paused">${paused}</p>`} | |
| 40 | <form method="post" action="${base}/wallet" class="mt"> | |
| 41 | ${formField({ | |
| 42 | label: "Monthly cap (US dollars)", | |
| 43 | name: "cap", | |
| 44 | value: cap === undefined ? "" : String(cap), | |
| 45 | mono: true, | |
| 46 | hint: `Whole dollars, 1 to ${WALLET_CAP_MAX_USD}; empty for no cap.`, | |
| 47 | })} | |
| 48 | <div class="form-actions">${btn("Save", { variant: "primary" })}</div> | |
| 49 | </form> | |
| 50 | <p class="muted small mt"> | |
Design principles 1 and 8: an Assumptions paragraph explains the page a second time. Fold the one needed fact (UTC month) into a single plain sentence. |
||
| 51 | A cap stops new runs, never one under way; spend is this repository's runs at list price over | |
| 52 | the UTC calendar month. | |
| 53 | </p>`; | |
| 54 | } | |
| 23 | 55 | const body = html`<section class="settings-block" data-wallet> |
| 24 | 56 | <h2>Wallet</h2> |
| 57 | ${capBlock} | |
| 25 | 58 | <p class="small">What ${w.app}'s last 20 spends paid for, newest first, each with the run behind it.</p> |
| 26 | 59 | ${w.spends.length === 0 |
| 27 | 60 | ? html`<p class="small">Nothing spent yet: the crew's runs on ${w.app} appear here as they report their cost.</p>` |
| @@ -45,3 +78,17 @@ export function walletPage(ctx: Ctx): Response { | ||
| 45 | 78 | notePhase(ctx.request, "render", performance.now() - rendering); |
| 46 | 79 | return response; |
| 47 | 80 | } |
| 81 | ||
| 82 | // POST /:owner/:name/wallet | |
| 83 | export async function walletSave(ctx: Ctx): Promise<Response> { | |
| 84 | const gate = await adminForm(ctx); | |
| 85 | if (gate instanceof Response) return gate; | |
| 86 | const { repo, form } = gate; | |
| 87 | const saved = saveCap(ctx.app, ctx.auth.user, repo, field(form, "cap")); | |
| 88 | if (!saved.ok && saved.error === "not_found") return repoNotFound(ctx); | |
| 89 | return flashTo( | |
| 90 | ctx, | |
| 91 | `${repoBase(repo)}/wallet`, | |
| 92 | saved.ok ? { message: capSavedWords(saved.value.capUsd) } : { tone: "danger", message: capInvalidWords }, | |
| 93 | ); | |
| 94 | } |
test/did-you-mean.test.ts +3 −1
| @@ -17,7 +17,9 @@ let servers: Awaited<ReturnType<typeof serve>>; | ||
| 17 | 17 | // that day's pushes. |
| 18 | 18 | // 40: the fork-reach lookup of the repository row adds one; the autonomy status's week read |
| 19 | 19 | // replaces the daily-ceiling read, so it adds none beside it. |
| 20 | const FOUND_QUERIES = 40; | |
| 20 | // 41: the repository page reads the repository's wallet cap, one primary-key read, to show the | |
| 21 | // wallet line (#13309). | |
| 22 | const FOUND_QUERIES = 41; | |
| 21 | 23 | const BARE_404_QUERIES = 3; // a 404 with no owner/name to suggest from |
| 22 | 24 | const NEAR_404_QUERIES = 16; // the same 404 for a mistyped repository |
| 23 | 25 | const cookies: Record<string, string> = {}; |
test/repo-wallet-routes.test.ts added +136
| @@ -0,0 +1,136 @@ | ||
| 1 | /** | |
| 2 | * The wallet's doors (#13309): GET and POST /:owner/:name/wallet, the repository page's one line, | |
| 3 | * the `wallet.cap` event's audience, and the terminal screen's text. | |
| 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 { createApp } from "../src/app.ts"; | |
| 10 | import { createRepo } from "../src/actions/repos.ts"; | |
| 11 | import { createUser } from "../src/core/users.ts"; | |
| 12 | import { classifiedAudience, eventAudience } from "../src/core/event_audience.ts"; | |
| 13 | import { listEvents } from "../src/core/events.ts"; | |
| 14 | import { createRun } from "../src/core/runs.ts"; | |
| 15 | import { monthCap } from "../src/core/wallet.ts"; | |
| 16 | import { serve } from "../src/http/server.ts"; | |
| 17 | import { walletLines } from "../src/tui/screens/wallet.ts"; | |
| 18 | import { quietLogs } from "./helpers/globals.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | let dir = ""; | |
| 23 | let app: ReturnType<typeof createApp>; | |
| 24 | let servers: Awaited<ReturnType<typeof serve>>; | |
| 25 | let repoId = ""; | |
| 26 | const cookies: Record<string, string> = {}; | |
| 27 | const people: Record<string, any> = {}; | |
| 28 | ||
| 29 | beforeAll(async () => { | |
| 30 | dir = await mkdtemp(join(tmpdir(), "forge-wallet-")); | |
| 31 | app = createApp({ dataDir: dir, port: 0 }); | |
| 32 | servers = await serve(app); | |
| 33 | for (const [username, first] of [["trevato", true], ["stranger", false]] as const) { | |
| 34 | const made: any = await createUser(app.db, { | |
| 35 | origin: "seed", trusted: true, username, email: `${username}@forge.local`, | |
| 36 | password: "a-good-passphrase", adminIfFirst: first, | |
| 37 | }); | |
| 38 | people[username] = made.value ?? made; | |
| 39 | const res = await fetch(servers.url + "/signin", { | |
| 40 | method: "POST", | |
| 41 | redirect: "manual", | |
| 42 | headers: { "content-type": "application/x-www-form-urlencoded", origin: servers.url }, | |
| 43 | body: new URLSearchParams({ username, password: "a-good-passphrase" }), | |
| 44 | }); | |
| 45 | cookies[username] = (res.headers.get("set-cookie") ?? "").split(";")[0] ?? ""; | |
| 46 | } | |
| 47 | const made: any = await createRepo(app, people.trevato, { name: "garden", visibility: "public" }); | |
| 48 | repoId = (made.value ?? made).id; | |
| 49 | }); | |
| 50 | afterAll(async () => { | |
| 51 | servers.stop(); | |
| 52 | app.close(); | |
| 53 | await rm(dir, { recursive: true, force: true }); | |
| 54 | }); | |
| 55 | ||
| 56 | const get = async (path: string, who?: string) => { | |
| 57 | const res = await fetch(servers.url + path, { redirect: "manual", headers: who ? { cookie: cookies[who]! } : {} }); | |
| 58 | return { res, body: await res.text() }; | |
| 59 | }; | |
| 60 | const post = (who: string, cap: string, origin: string | undefined = servers.url) => | |
| 61 | fetch(servers.url + "/trevato/garden/wallet", { | |
| 62 | method: "POST", | |
| 63 | redirect: "manual", | |
| 64 | headers: { | |
| 65 | "content-type": "application/x-www-form-urlencoded", | |
| 66 | cookie: cookies[who]!, | |
| 67 | ...(origin === undefined ? {} : { origin }), | |
| 68 | }, | |
| 69 | body: new URLSearchParams({ cap }), | |
| 70 | }); | |
| 71 | const spend = (usd: number) => { | |
| 72 | const run = createRun(app.db, { repoId, kind: "agent" }); | |
| 73 | app.db | |
| 74 | .query(`INSERT INTO usage (run_id, repo_id, kind, cost_usd, outcome, at) VALUES (?1, ?2, 'build', ?3, 'ok', ?4)`) | |
| 75 | .run(run.id, repoId, usd, new Date().toISOString()); | |
| 76 | }; | |
| 77 | ||
| 78 | test("GET /wallet is the admin's; anyone else is told the repository has no such page", async () => { | |
| 79 | const admin = await get("/trevato/garden/wallet", "trevato"); | |
| 80 | expect(admin.res.status).toBe(200); | |
| 81 | expect(admin.body).toContain("Spent this month"); | |
| 82 | expect(admin.body).not.toContain("Assumptions"); | |
| 83 | expect((await get("/trevato/garden/wallet", "stranger")).res.status).toBe(404); | |
| 84 | expect((await get("/trevato/garden/wallet")).res.status).toBe(404); | |
| 85 | }); | |
| 86 | ||
| 87 | test("POST /wallet refuses a cross-origin or a non-admin, and writes nothing", async () => { | |
| 88 | expect((await post("trevato", "5", "https://evil.example")).status).toBeGreaterThanOrEqual(400); | |
| 89 | expect((await post("stranger", "5")).status).toBe(404); | |
| 90 | expect(monthCap(app.db, repoId)).toBeUndefined(); | |
| 91 | expect(listEvents(app.db, { repoId, kind: "wallet.cap" })).toHaveLength(0); | |
| 92 | }); | |
| 93 | ||
| 94 | test("a valid POST flashes, writes the cap and a wallet.cap event; a bad amount writes nothing", async () => { | |
| 95 | const bad = await post("trevato", "1.5"); | |
| 96 | expect(bad.status).toBe(303); | |
| 97 | expect(monthCap(app.db, repoId)).toBeUndefined(); | |
| 98 | const good = await post("trevato", "7"); | |
| 99 | expect(good.status).toBe(303); | |
| 100 | expect(good.headers.get("location")).toContain("/trevato/garden/wallet"); | |
| 101 | expect(monthCap(app.db, repoId)).toBe(7); | |
| 102 | const events = listEvents(app.db, { repoId, kind: "wallet.cap" }); | |
| 103 | expect(events).toHaveLength(1); | |
| 104 | expect(events[0]!.payload).toEqual({ from: null, to: 7 }); | |
| 105 | expect((await get("/trevato/garden/wallet", "trevato")).body).toContain('value="7"'); | |
| 106 | }); | |
| 107 | ||
| 108 | test("the repository page shows the line to an admin once the cap is reached, to no one else", async () => { | |
| 109 | const quiet = await get("/trevato/garden", "trevato"); | |
| 110 | expect(quiet.body).not.toContain("wallet-line"); | |
| 111 | spend(7); | |
| 112 | const admin = await get("/trevato/garden", "trevato"); | |
| 113 | expect(admin.body).toContain('id="wallet-line"'); | |
| 114 | expect(admin.body).toContain("monthly cap of $7 is reached"); | |
| 115 | expect(admin.body).toContain('href="/trevato/garden/wallet"'); | |
| 116 | expect((await get("/trevato/garden", "stranger")).body).not.toContain("wallet-line"); | |
| 117 | expect((await get("/trevato/garden")).body).not.toContain("wallet-line"); | |
| 118 | // The wallet page says the cap once: the paused sentence, not a second statement of it. | |
| 119 | const page = (await get("/trevato/garden/wallet", "trevato")).body; | |
| 120 | expect(page.split("monthly cap of $7").length - 1).toBe(1); | |
| 121 | }); | |
| 122 | ||
| 123 | test("a wallet.cap event is for admins only, never readers or agents", () => { | |
| 124 | expect(classifiedAudience("wallet.cap")).toBe("admins"); | |
| 125 | expect(eventAudience("wallet.cap")).toBe("admins"); | |
| 126 | }); | |
| 127 | ||
| 128 | test("the terminal screen says the same: spend, the sentence, and how to set it; nothing to a non-admin", () => { | |
| 129 | const repo: any = app.db.query("SELECT id, owner_id AS ownerId FROM repo WHERE id = ?1").get(repoId); | |
| 130 | const full: any = { db: app.db, app, user: people.trevato }; | |
| 131 | const lines = walletLines(full, { ...repo, ownerName: "trevato", name: "garden" }, new Date()); | |
| 132 | expect(lines[0]).toContain("Spent this month: $7.00, cap $7."); | |
| 133 | expect(lines[1]).toContain("monthly cap of $7 is reached"); | |
| 134 | const other = walletLines({ ...full, user: people.stranger }, { ...repo, ownerName: "trevato", name: "garden" }, new Date()); | |
| 135 | expect(other).toEqual(["An admin of this repository manages its wallet."]); | |
| 136 | }); |
test/repo-wallet.test.ts added +99
| @@ -0,0 +1,99 @@ | ||
| 1 | /** | |
| 2 | * A repository's wallet (#13309): the monthly cap is whole dollars set by an admin; spend in the | |
| 3 | * month's ledger at the cap refuses the next run with one sentence naming the cap and the reset | |
| 4 | * date; raising the cap lets runs start again; the repository page says it in one line. | |
| 5 | */ | |
| 6 | ||
| 7 | import { afterAll, beforeAll, describe, expect, test } from "bun:test"; | |
| 8 | import { quietLogs } from "./helpers/globals.ts"; | |
| 9 | import { existsSync, rmSync } from "node:fs"; | |
| 10 | import type { App } from "../src/app.ts"; | |
| 11 | import type { Repo } from "../src/core/repos.ts"; | |
| 12 | import type { User } from "../src/core/users.ts"; | |
| 13 | import { assignIssue, openIssue } from "../src/actions/issues.ts"; | |
| 14 | import { updateRepoSettings } from "../src/actions/repos.ts"; | |
| 15 | import { saveCap } from "../src/actions/wallet.ts"; | |
| 16 | import { createRun } from "../src/core/runs.ts"; | |
| 17 | import { capReached, monthCap, monthSpent, resetDate } from "../src/core/wallet.ts"; | |
| 18 | import { agentRunSettled, startStandInCrew, stopStandInCrew, type StandInCrew } from "./helpers/crew-standin.ts"; | |
| 19 | ||
| 20 | quietLogs(); | |
| 21 | ||
| 22 | describe("a repository's monthly cap", () => { | |
| 23 | let standIn: StandInCrew; | |
| 24 | let app: App; | |
| 25 | let alice: User; | |
| 26 | let bot: User; | |
| 27 | let repo: Repo; | |
| 28 | ||
| 29 | beforeAll(async () => { | |
| 30 | standIn = await startStandInCrew({ autonomyEveryMs: 50 }); | |
| 31 | ({ app, alice, bot, repo } = standIn); | |
| 32 | const on = await updateRepoSettings(app, alice, repo, { | |
| 33 | autonomy: "autonomous", | |
| 34 | autonomyDirection: "Keep the garden small.", | |
| 35 | autonomyBy: alice.id, | |
| 36 | }); | |
| 37 | expect(on.ok).toBe(true); | |
| 38 | }, 30_000); | |
| 39 | afterAll(() => stopStandInCrew(standIn)); | |
| 40 | ||
| 41 | const spend = (usd: number, at: Date) => { | |
| 42 | const run = createRun(app.db, { repoId: repo.id, kind: "agent" }); | |
| 43 | app.db | |
| 44 | .query(`INSERT INTO usage (run_id, repo_id, kind, cost_usd, outcome, at) VALUES (?1, ?2, 'build', ?3, 'ok', ?4)`) | |
| 45 | .run(run.id, repo.id, usd, at.toISOString()); | |
| 46 | }; | |
| 47 | ||
| 48 | test("whole dollars only, an admin only, and empty clears it", () => { | |
| 49 | for (const bad of ["1.5", "-3", "0", "abc", "100001", "1e3", "99999999"]) | |
| 50 | expect(saveCap(app, alice, repo, bad)).toEqual({ ok: false, error: "invalid_amount" }); | |
| 51 | expect(monthCap(app.db, repo.id)).toBeUndefined(); | |
| 52 | expect(saveCap(app, undefined, repo, "5")).toEqual({ ok: false, error: "not_found" }); | |
| 53 | expect(saveCap(app, bot, repo, "5")).toEqual({ ok: false, error: "not_found" }); | |
| 54 | expect(saveCap(app, alice, repo, " 5 ")).toEqual({ ok: true, value: { capUsd: 5 } }); | |
| 55 | expect(monthCap(app.db, repo.id)).toBe(5); | |
| 56 | expect(saveCap(app, alice, repo, "")).toEqual({ ok: true, value: { capUsd: undefined } }); | |
| 57 | expect(monthCap(app.db, repo.id)).toBeUndefined(); | |
| 58 | }); | |
| 59 | ||
| 60 | test("spend counts the UTC month only, and the sentence names the cap and the reset date", () => { | |
| 61 | const now = new Date("2026-11-15T12:00:00Z"); | |
| 62 | saveCap(app, alice, repo, "10"); | |
| 63 | spend(4, new Date("2026-10-31T23:59:59Z")); | |
| 64 | spend(6, new Date("2026-11-01T00:00:00Z")); | |
| 65 | expect(monthSpent(app.db, repo.id, now)).toBe(6); | |
| 66 | expect(capReached(app.db, repo.id, now)).toBeUndefined(); | |
| 67 | spend(4, new Date("2026-11-10T00:00:00Z")); | |
| 68 | expect(resetDate(now)).toBe("2026-12-01"); | |
| 69 | expect(capReached(app.db, repo.id, now)).toBe( | |
| 70 | "This repository's monthly cap of $10 is reached; its crew starts no new runs until 2026-12-01 (UTC) or the cap is raised.", | |
| 71 | ); | |
| 72 | // The next month the ledger's old spend no longer counts. | |
| 73 | expect(capReached(app.db, repo.id, new Date("2026-12-02T00:00:00Z"))).toBeUndefined(); | |
| 74 | app.db.query("DELETE FROM usage").run(); | |
| 75 | saveCap(app, alice, repo, ""); | |
| 76 | }); | |
| 77 | ||
| 78 | test("spend driven to the cap refuses the next run; raising the cap lets one start", async () => { | |
| 79 | rmSync(standIn.argsFile, { force: true }); | |
| 80 | saveCap(app, alice, repo, "3"); | |
| 81 | spend(3, new Date()); | |
| 82 | const issue = openIssue(app, alice, repo, { title: "Prune the roses", body: "Before spring." }); | |
| 83 | if (!issue.ok) throw new Error(String(issue.error)); | |
| 84 | expect(assignIssue(app, alice, repo, issue.value, bot).ok).toBe(true); | |
| 85 | const refused = await agentRunSettled(app, repo, (r) => r.issueId === issue.value.id, 60_000); | |
| 86 | expect(refused.state).toBe("failed"); | |
| 87 | expect(refused.summary).toContain("monthly cap of $3 is reached"); | |
| 88 | expect(refused.summary).toContain(resetDate(new Date())); | |
| 89 | expect(existsSync(standIn.argsFile)).toBe(false); | |
| 90 | ||
| 91 | expect(saveCap(app, alice, repo, "50").ok).toBe(true); | |
| 92 | expect(capReached(app.db, repo.id, new Date())).toBeUndefined(); | |
| 93 | const issue2 = openIssue(app, alice, repo, { title: "Mow the lawn", body: "Soon." }); | |
| 94 | if (!issue2.ok) throw new Error(String(issue2.error)); | |
| 95 | expect(assignIssue(app, alice, repo, issue2.value, bot).ok).toBe(true); | |
| 96 | const next = await agentRunSettled(app, repo, (r) => r.issueId === issue2.value.id, 60_000); | |
| 97 | expect(next.summary).not.toContain("monthly cap"); | |
| 98 | }, 120_000); | |
| 99 | }); |
new above
offline
Design principle 1: this restates what the spend line above and the Assumptions paragraph below already say. Compute capReached once, and show one statement.