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

A repository has a wallet: its balance is what its crew and bets can spend #8727

Parked opened this in answer to
Closed without merging

torque/forge:torque/8718-a-repository-has-a-wallet-its-balance-is → main 5 commits fork

  • Closed without merging. Nothing was applied to main.

Review

Sign in to review this change.
24 files changed +1027 −25
README.md +4
@@ -467,6 +467,10 @@ days drawn beside it, on its page, in the terminal's Milestones screen and in
467467 the MCP's `milestones` tool (`closedPerDay`, `paceDate`); `docs/PLANNING.md`
468468 has the rule.
469469
470 ### Repository wallets
471
472 Each repository has a wallet at `/<owner>/<name>/wallet` and in the MCP `wallet` tool: an append-only ledger in integer cent-units whose entries always total the balance. It is an allocation, not money; no cash or payment provider exists. Weekly allocations expire at the reset and are spent first; granted funds keep. A run starts only if the repository (or its bet) has funds, and says so in one line otherwise. The old daily ceiling is carried over as seven days of weekly allocation. The owner moves funds between repositories or into a bet in one action. No dependency.
473
470474 ### The throughput keeper
471475
472476 Once a minute the forge measures its landing rate, names the one cause binding it, and lifts Flow only or unsticks assigned issues when that is its to do; if landings do not rise in 2 h it puts the switch back and asks the owner one question with one button. It shows as a line on home and `/boards` (a site admin sees repository names; everyone else a repository-free cause), in the MCP `flow` report, in the terminal's Flow dialog (`l` answers) and as "Forge per day" on the crew scorecard. No model, no dependency. See `docs/features/keeper.md`.
src/actions/wallet.ts added +115
@@ -0,0 +1,115 @@
1 /**
2 * A repository's wallet, as the owner works it (#8718): read it, move
3 * allocation between repositories or into a bet in one action, set the
4 * weekly allocation. Reading needs read access; changing needs admin of the
5 * repository the funds leave. The words say "allocation" because that is
6 * what it is until cash exists.
7 */
8
9 import type { App } from "../app.ts";
10 import { err, ok, type Result } from "../kernel/result.ts";
11 import type { User } from "../core/users.ts";
12 import { getRepo, type Repo } from "../core/repos.ts";
13 import {
14 type Balance,
15 bets,
16 balanceOf,
17 type Entry,
18 ledger,
19 type MoveError,
20 moveUnits,
21 nextReset,
22 setWeekly,
23 settle,
24 weeklyUnits,
25 } from "../core/wallet.ts";
26 import { requireReader, requireRepoAdmin } from "./access.ts";
27
28 export interface WalletView {
29 readonly balance: Balance;
30 readonly weeklyUnits: number;
31 readonly resetsAt: string;
32 readonly bets: { bet: string; balance: Balance }[];
33 readonly entries: Entry[];
34 }
35
36 /** Said at the top of every surface that shows a wallet. */
37 export const WALLET_SAYS =
38 "An allocation, not money: units of list price the crew and bets may spend. Subscription funds refill each Monday (UTC) and what is left expires; cash funds keep. No cash can be added yet.";
39
40 export function readWallet(app: App, actor: User | undefined, repo: Repo, now = new Date()): Result<WalletView, "not_found"> {
41 const reader = requireReader(app, actor, repo);
42 if (!reader.ok) return reader;
43 settle(app.db, repo.id, repo.autonomyCeilingUsd, now);
44 return ok({
45 balance: balanceOf(app.db, repo.id),
46 weeklyUnits: weeklyUnits(app.db, repo.id, repo.autonomyCeilingUsd),
47 resetsAt: nextReset(now).toISOString(),
48 bets: bets(app.db, repo.id),
49 entries: ledger(app.db, repo.id),
50 });
51 }
52
53 /**
54 * Move allocation from this repository's pool (or one of its bets) to another
55 * repository's pool, or into one of that repository's bets. `toRepo` is
56 * `owner/name`; the actor must administer the repository the funds leave and
57 * be able to see the one they reach.
58 */
59 export function moveFunds(
60 app: App,
61 actor: User | undefined,
62 repo: Repo,
63 o: { units: number; fromBet: string | null; toRepo: string | null; toBet: string | null },
64 now = new Date(),
65 ): Result<{ id: string }, "not_found" | MoveError | "no_such_repo"> {
66 const admin = requireRepoAdmin(app, actor, repo);
67 if (!admin.ok) return admin;
68 let target = repo;
69 if (o.toRepo !== null && o.toRepo !== `${repo.ownerName}/${repo.name}`) {
70 const [owner, name, ...rest] = o.toRepo.split("/");
71 const found = owner && name && rest.length === 0 ? getRepo(app.db, owner, name) : undefined;
72 if (!found || !requireReader(app, actor, found).ok) return err("no_such_repo");
73 target = found;
74 }
75 settle(app.db, repo.id, repo.autonomyCeilingUsd, now);
76 settle(app.db, target.id, target.autonomyCeilingUsd, now);
77 const moved = moveUnits(app.db, {
78 from: { repoId: repo.id, bet: o.fromBet },
79 to: { repoId: target.id, bet: o.toBet },
80 units: o.units,
81 actorId: admin.value.id,
82 now,
83 });
84 if (!moved.ok) return err(moved.error);
85 app.bus.append({
86 kind: "wallet.moved",
87 actorId: admin.value.id,
88 repoId: repo.id,
89 payload: { id: moved.id, units: o.units, to: `${target.ownerName}/${target.name}`, toBet: o.toBet, fromBet: o.fromBet },
90 });
91 return ok({ id: moved.id });
92 }
93
94 /** The owner sets how much the repository's subscription fund refills each week. */
95 export function setWeeklyAllocation(
96 app: App,
97 actor: User | undefined,
98 repo: Repo,
99 units: number,
100 now = new Date(),
101 ): Result<{ weeklyUnits: number }, "not_found" | "invalid_amount"> {
102 const admin = requireRepoAdmin(app, actor, repo);
103 if (!admin.ok) return admin;
104 if (!setWeekly(app.db, repo.id, units, admin.value.id, now)) return err("invalid_amount");
105 app.bus.append({ kind: "wallet.weekly_set", actorId: admin.value.id, repoId: repo.id, payload: { units } });
106 return ok({ weeklyUnits: units });
107 }
108
109 export const MOVE_SAYS: Record<MoveError | "no_such_repo", string> = {
110 invalid_amount: "The amount is a positive number of dollars up to 10000.",
111 invalid_bet: "A bet's name is lowercase letters, digits and dashes.",
112 same_place: "That is where the funds already are.",
113 insufficient: "The wallet does not hold that much.",
114 no_such_repo: "No repository by that name that you can see.",
115 };
src/core/event_audience.ts +2
@@ -186,6 +186,8 @@ export function classifiedAudience(kind: string): EventAudience | undefined {
186186 kind === "repo.upstream_follow" ||
187187 kind === "repo.upstream_checked" ||
188188 kind === "repo.crew_outsiders" ||
189 // A wallet is the owner's book-keeping (#8718).
190 kind.startsWith("wallet.") ||
189191 // A clog starting names the forge's own pile-up: the owner's to hear (#6524).
190192 kind.startsWith("clog.") ||
191193 // The release keeper's steps name images and probe numbers: the forge owner's (`keeper/keeper.ts`, #7557).
src/core/migration-pins/20261102200000-repo-wallet.pin added +1
@@ -0,0 +1,1 @@
1 ab3eaf606f94238f23113c8c53a4cebb9b7e7873304597be6698d7c4bfe6d8f5
src/core/migrations/20261102200000-repo-wallet.ts added +34
@@ -0,0 +1,34 @@
1 // A repository's wallet (#8718): an append-only ledger of integer units
2 // (millionths of a list-price dollar), and the weekly allocation that refills
3 // its subscription fund. No row in repo_wallet means "the old daily ceiling
4 // times seven", so every existing ceiling carries over without a data step.
5 // Entries are never changed or removed: the triggers refuse. Additive.
6 export default `
7 CREATE TABLE repo_wallet (
8 repo_id TEXT PRIMARY KEY,
9 weekly_units INTEGER NOT NULL CHECK (weekly_units >= 0),
10 set_by TEXT,
11 set_at TEXT NOT NULL
12 );
13 CREATE TABLE wallet_entry (
14 id INTEGER PRIMARY KEY AUTOINCREMENT,
15 repo_id TEXT NOT NULL,
16 bet TEXT,
17 kind TEXT NOT NULL CHECK (kind IN ('weekly','expiry','run','move_out','move_in','grant')),
18 fund TEXT NOT NULL CHECK (fund IN ('subscription','cash')),
19 units INTEGER NOT NULL,
20 at TEXT NOT NULL,
21 week TEXT,
22 run_id TEXT,
23 move_id TEXT,
24 actor_id TEXT,
25 note TEXT NOT NULL DEFAULT ''
26 );
27 CREATE INDEX wallet_entry_repo ON wallet_entry(repo_id, id);
28 CREATE UNIQUE INDEX wallet_entry_week ON wallet_entry(repo_id, week) WHERE kind = 'weekly';
29 CREATE UNIQUE INDEX wallet_entry_run ON wallet_entry(run_id) WHERE run_id IS NOT NULL;
30 CREATE TRIGGER wallet_entry_no_update BEFORE UPDATE ON wallet_entry
31 BEGIN SELECT RAISE(ABORT, 'wallet entries are append only'); END;
32 CREATE TRIGGER wallet_entry_no_delete BEFORE DELETE ON wallet_entry
33 BEGIN SELECT RAISE(ABORT, 'wallet entries are append only'); END;
34 `;
src/core/wallet.ts added +316
@@ -0,0 +1,316 @@
1 /**
2 * A repository's wallet (#8718): an allocation the crew and bets spend, kept
3 * as an append-only ledger in integer units — millionths of a list-price
4 * dollar (`UNIT`), never a float dollar. It is not money and no payment
5 * provider stands behind it. Two funds: `subscription` refills each UTC week
6 * (Monday 00:00) from the repository's weekly allocation and what is left
7 * expires at the next reset, so it is spent first; `cash` keeps. The balance
8 * IS the sum of the entries — there is no second number to drift. A bet's
9 * envelope is the same ledger under `bet`. Pure data; who may move funds is
10 * the action's to decide (`actions/wallet.ts`).
11 */
12
13 import type { Database } from "bun:sqlite";
14 import { id as newId, idFloor } from "../kernel/id.ts";
15 import { transact } from "../kernel/db.ts";
16
17 /** Units in one list-price dollar. */
18 export const UNIT = 1_000_000;
19 /** The most one move or grant may be: 10 000 list-price dollars. */
20 export const MOVE_MAX = 10_000 * UNIT;
21
22 export type Fund = "subscription" | "cash";
23 export type EntryKind = "weekly" | "expiry" | "run" | "move_out" | "move_in" | "grant";
24
25 export interface Entry {
26 readonly id: number;
27 readonly repoId: string;
28 readonly bet: string | null;
29 readonly kind: EntryKind;
30 readonly fund: Fund;
31 readonly units: number;
32 readonly at: string;
33 readonly runId: string | null;
34 readonly note: string;
35 }
36
37 export interface Balance {
38 readonly subscription: number;
39 readonly cash: number;
40 readonly total: number;
41 }
42
43 /** A bet's name in the ledger: lowercase letters, digits and dashes. */
44 export const validBet = (s: string): boolean => /^[a-z0-9][a-z0-9-]{0,39}$/.test(s);
45
46 /** List-price dollars to whole units; the one place a float becomes an integer. */
47 export const toUnits = (usd: number): number => (Number.isFinite(usd) && usd > 0 ? Math.round(usd * UNIT) : 0);
48
49 /** Typed list-price dollars ("12", "12.5", "0.000001") to units by digits alone, or undefined: no float is ever formed. */
50 export function parseUnits(text: string): number | undefined {
51 const m = /^(\d{1,7})(?:\.(\d{1,6}))?$/.exec(text.trim());
52 if (!m) return undefined;
53 return Number(m[1]) * UNIT + Number((m[2] ?? "").padEnd(6, "0"));
54 }
55
56 /** Units as dollars-and-cents text from integer math, truncated toward zero. */
57 export function unitsText(units: number): string {
58 const cents = Math.trunc(units / (UNIT / 100));
59 const abs = Math.abs(cents);
60 return `${cents < 0 ? "-" : ""}$${Math.trunc(abs / 100)}.${String(abs % 100).padStart(2, "0")}`;
61 }
62
63 /** The UTC Monday 00:00 that opens the week holding `now`. */
64 export function weekStart(now: Date): Date {
65 const day = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));
66 day.setUTCDate(day.getUTCDate() - ((day.getUTCDay() + 6) % 7));
67 return day;
68 }
69
70 /** The next reset, when subscription funds expire. */
71 export function nextReset(now: Date): Date {
72 const next = weekStart(now);
73 next.setUTCDate(next.getUTCDate() + 7);
74 return next;
75 }
76
77 /**
78 * The weekly allocation: what the owner set, else seven of the repository's
79 * old daily ceilings, so every existing ceiling carries over unchanged.
80 */
81 export function weeklyUnits(db: Database, repoId: string, dailyCeilingUsd: number): number {
82 const row = db
83 .query<{ w: number }, [string]>("SELECT weekly_units AS w FROM repo_wallet WHERE repo_id = ?1")
84 .get(repoId);
85 return row ? row.w : toUnits(dailyCeilingUsd) * 7;
86 }
87
88 const weeklySet = (db: Database, repoId: string): boolean =>
89 db.query("SELECT 1 FROM repo_wallet WHERE repo_id = ?1").get(repoId) !== null;
90
91 /** The pool's allocation entered since the week began: the refill and any ceiling grants. */
92 const allocatedSince = (db: Database, repoId: string, start: Date): number =>
93 db
94 .query<{ n: number }, [string, string]>(
95 `SELECT COALESCE(SUM(units), 0) AS n FROM wallet_entry
96 WHERE repo_id = ?1 AND bet IS NULL AND fund = 'subscription' AND at >= ?2
97 AND (kind = 'weekly' OR (kind = 'grant' AND note LIKE 'daily ceiling changed%'))`,
98 )
99 .get(repoId, start.toISOString())?.n ?? 0;
100
101 const scopeSum = (db: Database, repoId: string, bet: string | null, fund: Fund): number =>
102 db
103 .query<{ n: number }, [string, string | null, string]>(
104 `SELECT COALESCE(SUM(units), 0) AS n FROM wallet_entry
105 WHERE repo_id = ?1 AND bet IS ?2 AND fund = ?3`,
106 )
107 .get(repoId, bet, fund)?.n ?? 0;
108
109 /** The balance of the repository's pool (`bet` null) or of one bet's envelope: the sum of its entries. */
110 export function balanceOf(db: Database, repoId: string, bet: string | null = null): Balance {
111 const subscription = scopeSum(db, repoId, bet, "subscription");
112 const cash = scopeSum(db, repoId, bet, "cash");
113 return { subscription, cash, total: subscription + cash };
114 }
115
116 function append(
117 db: Database,
118 e: {
119 repoId: string;
120 bet?: string | null;
121 kind: EntryKind;
122 fund: Fund;
123 units: number;
124 at: Date;
125 week?: string;
126 runId?: string;
127 moveId?: string;
128 actorId?: string | null;
129 note?: string;
130 },
131 ): void {
132 db.query(
133 `INSERT INTO wallet_entry (repo_id, bet, kind, fund, units, at, week, run_id, move_id, actor_id, note)
134 VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)`,
135 ).run(
136 e.repoId,
137 e.bet ?? null,
138 e.kind,
139 e.fund,
140 e.units,
141 e.at.toISOString(),
142 e.week ?? null,
143 e.runId ?? null,
144 e.moveId ?? null,
145 e.actorId ?? null,
146 e.note ?? "",
147 );
148 }
149
150 /** Which scopes (the pool and each bet) hold a subscription remainder. */
151 const subscriptionScopes = (db: Database, repoId: string): { bet: string | null; n: number }[] =>
152 db
153 .query<{ bet: string | null; n: number }, [string]>(
154 `SELECT bet, SUM(units) AS n FROM wallet_entry
155 WHERE repo_id = ?1 AND fund = 'subscription' GROUP BY bet HAVING SUM(units) != 0`,
156 )
157 .all(repoId);
158
159 /**
160 * Bring the ledger up to `now`, appending what is owed and nothing else, so
161 * the same state gives the same entries: the week's refill (after expiring
162 * what the last week left), and each finished run's cost not yet entered,
163 * drawn from the subscription fund first and from cash for the rest.
164 */
165 export function settle(db: Database, repoId: string, dailyCeilingUsd: number, now: Date): void {
166 const start = weekStart(now);
167 const week = start.toISOString().slice(0, 10);
168 // Runs that began in the week before still settle; older ones are history.
169 const since = new Date(start.getTime() - 7 * 86_400_000);
170 const owed = db
171 .query<{ id: string; cost: number }, [string, string]>(
172 `SELECT r.id AS id, r.cost_usd AS cost FROM run r
173 WHERE r.repo_id = ?1 AND r.id >= ?2 AND r.kind = 'agent' AND r.cost_usd > 0
174 AND NOT EXISTS (SELECT 1 FROM wallet_entry w WHERE w.run_id = r.id)
175 ORDER BY r.id`,
176 )
177 .all(repoId, idFloor(since.getTime()));
178 const refilled =
179 db
180 .query<{ n: number }, [string, string]>(
181 "SELECT COUNT(*) AS n FROM wallet_entry WHERE repo_id = ?1 AND kind = 'weekly' AND week = ?2",
182 )
183 .get(repoId, week)?.n === 1;
184 const weekly = weeklyUnits(db, repoId, dailyCeilingUsd);
185 // With no weekly allocation set, the week's allocation follows the daily ceiling as it is
186 // changed: the drift between seven of it and what was refilled is entered as one signed grant.
187 const drift = refilled && !weeklySet(db, repoId) ? weekly - allocatedSince(db, repoId, start) : 0;
188 if (owed.length === 0 && drift === 0 && (refilled || weekly === 0)) return;
189 transact(db, () => {
190 if (drift !== 0)
191 append(db, { repoId, kind: "grant", fund: "subscription", units: drift, at: now, note: "daily ceiling changed: the week's allocation follows" });
192 if (!refilled && weekly > 0) {
193 for (const s of subscriptionScopes(db, repoId))
194 if (s.n > 0)
195 append(db, { repoId, bet: s.bet, kind: "expiry", fund: "subscription", units: -s.n, at: start, note: "the week's reset" });
196 try {
197 append(db, { repoId, kind: "weekly", fund: "subscription", units: weekly, at: start, week, note: "weekly allocation" });
198 } catch {
199 // A second process refilled this week first (the unique index); the allocation stands once.
200 }
201 }
202 for (const run of owed) {
203 const cost = toUnits(run.cost);
204 if (cost === 0) continue;
205 const fromSub = Math.max(0, Math.min(cost, scopeSum(db, repoId, null, "subscription")));
206 const fromCash = cost - fromSub;
207 const at = now;
208 if (fromSub > 0) append(db, { repoId, kind: "run", fund: "subscription", units: -fromSub, at, runId: run.id, note: "run cost at list price" });
209 if (fromCash > 0)
210 // The unique run index allows one entry per run: a run that spans both funds records the subscription part under its id and the cash part under none.
211 append(db, { repoId, kind: "run", fund: "cash", units: -fromCash, at, ...(fromSub > 0 ? {} : { runId: run.id }), note: fromSub > 0 ? `run ${run.id} cost beyond the subscription fund` : "run cost at list price" });
212 }
213 });
214 }
215
216 /** The balance after settling to `now`: what a page shows. */
217 export function balanceNow(db: Database, repoId: string, dailyCeilingUsd: number, now: Date): Balance {
218 settle(db, repoId, dailyCeilingUsd, now);
219 return balanceOf(db, repoId);
220 }
221
222 export type MoveError = "invalid_amount" | "invalid_bet" | "same_place" | "insufficient";
223
224 /**
225 * Move `units` from one place to another in one transaction: each place is a
226 * repository pool or one of its bets. The receiving side gets the same funds
227 * the giving side gave, subscription first, so a move cannot turn an
228 * expiring allocation into keeping cash. Returns the move's id.
229 */
230 export function moveUnits(
231 db: Database,
232 o: {
233 from: { repoId: string; bet: string | null };
234 to: { repoId: string; bet: string | null };
235 units: number;
236 actorId: string;
237 now: Date;
238 note?: string;
239 },
240 ): { ok: true; id: string } | { ok: false; error: MoveError } {
241 const { from, to, units } = o;
242 if (!Number.isSafeInteger(units) || units <= 0 || units > MOVE_MAX) return { ok: false, error: "invalid_amount" };
243 if ((from.bet !== null && !validBet(from.bet)) || (to.bet !== null && !validBet(to.bet))) return { ok: false, error: "invalid_bet" };
244 if (from.repoId === to.repoId && from.bet === to.bet) return { ok: false, error: "same_place" };
245 return transact(db, () => {
246 const sub = Math.max(0, scopeSum(db, from.repoId, from.bet, "subscription"));
247 const cash = Math.max(0, scopeSum(db, from.repoId, from.bet, "cash"));
248 if (sub + cash < units) return { ok: false as const, error: "insufficient" as const };
249 const takeSub = Math.min(sub, units);
250 const takeCash = units - takeSub;
251 const moveId = newId();
252 for (const [fund, n] of [["subscription", takeSub], ["cash", takeCash]] as const) {
253 if (n === 0) continue;
254 const base = { fund, at: o.now, moveId, actorId: o.actorId, note: o.note ?? "" };
255 append(db, { ...base, repoId: from.repoId, bet: from.bet, kind: "move_out", units: -n });
256 append(db, { ...base, repoId: to.repoId, bet: to.bet, kind: "move_in", units: n });
257 }
258 return { ok: true as const, id: moveId };
259 });
260 }
261
262 /** Set the weekly allocation. False when it is not a whole, sane number of units. */
263 export function setWeekly(db: Database, repoId: string, units: number, by: string, now: Date): boolean {
264 if (!Number.isSafeInteger(units) || units < 0 || units > MOVE_MAX * 10) return false;
265 db.query(
266 `INSERT INTO repo_wallet (repo_id, weekly_units, set_by, set_at) VALUES (?1, ?2, ?3, ?4)
267 ON CONFLICT(repo_id) DO UPDATE SET weekly_units = ?2, set_by = ?3, set_at = ?4`,
268 ).run(repoId, units, by, now.toISOString());
269 return true;
270 }
271
272 /** The newest entries first. */
273 export function ledger(db: Database, repoId: string, limit = 100): Entry[] {
274 return db
275 .query<
276 { id: number; repo_id: string; bet: string | null; kind: EntryKind; fund: Fund; units: number; at: string; run_id: string | null; note: string },
277 [string, number]
278 >(
279 `SELECT id, repo_id, bet, kind, fund, units, at, run_id, note FROM wallet_entry
280 WHERE repo_id = ?1 ORDER BY id DESC LIMIT ?2`,
281 )
282 .all(repoId, Math.max(1, Math.min(500, limit)))
283 .map((r) => ({ id: r.id, repoId: r.repo_id, bet: r.bet, kind: r.kind, fund: r.fund, units: r.units, at: r.at, runId: r.run_id, note: r.note }));
284 }
285
286 /** The bets that hold an envelope here, with their balances. */
287 export function bets(db: Database, repoId: string): { bet: string; balance: Balance }[] {
288 return db
289 .query<{ bet: string }, [string]>("SELECT DISTINCT bet FROM wallet_entry WHERE repo_id = ?1 AND bet IS NOT NULL ORDER BY bet")
290 .all(repoId)
291 .map((r) => ({ bet: r.bet, balance: balanceOf(db, repoId, r.bet) }));
292 }
293
294 /**
295 * Whether a run may start: the bet's envelope has funds, or, with no bet,
296 * the repository's pool does. The one line it says otherwise is the reason
297 * every surface shows.
298 */
299 export function mayStart(
300 db: Database,
301 repoId: string,
302 dailyCeilingUsd: number,
303 now: Date,
304 bet: string | null = null,
305 ): { ok: true } | { ok: false; says: string } {
306 settle(db, repoId, dailyCeilingUsd, now);
307 const b = balanceOf(db, repoId, bet);
308 if (b.total > 0) return { ok: true };
309 return {
310 ok: false,
311 says:
312 bet === null
313 ? `No run starts: this repository's wallet is empty (${unitsText(b.total)} allocated); it refills Monday ${nextReset(now).toISOString().slice(0, 10)}, or the owner moves funds in.`
314 : `No run starts: bet ${bet} has no funds left (${unitsText(b.total)}); the owner moves funds into it.`,
315 };
316 }
src/crew/autonomy.ts +2 −1
@@ -92,6 +92,7 @@ import {
9292 } from "../core/runs.ts";
9393 import {
9494 agentFor,
95 atCeiling,
9596 CHECK_FAILED_LIMIT,
9697 lastHumanWord,
9798 queueAgentRun,
@@ -316,7 +317,7 @@ export function autonomyStatus(
316317 ? "nobody"
317318 : crew.length === 0
318319 ? "no crew"
319 : spent >= repo.autonomyCeilingUsd
320 : atCeiling(app.db, repo, now)
320321 ? "ceiling"
321322 : ceilingReached(spentTodayEverywhere(app.db, now), forgeCap)
322323 ? "forge ceiling"
src/crew/conversation_confirm.ts +4
@@ -56,6 +56,10 @@ export const ASKING: Readonly<Record<string, Asking>> = {
5656 subscription_wake: { does: "use a resting subscription again now" },
5757 model_grant: { does: "give an account a monthly model grant", undo: () => "`model_grant` with `usdPerMonth: 0` takes it back" },
5858 model_ceiling: { does: "cap an account's model spend", undo: () => "`model_ceiling` with both `null` clears it" },
59 wallet: {
60 does: "move a repository's allocation or set its weekly sum",
61 asks: (a) => a["move"] !== undefined || a["weekly"] !== undefined,
62 },
5963 limits: { does: "change one of the forge's limits", undo: () => "`limits` with `value: \"\"` restores the default" },
6064 // Secrets and credentials.
6165 secrets: { does: "set or remove a sealed secret", asks: not("action", "list") },
src/crew/dispatch.ts +12 −7
@@ -20,6 +20,7 @@ import { emailVerified } from "../core/verify.ts";
2020 import { rmSync } from "node:fs";
2121 import type { App } from "../app.ts";
2222 import { transact } from "../kernel/db.ts";
23 import { mayStart } from "../core/wallet.ts";
2324 import { addComment } from "../actions/issues.ts";
2425 import { planAnotherRound } from "../actions/give_back.ts";
2526 import { announceRun } from "../actions/runs.ts";
@@ -94,7 +95,6 @@ import {
9495 parkForBreaker,
9596 parkPull,
9697 settleAgentRun,
97 spentToday,
9898 } from "./autonomy.ts";
9999 import { checksFor } from "../checks/service.ts";
100100 import { redMain, sharedWithMain } from "../checks/red_main.ts";
@@ -361,12 +361,17 @@ function unstickDue(app: App, repo: Repo, issue: Issue): boolean {
361361 return unstickOwed(app.db, repo, last?.at ?? "");
362362 }
363363
364 /** Whether `spentUsd` has reached the repository's daily ceiling: the test that stops a run being queued. */
364 /**
365 * Whether the repository's wallet has no funds left: the test that stops a
366 * run being queued (#8718; it was the daily ceiling). Its one-line reason is
367 * `mayStart`'s.
368 */
365369 export function atCeiling(
366 repo: Pick<Repo, "autonomyCeilingUsd">,
367 spentUsd: number,
370 db: App["db"],
371 repo: Pick<Repo, "id" | "autonomyCeilingUsd">,
372 now = new Date(),
368373 ): boolean {
369 return spentUsd >= repo.autonomyCeilingUsd;
374 return !mayStart(db, repo.id, repo.autonomyCeilingUsd, now).ok;
370375 }
371376
372377 /** Queue a run about an issue for an agent, unless one is already waiting. */
@@ -401,9 +406,9 @@ export function queueAgentRun(
401406 if (
402407 reason !== "assigned" &&
403408 repo.autonomy === "autonomous" &&
404 atCeiling(repo, spentToday(app.db, repo.id))
409 atCeiling(app.db, repo)
405410 ) {
406 log.info("at the ceiling; not queued", {
411 log.info("the wallet is empty; not queued", {
407412 repo: `${repo.ownerName}/${repo.name}`,
408413 issue: issue.number,
409414 reason,
src/crew/idle_reason.ts +2 −2
@@ -17,7 +17,7 @@ import { listAutonomousRepos } from "../core/repos.ts";
1717 import { listActive } from "../core/runs.ts";
1818 import { standings } from "../core/standing.ts";
1919 import { grantedAccounts } from "../core/subscriptions.ts";
20 import { slottedRuns, spentToday } from "./autonomy.ts";
20 import { slottedRuns } from "./autonomy.ts";
2121 import { atCeiling } from "./dispatch.ts";
2222 import { heldNow } from "./held.ts";
2323 import { pace } from "./pacing.ts";
@@ -39,7 +39,7 @@ export function idleReason(app: App, now: Date): IdleReason | null {
3939 const active = listActive(db, "agent").filter((r) => r.repoId === repo.id);
4040 if (slottedRuns(active, crew).length >= repo.autonomySlots) return null;
4141
42 if (atCeiling(repo, spentToday(db, repo.id, now))) return { word: "ceiling reached", href: "/meter" };
42 if (atCeiling(db, repo, now)) return { word: "ceiling reached", href: "/meter" };
4343
4444 const granted = grantedAccounts(db, repo.id, repo.ownerId);
4545 if (granted.length > 0) {
src/design/activity.ts +2
@@ -146,6 +146,8 @@ const WORDS: Record<string, string> = {
146146 "repo.upstream_follow": "changed which upstream the repository follows",
147147 "repo.following": "turned following an upstream on or off",
148148 "repo.crew_outsiders": "changed who may trigger the crew",
149 "wallet.moved": "moved allocation from a repository wallet",
150 "wallet.weekly_set": "set a repository's weekly allocation",
149151 "repo.mirrored": "mirrored a repository",
150152 "repo.imported": "imported issues and pulls",
151153 "repo.pinned": "pinned a repository",
src/flow/keeper_cause.ts +2 −2
@@ -12,7 +12,7 @@ import { listAutonomousRepos } from "../core/repos.ts";
1212 import { listActive } from "../core/runs.ts";
1313 import { standings } from "../core/standing.ts";
1414 import { grantedAccounts } from "../core/subscriptions.ts";
15 import { slottedRuns, spentToday } from "../crew/autonomy.ts";
15 import { slottedRuns } from "../crew/autonomy.ts";
1616 import { atCeiling } from "../crew/dispatch.ts";
1717 import { heldNow } from "../crew/held.ts";
1818 import { pace } from "../crew/pacing.ts";
@@ -157,7 +157,7 @@ export function readKeeperFacts(app: App, now: Date): KeeperFacts {
157157 running: slottedRuns(active, crew).length,
158158 slots: repo.autonomySlots,
159159 ceilingUsd: repo.autonomyCeilingUsd,
160 atCeiling: atCeiling(repo, spentToday(db, repo.id, now)),
160 atCeiling: atCeiling(db, repo, now),
161161 noHeadroom,
162162 resetsAt,
163163 });
src/http/mcp/tools/index.ts +1
@@ -165,6 +165,7 @@ export { tool as usage } from "./usage.ts";
165165 export { tool as variant } from "./variant.ts";
166166 export { tool as vision } from "./vision.ts";
167167 export { tool as wait_for } from "./wait_for.ts";
168 export { tool as wallet } from "./wallet.ts";
168169 export { tool as watch } from "./watch.ts";
169170 export { tool as waves } from "./waves.ts";
170171 export { tool as whoami_can } from "./whoami_can.ts";
src/http/mcp/tools/wallet.ts added +56
@@ -0,0 +1,56 @@
1 import { MOVE_SAYS, moveFunds, readWallet, setWeeklyAllocation, WALLET_SAYS } from "../../../actions/wallet.ts";
2 import { parseUnits, unitsText } from "../../../core/wallet.ts";
3 import { good, bad, type Tool, REPO_ARG, repoArg, isAnswer } from "../shared.ts";
4
5 const str = (v: unknown): string | null => (typeof v === "string" && v.trim() !== "" ? v.trim() : null);
6
7 export const tool: Tool = {
8 name: "wallet",
9 doc: "`{ repo, move?: { amount, fromBet?, toRepo?, toBet? }, weekly? }`: a repository's wallet — an allocation, not money: its balance by fund, bets and ledger (units are millionths of a list-price dollar); `move` shifts `amount` (list-price dollars, as text) to another repository or into a bet, `weekly` sets the weekly allocation; both are for the repository's admin",
10 description:
11 "Read a repository's wallet (an allocation, not money); move funds or set the weekly sum (admin).",
12 inputSchema: {
13 type: "object",
14 properties: {
15 repo: REPO_ARG,
16 move: {
17 type: "object",
18 properties: {
19 amount: { type: "string", description: "List-price dollars as text, e.g. \"12.50\"." },
20 fromBet: { type: "string" },
21 toRepo: { type: "string", description: "owner/name; absent: this repository." },
22 toBet: { type: "string" },
23 },
24 required: ["amount"],
25 },
26 weekly: { type: "string", description: "Weekly allocation, list-price dollars as text." },
27 },
28 required: ["repo"],
29 },
30 writes: true,
31 readsWithout: ["move", "weekly"],
32 run(ctx, user, args) {
33 const repo = repoArg(ctx, user, args);
34 if (isAnswer(repo)) return repo;
35 if (args["move"] !== undefined) {
36 const m = args["move"];
37 if (m === null || typeof m !== "object" || Array.isArray(m)) return bad("invalid", "`move` is an object with an amount");
38 const o = m as Record<string, unknown>;
39 const units = typeof o["amount"] === "string" ? parseUnits(o["amount"]) : undefined;
40 if (units === undefined) return bad("invalid_amount", MOVE_SAYS.invalid_amount);
41 const moved = moveFunds(ctx.app, user, repo, { units, fromBet: str(o["fromBet"]), toRepo: str(o["toRepo"]), toBet: str(o["toBet"]) });
42 if (!moved.ok) return bad(moved.error, moved.error === "not_found" ? "only an admin of this repository moves its funds" : MOVE_SAYS[moved.error]);
43 return good({ moved: moved.value.id, says: `Moved ${unitsText(units)} of allocation.` });
44 }
45 if (args["weekly"] !== undefined) {
46 const units = typeof args["weekly"] === "string" ? parseUnits(args["weekly"]) : undefined;
47 if (units === undefined) return bad("invalid_amount", MOVE_SAYS.invalid_amount);
48 const set = setWeeklyAllocation(ctx.app, user, repo, units);
49 if (!set.ok) return bad(set.error, "only an admin of this repository sets its allocation");
50 return good({ weeklyUnits: set.value.weeklyUnits, says: `Weekly allocation is ${unitsText(units)}.` });
51 }
52 const view = readWallet(ctx.app, user, repo);
53 if (!view.ok) return bad("not_found", "no such repository");
54 return good({ ...view.value, says: WALLET_SAYS });
55 },
56 };
src/http/server.ts +4
@@ -5,6 +5,7 @@
55 * verdict. Auth is resolved once per request and handed to handlers as data.
66 */
77
8 import { walletMove, walletPage, walletWeekly } from "../web/pages/wallet.ts";
89 import { followUpstreamCheck, followUpstreamUpdate } from "../web/pages/upstream-follow.ts";
910 import { secureFor } from "./cookie_secure.ts";
1011 import { refusedByDatabase, shownRefusal } from "./refusal.ts";
@@ -1302,6 +1303,9 @@ export function buildRouter(): Router<Handler> {
13021303 router.add("POST", "/:owner/:name/settings/pillars", pillarUpdate);
13031304 router.add("GET", "/:owner/:name/settings/autonomy", autonomySettingsPage);
13041305 router.add("POST", "/:owner/:name/settings/autonomy", autonomySettingsUpdate);
1306 router.add("GET", "/:owner/:name/wallet", walletPage);
1307 router.add("POST", "/:owner/:name/wallet/move", walletMove);
1308 router.add("POST", "/:owner/:name/wallet/weekly", walletWeekly);
13051309 router.add("POST", "/:owner/:name/settings/holds", fileHoldUpdate);
13061310 router.add("POST", "/:owner/:name/settings/upstream", followUpstreamUpdate);
13071311 router.add("POST", "/:owner/:name/settings/upstream/check", followUpstreamCheck);
src/web/pages/wallet.ts added +155
@@ -0,0 +1,155 @@
1 /**
2 * A repository's wallet page (#8718): the balance, the ledger and, for its
3 * admin, the one form that moves allocation to another repository or into a
4 * bet. It says what it is — an allocation, not money — before anything else.
5 * GET /:owner/:name/wallet; POST …/wallet/move and …/wallet/weekly.
6 */
7
8 import { MOVE_SAYS, moveFunds, readWallet, setWeeklyAllocation, WALLET_SAYS } from "../../actions/wallet.ts";
9 import { notePhase, takeSessionTime } from "../../core/route_timing.ts";
10 import { canAdmin, type Repo } from "../../core/repos.ts";
11 import { parseUnits, unitsText, type Entry } from "../../core/wallet.ts";
12 import type { Ctx } from "../../http/context.ts";
13 import { crumbsFor, loadRepo, repoBase, repoHeader, repoNotFound } from "../chrome.ts";
14 import { field as formField, readForm, type Form } from "../form.ts";
15 import { html, type Html } from "../html.ts";
16 import { flashTo, page } from "../layout.ts";
17 import { btn, card, field } from "../ui.ts";
18
19 const KIND_WORDS: Record<Entry["kind"], string> = {
20 weekly: "weekly allocation",
21 expiry: "expired at the weekly reset",
22 run: "run",
23 move_out: "moved out",
24 move_in: "moved in",
25 grant: "granted",
26 };
27
28 const signed = (units: number): string => `${units > 0 ? "+" : ""}${unitsText(units)}`;
29
30 function ledgerTable(entries: readonly Entry[]): Html {
31 if (entries.length === 0) return html`<p class="muted">Nothing has happened here yet.</p>`;
32 return html`<div class="table-scroll">
33 <table class="table" data-dense aria-label="Ledger, newest first">
34 <thead>
35 <tr>
36 <th scope="col">When (UTC)</th>
37 <th scope="col">What</th>
38 <th scope="col">Fund</th>
39 <th scope="col">Bet</th>
40 <th scope="col" class="num">Units, list price</th>
41 </tr>
42 </thead>
43 <tbody>
44 ${entries.map(
45 (e) => html`<tr>
46 <td>${e.at.slice(0, 16).replace("T", " ")}</td>
47 <td>${KIND_WORDS[e.kind]}${e.runId !== null ? html` <code>${e.runId.slice(-6)}</code>` : null}${e.note !== "" && e.kind !== "run" ? html` <span class="muted">${e.note}</span>` : null}</td>
48 <td>${e.fund}</td>
49 <td>${e.bet ?? "—"}</td>
50 <td class="num">${signed(e.units)}</td>
51 </tr>`,
52 )}
53 </tbody>
54 </table>
55 </div>`;
56 }
57
58 // GET /:owner/:name/wallet
59 export function walletPage(ctx: Ctx): Response {
60 notePhase(ctx.request, "session", takeSessionTime(ctx.request));
61 const repo = loadRepo(ctx);
62 if (!repo) return repoNotFound(ctx);
63 const view = readWallet(ctx.app, ctx.auth.user, repo);
64 if (!view.ok) return repoNotFound(ctx);
65 const w = view.value;
66 const base = repoBase(repo);
67 const admin = canAdmin(ctx.app.db, repo, ctx.auth.user);
68 const forms = !admin
69 ? null
70 : html`${card(
71 html`<form method="post" action="${base}/wallet/move">
72 ${field({ label: "Amount (list-price dollars)", name: "amount", type: "text", required: true, mono: true, hint: "Taken from the subscription fund first, then cash; the receiver gets the same funds." })}
73 ${field({ label: "From bet (blank: the repository's pool)", name: "from_bet", type: "text", mono: true })}
74 ${field({ label: "To repository (blank: this one)", name: "to_repo", type: "text", mono: true, placeholder: `${repo.ownerName}/${repo.name}` })}
75 ${field({ label: "Into bet (blank: that repository's pool)", name: "to_bet", type: "text", mono: true, hint: "Lowercase letters, digits and dashes. A bet's appetite is drawn from this wallet." })}
76 <div class="form-actions">${btn("Move", { variant: "primary" })}</div>
77 </form>`,
78 { head: html`<h2>Move allocation</h2>` },
79 )}
80 ${card(
81 html`<form method="post" action="${base}/wallet/weekly">
82 ${field({ label: "Weekly allocation (list-price dollars)", name: "weekly", type: "text", required: true, mono: true, value: unitsText(w.weeklyUnits).slice(1), hint: "Refills the subscription fund each Monday 00:00 UTC. Until you set it, seven days of the old daily ceiling." })}
83 <div class="form-actions">${btn("Save", { variant: "primary" })}</div>
84 </form>`,
85 { head: html`<h2>Weekly allocation</h2>` },
86 )}`;
87 const rendering = performance.now();
88 const response = page({
89 ctx,
90 title: `Wallet · ${repo.ownerName}/${repo.name}`,
91 crumbs: crumbsFor(repo),
92 body: html`${repoHeader(ctx, repo, "none", { compact: true })}
93 <p class="muted" id="wallet-says">${WALLET_SAYS}</p>
94 ${card(
95 html`<dl>
96 <dt>Balance</dt>
97 <dd id="wallet-total"><b>${unitsText(w.balance.total)}</b> allocated, list price</dd>
98 <dt>Subscription fund</dt>
99 <dd>${unitsText(w.balance.subscription)} — expires ${w.resetsAt.slice(0, 10)} 00:00 UTC</dd>
100 <dt>Cash fund</dt>
101 <dd>${unitsText(w.balance.cash)}</dd>
102 <dt>Weekly allocation</dt>
103 <dd>${unitsText(w.weeklyUnits)}</dd>
104 </dl>
105 ${w.bets.length === 0
106 ? null
107 : html`<h3>Bets</h3>
108 <ul>${w.bets.map((b) => html`<li><b>${b.bet}</b> ${unitsText(b.balance.total)}</li>`)}</ul>`}`,
109 { head: html`<h2>Wallet</h2>` },
110 )}
111 ${forms}
112 ${card(ledgerTable(w.entries), { head: html`<h2>Ledger</h2>`, pad: false })}`,
113 });
114 notePhase(ctx.request, "render", performance.now() - rendering);
115 return response;
116 }
117
118 async function walletForm(ctx: Ctx): Promise<{ repo: Repo; form: Form } | Response> {
119 const repo = loadRepo(ctx);
120 if (!repo || !canAdmin(ctx.app.db, repo, ctx.auth.user)) return repoNotFound(ctx);
121 const form = await readForm(ctx, "admin");
122 if (form instanceof Response) return form;
123 return { repo, form };
124 }
125
126 // POST /:owner/:name/wallet/move
127 export async function walletMove(ctx: Ctx): Promise<Response> {
128 const gate = await walletForm(ctx);
129 if (gate instanceof Response) return gate;
130 const { repo, form } = gate;
131 const back = `${repoBase(repo)}/wallet`;
132 const units = parseUnits(formField(form, "amount"));
133 if (units === undefined) return flashTo(ctx, back, { tone: "danger", message: MOVE_SAYS.invalid_amount });
134 const blank = (s: string): string | null => (s.trim() === "" ? null : s.trim());
135 const moved = moveFunds(ctx.app, ctx.auth.user, repo, {
136 units,
137 fromBet: blank(formField(form, "from_bet")),
138 toRepo: blank(formField(form, "to_repo")),
139 toBet: blank(formField(form, "to_bet")),
140 });
141 if (!moved.ok) return flashTo(ctx, back, { tone: "danger", message: moved.error === "not_found" ? "Not allowed." : MOVE_SAYS[moved.error] });
142 return flashTo(ctx, back, { message: `Moved ${unitsText(units)} of allocation.` });
143 }
144
145 // POST /:owner/:name/wallet/weekly
146 export async function walletWeekly(ctx: Ctx): Promise<Response> {
147 const gate = await walletForm(ctx);
148 if (gate instanceof Response) return gate;
149 const { repo, form } = gate;
150 const back = `${repoBase(repo)}/wallet`;
151 const units = parseUnits(formField(form, "weekly"));
152 const set = units === undefined ? undefined : setWeeklyAllocation(ctx.app, ctx.auth.user, repo, units);
153 if (set === undefined || !set.ok) return flashTo(ctx, back, { tone: "danger", message: MOVE_SAYS.invalid_amount });
154 return flashTo(ctx, back, { message: `Weekly allocation is ${unitsText(set.value.weeklyUnits)}.` });
155 }
src/web/studio/crew.ts +7 −6
@@ -36,6 +36,7 @@ import { governorSeen } from "../../crew/governed.ts";
3636 import { crewOffInPreview } from "../../crew/preview.ts";
3737 import type { Ctx } from "../../http/context.ts";
3838 import { repoBase } from "../chrome.ts";
39 import { balanceNow, unitsText } from "../../core/wallet.ts";
3940 import { html, raw, type Html } from "../html.ts";
4041 import { icon } from "../icons.ts";
4142 import { crewReadiness } from "../pages/crew.ts";
@@ -367,10 +368,10 @@ function autonomyCard(ctx: Ctx, repo: Repo, base: string, admin: boolean): Html
367368 : html`<dl>
368369 <dt>Mode</dt>
369370 <dd>${repo.autonomy === "autonomous" ? "Autonomous" : "Assisted"}</dd>
370 <dt>Today</dt>
371 <dt>Wallet</dt>
371372 <dd>
372 $${status.spentTodayUsd.toFixed(2)} of
373 $${status.ceilingUsd.toFixed(0)}
373 ${unitsText(balanceNow(ctx.app.db, repo.id, repo.autonomyCeilingUsd, new Date()).total)} of allocation left
374 · <a href="${base}/wallet">wallet and ledger</a>
374375 </dd>
375376 <dt>Slots</dt>
376377 <dd>${status.active} of ${status.slots} in use</dd>
@@ -384,7 +385,7 @@ function autonomyCard(ctx: Ctx, repo: Repo, base: string, admin: boolean): Html
384385 ? html`<dt>Paused</dt>
385386 <dd>
386387 ${status.paused === "ceiling"
387 ? "at the ceiling, until 00:00 UTC"
388 ? "wallet empty, until it is refilled or funds are moved in"
388389 : status.paused}
389390 </dd>`
390391 : null}
@@ -454,11 +455,11 @@ ${repo.autonomyDirection}</textarea
454455 ],
455456 })}
456457 ${field({
457 label: "Ceiling per day",
458 label: "Allocation per day",
458459 name: "ceiling",
459460 value: String(repo.autonomyCeilingUsd),
460461 type: "number",
461 hint: `Dollars of agent spend on this ${getAppByRepo(ctx.app.db, repo.id) === undefined ? "repository" : "app"} per UTC day. At the ceiling the crew stops picking until midnight; nothing in flight is cut.`,
462 hint: `Dollars of agent spend on this ${getAppByRepo(ctx.app.db, repo.id) === undefined ? "repository" : "app"} per UTC day, carried as seven of them for the week's wallet allocation (an allocation, not money). When the wallet is empty the crew stops picking; nothing in flight is cut. Once you set the weekly allocation on the wallet page, that number rules.`,
462463 })}
463464 <div class="form-actions">${btn("Save", { variant: "primary" })}</div>
464465 </form>`;
test/autonomy.test.ts +2 −2
@@ -190,9 +190,9 @@ describe("a repository on its own", () => {
190190 reason: "assigned",
191191 });
192192 claimRun(app.db, spent.id);
193 finishRun(app.db, spent.id, { state: "ok", summary: "done", costUsd: 7 });
193 finishRun(app.db, spent.id, { state: "ok", summary: "done", costUsd: 70 });
194194 const status = autonomyStatus(app, fresh());
195 expect(status.spentTodayUsd).toBeCloseTo(11, 5);
195 expect(status.spentTodayUsd).toBeCloseTo(74, 5);
196196 expect(status.paused).toBe("ceiling");
197197 expect(status.resumesAt).not.toBeNull();
198198 expect(await driveRepo(app, fresh())).toBe("paused");
test/home-builders-idle.test.ts +1 −1
@@ -131,7 +131,7 @@ test("no subscription with headroom: the granted account's window is full", asyn
131131 test("ceiling reached outranks the others", async () => {
132132 const spent = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: builder.id, reason: "assigned" });
133133 claimRun(app.db, spent.id);
134 finishRun(app.db, spent.id, { state: "ok", summary: "done", costUsd: 12 });
134 finishRun(app.db, spent.id, { state: "ok", summary: "done", costUsd: 80 });
135135 const page = await home();
136136 expect(tile(page)).toContain("ceiling reached");
137137 expect(tile(page)).toContain('href="/meter"');
test/idle-reason.test.ts +2 −2
@@ -95,7 +95,7 @@ describe("idleReason", () => {
9595
9696 test("ceiling reached", () => {
9797 open("Work");
98 spend(10);
98 spend(70);
9999 expect(idleReason(app, new Date())).toEqual({ word: "ceiling reached", href: "/meter" });
100100 });
101101
@@ -125,7 +125,7 @@ describe("idleReason", () => {
125125 });
126126
127127 test("the first reason that holds wins: the ceiling before nothing", () => {
128 spend(10);
128 spend(70);
129129 expect(idleReason(app, new Date())?.word).toBe("ceiling reached");
130130 });
131131
test/mcp.test.ts +1
@@ -329,6 +329,7 @@ describe("the forge over MCP", () => {
329329 "land_past_gate",
330330 "repo_labels",
331331 "wait_for",
332 "wallet",
332333 "confirm_wait",
333334 "attach_look",
334335 "hold",
test/studio-shipping.test.ts +1 −1
@@ -364,7 +364,7 @@ describe("a stranger sees the app, not the owner's books", () => {
364364 expect(owner).toContain("keeper");
365365 expect(owner).toContain(">Crew<");
366366 expect(owner).toContain(">On its own<");
367 expect(owner).toMatch(/\$42\.50\s+of\s+\$25/);
367 expect(owner).toMatch(/\$132\.50\s+of allocation left/);
368368 // The crew card says the governor's reason in one line (#7644).
369369 expect(owner).toMatch(/<dt>Governor<\/dt>\s*<dd>Builders \d+: /);
370370 expect(owner).toContain("Remove");
test/tui-dashboard-idle.test.ts +1 −1
@@ -68,7 +68,7 @@ test("the admin's home prints the reason's line; nobody else's does", async () =
6868 .query("UPDATE repo SET autonomy = 'autonomous', autonomy_by = ?2, autonomy_ceiling_usd = 1, autonomy_slots = 2 WHERE id = ?1")
6969 .run(made.value.id, alice.id);
7070 const run = createRun(forge.db, { repoId: made.value.id, kind: "agent", actorId: getUserByName(forge.db, "idlebot")!.id });
71 forge.db.query("UPDATE run SET cost_usd = 5, state = 'ok' WHERE id = ?1").run(run.id);
71 forge.db.query("UPDATE run SET cost_usd = 8, state = 'ok' WHERE id = ?1").run(run.id);
7272
7373 const reason = idleReason(forge, new Date());
7474 expect(reason).toEqual({ word: "ceiling reached", href: "/meter" });
test/wallet.test.ts added +300
@@ -0,0 +1,300 @@
1 /**
2 * A repository's wallet (#8718): an append-only ledger in integer units whose
3 * sum is the balance, a weekly allocation that carries the old daily ceiling,
4 * subscription funds spent first and expiring at the reset, one action to
5 * move funds, and a run that starts only with funds.
6 */
7 import { afterAll, beforeAll, describe, expect, test } from "bun:test";
8 import { mkdtemp, rm } from "node:fs/promises";
9 import { tmpdir } from "node:os";
10 import { join } from "node:path";
11 import { moveFunds, readWallet, setWeeklyAllocation } from "../src/actions/wallet.ts";
12 import { createRepo } from "../src/actions/repos.ts";
13 import { createApp, type App } from "../src/app.ts";
14 import type { Repo } from "../src/core/repos.ts";
15 import { createRun } from "../src/core/runs.ts";
16 import type { User } from "../src/core/users.ts";
17 import { atCeiling } from "../src/crew/dispatch.ts";
18 import { serve, type Servers } from "../src/http/server.ts";
19 import {
20 balanceOf,
21 ledger,
22 mayStart,
23 moveUnits,
24 parseUnits,
25 settle,
26 toUnits,
27 UNIT,
28 unitsText,
29 weekStart,
30 } from "../src/core/wallet.ts";
31 import { mcpTool } from "./helpers/mcp.ts";
32 import { seedAdmin } from "./helpers/admin.ts";
33 import { createSession } from "../src/core/sessions.ts";
34
35 // A Wednesday; its week opens Monday 2026-10-05 and the next opens 2026-10-12.
36 const WED = new Date("2026-10-07T12:00:00Z");
37 const NEXT_WED = new Date("2026-10-14T12:00:00Z");
38
39 let dataDir = "";
40 let app: App;
41 let servers: Servers;
42 let alice: User;
43 let cookie = "";
44 let n = 0;
45
46 const mint = async (ceilingUsd: number): Promise<Repo> => {
47 const made = await createRepo(app, alice, { name: `w${n++}`, visibility: "private" });
48 if (!made.ok) throw new Error(String(made.error));
49 app.db.query("UPDATE repo SET autonomy_ceiling_usd = ?2 WHERE id = ?1").run(made.value.id, ceilingUsd);
50 return { ...made.value, autonomyCeilingUsd: ceilingUsd };
51 };
52 const spend = (repo: Repo, usd: number) => {
53 const run = createRun(app.db, { repoId: repo.id, kind: "agent", actorId: alice.id });
54 app.db.query("UPDATE run SET cost_usd = ?2, state = 'ok' WHERE id = ?1").run(run.id, usd);
55 };
56 const sum = (repo: Repo): number =>
57 app.db.query<{ n: number }, [string]>("SELECT COALESCE(SUM(units),0) AS n FROM wallet_entry WHERE repo_id = ?1").get(repo.id)!.n;
58
59 beforeAll(async () => {
60 dataDir = await mkdtemp(join(tmpdir(), "forge-wallet-"));
61 app = createApp({ dataDir, port: 0 });
62 servers = await serve(app);
63 const made = await seedAdmin(app, { username: "alice", email: "[email protected]", password: "correct-horse-battery" });
64 if (!made.ok) throw new Error(made.error);
65 alice = made.value;
66 cookie = `forge_session=${createSession(app.db, alice.id).token}`;
67 });
68
69 afterAll(async () => {
70 servers.stop();
71 app.close();
72 await rm(dataDir, { recursive: true, force: true });
73 });
74
75 describe("units", () => {
76 test("dollars become integers by digits, never floats", () => {
77 expect(parseUnits("12.5")).toBe(12_500_000);
78 expect(parseUnits("0.000001")).toBe(1);
79 expect(parseUnits("1e3")).toBeUndefined();
80 expect(parseUnits("-1")).toBeUndefined();
81 expect(parseUnits("1.1234567")).toBeUndefined();
82 expect(toUnits(0.1 + 0.2)).toBe(300_000);
83 expect(unitsText(12_345_678)).toBe("$12.34");
84 expect(unitsText(-5 * UNIT)).toBe("-$5.00");
85 });
86 test("the week opens on a UTC Monday", () => {
87 expect(weekStart(WED).toISOString()).toBe("2026-10-05T00:00:00.000Z");
88 expect(weekStart(new Date("2026-10-11T23:59:59Z")).toISOString()).toBe("2026-10-05T00:00:00.000Z");
89 });
90 });
91
92 describe("the ledger", () => {
93 test("an existing daily ceiling carries over as seven days of allocation", async () => {
94 const repo = await mint(20);
95 settle(app.db, repo.id, 20, WED);
96 expect(balanceOf(app.db, repo.id).total).toBe(140 * UNIT);
97 expect(ledger(app.db, repo.id).map((e) => e.kind)).toEqual(["weekly"]);
98 });
99
100 test("settling twice appends nothing more: the same state gives the same ledger", async () => {
101 const repo = await mint(2);
102 spend(repo, 1.5);
103 settle(app.db, repo.id, 2, WED);
104 const once = ledger(app.db, repo.id);
105 settle(app.db, repo.id, 2, WED);
106 expect(ledger(app.db, repo.id)).toEqual(once);
107 });
108
109 test("each run's cost is an entry at list price, and the balance is the sum of the entries", async () => {
110 const repo = await mint(1);
111 spend(repo, 1.25);
112 spend(repo, 0.5);
113 settle(app.db, repo.id, 1, WED);
114 const b = balanceOf(app.db, repo.id);
115 expect(b.total).toBe(7 * UNIT - 1_250_000 - 500_000);
116 expect(b.total).toBe(sum(repo));
117 expect(ledger(app.db, repo.id).filter((e) => e.kind === "run").map((e) => e.units).sort()).toEqual([-1_250_000, -500_000]);
118 });
119
120 test("entries are append only", async () => {
121 const repo = await mint(1);
122 settle(app.db, repo.id, 1, WED);
123 expect(() => app.db.query("UPDATE wallet_entry SET units = 1 WHERE repo_id = ?1").run(repo.id)).toThrow(/append only/);
124 expect(() => app.db.query("DELETE FROM wallet_entry WHERE repo_id = ?1").run(repo.id)).toThrow(/append only/);
125 });
126
127 test("subscription funds expire at the weekly reset; cash keeps", async () => {
128 const repo = await mint(1);
129 settle(app.db, repo.id, 1, WED);
130 app.db
131 .query("INSERT INTO wallet_entry (repo_id, kind, fund, units, at) VALUES (?1, 'grant', 'cash', ?2, ?3)")
132 .run(repo.id, 3 * UNIT, WED.toISOString());
133 settle(app.db, repo.id, 1, NEXT_WED);
134 const b = balanceOf(app.db, repo.id);
135 expect(b.subscription).toBe(7 * UNIT); // last week's expired, this week's refilled
136 expect(b.cash).toBe(3 * UNIT);
137 expect(ledger(app.db, repo.id).some((e) => e.kind === "expiry" && e.units === -7 * UNIT)).toBe(true);
138 expect(b.total).toBe(sum(repo));
139 });
140
141 test("a run is paid from the subscription fund first, then cash", async () => {
142 const repo = await mint(1);
143 settle(app.db, repo.id, 1, WED);
144 app.db
145 .query("INSERT INTO wallet_entry (repo_id, kind, fund, units, at) VALUES (?1, 'grant', 'cash', ?2, ?3)")
146 .run(repo.id, 5 * UNIT, WED.toISOString());
147 spend(repo, 9);
148 settle(app.db, repo.id, 1, WED);
149 const b = balanceOf(app.db, repo.id);
150 expect(b.subscription).toBe(0);
151 expect(b.cash).toBe(3 * UNIT);
152 });
153 });
154
155 describe("a run starts only with funds", () => {
156 test("empty wallet: no run, in one line; refilled by the reset", async () => {
157 const repo = await mint(1);
158 expect(mayStart(app.db, repo.id, 1, WED).ok).toBe(true);
159 spend(repo, 7);
160 expect(atCeiling(app.db, repo, WED)).toBe(true);
161 const no = mayStart(app.db, repo.id, 1, WED);
162 expect(no.ok).toBe(false);
163 if (!no.ok) {
164 expect(no.says.split("\n")).toHaveLength(1);
165 expect(no.says).toContain("wallet is empty");
166 expect(no.says).toContain("2026-10-12");
167 }
168 expect(atCeiling(app.db, repo, NEXT_WED)).toBe(false);
169 });
170
171 test("a bet runs on its own envelope", async () => {
172 const repo = await mint(1);
173 settle(app.db, repo.id, 1, WED);
174 expect(mayStart(app.db, repo.id, 1, WED, "ship-it").ok).toBe(false);
175 const moved = moveFunds(app, alice, repo, { units: 2 * UNIT, fromBet: null, toRepo: null, toBet: "ship-it" }, WED);
176 expect(moved.ok).toBe(true);
177 expect(mayStart(app.db, repo.id, 1, WED, "ship-it").ok).toBe(true);
178 expect(balanceOf(app.db, repo.id, "ship-it").total).toBe(2 * UNIT);
179 expect(balanceOf(app.db, repo.id).total).toBe(5 * UNIT);
180 });
181 });
182
183 describe("moving funds", () => {
184 test("between repositories conserves the total, and keeps the funds' kind", async () => {
185 const a = await mint(1);
186 const b = await mint(1);
187 settle(app.db, a.id, 1, WED);
188 settle(app.db, b.id, 1, WED);
189 const before = sum(a) + sum(b);
190 const moved = moveFunds(app, alice, a, { units: 1_000_001, fromBet: null, toRepo: `${b.ownerName}/${b.name}`, toBet: null }, WED);
191 expect(moved.ok).toBe(true);
192 expect(sum(a) + sum(b)).toBe(before);
193 expect(balanceOf(app.db, a.id).total).toBe(7 * UNIT - 1_000_001);
194 expect(balanceOf(app.db, b.id).subscription).toBe(7 * UNIT + 1_000_001);
195 expect(balanceOf(app.db, b.id).cash).toBe(0);
196 });
197
198 test("refuses more than the wallet holds, nonsense amounts and bad names, changing nothing", async () => {
199 const a = await mint(1);
200 settle(app.db, a.id, 1, WED);
201 const before = sum(a);
202 const bad = (units: number, toBet: string | null) =>
203 moveFunds(app, alice, a, { units, fromBet: null, toRepo: null, toBet }, WED);
204 expect(bad(8 * UNIT, "x")).toEqual({ ok: false, error: "insufficient" });
205 expect(bad(0, "x")).toEqual({ ok: false, error: "invalid_amount" });
206 expect(bad(1.5, "x")).toEqual({ ok: false, error: "invalid_amount" });
207 expect(bad(UNIT, "Bad Name")).toEqual({ ok: false, error: "invalid_bet" });
208 expect(bad(UNIT, null)).toEqual({ ok: false, error: "same_place" });
209 expect(sum(a)).toBe(before);
210 });
211
212 test("a move is atomic: nothing is left half done when the second entry cannot be written", async () => {
213 const a = await mint(1);
214 settle(app.db, a.id, 1, WED);
215 const before = ledger(app.db, a.id).length;
216 expect(() =>
217 moveUnits(app.db, { from: { repoId: a.id, bet: null }, to: { repoId: a.id, bet: "ok" }, units: UNIT, actorId: alice.id, now: new Date("nope") }),
218 ).toThrow();
219 expect(ledger(app.db, a.id)).toHaveLength(before);
220 });
221
222 test("only the repository's admin moves or sets, and a stranger sees nothing", async () => {
223 const a = await mint(1);
224 const bob = await seedAdmin(app, { username: "bob", email: "[email protected]", password: "correct-horse-battery" });
225 if (!bob.ok) throw new Error(bob.error);
226 const plain = { ...bob.value, isAdmin: false };
227 expect(moveFunds(app, undefined, a, { units: UNIT, fromBet: null, toRepo: null, toBet: "x" }).ok).toBe(false);
228 expect(moveFunds(app, plain, a, { units: UNIT, fromBet: null, toRepo: null, toBet: "x" }).ok).toBe(false);
229 expect(setWeeklyAllocation(app, plain, a, UNIT).ok).toBe(false);
230 expect(readWallet(app, plain, a).ok).toBe(false);
231 });
232
233 test("the weekly allocation, once set, replaces the carried ceiling", async () => {
234 const a = await mint(20);
235 expect(setWeeklyAllocation(app, alice, a, 10 * UNIT, WED).ok).toBe(true);
236 expect(readWallet(app, alice, a, WED)).toMatchObject({ ok: true, value: { weeklyUnits: 10 * UNIT } });
237 expect(balanceOf(app.db, a.id).total).toBe(10 * UNIT);
238 });
239 });
240
241 describe("reached by a person and an agent", () => {
242 test("the page says it is an allocation, shows the ledger, and the form moves funds", async () => {
243 const a = await mint(1);
244 const base = servers.url;
245 const page = await (await fetch(`${base}/${a.ownerName}/${a.name}/wallet`, { headers: { cookie } })).text();
246 expect(page).toContain("An allocation, not money");
247 expect(page).toContain("weekly allocation");
248 const res = await fetch(`${base}/${a.ownerName}/${a.name}/wallet/move`, {
249 method: "POST",
250 redirect: "manual",
251 headers: { cookie, origin: base, "content-type": "application/x-www-form-urlencoded" },
252 body: new URLSearchParams({ amount: "1.5", to_bet: "launch" }),
253 });
254 expect(res.status).toBeLessThan(400);
255 expect(balanceOf(app.db, a.id, "launch").total).toBe(1_500_000);
256 const cross = await fetch(`${base}/${a.ownerName}/${a.name}/wallet/move`, {
257 method: "POST",
258 redirect: "manual",
259 headers: { cookie, origin: "https://evil.example", "content-type": "application/x-www-form-urlencoded" },
260 body: new URLSearchParams({ amount: "1", to_bet: "launch" }),
261 });
262 expect(cross.status).toBe(403);
263 expect(balanceOf(app.db, a.id, "launch").total).toBe(1_500_000);
264 const anon = await fetch(`${base}/${a.ownerName}/${a.name}/wallet`);
265 expect(anon.status).toBe(404);
266 });
267
268 test("the MCP tool reads, moves and sets", async () => {
269 const a = await mint(1);
270 const minted = await fetch(`${servers.url}/api/v1/tokens`, {
271 method: "POST",
272 headers: { "content-type": "application/json" },
273 body: JSON.stringify({ adminConfirm: true, username: "alice", password: "correct-horse-battery", name: "mcp", scope: "admin" }),
274 });
275 const token = ((await minted.json()) as { token: string }).token;
276 const repo = `${a.ownerName}/${a.name}`;
277 const read = await mcpTool(servers.url, token, "wallet", { repo });
278 expect(read.value.says).toContain("not money");
279 expect(read.value.balance.total).toBe(7 * UNIT);
280 const moved = await mcpTool(servers.url, token, "wallet", { repo, move: { amount: "2", toBet: "b1" } });
281 expect(moved.value.says).toBe("Moved $2.00 of allocation.");
282 const refused = await mcpTool(servers.url, token, "wallet", { repo, move: { amount: "999" } });
283 expect(refused.error).toBeDefined();
284 const set = await mcpTool(servers.url, token, "wallet", { repo, weekly: "3" });
285 expect(set.value.weeklyUnits).toBe(3 * UNIT);
286 });
287 });
288
289 test("changing the daily ceiling mid-week moves the week's allocation, and the ledger still totals the balance", async () => {
290 const repo = await mint(10);
291 settle(app.db, repo.id, 10, WED);
292 expect(balanceOf(app.db, repo.id).total).toBe(70 * UNIT);
293 settle(app.db, repo.id, 0, WED);
294 expect(balanceOf(app.db, repo.id).total).toBe(0);
295 expect(mayStart(app.db, repo.id, 0, WED).ok).toBe(false);
296 settle(app.db, repo.id, 20, WED);
297 expect(balanceOf(app.db, repo.id).total).toBe(140 * UNIT);
298 settle(app.db, repo.id, 20, WED);
299 expect(ledger(app.db, repo.id).reduce((t, e) => t + e.units, 0)).toBe(140 * UNIT);
300 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs