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

A repository under 10% of its monthly wallet says so on its page and in the feed, once #13983

Merged opened this

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

Merged

scout/forge:scout/13969-a-repository-under-10-of-its-monthly-wal → main 1 commit fork 1 thread · 1 unresolved

  • Merged. scout/13969-a-repository-under-10-of-its-monthly-wal was merged into main as 83b70f4.

Review

Sign in to review this change.
7 files changed +133 −1
docs/features/cost-ledger.md +4
@@ -85,3 +85,7 @@ An admin of a repository can hold a cap on what its crew spends in a month. Spen
8585 - **Resume.** Raise or remove the cap, or wait for the new month. The check is in `executeAgentRun` (`src/crew/runner.ts`).
8686
8787 Tests: `test/repo-wallet.test.ts`, `test/repo-wallet-routes.test.ts`.
88
89 ## A low wallet says so once a month
90
91 Once what is left of a repository's monthly cap is under 10%, one `wallet.low` event goes on the feed for the repository's admins ("Wallet low: $9 left of $100 this month"), written by the crew's usage ticks (`noteLowWallet`, `src/core/wallet.ts`). At zero it reads "Wallet spent", since zero left is under 10% too. One per repository per UTC month: raising the cap and crossing again says nothing more. The page's own quiet line (under 20%) is separate.
src/core/event_audience.ts +2
@@ -267,6 +267,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
267267 kind === "forge_up" ||
268268 // A repository's monthly spend cap, set or cleared, is its admins' (`actions/wallet.ts`).
269269 kind === "wallet.cap" ||
270 // A wallet under a tenth of its cap, once a month, is theirs to hear first (`core/wallet.ts`).
271 kind === "wallet.low" ||
270272 // Who is trusted to fold in, and the switch that stops it, are the owner's
271273 // (`actions/trusted_sources.ts`).
272274 kind.startsWith("trust.") ||
src/core/wallet.ts +30
@@ -6,6 +6,7 @@
66 */
77
88 import type { Database } from "bun:sqlite";
9 import type { EventBus } from "./events.ts";
910 import { monthStart } from "./model_grant.ts";
1011
1112 export const WALLET_CAP_MAX_USD = 100_000;
@@ -90,3 +91,32 @@ export function balanceWords(cap: number | undefined, spent: number, now: Date):
9091 }
9192 return `${money(cap - spent)} of the $${cap} monthly cap is left; it resets ${resetDate(now)} (UTC).`;
9293 }
94
95 /** The feed hears of a low wallet once what is left is under this share of the cap (#13969). */
96 export const WALLET_NOTICE_SHARE = 0.1;
97
98 /** The words the feed carries: what is left, or, at zero, that the wallet is spent. */
99 export const lowNoticeWords = (left: number, cap: number): string =>
100 left <= 0
101 ? `Wallet spent: nothing left of ${dollars(cap)}; the crew starts no new runs until the cap is raised or the month resets`
102 : `Wallet low: ${dollars(left)} left of ${dollars(cap)} this month`;
103
104 /**
105 * One `wallet.low` event per repository per UTC month, once what is left is under
106 * WALLET_NOTICE_SHARE of the cap. Zero left counts as under (the owner hears it was spent, which
107 * is the last warning), and no cap says nothing. Raising the cap and crossing again in the same
108 * month says nothing more: the month's event is the record. True when it wrote one.
109 */
110 export function noteLowWallet(db: Database, bus: EventBus, repoId: string, now: Date): boolean {
111 const cap = monthCap(db, repoId);
112 if (cap === undefined) return false;
113 const left = cap - monthSpent(db, repoId, now);
114 if (left >= cap * WALLET_NOTICE_SHARE) return false;
115 const month = now.toISOString().slice(0, 7);
116 const said = db
117 .query("SELECT 1 FROM event WHERE kind = 'wallet.low' AND repo_id = ?1 AND json_extract(payload, '$.month') = ?2 LIMIT 1")
118 .get(repoId, month);
119 if (said !== null) return false;
120 bus.append({ kind: "wallet.low", repoId, payload: { month, capUsd: cap, left: Math.max(0, Math.round(left * 100) / 100) } });
121 return true;
122 }
src/crew/runner.ts +3 −1
@@ -168,7 +168,7 @@ import { owed } from "./team_share.ts";
168168 import { pauseReason } from "./pacing.ts";
169169 import { grantLeft } from "../core/model_grant.ts";
170170 import { modelAccess } from "./model_access.ts";
171 import { capReached } from "../core/wallet.ts";
171 import { capReached, noteLowWallet } from "../core/wallet.ts";
172172 import { dailyLeft, reserveCeiling } from "../core/account_ceiling.ts";
173173 import {
174174 credentialEnvOf,
@@ -879,6 +879,7 @@ function meterLive(
879879 outcome: "running",
880880 at: new Date(now).toISOString(),
881881 });
882 noteLowWallet(app.db, app.bus, run.repoId, new Date(now));
882883 // The cap is checked on each spend tick, not only at the start.
883884 if (meter.grantOwner !== undefined && meter.stoppedFor === undefined) {
884885 const left = grantLeft(app.db, meter.grantOwner, new Date(now));
@@ -931,6 +932,7 @@ function meterUsage(
931932 outcome: result,
932933 at: ended.toISOString(),
933934 });
935 noteLowWallet(app.db, app.bus, run.repoId, ended);
934936 } catch (error) {
935937 log.warn("usage not recorded", { run: run.id, error: String(error) });
936938 }
src/design/activity.ts +1
@@ -226,6 +226,7 @@ const WORDS: Record<string, string> = {
226226 "webhook.deleted": "removed a webhook",
227227 "webhook.paused": "paused a webhook",
228228 "webhook.resumed": "resumed a webhook",
229 "wallet.low": "has under a tenth of its monthly wallet left",
229230 "webhook.failing": "had a webhook fail three deliveries in a row",
230231 "origin.connected": "connected an origin",
231232 "origin.disconnected": "disconnected an origin",
src/feed/items.ts +7
@@ -42,6 +42,7 @@ import { hotSays, standingHot, standingWide, wideSays } from "../crew/hot_files.
4242 import { conflictsOf, conflictWords } from "../crew/stale_asks.ts";
4343 import { ago } from "./rank.ts";
4444 import { plainWords } from "./plain.ts";
45 import { lowNoticeWords } from "../core/wallet.ts";
4546 import { askLinesFor } from "../web/studio/asks.ts";
4647
4748 export type FeedKind =
@@ -877,6 +878,12 @@ function fromEvent(
877878 urgency: 3,
878879 };
879880 }
881 // A wallet under a tenth of its cap, once a month, for the admins (`core/wallet.ts`).
882 case "wallet.low": {
883 const cap = typeof p["capUsd"] === "number" ? p["capUsd"] : 0;
884 const left = typeof p["left"] === "number" ? p["left"] : 0;
885 return { ...common, kind: "map", link: `${base(repo)}/wallet`, what: lowNoticeWords(left, cap), urgency: 2 };
886 }
880887 case "crew.governed":
881888 return {
882889 ...common,
test/wallet-low.test.ts added +86
@@ -0,0 +1,86 @@
1 /**
2 * A wallet under a tenth of its cap says so once a month: one `wallet.low` event, one feed post for
3 * the admins, however many times spend crosses the threshold (#13969).
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 { createRun } from "../src/core/runs.ts";
13 import { listEvents } from "../src/core/events.ts";
14 import { classifiedAudience } from "../src/core/event_audience.ts";
15 import { noteLowWallet, setMonthCap } from "../src/core/wallet.ts";
16 import { readFeed } from "../src/feed/feed.ts";
17 import { quietLogs } from "./helpers/globals.ts";
18
19 quietLogs();
20
21 let dir = "";
22 let app: ReturnType<typeof createApp>;
23 let repoId = "";
24 let ownerId = "";
25 let owner: any;
26 const now = new Date("2026-11-16T12:00:00Z");
27
28 beforeAll(async () => {
29 dir = await mkdtemp(join(tmpdir(), "forge-wallet-notice-"));
30 app = createApp({ dataDir: dir, port: 0 });
31 const made: any = await createUser(app.db, {
32 origin: "seed", trusted: true, username: "trevato", email: "[email protected]",
33 password: "a-good-passphrase", adminIfFirst: true,
34 });
35 owner = made.value ?? made;
36 ownerId = owner.id;
37 const r: any = await createRepo(app, owner, { name: "garden", visibility: "public" });
38 repoId = (r.value ?? r).id;
39 });
40 afterAll(async () => {
41 app.close();
42 await rm(dir, { recursive: true, force: true });
43 });
44
45 const spend = (usd: number, at: Date) => {
46 const run = createRun(app.db, { repoId, kind: "agent" });
47 app.db.query(`INSERT INTO usage (run_id, repo_id, kind, cost_usd, outcome, at) VALUES (?1, ?2, 'build', ?3, 'ok', ?4)`).run(run.id, repoId, usd, at.toISOString());
48 };
49 const lows = () => listEvents(app.db, { repoId, kind: "wallet.low" });
50 const posts = () => readFeed(app.db, owner, { now: Date.now(), limit: 100 }).items.filter((c) => c.what.startsWith("Wallet "));
51
52 test("no cap, or 10% or more left, says nothing", () => {
53 expect(noteLowWallet(app.db, app.bus, repoId, now)).toBe(false);
54 setMonthCap(app.db, repoId, 100, ownerId, now);
55 spend(90, now);
56 expect(noteLowWallet(app.db, app.bus, repoId, now)).toBe(false);
57 expect(lows()).toHaveLength(0);
58 });
59
60 test("crossing under 10% twice in a month writes one event and one feed post", () => {
61 spend(1, now);
62 expect(noteLowWallet(app.db, app.bus, repoId, now)).toBe(true);
63 // Raise the cap, climb back over the line, cross again.
64 setMonthCap(app.db, repoId, 200, ownerId, now);
65 expect(noteLowWallet(app.db, app.bus, repoId, now)).toBe(false);
66 spend(100, now);
67 expect(noteLowWallet(app.db, app.bus, repoId, now)).toBe(false);
68 expect(lows()).toHaveLength(1);
69 const posts1 = posts();
70 expect(posts1).toHaveLength(1);
71 expect(posts1[0]!.what).toBe("Wallet low: $9 left of $100 this month");
72 });
73
74 test("a new month may say it again, and a spent wallet says so plainly", () => {
75 const next = new Date("2026-12-02T12:00:00Z");
76 setMonthCap(app.db, repoId, 10, ownerId, next);
77 spend(10, next);
78 expect(noteLowWallet(app.db, app.bus, repoId, next)).toBe(true);
79 expect(noteLowWallet(app.db, app.bus, repoId, next)).toBe(false);
80 expect(lows()).toHaveLength(2);
81 expect(String((lows()[0]!.payload as any).left)).toBe("0");
82 });
83
84 test("the event is for admins", () => {
85 expect(classifiedAudience("wallet.low")).toBe("admins");
86 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs